{-|

The @aregister@ command lists a single account's transactions,
like the account register in hledger-ui and hledger-web,
and unlike the register command which lists postings across multiple accounts.

-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands.Aregister (
  aregistermode
 ,aregister
 -- ,showPostingWithBalanceForVty
 ,tests_Aregister
) where

import Data.Default (def)
import Data.List (find, nub)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Foldable (for_)
import Data.Map qualified as Map
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Control.Monad (unless, when)
import Safe (readMay)
import System.Console.CmdArgs.Explicit (flagNone, flagReq)
import System.IO qualified as IO
import Text.Blaze.Html5 ((!), preEscapedToHtml)
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A
import Text.Tabular.AsciiWide hiding (render)

import Hledger
import Hledger.Cli.Chart (accountTransactionsReportAsChart, chartFlag, chartRequested, writeChart)
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils
import Hledger.Write.Csv (CSV, printCSV, printTSV)
import Hledger.Write.Html (formatRow, formatTitle, htmlAsLazyText, nl, toHtml)
import Hledger.Write.Html.Attribute (tableStylesheet)
import Hledger.Write.Ods (printFods)
import Hledger.Write.Spreadsheet qualified as Spr

aregistermode :: Mode RawOpts
aregistermode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Aregister.txt")
  ([
   [String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"txn-dates"] (String -> RawOpts -> RawOpts
setboolopt String
"txn-dates") 
     String
"filter strictly by transaction date, not posting date. Warning: this can show a wrong running balance."
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"no-elide"] (String -> RawOpts -> RawOpts
setboolopt String
"no-elide") String
"don't show only 2 commodities per amount"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"cumulative"] (String -> RawOpts -> RawOpts
setboolopt String
"cumulative")
     (String
accumprefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"show running total from report start date")
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"historical",String
"H"] (String -> RawOpts -> RawOpts
setboolopt String
"historical")
     (String
accumprefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"show historical running total/balance (includes postings before report start date) (default)")
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"average",String
"A"] (String -> RawOpts -> RawOpts
setboolopt String
"average")
     String
"show running average of transaction amounts instead of balance (implies --empty and, unless -H is used, --cumulative)"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"related",String
"r"] (String -> RawOpts -> RawOpts
setboolopt String
"related") String
"show the other accounts in each transaction (default)"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"matched"] (String -> RawOpts -> RawOpts
setboolopt String
"matched") String
"show the matched accounts (this account or its subaccounts) instead"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"invert"] (String -> RawOpts -> RawOpts
setboolopt String
"invert") String
"display all amounts with reversed sign"
  ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"drop"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"drop" String
s RawOpts
opts) String
"N" String
"omit N leading account name parts"
  ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"heading"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"heading" String
s RawOpts
opts) String
"YN"
     String
"show heading row above table: yes (default) or no"
  ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"width",String
"w"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"width" String
s RawOpts
opts) String
"N"
     (String
"set output width (default: " String -> String -> String
forall a. [a] -> [a] -> [a]
++
#ifdef mingw32_HOST_OS
      show defaultWidth
#else
      String
"terminal width"
#endif
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"). -wN,M sets description width as well."
     )
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"align-all"] (String -> RawOpts -> RawOpts
setboolopt String
"align-all") String
"guarantee alignment across all lines (slower)"
  ,[String] -> Flag RawOpts
outputFormatFlag [String
"txt",String
"html",String
"csv",String
"tsv",String
"json",String
"svg"]
  ,Flag RawOpts
outputFileFlag
  ,Flag RawOpts
outputViewFlag
  ,Flag RawOpts
chartFlag
  ])
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"ACCTPAT [QUERY]")
  where
    accumprefix :: String
accumprefix = String
"accumulation mode: "

-- based on Hledger.UI.RegisterScreen:

-- | Print an account register report for a specified account.
aregister :: CliOpts -> Journal -> IO ()
aregister :: CliOpts -> Journal -> IO ()
aregister opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts,reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec} Journal
j = do
  -- the first argument specifies the account, any remaining arguments are a filter query
  let help :: String
help = String
"aregister needs an ACCTPAT argument to select an account"
  (apat,querystr) <- case String -> RawOpts -> [String]
listofstringopt String
"args" RawOpts
rawopts of
      []     -> String -> IO (String, [AccountName])
forall a. String -> a
error' (String -> IO (String, [AccountName]))
-> String -> IO (String, [AccountName])
forall a b. (a -> b) -> a -> b
$ String
help String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
".\nPlease provide an account name or a (case-insensitive, infix, regexp) pattern."
      (String
a:[String]
as) -> (String, [AccountName]) -> IO (String, [AccountName])
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String
a, (String -> AccountName) -> [String] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map String -> AccountName
T.pack [String]
as)
  let
    -- keep synced with findMatchedByArgument's matching
    acct = AccountName -> Maybe AccountName -> AccountName
forall a. a -> Maybe a -> a
fromMaybe (String -> AccountName
forall a. String -> a
error' (String -> AccountName) -> String -> AccountName
forall a b. (a -> b) -> a -> b
$ String
help String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
", but " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
apatString -> String -> String
forall a. [a] -> [a] -> [a]
++String
" did not match any account.")   -- PARTIAL:
           (Maybe AccountName -> AccountName)
-> ([AccountName] -> Maybe AccountName)
-> [AccountName]
-> AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [AccountName] -> Maybe AccountName
firstMatch ([AccountName] -> AccountName) -> [AccountName] -> AccountName
forall a b. (a -> b) -> a -> b
$ Journal -> [AccountName]
journalAccountNamesDeclaredOrImplied Journal
j
    firstMatch = case AccountName -> Either String Regexp
