| 1 |
{-| |
| 2 |
|
| 3 |
The @aregister@ command lists a single account's transactions, |
| 4 |
like the account register in hledger-ui and hledger-web, |
| 5 |
and unlike the register command which lists postings across multiple accounts. |
| 6 |
|
| 7 |
-} |
| 8 |
|
| 9 |
{-# LANGUAGE CPP #-} |
| 10 |
{-# LANGUAGE NamedFieldPuns #-} |
| 11 |
{-# LANGUAGE OverloadedStrings #-} |
| 12 |
{-# LANGUAGE RecordWildCards #-} |
| 13 |
{-# LANGUAGE TemplateHaskell #-} |
| 14 |
|
| 15 |
module Hledger.Cli.Commands.Aregister ( |
| 16 |
aregistermode |
| 17 |
,aregister |
| 18 |
-- ,showPostingWithBalanceForVty |
| 19 |
,tests_Aregister |
| 20 |
) where |
| 21 |
|
| 22 |
import Data.Default (def) |
| 23 |
import Data.List (find, nub) |
| 24 |
import Data.Maybe (fromMaybe) |
| 25 |
import Data.Text (Text) |
| 26 |
import Data.Foldable (for_) |
| 27 |
import Data.Map qualified as Map |
| 28 |
import Data.Text qualified as T |
| 29 |
import Data.Text.Lazy qualified as TL |
| 30 |
import Data.Text.Lazy.Builder qualified as TB |
| 31 |
import Control.Monad (when) |
| 32 |
import Lucid qualified as L hiding (Html) |
| 33 |
import Safe (readMay) |
| 34 |
import System.Console.CmdArgs.Explicit (flagNone, flagReq) |
| 35 |
import System.IO qualified as IO |
| 36 |
import Text.Tabular.AsciiWide hiding (render) |
| 37 |
|
| 38 |
import Hledger |
| 39 |
import Hledger.Cli.CliOptions |
| 40 |
import Hledger.Cli.Utils |
| 41 |
import Hledger.Write.Csv (CSV, printCSV, printTSV) |
| 42 |
import Hledger.Write.Html (formatRow, htmlAsLazyText, toHtml) |
| 43 |
import Hledger.Write.Ods (printFods) |
| 44 |
import Hledger.Write.Spreadsheet qualified as Spr |
| 45 |
|
| 46 |
aregistermode = hledgerCommandMode |
| 47 |
$(embedFileRelative "Hledger/Cli/Commands/Aregister.txt") |
| 48 |
([ |
| 49 |
flagNone ["txn-dates"] (setboolopt "txn-dates") |
| 50 |
"filter strictly by transaction date, not posting date. Warning: this can show a wrong running balance." |
| 51 |
,flagNone ["no-elide"] (setboolopt "no-elide") "don't show only 2 commodities per amount" |
| 52 |
,flagNone ["cumulative"] (setboolopt "cumulative") |
| 53 |
(accumprefix ++ "show running total from report start date") |
| 54 |
,flagNone ["historical","H"] (setboolopt "historical") |
| 55 |
(accumprefix ++ "show historical running total/balance (includes postings before report start date) (default)") |
| 56 |
-- ,flagNone ["average","A"] (setboolopt "average") |
| 57 |
-- "show running average of posting amounts instead of total (implies --empty)" |
| 58 |
-- ,flagNone ["related","r"] (setboolopt "related") "show postings' siblings instead" |
| 59 |
,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign" |
| 60 |
,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "omit N leading account name parts" |
| 61 |
,flagReq ["heading"] (\s opts -> Right $ setopt "heading" s opts) "YN" |
| 62 |
"show heading row above table: yes (default) or no" |
| 63 |
,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N" |
| 64 |
("set output width (default: " ++ |
| 65 |
#ifdef mingw32_HOST_OS |
| 66 |
show defaultWidth |
| 67 |
#else |
| 68 |
"terminal width" |
| 69 |
#endif |
| 70 |
++ "). -wN,M sets description width as well." |
| 71 |
) |
| 72 |
,flagNone ["align-all"] (setboolopt "align-all") "guarantee alignment across all lines (slower)" |
| 73 |
,outputFormatFlag ["txt","html","csv","tsv","json"] |
| 74 |
,outputFileFlag |
| 75 |
]) |
| 76 |
cligeneralflagsgroups1 |
| 77 |
hiddenflags |
| 78 |
([], Just $ argsFlag "ACCTPAT [QUERY]") |
| 79 |
where |
| 80 |
accumprefix = "accumulation mode: " |
| 81 |
|
| 82 |
-- based on Hledger.UI.RegisterScreen: |
| 83 |
|
| 84 |
-- | Print an account register report for a specified account. |
| 85 |
aregister :: CliOpts -> Journal -> IO () |
| 86 |
aregister opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do |
| 87 |
-- the first argument specifies the account, any remaining arguments are a filter query |
| 88 |
let help = "aregister needs an ACCTPAT argument to select an account" |
| 89 |
(apat,querystr) <- case listofstringopt "args" rawopts of |
| 90 |
[] -> error' $ help <> ".\nPlease provide an account name or a (case-insensitive, infix, regexp) pattern." |
| 91 |
(a:as) -> return (a, map T.pack as) |
| 92 |
let |
| 93 |
-- keep synced with findMatchedByArgument's matching |
| 94 |
acct = fromMaybe (error' $ help <> ", but " ++ show apat++" did not match any account.") -- PARTIAL: |
| 95 |
. firstMatch $ journalAccountNamesDeclaredOrImplied j |
| 96 |
firstMatch = case toRegexCI $ T.pack apat of |
| 97 |
Right re -> find (regexMatchText re) |
| 98 |
Left _ -> const Nothing |
| 99 |
-- gather report options |
| 100 |
inclusive = True -- tree_ ropts |
| 101 |
thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) acct |
| 102 |
ropts' = (_rsReportOpts rspec) { |
| 103 |
-- ignore any depth limit, as in postingsReport; allows register's total to match balance reports (cf #1468) |
| 104 |
depth_=DepthSpec Nothing [] |
| 105 |
, balanceaccum_ = |
| 106 |
case balanceaccum_ $ _rsReportOpts rspec of |
| 107 |
PerPeriod -> Historical |
| 108 |
ba -> ba |
| 109 |
, querystring_ = querystr |
| 110 |
} |
| 111 |
wd = whichDate ropts' |
| 112 |
-- and regenerate the ReportSpec, making sure to use the above |
| 113 |
rspec' <- either fail return $ updateReportSpec ropts' rspec |
| 114 |
let |
| 115 |
-- run the report |
| 116 |
-- TODO: need to also pass the queries so we can choose which date to render - move them into the report ? |
| 117 |
items = accountTransactionsReport rspec' j thisacctq |
| 118 |
items' = |
| 119 |
styleAmounts (journalCommodityStylesWith HardRounding j) $ |
| 120 |
(if empty_ ropts' then id else filter (not . mixedAmountLooksZero . fifth6)) $ |
| 121 |
reverse items |
| 122 |
-- select renderer |
| 123 |
render | fmt=="txt" = accountTransactionsReportAsText opts (_rsQuery rspec') thisacctq |
| 124 |
| fmt=="html" = accountTransactionsReportAsHTML opts (_rsQuery rspec') thisacctq |
| 125 |
| fmt=="csv" = printCSV . accountTransactionsReportAsCsv opts hd wd (_rsQuery rspec') thisacctq |
| 126 |
| fmt=="tsv" = printTSV . accountTransactionsReportAsCsv opts hd wd (_rsQuery rspec') thisacctq |
| 127 |
| fmt=="fods" = |
| 128 |
printFods IO.localeEncoding . Map.singleton "Aregister" . |
| 129 |
(,) (1,0) . |
| 130 |
accountTransactionsReportAsSpreadsheet opts oneLineNoCostFmt hd wd (_rsQuery rspec') thisacctq |
| 131 |
| fmt=="json" = toJsonText |
| 132 |
| otherwise = error' $ unsupportedOutputFormatError fmt -- PARTIAL: |
| 133 |
where |
| 134 |
hd = headingopt opts |
| 135 |
fmt = outputFormatFromOpts opts |
| 136 |
|
| 137 |
writeOutputLazyText opts $ render items' |
| 138 |
|
| 139 |
accountTransactionsReportAsCsv :: |
| 140 |
CliOpts -> Bool -> WhichDate -> Query -> Query -> AccountTransactionsReport -> CSV |
| 141 |
accountTransactionsReportAsCsv opts hd wd reportq thisacctq = |
| 142 |
Spr.rawTableContent . |
| 143 |
accountTransactionsReportAsSpreadsheet opts machineFmt hd wd reportq thisacctq |
| 144 |
|
| 145 |
accountTransactionsReportAsSpreadsheet :: |
| 146 |
CliOpts -> AmountFormat -> Bool -> |
| 147 |
WhichDate -> Query -> Query -> AccountTransactionsReport -> |
| 148 |
[[Spr.Cell Spr.NumLines Text]] |
| 149 |
accountTransactionsReportAsSpreadsheet opts fmt hd wd reportq thisacctq is = |
| 150 |
optional hd |
| 151 |
[Spr.addHeaderBorders $ map Spr.headerCell $ |
| 152 |
["txnidx","date","code","description","otheraccounts","change","balance"]] |
| 153 |
++ |
| 154 |
map (accountTransactionsReportItemAsRecord opts fmt True wd reportq thisacctq) is |
| 155 |
|
| 156 |
accountTransactionsReportItemAsRecord :: |
| 157 |
CliOpts -> AmountFormat -> Bool -> |
| 158 |
WhichDate -> Query -> Query -> AccountTransactionsReportItem -> |
| 159 |
[Spr.Cell Spr.NumLines Text] |
| 160 |
accountTransactionsReportItemAsRecord |
| 161 |
opts fmt internals wd reportq thisacctq |
| 162 |
(t@Transaction{tindex,tcode,tdescription}, _, _issplit, otheraccts, change, balance) |
| 163 |
= (optional internals [Spr.integerCell tindex]) ++ |
| 164 |
date : |
| 165 |
(optional internals [cell tcode]) ++ |
| 166 |
[cell tdescription, |
| 167 |
cell $ T.intercalate ", " $ map dropAcct $ nub otheraccts, |
| 168 |
amountCell change, |
| 169 |
amountCell balance] |
| 170 |
where |
| 171 |
dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ opts)) |
| 172 |
cell = Spr.defaultCell |
| 173 |
date = |
| 174 |
(Spr.defaultCell $ showDate $ |
| 175 |
transactionRegisterDate wd reportq thisacctq t) |
| 176 |
{Spr.cellType = Spr.TypeDate} |
| 177 |
amountCell amt = |
| 178 |
wbToText <$> Spr.cellFromMixedAmount fmt (Spr.Class "amount", amt) |
| 179 |
|
| 180 |
-- | Render a register report as a HTML snippet. |
| 181 |
accountTransactionsReportAsHTML :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text |
| 182 |
accountTransactionsReportAsHTML copts reportq thisacctq items = |
| 183 |
htmlAsLazyText $ do |
| 184 |
L.link_ [L.rel_ "stylesheet", L.href_ "hledger.css"] |
| 185 |
L.table_ $ do |
| 186 |
when (headingopt copts) $ L.thead_ $ L.tr_ $ do |
| 187 |
L.th_ "date" |
| 188 |
L.th_ "description" |
| 189 |
L.th_ "otheraccounts" |
| 190 |
L.th_ "change" |
| 191 |
L.th_ "balance" |
| 192 |
L.tbody_ $ for_ items $ |
| 193 |
formatRow . map (fmap toHtml) . |
| 194 |
accountTransactionsReportItemAsRecord copts |
| 195 |
oneLineNoCostFmt False |
| 196 |
(whichDate $ _rsReportOpts $ reportspec_ copts) |
| 197 |
reportq thisacctq |
| 198 |
|
| 199 |
-- | Render a register report as plain text suitable for console output. |
| 200 |
accountTransactionsReportAsText :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text |
| 201 |
accountTransactionsReportAsText copts reportq thisacctq items = TB.toLazyText $ |
| 202 |
(optional (headingopt copts) $ title <> TB.singleton '\n') |
| 203 |
<> |
| 204 |
postingsOrTransactionsReportAsText alignAll copts itemAsText itemamt itembal items |
| 205 |
where |
| 206 |
alignAll = boolopt "align-all" $ rawopts_ copts |
| 207 |
itemAsText = accountTransactionsReportItemAsText copts reportq thisacctq |
| 208 |
itemamt (_,_,_,_,a,_) = a |
| 209 |
itembal (_,_,_,_,_,a) = a |
| 210 |
|
| 211 |
-- show a title indicating which account was picked, which can be confusing otherwise |
| 212 |
title = maybe mempty (\s -> foldMap TB.fromText ["Transactions in ", s, " and subaccounts", qmsg, ":"]) macct |
| 213 |
where |
| 214 |
-- XXX temporary hack ? recover the account name from the query |
| 215 |
macct = case filterQuery queryIsAcct thisacctq of |
| 216 |
Acct r -> Just . T.drop 1 . T.dropEnd 5 $ reString r -- Acct "^JS:expenses(:|$)" |
| 217 |
_ -> Nothing -- shouldn't happen |
| 218 |
-- show a hint in the title when results are restricted by an extra query (other than depth or date or date2) |
| 219 |
qmsg = if hasextraquery then " (matching query)" else "" |
| 220 |
where |
| 221 |
hasextraquery = |
| 222 |
length (querystring_ $ _rsReportOpts $ reportspec_ copts) > 1 |
| 223 |
&& not (queryIsNull $ filterQuery (not.(\q->queryIsDepth q || queryIsDateOrDate2 q)) reportq) |
| 224 |
|
| 225 |
headingopt :: CliOpts -> Bool |
| 226 |
headingopt = fromMaybe True . maybeynopt "heading" . rawopts_ |
| 227 |
|
| 228 |
optional :: (Monoid p) => Bool -> p -> p |
| 229 |
optional b x = if b then x else mempty |
| 230 |
|
| 231 |
|
| 232 |
-- | Render one account register report line item as plain text. Layout is like so: |
| 233 |
-- @ |
| 234 |
-- <---------------- width (specified, terminal width, or 80) --------------------> |
| 235 |
-- date (10) description other accounts change (12) balance (12) |
| 236 |
-- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA |
| 237 |
-- @ |
| 238 |
-- If description's width is specified, account will use the remaining space. |
| 239 |
-- Otherwise, description and account divide up the space equally. |
| 240 |
-- |
| 241 |
-- Returns a string which can be multi-line, eg if the running balance |
| 242 |
-- has multiple commodities. |
| 243 |
-- |
| 244 |
accountTransactionsReportItemAsText :: CliOpts -> Query -> Query -> Int -> Int |
| 245 |
-> (AccountTransactionsReportItem, [WideBuilder], [WideBuilder]) |
| 246 |
-> TB.Builder |
| 247 |
accountTransactionsReportItemAsText |
| 248 |
copts@CliOpts{reportspec_=ReportSpec{_rsReportOpts=ropts}} |
| 249 |
reportq thisacctq preferredamtwidth preferredbalwidth |
| 250 |
((t@Transaction{tdescription}, _, _issplit, otheraccts, _, _), amt, bal) = |
| 251 |
-- Transaction -- the transaction, unmodified |
| 252 |
-- Transaction -- the transaction, as seen from the current account |
| 253 |
-- Bool -- is this a split (more than one posting to other accounts) ? |
| 254 |
-- [AccountName] -- the other account(s), if any |
| 255 |
-- MixedAmount -- the amount posted to the current account(s) (or total amount posted) |
| 256 |
-- MixedAmount -- the register's running total or the current account(s)'s historical balance, after this transaction |
| 257 |
table <> TB.singleton '\n' |
| 258 |
where |
| 259 |
dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ copts)) |
| 260 |
table = renderRowB def{tableBorders=False, borderSpaces=False} . Group NoLine $ map Header |
| 261 |
[ textCell TopLeft $ fitText (Just datewidth) (Just datewidth) True True date |
| 262 |
, spacerCell |
| 263 |
, textCell TopLeft $ fitText (Just descwidth) (Just descwidth) True True tdescription |
| 264 |
, spacerCell2 |
| 265 |
, textCell TopLeft $ fitText (Just acctwidth) (Just acctwidth) True True accts |
| 266 |
, spacerCell2 |
| 267 |
, Cell TopRight $ map (pad amtwidth) amt |
| 268 |
, spacerCell2 |
| 269 |
, Cell BottomRight $ map (pad balwidth) bal |
| 270 |
] |
| 271 |
spacerCell = Cell BottomLeft [WideBuilder (TB.singleton ' ') 1] |
| 272 |
spacerCell2 = Cell BottomLeft [WideBuilder (TB.fromString " ") 2] |
| 273 |
pad fullwidth amt1 = WideBuilder (TB.fromText $ T.replicate w " ") w <> amt1 |
| 274 |
where w = fullwidth - wbWidth amt1 |
| 275 |
-- calculate widths |
| 276 |
(totalwidth,mdescwidth) = registerWidthsFromOpts copts |
| 277 |
(datewidth, date) = (10, showDate $ transactionRegisterDate wd reportq thisacctq t) |
| 278 |
where wd = whichDate ropts |
| 279 |
(amtwidth, balwidth) |
| 280 |
| shortfall <= 0 = (preferredamtwidth, preferredbalwidth) |
| 281 |
| otherwise = (adjustedamtwidth, adjustedbalwidth) |
| 282 |
where |
| 283 |
mincolwidth = 2 -- columns always show at least an ellipsis |
| 284 |
maxamtswidth = max 0 (totalwidth - (datewidth + 1 + mincolwidth + 2 + mincolwidth + 2 + 2)) |
| 285 |
shortfall = (preferredamtwidth + preferredbalwidth) - maxamtswidth |
| 286 |
amtwidthproportion = fromIntegral preferredamtwidth `divideSafe` fromIntegral (preferredamtwidth + preferredbalwidth) |
| 287 |
adjustedamtwidth = round $ amtwidthproportion * fromIntegral maxamtswidth |
| 288 |
adjustedbalwidth = maxamtswidth - adjustedamtwidth |
| 289 |
|
| 290 |
remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth) |
| 291 |
(descwidth, acctwidth) = (w, remaining - 2 - w) |
| 292 |
where w = fromMaybe ((remaining - 2) `div` 2) mdescwidth |
| 293 |
|
| 294 |
accts = T.intercalate ", " . map (dropAcct . accountSummarisedName) $ nub otheraccts |
| 295 |
|
| 296 |
-- tests |
| 297 |
|
| 298 |
tests_Aregister = testGroup "Aregister" [ |
| 299 |
|
| 300 |
] |