toRegexCI (AccountName -> Either String Regexp)
-> AccountName -> Either String Regexp
forall a b. (a -> b) -> a -> b
$ String -> AccountName
T.pack String
apat of
        Right Regexp
re -> (AccountName -> Bool) -> [AccountName] -> Maybe AccountName
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Regexp -> AccountName -> Bool
regexMatchText Regexp
re)
        Left  String
_  -> Maybe AccountName -> [AccountName] -> Maybe AccountName
forall a b. a -> b -> a
const Maybe AccountName
forall a. Maybe a
Nothing
    -- gather report options
    inclusive = Bool
True  -- tree_ ropts
    thisacctq = Regexp -> Query
Acct (Regexp -> Query) -> Regexp -> Query
forall a b. (a -> b) -> a -> b
$ (if Bool
inclusive then AccountName -> Regexp
accountNameToAccountRegex else AccountName -> Regexp
accountNameToAccountOnlyRegex) AccountName
acct
    ropts = ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec
    ropts' = ReportOpts
ropts {
        -- ignore any depth limit, as in postingsReport; allows register's total to match balance reports (cf #1468)
        depth_=DepthSpec Nothing []
        -- historical by default, or cumulative with --average (averaging over the report period, like register)
      , balanceaccum_ =
          case balanceaccum_ ropts of
            BalanceAccumulation
PerPeriod | ReportOpts -> Bool
average_ ReportOpts
ropts -> BalanceAccumulation
Cumulative
                      | Bool
otherwise      -> BalanceAccumulation
Historical
            BalanceAccumulation
ba -> BalanceAccumulation
ba
        -- with --average, show all transactions, since they all affect the average
      , empty_ = empty_ ropts || average_ ropts
      , querystring_ = querystr
      }
    wd = ReportOpts -> WhichDate
whichDate ReportOpts
ropts'
  -- and regenerate the ReportSpec, making sure to use the above
  rspec' <- either fail return $ updateReportSpec ropts' rspec
  let
    -- run the report
    -- TODO: need to also pass the queries so we can choose which date to render - move them into the report ?
    items = ReportSpec -> Journal -> Query -> AccountTransactionsReport
accountTransactionsReport ReportSpec
rspec' Journal
j Query
thisacctq
    items' =
      Map AccountName AmountStyle
-> AccountTransactionsReport -> AccountTransactionsReport
forall a. HasAmounts a => Map AccountName AmountStyle -> a -> a
styleAmounts (Rounding -> Journal -> Map AccountName AmountStyle
journalCommodityStylesWith Rounding
HardRounding Journal
j) (AccountTransactionsReport -> AccountTransactionsReport)
-> AccountTransactionsReport -> AccountTransactionsReport
forall a b. (a -> b) -> a -> b
$
      (if ReportOpts -> Bool
empty_ ReportOpts
ropts' then AccountTransactionsReport -> AccountTransactionsReport
forall a. a -> a
id else ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
  MixedAmount)
 -> Bool)
-> AccountTransactionsReport -> AccountTransactionsReport
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> Bool)
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> Bool
mixedAmountLooksZero (MixedAmount -> Bool)
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> MixedAmount)
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
-> MixedAmount
forall {a} {b} {c} {d} {e} {f}. (a, b, c, d, e, f) -> e
fifth6)) (AccountTransactionsReport -> AccountTransactionsReport)
-> AccountTransactionsReport -> AccountTransactionsReport
forall a b. (a -> b) -> a -> b
$
      AccountTransactionsReport -> AccountTransactionsReport
forall a. [a] -> [a]
reverse AccountTransactionsReport
items
    -- select renderer
    render | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"txt"  = CliOpts -> Query -> Query -> AccountTransactionsReport -> Text
accountTransactionsReportAsText CliOpts
opts (ReportSpec -> Query
_rsQuery ReportSpec
rspec') Query
thisacctq
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"html" = CliOpts -> Query -> Query -> AccountTransactionsReport -> Text
accountTransactionsReportAsHTML CliOpts
opts (ReportSpec -> Query
_rsQuery ReportSpec
rspec') Query
thisacctq
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"csv"  = CSV -> Text
printCSV (CSV -> Text)
-> (AccountTransactionsReport -> CSV)
-> AccountTransactionsReport
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CliOpts
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> CSV
accountTransactionsReportAsCsv CliOpts
opts Bool
hd WhichDate
wd (ReportSpec -> Query
_rsQuery ReportSpec
rspec') Query
thisacctq
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"tsv"  = CSV -> Text
printTSV (CSV -> Text)
-> (AccountTransactionsReport -> CSV)
-> AccountTransactionsReport
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CliOpts
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> CSV
accountTransactionsReportAsCsv CliOpts
opts Bool
hd WhichDate
wd (ReportSpec -> Query
_rsQuery ReportSpec
rspec') Query
thisacctq
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"fods" =
                TextEncoding
-> Map AccountName ((Int, Int), [[Cell NumLines AccountName]])
-> Text
printFods TextEncoding
IO.localeEncoding (Map AccountName ((Int, Int), [[Cell NumLines AccountName]])
 -> Text)
-> (AccountTransactionsReport
    -> Map AccountName ((Int, Int), [[Cell NumLines AccountName]]))
-> AccountTransactionsReport
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName
-> ((Int, Int), [[Cell NumLines AccountName]])
-> Map AccountName ((Int, Int), [[Cell NumLines AccountName]])
forall k a. k -> a -> Map k a
Map.singleton AccountName
"Aregister" (((Int, Int), [[Cell NumLines AccountName]])
 -> Map AccountName ((Int, Int), [[Cell NumLines AccountName]]))
-> (AccountTransactionsReport
    -> ((Int, Int), [[Cell NumLines AccountName]]))
-> AccountTransactionsReport
-> Map AccountName ((Int, Int), [[Cell NumLines AccountName]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                (,) (Int
1,Int
0) ([[Cell NumLines AccountName]]
 -> ((Int, Int), [[Cell NumLines AccountName]]))
-> (AccountTransactionsReport -> [[Cell NumLines AccountName]])
-> AccountTransactionsReport
-> ((Int, Int), [[Cell NumLines AccountName]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> [[Cell NumLines AccountName]]
accountTransactionsReportAsSpreadsheet CliOpts
opts AmountFormat
oneLineNoCostFmt Bool
hd WhichDate
wd (ReportSpec -> Query
_rsQuery ReportSpec
rspec') Query
thisacctq
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"json" = AccountTransactionsReport -> Text
forall a. ToJSON a => a -> Text
toJsonText
           | Bool
otherwise   = String -> AccountTransactionsReport -> Text
forall a. String -> a
error' (String -> AccountTransactionsReport -> Text)
-> String -> AccountTransactionsReport -> Text
forall a b. (a -> b) -> a -> b
$ String -> String
unsupportedOutputFormatError String
fmt  -- PARTIAL:
      where
        hd :: Bool
hd = CliOpts -> Bool
headingopt CliOpts
opts
        fmt :: String
fmt = CliOpts -> String
outputFormatFromOpts CliOpts
opts

  if chartRequested opts
  then writeChart opts (Just $ render items') $
       accountTransactionsReportAsChart (journalAccountType j) (accountTransactionsReportTitle opts (_rsQuery rspec') thisacctq) acct
         (transactionRegisterDate wd (_rsQuery rspec') thisacctq) items'
  else writeOutputLazyText opts $ render items'

accountTransactionsReportAsCsv ::
  CliOpts -> Bool -> WhichDate -> Query -> Query -> AccountTransactionsReport -> CSV
accountTransactionsReportAsCsv :: CliOpts
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> CSV
accountTransactionsReportAsCsv CliOpts
opts Bool
hd WhichDate
wd Query
reportq Query
thisacctq AccountTransactionsReport
atr =
  case CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> [[Cell NumLines AccountName]]
accountTransactionsReportAsSpreadsheet CliOpts
opts AmountFormat
machineFmt Bool
hd WhichDate
wd Query
reportq Query
thisacctq AccountTransactionsReport
atr of
    []                    -> []
    rows :: [[Cell NumLines AccountName]]
rows@([Cell NumLines AccountName]
headerrow : [[Cell NumLines AccountName]]
_) -> [[Cell NumLines AccountName]] -> CSV
forall (f :: * -> *) border text.
Functor f =>
[f (Cell border text)] -> [f text]
Spr.rawTableContent ([[Cell NumLines AccountName]] -> CSV)
-> [[Cell NumLines AccountName]] -> CSV
forall a b. (a -> b) -> a -> b
$ [Cell NumLines AccountName] -> [[Cell NumLines AccountName]]
forall {border} {a}.
Lines border =>
[a] -> [[Cell border AccountName]]
titleRows [Cell NumLines AccountName]
headerrow [[Cell NumLines AccountName]]
-> [[Cell NumLines AccountName]] -> [[Cell NumLines AccountName]]
forall a. [a] -> [a] -> [a]
++ [[Cell NumLines AccountName]]
rows
  where
    titleText :: AccountName
titleText = ReportOpts -> AccountName -> AccountName
effectiveTitle (ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
opts) AccountName
""
    titleRows :: [a] -> [[Cell border AccountName]]
titleRows [a]
headerrow
      | AccountName -> Bool
T.null AccountName
titleText = []
      | Bool
otherwise        = [[a] -> Cell border AccountName -> [Cell border AccountName]
forall border text a.
(Lines border, Monoid text) =>
[a] -> Cell border text -> [Cell border text]
Spr.horizontalSpan [a]
headerrow (AccountName -> Cell border AccountName
forall borders.
Lines borders =>
AccountName -> Cell borders AccountName
Spr.headerCell AccountName
titleText)]

accountTransactionsReportAsSpreadsheet ::
  CliOpts -> AmountFormat -> Bool ->
  WhichDate -> Query -> Query -> AccountTransactionsReport ->
  [[Spr.Cell Spr.NumLines Text]]
accountTransactionsReportAsSpreadsheet :: CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> AccountTransactionsReport
-> [[Cell NumLines AccountName]]
accountTransactionsReportAsSpreadsheet CliOpts
opts AmountFormat
fmt Bool
hd WhichDate
wd Query
reportq Query
thisacctq AccountTransactionsReport
is =
  Bool
-> [[Cell NumLines AccountName]] -> [[Cell NumLines AccountName]]
forall p. Monoid p => Bool -> p -> p
optional Bool
hd
    [[Cell () AccountName] -> [Cell NumLines AccountName]
forall (f :: * -> *) text.
Functor f =>
f (Cell () text) -> f (Cell NumLines text)
Spr.addHeaderBorders ([Cell () AccountName] -> [Cell NumLines AccountName])
-> [Cell () AccountName] -> [Cell NumLines AccountName]
forall a b. (a -> b) -> a -> b
$ (AccountName -> Cell () AccountName)
-> [AccountName] -> [Cell () AccountName]
forall a b. (a -> b) -> [a] -> [b]
map AccountName -> Cell () AccountName
forall borders.
Lines borders =>
AccountName -> Cell borders AccountName
Spr.headerCell ([AccountName] -> [Cell () AccountName])
-> [AccountName] -> [Cell () AccountName]
forall a b. (a -> b) -> a -> b
$
      [AccountName
"txnidx",AccountName
"date",AccountName
"code",AccountName
"description",AccountName
"otheraccounts",AccountName
"amount",AccountName
"balance"]]
  [[Cell NumLines AccountName]]
-> [[Cell NumLines AccountName]] -> [[Cell NumLines AccountName]]
forall a. [a] -> [a] -> [a]
++
  ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
  MixedAmount)
 -> [Cell NumLines AccountName])
-> AccountTransactionsReport -> [[Cell NumLines AccountName]]
forall a b. (a -> b) -> [a] -> [b]
map (CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [Cell NumLines AccountName]
accountTransactionsReportItemAsRecord CliOpts
opts AmountFormat
fmt Bool
True WhichDate
wd Query
reportq Query
thisacctq) AccountTransactionsReport
is

accountTransactionsReportItemAsRecord ::
  CliOpts -> AmountFormat -> Bool ->
  WhichDate -> Query -> Query -> AccountTransactionsReportItem ->
  [Spr.Cell Spr.NumLines Text]
accountTransactionsReportItemAsRecord :: CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [Cell NumLines AccountName]
accountTransactionsReportItemAsRecord
  CliOpts
opts AmountFormat
fmt Bool
internals WhichDate
wd Query
reportq Query
thisacctq
  item :: (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
item@(t :: Transaction
t@Transaction{Integer
tindex :: Integer
tindex :: Transaction -> Integer
tindex,AccountName
tcode :: AccountName
tcode :: Transaction -> AccountName
tcode,AccountName
tdescription :: AccountName
tdescription :: Transaction -> AccountName
tdescription}, Transaction
_, Bool
_issplit, [AccountName]
_, MixedAmount
change, MixedAmount
balance)
  = (Bool -> [Cell NumLines AccountName] -> [Cell NumLines AccountName]
forall p. Monoid p => Bool -> p -> p
optional Bool
internals [Integer -> Cell NumLines AccountName
forall border. Lines border => Integer -> Cell border AccountName
Spr.integerCell Integer
tindex]) [Cell NumLines AccountName]
-> [Cell NumLines AccountName] -> [Cell NumLines AccountName]
forall a. [a] -> [a] -> [a]
++
    Cell NumLines AccountName
date Cell NumLines AccountName
-> [Cell NumLines AccountName] -> [Cell NumLines AccountName]
forall a. a -> [a] -> [a]
:
    (Bool -> [Cell NumLines AccountName] -> [Cell NumLines AccountName]
forall p. Monoid p => Bool -> p -> p
optional Bool
internals [AccountName -> Cell NumLines AccountName
forall {text}. text -> Cell NumLines text
cell AccountName
tcode]) [Cell NumLines AccountName]
-> [Cell NumLines AccountName] -> [Cell NumLines AccountName]
forall a. [a] -> [a] -> [a]
++
    [AccountName -> Cell NumLines AccountName
forall {text}. text -> Cell NumLines text
cell AccountName
tdescription,
     AccountName -> Cell NumLines AccountName
forall {text}. text -> Cell NumLines text
cell (AccountName -> Cell NumLines AccountName)
-> AccountName -> Cell NumLines AccountName
forall a b. (a -> b) -> a -> b
$ AccountName -> [AccountName] -> AccountName
T.intercalate AccountName
", " ([AccountName] -> AccountName) -> [AccountName] -> AccountName
forall a b. (a -> b) -> a -> b
$ (AccountName -> AccountName) -> [AccountName] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map AccountName -> AccountName
dropAcct ([AccountName] -> [AccountName]) -> [AccountName] -> [AccountName]
forall a b. (a -> b) -> a -> b
$ CliOpts
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [AccountName]
itemAccountNames CliOpts
opts Query
thisacctq (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
item,
     MixedAmount -> Cell NumLines AccountName
forall {border}.
Lines border =>
MixedAmount -> Cell border AccountName
amountCell MixedAmount
change,
     MixedAmount -> Cell NumLines AccountName
forall {border}.
Lines border =>
MixedAmount -> Cell border AccountName
amountCell MixedAmount
balance]
  where
    dropAcct :: AccountName -> AccountName
dropAcct = Int -> AccountName -> AccountName
accountNameDrop (Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 (Maybe Int -> Int) -> Maybe Int -> Int
forall a b. (a -> b) -> a -> b
$ String -> Maybe Int
forall a. Read a => String -> Maybe a
readMay (String -> Maybe Int) -> Maybe String -> Maybe Int
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< String -> RawOpts -> Maybe String
maybestringopt String
"drop" (CliOpts -> RawOpts
rawopts_ CliOpts
opts))
    cell :: text -> Cell NumLines text
cell = text -> Cell NumLines text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell
    date :: Cell NumLines AccountName
date =
        (AccountName -> Cell NumLines AccountName
forall border text. Lines border => text -> Cell border text
Spr.defaultCell (AccountName -> Cell NumLines AccountName)
-> AccountName -> Cell NumLines AccountName
forall a b. (a -> b) -> a -> b
$ Day -> AccountName
showDate (Day -> AccountName) -> Day -> AccountName
forall a b. (a -> b) -> a -> b
$
         WhichDate -> Query -> Query -> Transaction -> Day
transactionRegisterDate WhichDate
wd Query
reportq Query
thisacctq Transaction
t)
            {Spr.cellType = Spr.TypeDate}
    amountCell :: MixedAmount -> Cell border AccountName
amountCell MixedAmount
amt =
      WideBuilder -> AccountName
wbToText (WideBuilder -> AccountName)
-> Cell border WideBuilder -> Cell border AccountName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AmountFormat -> (Class, MixedAmount) -> Cell border WideBuilder
forall border.
Lines border =>
AmountFormat -> (Class, MixedAmount) -> Cell border WideBuilder
Spr.cellFromMixedAmount AmountFormat
fmt (AccountName -> Class
Spr.Class AccountName
"amount", MixedAmount
amt)

-- | Render a register report as a HTML snippet.
accountTransactionsReportAsHTML :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text
accountTransactionsReportAsHTML :: CliOpts -> Query -> Query -> AccountTransactionsReport -> Text
accountTransactionsReportAsHTML CliOpts
copts Query
reportq Query
thisacctq AccountTransactionsReport
items =
  (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ MarkupM () -> Text
htmlAsLazyText (MarkupM () -> Text) -> MarkupM () -> Text
forall a b. (a -> b) -> a -> b
$ do
    -- the builtin styles, then the optional user stylesheet so it can override them
    MarkupM () -> MarkupM ()
H.style (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ AccountName -> MarkupM ()
forall a. ToMarkup a => a -> MarkupM ()
preEscapedToHtml AccountName
tableStylesheet
    MarkupM ()
nl
    MarkupM ()
H.link MarkupM () -> Attribute -> MarkupM ()
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.rel AttributeValue
"stylesheet" MarkupM () -> Attribute -> MarkupM ()
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.href AttributeValue
"hledger.css"
    MarkupM ()
nl
    let title :: AccountName
title = CliOpts -> Query -> Query -> AccountName
accountTransactionsReportTitle CliOpts
copts Query
reportq Query
thisacctq
    Bool -> MarkupM () -> MarkupM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (AccountName -> Bool
T.null AccountName
title) (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ AccountName -> MarkupM ()
formatTitle AccountName
title
    MarkupM () -> MarkupM ()
H.table (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ do
      MarkupM ()
nl
      Bool -> MarkupM () -> MarkupM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (CliOpts -> Bool
headingopt CliOpts
copts) (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ do
        MarkupM () -> MarkupM ()
H.thead (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ MarkupM () -> MarkupM ()
H.tr (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ do
          MarkupM () -> MarkupM ()
H.th MarkupM ()
"date"
          MarkupM () -> MarkupM ()
H.th MarkupM ()
"description"
          MarkupM () -> MarkupM ()
H.th MarkupM ()
"otheraccounts"
          MarkupM () -> MarkupM ()
H.th MarkupM ()
"amount"
          MarkupM () -> MarkupM ()
H.th MarkupM ()
"balance"
        MarkupM ()
nl
      MarkupM () -> MarkupM ()
H.tbody (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ AccountTransactionsReport
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> MarkupM ())
-> MarkupM ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ AccountTransactionsReport
items (((Transaction, Transaction, Bool, [AccountName], MixedAmount,
   MixedAmount)
  -> MarkupM ())
 -> MarkupM ())
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> MarkupM ())
-> MarkupM ()
forall a b. (a -> b) -> a -> b
$
        [Cell NumLines (MarkupM ())] -> MarkupM ()
forall border.
Lines border =>
[Cell border (MarkupM ())] -> MarkupM ()
formatRow ([Cell NumLines (MarkupM ())] -> MarkupM ())
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> [Cell NumLines (MarkupM ())])
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> MarkupM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Cell NumLines AccountName -> Cell NumLines (MarkupM ()))
-> [Cell NumLines AccountName] -> [Cell NumLines (MarkupM ())]
forall a b. (a -> b) -> [a] -> [b]
map ((AccountName -> MarkupM ())
-> Cell NumLines AccountName -> Cell NumLines (MarkupM ())
forall a b. (a -> b) -> Cell NumLines a -> Cell NumLines b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap AccountName -> MarkupM ()
forall a. ToMarkup a => a -> MarkupM ()
toHtml) ([Cell NumLines AccountName] -> [Cell NumLines (MarkupM ())])
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> [Cell NumLines AccountName])
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [Cell NumLines (MarkupM ())]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
        CliOpts
-> AmountFormat
-> Bool
-> WhichDate
-> Query
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [Cell NumLines AccountName]
accountTransactionsReportItemAsRecord CliOpts
copts
          AmountFormat
oneLineNoCostFmt Bool
False
          (ReportOpts -> WhichDate
whichDate (ReportOpts -> WhichDate) -> ReportOpts -> WhichDate
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
copts)
          Query
reportq Query
thisacctq

-- | Render a register report as plain text suitable for console output.
accountTransactionsReportAsText :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text
accountTransactionsReportAsText :: CliOpts -> Query -> Query -> AccountTransactionsReport -> Text
accountTransactionsReportAsText CliOpts
copts Query
reportq Query
thisacctq AccountTransactionsReport
items = Builder -> Text
TB.toLazyText (Builder -> Text) -> Builder -> Text
forall a b. (a -> b) -> a -> b
$
    Builder
titleBuilder
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<>
    Bool
-> CliOpts
-> (Int
    -> Int
    -> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
         MixedAmount),
        [WideBuilder], [WideBuilder])
    -> Builder)
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> MixedAmount)
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount)
    -> MixedAmount)
-> AccountTransactionsReport
-> Builder
forall a.
Bool
-> CliOpts
-> (Int -> Int -> (a, [WideBuilder], [WideBuilder]) -> Builder)
-> (a -> MixedAmount)
-> (a -> MixedAmount)
-> [a]
-> Builder
postingsOrTransactionsReportAsText Bool
alignAll CliOpts
copts Int
-> Int
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount),
    [WideBuilder], [WideBuilder])
-> Builder
itemAsText (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
-> MixedAmount
forall {a} {b} {c} {d} {e} {f}. (a, b, c, d, e, f) -> e
itemamt (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
-> MixedAmount
forall {a} {b} {c} {d} {e} {f}. (a, b, c, d, e, f) -> f
itembal AccountTransactionsReport
items
  where
    alignAll :: Bool
alignAll = String -> RawOpts -> Bool
boolopt String
"align-all" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
copts
    itemAsText :: Int
-> Int
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount),
    [WideBuilder], [WideBuilder])
-> Builder
itemAsText = CliOpts
-> Query
-> Query
-> Int
-> Int
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount),
    [WideBuilder], [WideBuilder])
-> Builder
accountTransactionsReportItemAsText CliOpts
copts Query
reportq Query
thisacctq
    itemamt :: (a, b, c, d, e, f) -> e
itemamt (a
_,b
_,c
_,d
_,e
a,f
_) = e
a
    itembal :: (a, b, c, d, e, f) -> f
itembal (a
_,b
_,c
_,d
_,e
_,f
a) = f
a

    title :: AccountName
title = CliOpts -> Query -> Query -> AccountName
accountTransactionsReportTitle CliOpts
copts Query
reportq Query
thisacctq
    titleBuilder :: Builder
titleBuilder | AccountName -> Bool
T.null AccountName
title = Builder
forall a. Monoid a => a
mempty
                 | Bool
otherwise    = AccountName -> Builder
TB.fromText AccountName
title Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Char -> Builder
TB.singleton Char
'\n'

-- | The heading for an account transactions report: a description of the
-- account shown, or --title's value if that was provided (possibly empty).
-- Also empty when --heading=no.
accountTransactionsReportTitle :: CliOpts -> Query -> Query -> Text
accountTransactionsReportTitle :: CliOpts -> Query -> Query -> AccountName
accountTransactionsReportTitle CliOpts
copts Query
reportq Query
thisacctq
  | Bool -> Bool
not (CliOpts -> Bool
headingopt CliOpts
copts) = AccountName
""
  | Bool
otherwise = ReportOpts -> AccountName -> AccountName
effectiveTitle (ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
copts) AccountName
defaultTitle
  where
    -- show a heading indicating which account was picked, which can be confusing otherwise
    defaultTitle :: AccountName
defaultTitle = AccountName
-> (AccountName -> AccountName) -> Maybe AccountName -> AccountName
forall b a. b -> (a -> b) -> Maybe a -> b
maybe AccountName
"" (\AccountName
s -> [AccountName] -> AccountName
T.concat [AccountName
"Transactions in ", AccountName
s, AccountName
" and subaccounts", AccountName
qmsg, AccountName
":"]) Maybe AccountName
macct
      where
        -- XXX temporary hack ? recover the account name from the query
        macct :: Maybe AccountName
macct = case (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsAcct Query
thisacctq of
                  Acct Regexp
r -> AccountName -> Maybe AccountName
forall a. a -> Maybe a
Just (AccountName -> Maybe AccountName)
-> (AccountName -> AccountName) -> AccountName -> Maybe AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> AccountName -> AccountName
T.drop Int
1 (AccountName -> AccountName)
-> (AccountName -> AccountName) -> AccountName -> AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> AccountName -> AccountName
T.dropEnd Int
5 (AccountName -> Maybe AccountName)
-> AccountName -> Maybe AccountName
forall a b. (a -> b) -> a -> b
$ Regexp -> AccountName
reString Regexp
r  -- Acct "^JS:expenses(:|$)"
                  Query
_      -> Maybe AccountName
forall a. Maybe a
Nothing  -- shouldn't happen
        -- show a hint in the title when results are restricted by an extra query (other than depth or date or date2)
        qmsg :: AccountName
qmsg = if Bool
hasextraquery then AccountName
" (matching query)" else AccountName
""
          where
            hasextraquery :: Bool
hasextraquery =
              [AccountName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (ReportOpts -> [AccountName]
querystring_ (ReportOpts -> [AccountName]) -> ReportOpts -> [AccountName]
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
copts) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
              Bool -> Bool -> Bool
&& Bool -> Bool
not (Query -> Bool
queryIsNull (Query -> Bool) -> Query -> Bool
forall a b. (a -> b) -> a -> b
$ (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
q->Query -> Bool
queryIsDepth Query
q Bool -> Bool -> Bool
|| Query -> Bool
queryIsDateOrDate2 Query
q)) Query
reportq)

headingopt :: CliOpts -> Bool
headingopt :: CliOpts -> Bool
headingopt = Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
True (Maybe Bool -> Bool) -> (CliOpts -> Maybe Bool) -> CliOpts -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> RawOpts -> Maybe Bool
maybeynopt String
"heading" (RawOpts -> Maybe Bool)
-> (CliOpts -> RawOpts) -> CliOpts -> Maybe Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CliOpts -> RawOpts
rawopts_

-- | Should the account column show the matched accounts (--matched) rather than
-- the other accounts in each transaction (-r/--related, the default) ?
-- The last of these flags wins.
matchedopt :: CliOpts -> Bool
matchedopt :: CliOpts -> Bool
matchedopt = Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
False (Maybe Bool -> Bool) -> (CliOpts -> Maybe Bool) -> CliOpts -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Maybe Bool) -> RawOpts -> Maybe Bool
forall a. (String -> Maybe a) -> RawOpts -> Maybe a
choiceopt String -> Maybe Bool
forall {a}. (Eq a, IsString a) => a -> Maybe Bool
parse (RawOpts -> Maybe Bool)
-> (CliOpts -> RawOpts) -> CliOpts -> Maybe Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CliOpts -> RawOpts
rawopts_
  where parse :: a -> Maybe Bool
parse a
s = a -> [(a, Bool)] -> Maybe Bool
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup a
s [(a
"matched", Bool
True), (a
"related", Bool
False)]

-- | The account names to show for an account register report item:
-- by default, the other accounts involved in the transaction;
-- with --matched, the accounts matched by the account query
-- (this account or its subaccounts), among the postings selected by any extra query.
itemAccountNames :: CliOpts -> Query -> AccountTransactionsReportItem -> [AccountName]
itemAccountNames :: CliOpts
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [AccountName]
itemAccountNames CliOpts
opts Query
thisacctq (Transaction
_, Transaction
tacct, Bool
_, [AccountName]
otheraccts, MixedAmount
_, MixedAmount
_)
  | CliOpts -> Bool
matchedopt CliOpts
opts = [AccountName] -> [AccountName]
forall a. Eq a => [a] -> [a]
nub ([AccountName] -> [AccountName])
-> ([Posting] -> [AccountName]) -> [Posting] -> [AccountName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> AccountName) -> [Posting] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> AccountName
paccount ([Posting] -> [AccountName])
-> ([Posting] -> [Posting]) -> [Posting] -> [AccountName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> Posting -> Bool
matchesPosting Query
thisacctq) ([Posting] -> [AccountName]) -> [Posting] -> [AccountName]
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
tacct
  | Bool
otherwise       = [AccountName] -> [AccountName]
forall a. Eq a => [a] -> [a]
nub [AccountName]
otheraccts

optional :: (Monoid p) => Bool -> p -> p
optional :: forall p. Monoid p => Bool -> p -> p
optional Bool
b p
x = if Bool
b then p
x else p
forall a. Monoid a => a
mempty


-- | Render one account register report line item as plain text. Layout is like so:
-- @
-- <---------------- width (specified, terminal width, or 80) -------------------->
-- date (10)  description           other accounts       amount (12)   balance (12)
-- DDDDDDDDDD dddddddddddddddddddd  aaaaaaaaaaaaaaaaaaa  AAAAAAAAAAAA  AAAAAAAAAAAA
-- @
-- If description's width is specified, account will use the remaining space.
-- Otherwise, description and account divide up the space equally.
--
-- Returns a string which can be multi-line, eg if the running balance
-- has multiple commodities.
--
accountTransactionsReportItemAsText :: CliOpts -> Query -> Query -> Int -> Int
                                    -> (AccountTransactionsReportItem, [WideBuilder], [WideBuilder])
                                    -> TB.Builder
accountTransactionsReportItemAsText :: CliOpts
-> Query
-> Query
-> Int
-> Int
-> ((Transaction, Transaction, Bool, [AccountName], MixedAmount,
     MixedAmount),
    [WideBuilder], [WideBuilder])
-> Builder
accountTransactionsReportItemAsText
  copts :: CliOpts
copts@CliOpts{reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts}}
  Query
reportq Query
thisacctq Int
preferredamtwidth Int
preferredbalwidth
  (item :: (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
item@(t :: Transaction
t@Transaction{AccountName
tdescription :: Transaction -> AccountName
tdescription :: AccountName
tdescription}, Transaction
_, Bool
_issplit, [AccountName]
_, MixedAmount
_, MixedAmount
_), [WideBuilder]
amt, [WideBuilder]
bal) =
    -- Transaction -- the transaction, unmodified
    -- Transaction -- the transaction, as seen from the current account
    -- Bool        -- is this a split (more than one posting to other accounts) ?
    -- [AccountName] -- the other account(s), if any
    -- MixedAmount -- the amount posted to the current account(s) (or total amount posted)
    -- MixedAmount -- the register's running total or the current account(s)'s historical balance, after this transaction
    Builder
table Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Char -> Builder
TB.singleton Char
'\n'
  where
    dropAcct :: AccountName -> AccountName
dropAcct = Int -> AccountName -> AccountName
accountNameDrop (Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 (Maybe Int -> Int) -> Maybe Int -> Int
forall a b. (a -> b) -> a -> b
$ String -> Maybe Int
forall a. Read a => String -> Maybe a
readMay (String -> Maybe Int) -> Maybe String -> Maybe Int
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< String -> RawOpts -> Maybe String
maybestringopt String
"drop" (CliOpts -> RawOpts
rawopts_ CliOpts
copts))
    table :: Builder
table = TableOpts -> Header Cell -> Builder
renderRowB TableOpts
forall a. Default a => a
def{tableBorders=False, borderSpaces=False} (Header Cell -> Builder)
-> ([Header Cell] -> Header Cell) -> [Header Cell] -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Properties -> [Header Cell] -> Header Cell
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Cell] -> Builder) -> [Header Cell] -> Builder
forall a b. (a -> b) -> a -> b
$ (Cell -> Header Cell) -> [Cell] -> [Header Cell]
forall a b. (a -> b) -> [a] -> [b]
map Cell -> Header Cell
forall h. h -> Header h
Header
      [ Align -> AccountName -> Cell
textCell Align
TopLeft (AccountName -> Cell) -> AccountName -> Cell
forall a b. (a -> b) -> a -> b
$ Maybe Int
-> Maybe Int -> Bool -> Bool -> AccountName -> AccountName
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
datewidth) (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
datewidth) Bool
True Bool
True AccountName
date
      , Cell
spacerCell
      , Align -> AccountName -> Cell
textCell Align
TopLeft (AccountName -> Cell) -> AccountName -> Cell
forall a b. (a -> b) -> a -> b
$ Maybe Int
-> Maybe Int -> Bool -> Bool -> AccountName -> AccountName
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
descwidth) (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
descwidth) Bool
True Bool
True AccountName
tdescription
      , Cell
spacerCell2
      , Align -> AccountName -> Cell
textCell Align
TopLeft (AccountName -> Cell) -> AccountName -> Cell
forall a b. (a -> b) -> a -> b
$ Maybe Int
-> Maybe Int -> Bool -> Bool -> AccountName -> AccountName
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
acctwidth) (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
acctwidth) Bool
True Bool
True AccountName
accts
      , Cell
spacerCell2
      , Align -> [WideBuilder] -> Cell
Cell Align
TopRight ([WideBuilder] -> Cell) -> [WideBuilder] -> Cell
forall a b. (a -> b) -> a -> b
$ (WideBuilder -> WideBuilder) -> [WideBuilder] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> WideBuilder -> WideBuilder
pad Int
amtwidth) [WideBuilder]
amt
      , Cell
spacerCell2
      , Align -> [WideBuilder] -> Cell
Cell Align
BottomRight ([WideBuilder] -> Cell) -> [WideBuilder] -> Cell
forall a b. (a -> b) -> a -> b
$ (WideBuilder -> WideBuilder) -> [WideBuilder] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> WideBuilder -> WideBuilder
pad Int
balwidth) [WideBuilder]
bal
      ]
    spacerCell :: Cell
spacerCell  = Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [Builder -> Int -> WideBuilder
WideBuilder (Char -> Builder
TB.singleton Char
' ') Int
1]
    spacerCell2 :: Cell
spacerCell2 = Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [Builder -> Int -> WideBuilder
WideBuilder (String -> Builder
TB.fromString String
"  ") Int
2]
    pad :: Int -> WideBuilder -> WideBuilder
pad Int
fullwidth WideBuilder
amt1 = Builder -> Int -> WideBuilder
WideBuilder (AccountName -> Builder
TB.fromText (AccountName -> Builder) -> AccountName -> Builder
forall a b. (a -> b) -> a -> b
$ Int -> AccountName -> AccountName
T.replicate Int
w AccountName
" ") Int
w WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> WideBuilder
amt1
      where w :: Int
w = Int
fullwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- WideBuilder -> Int
wbWidth WideBuilder
amt1
    -- calculate widths
    (Int
totalwidth,Maybe Int
mdescwidth) = CliOpts -> (Int, Maybe Int)
registerWidthsFromOpts CliOpts
copts
    (Int
datewidth, AccountName
date) = (Int
10, Day -> AccountName
showDate (Day -> AccountName) -> Day -> AccountName
forall a b. (a -> b) -> a -> b
$ WhichDate -> Query -> Query -> Transaction -> Day
transactionRegisterDate WhichDate
wd Query
reportq Query
thisacctq Transaction
t)
      where wd :: WhichDate
wd = ReportOpts -> WhichDate
whichDate ReportOpts
ropts
    (Int
amtwidth, Int
balwidth)
      | Int
shortfall Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = (Int
preferredamtwidth, Int
preferredbalwidth)
      | Bool
otherwise      = (Int
adjustedamtwidth, Int
adjustedbalwidth)
      where
        mincolwidth :: Int
mincolwidth = Int
2 -- columns always show at least an ellipsis
        maxamtswidth :: Int
maxamtswidth = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
totalwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- (Int
datewidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
mincolwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
mincolwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2))
        shortfall :: Int
shortfall = (Int
preferredamtwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
preferredbalwidth) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
maxamtswidth
        amtwidthproportion :: Double
amtwidthproportion = Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
preferredamtwidth Double -> Double -> Double
forall a. (Eq a, Fractional a) => a -> a -> a
`divideSafe` Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int
preferredamtwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
preferredbalwidth)
        adjustedamtwidth :: Int
adjustedamtwidth = Double -> Int
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
round (Double -> Int) -> Double -> Int
forall a b. (a -> b) -> a -> b
$ Double
amtwidthproportion Double -> Double -> Double
forall a. Num a => a -> a -> a
* Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
maxamtswidth
        adjustedbalwidth :: Int
adjustedbalwidth = Int
maxamtswidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
adjustedamtwidth

    remaining :: Int
remaining = Int
totalwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- (Int
datewidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
amtwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
balwidth)
    (Int
descwidth, Int
acctwidth) = (Int
w, Int
remaining Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
w)
      where w :: Int
w = Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe ((Int
remaining Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
2) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
2) Maybe Int
mdescwidth

    accts :: AccountName
accts = AccountName -> [AccountName] -> AccountName
T.intercalate AccountName
", " ([AccountName] -> AccountName)
-> ([AccountName] -> [AccountName]) -> [AccountName] -> AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AccountName -> AccountName) -> [AccountName] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> AccountName
dropAcct (AccountName -> AccountName)
-> (AccountName -> AccountName) -> AccountName -> AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName -> AccountName
accountSummarisedName) ([AccountName] -> AccountName) -> [AccountName] -> AccountName
forall a b. (a -> b) -> a -> b
$ CliOpts
-> Query
-> (Transaction, Transaction, Bool, [AccountName], MixedAmount,
    MixedAmount)
-> [AccountName]
itemAccountNames CliOpts
copts Query
thisacctq (Transaction, Transaction, Bool, [AccountName], MixedAmount,
 MixedAmount)
item

-- tests

tests_Aregister :: TestTree
tests_Aregister = String -> [TestTree] -> TestTree
testGroup String
"Aregister" [

 ]