Debian Codegraph @

Hledger/Cli/Commands/Balance.hs

raw
1 {-|
2
3 A ledger-compatible @balance@ command, with additional support for
4 multi-column reports.
5
6 Here is a description/specification for the balance command. See also
7 "Hledger.Reports" -> \"Balance reports\".
8
9
10 /Basic balance report/
11
12 With no report interval (@--monthly@ etc.), hledger's balance
13 command emulates ledger's, showing accounts indented according to
14 hierarchy, along with their total amount posted (including subaccounts).
15
16 Here's an example. With @examples/sample.journal@, which defines the following account tree:
17
18 @
19 assets
20 bank
21 checking
22 saving
23 cash
24 expenses
25 food
26 supplies
27 income
28 gifts
29 salary
30 liabilities
31 debts
32 @
33
34 the basic @balance@ command gives this output:
35
36 @
37 $ hledger -f sample.journal balance
38 $-1 assets
39 $1 bank:saving
40 $-2 cash
41 $2 expenses
42 $1 food
43 $1 supplies
44 $-2 income
45 $-1 gifts
46 $-1 salary
47 $1 liabilities:debts
48 --------------------
49 0
50 @
51
52 Subaccounts are displayed indented below their parent. Only the account leaf name (the final part) is shown.
53 (With @--flat@, account names are shown in full and unindented.)
54
55 Each account's \"balance\" is the sum of postings in that account and any subaccounts during the report period.
56 When the report period includes all transactions, this is equivalent to the account's current balance.
57
58 The overall total of the highest-level displayed accounts is shown below the line.
59 (The @--no-total/-N@ flag prevents this.)
60
61 /Eliding and omitting/
62
63 Accounts which have a zero balance, and no non-zero subaccount
64 balances, are normally omitted from the report.
65 (The @--empty/-E@ flag forces such accounts to be displayed.)
66 Eg, above @checking@ is omitted because it has a zero balance and no subaccounts.
67
68 Accounts which have a single subaccount also being displayed, with the same balance,
69 are normally elided into the subaccount's line.
70 (The @--no-elide@ flag prevents this.)
71 Eg, above @bank@ is elided to @bank:saving@ because it has only a
72 single displayed subaccount (@saving@) and their balance is the same
73 ($1). Similarly, @liabilities@ is elided to @liabilities:debts@.
74
75 /Date limiting/
76
77 The default report period is that of the whole journal, including all
78 known transactions. The @--begin\/-b@, @--end\/-e@, @--period\/-p@
79 options or @date:@/@date2:@ patterns can be used to report only
80 on transactions before and/or after specified dates.
81
82 /Depth limiting/
83
84 The @--depth@ option can be used to limit the depth of the balance report.
85 Eg, to see just the top level accounts (still including their subaccount balances):
86
87 @
88 $ hledger -f sample.journal balance --depth 1
89 $-1 assets
90 $2 expenses
91 $-2 income
92 $1 liabilities
93 --------------------
94 0
95 @
96
97 /Account limiting/
98
99 With one or more account pattern arguments, the report is restricted
100 to accounts whose name matches one of the patterns, plus their parents
101 and subaccounts. Eg, adding the pattern @o@ to the first example gives:
102
103 @
104 $ hledger -f sample.journal balance o
105 $1 expenses:food
106 $-2 income
107 $-1 gifts
108 $-1 salary
109 --------------------
110 $-1
111 @
112
113 * The @o@ pattern matched @food@ and @income@, so they are shown.
114
115 * @food@'s parent (@expenses@) is shown even though the pattern didn't
116 match it, to clarify the hierarchy. The usual eliding rules cause it to be elided here.
117
118 * @income@'s subaccounts are also shown.
119
120 /Multi-column balance report/
121
122 hledger's balance command will show multiple columns when a reporting
123 interval is specified (eg with @--monthly@), one column for each sub-period.
124
125 There are three accumulation strategies for multi-column balance report, indicated by
126 the heading:
127
128 * A \"period balance\" (or \"flow\") report (with @--change@, the default) shows the
129 change of account balance in each period, which is equivalent to the sum of postings
130 in each period. Here, checking's balance increased by 10 in Feb:
131
132 > Change of balance (flow):
133 >
134 > Jan Feb Mar
135 > assets:checking 20 10 -5
136
137 * A \"cumulative balance\" report (with @--cumulative@) shows the accumulated ending balance
138 across periods, starting from zero at the report's start date.
139 Here, 30 is the sum of checking postings during Jan and Feb:
140
141 > Ending balance (cumulative):
142 >
143 > Jan Feb Mar
144 > assets:checking 20 30 25
145
146 * A \"historical balance\" report (with @--historical/-H@) also shows ending balances,
147 but it includes the starting balance from any postings before the report start date.
148 Here, 130 is the balance from all checking postings at the end of Feb, including
149 pre-Jan postings which created a starting balance of 100:
150
151 > Ending balance (historical):
152 >
153 > Jan Feb Mar
154 > assets:checking 120 130 125
155
156 /Eliding and omitting, 2/
157
158 Here's a (imperfect?) specification for the eliding/omitting behaviour:
159
160 * Each account is normally displayed on its own line.
161
162 * An account less deep than the report's max depth, with just one
163 interesting subaccount, and the same balance as the subaccount, is
164 non-interesting, and prefixed to the subaccount's line, unless
165 @--no-elide@ is in effect.
166
167 * An account with a zero inclusive balance and less than two interesting
168 subaccounts is not displayed at all, unless @--empty@ is in effect.
169
170 * Multi-column balance reports show full account names with no eliding
171 (like @--flat@). Accounts (and periods) are omitted as described below.
172
173 /Which accounts to show in balance reports/
174
175 By default:
176
177 * single-column: accounts with non-zero balance in report period.
178 (With @--flat@: accounts with non-zero balance and postings.)
179
180 * change: accounts with postings and non-zero period balance in any period
181
182 * cumulative: accounts with non-zero cumulative balance in any period
183
184 * historical: accounts with non-zero historical balance in any period
185
186 With @-E/--empty@:
187
188 * single-column: accounts with postings in report period
189
190 * change: accounts with postings in report period
191
192 * cumulative: accounts with postings in report period
193
194 * historical: accounts with non-zero starting balance +
195 accounts with postings in report period
196
197 /Which periods (columns) to show in balance reports/
198
199 An empty period/column is one where no report account has any postings.
200 A zero period/column is one where no report account has a non-zero period balance.
201
202 Currently,
203
204 by default:
205
206 * single-column: N/A
207
208 * change: all periods within the overall report period,
209 except for leading and trailing empty periods
210
211 * cumulative: all periods within the overall report period,
212 except for leading and trailing empty periods
213
214 * historical: all periods within the overall report period,
215 except for leading and trailing empty periods
216
217 With @-E/--empty@:
218
219 * single-column: N/A
220
221 * change: all periods within the overall report period
222
223 * cumulative: all periods within the overall report period
224
225 * historical: all periods within the overall report period
226
227 /What to show in empty cells/
228
229 An empty periodic balance report cell is one which has no corresponding postings.
230 An empty cumulative/historical balance report cell is one which has no corresponding
231 or prior postings, ie the account doesn't exist yet.
232 Currently, empty cells show 0.
233
234 -}
235
236 {-# LANGUAGE CPP #-}
237 {-# LANGUAGE OverloadedStrings #-}
238 {-# LANGUAGE NamedFieldPuns #-}
239 {-# LANGUAGE RecordWildCards #-}
240 {-# LANGUAGE ScopedTypeVariables #-}
241 {-# LANGUAGE TemplateHaskell #-}
242
243 module Hledger.Cli.Commands.Balance (
244 -- ** balance command
245 balancemode
246 ,balance
247 -- ** balance output rendering
248 ,balanceReportAsText
249 ,balanceReportAsCsv
250 ,balanceReportAsSpreadsheet
251 ,balanceReportItemAsText
252 ,budgetReportAsText
253 ,budgetReportAsCsv
254 ,budgetReportAsSpreadsheet
255 ,multiBalanceRowAsCellBuilders
256 ,multiBalanceRowAsCsvText
257 ,multiBalanceRowAsText
258 ,multiBalanceReportAsText
259 ,multiBalanceReportAsCsv
260 ,multiBalanceReportAsHtml
261 ,multiBalanceReportAsTable
262 ,multiBalanceReportTableAsText
263 ,multiBalanceReportAsSpreadsheet
264 ,multiBalanceReportAsSpreadsheetParts
265 ,multiBalanceHasTotalsColumn
266 ,addTotalBorders
267 ,simpleDateSpanCell
268 ,tidyColumnLabels
269 ,nbsp
270 ,RowClass(..)
271 -- ** Tests
272 ,tests_Balance
273 ) where
274
275 import Control.Arrow (second, (***))
276 import Control.Monad (guard)
277 import Data.Decimal (roundTo)
278 import Data.Default (def)
279 import Data.Function (on)
280 import Data.List (find, transpose)
281 #if !MIN_VERSION_base(4,20,0)
282 import Data.List (foldl')
283 #endif
284 import Data.Map qualified as Map
285 import Data.Set qualified as S
286 import Data.Maybe (mapMaybe, fromMaybe)
287 import Data.Tuple (swap)
288 import Data.Text (Text)
289 import Data.Text qualified as T
290 import Data.Text.Lazy qualified as TL
291 import Data.Text.Lazy.Builder qualified as TB
292 import Data.Time (addDays, fromGregorian)
293 import System.Console.CmdArgs.Explicit as C (flagNone, flagReq, flagOpt)
294 import Safe (headMay, maximumMay)
295 import Text.Tabular.AsciiWide
296 (Header(..), Align(..), Properties(..), Cell(..), Table(..), TableOpts(..),
297 cellWidth, concatTables, renderColumns, renderRowB, renderTableByRowsB, textCell)
298
299 import System.IO qualified as IO
300
301 import Hledger
302 import Hledger.Cli.CliOptions
303 import Hledger.Cli.Utils
304 import Hledger.Cli.Anchor (setAccountAnchor, dateSpanCell, headerDateSpanCell)
305 import Hledger.Write.Csv (CSV, printCSV, printTSV)
306 import Hledger.Write.Ods (printFods)
307 import Hledger.Write.Html (Html, styledTableHtml, htmlAsLazyText, toHtml)
308 import Hledger.Write.Spreadsheet (rawTableContent, headerCell,
309 addHeaderBorders, addRowSpanHeader,
310 cellFromMixedAmount, cellsFromMixedAmount)
311 import Hledger.Write.Spreadsheet qualified as Ods
312
313
314 -- | Command line options for this command.
315 balancemode = hledgerCommandMode
316 $(embedFileRelative "Hledger/Cli/Commands/Balance.txt")
317 (
318 -- https://hledger.org/dev/hledger.html#calculation-mode :
319 [flagNone ["sum"] (setboolopt "sum")
320 (calcprefix ++ "show sum of posting amounts (default)")
321 ,flagNone ["valuechange"] (setboolopt "valuechange")
322 (calcprefix ++ "show total change of value of period-end historical balances (caused by deposits, withdrawals, market price fluctuations)")
323 ,flagNone ["gain"] (setboolopt "gain")
324 (calcprefix ++ "show unrealised capital gain/loss (historical balance value minus cost basis)")
325 -- XXX --budget[=DESCPAT], --forecast[=PERIODEXP], could be more consistent
326 ,flagOpt "" ["budget"] (\s opts -> Right $ setopt "budget" s opts) "DESCPAT"
327 (unlines
328 [ calcprefix ++ "show sum of posting amounts together with budget goals defined by periodic"
329 , "transactions. With a DESCPAT argument (must be separated by = not space),"
330 , "use only periodic transactions with matching description"
331 , "(case insensitive substring match)."
332 ])
333 ,flagNone ["count"] (setboolopt "count")
334 (calcprefix ++ "show the count of postings")
335
336 -- https://hledger.org/dev/hledger.html#accumulation-mode :
337 ,flagNone ["change"] (setboolopt "change")
338 (accumprefix ++ "accumulate amounts from column start to column end (in multicolumn reports, default)")
339 ,flagNone ["cumulative"] (setboolopt "cumulative")
340 (accumprefix ++ "accumulate amounts from report start (specified by e.g. -b/--begin) to column end")
341 ,flagNone ["historical","H"] (setboolopt "historical")
342 (accumprefix ++ "accumulate amounts from journal start to column end (includes postings before report start date)")
343 ]
344
345 -- other options specific to this command:
346 ++ flattreeflags True ++
347 [flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "in list mode, omit N leading account name parts"
348 ,flagNone ["declared"] (setboolopt "declared") "include non-parent declared accounts (best used with -E)"
349 ,flagNone ["average","A"] (setboolopt "average") "show a row average column (in multicolumn reports)"
350 ,flagNone ["row-total","T"] (setboolopt "row-total") "show a row total column (in multicolumn reports)"
351 ,flagNone ["summary-only"] (setboolopt "summary-only") "display only row summaries (e.g. row total, average) (in multicolumn reports)"
352 ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"
353 ,flagNone ["no-elide"] (setboolopt "no-elide") "in tree mode, don't squash boring parent accounts"
354 ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format (in simple reports)"
355 ,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by amount instead of account code/name (in flat mode). With multiple columns, sorts by the row total, or by row average if that is displayed."
356 ,flagNone ["percent", "%"] (setboolopt "percent") "express values in percentage of each column's total"
357 ,flagNone ["related","r"] (setboolopt "related") "show the other accounts transacted with, instead"
358 ,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign"
359 ,flagNone ["transpose"] (setboolopt "transpose") "switch rows and columns (use vertical time axis)"
360 ,flagReq ["layout"] (\s opts -> Right $ setopt "layout" s opts) "ARG"
361 (unlines
362 ["how to lay out multi-commodity amounts and the overall table:"
363 ,"'wide[,W]': commodities on same line, up to W wide"
364 ,"'tall' : commodities on separate lines"
365 ,"'bare' : commodity symbols in a separate column"
366 ,"'tidy' : each data field in its own column"
367 ])
368 ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "URLPREFIX" "in html output, generate links to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"
369
370 -- output:
371 ,outputFormatFlag ["txt","html","csv","tsv","json","fods"]
372 ,outputFileFlag
373
374 ]
375 )
376 cligeneralflagsgroups1
377 (hiddenflags ++
378 [ flagNone ["commodity-column"] (setboolopt "commodity-column")
379 "show commodity symbols in a separate column, amounts as bare numbers, one row per commodity"
380 ])
381 ([], Just $ argsFlag "[QUERY]")
382
383 where
384 calcprefix = "calculation mode: "
385 accumprefix = "accumulation mode: "
386
387 -- | The balance command, prints a balance report.
388 balance :: CliOpts -> Journal -> IO ()
389 balance opts@CliOpts{reportspec_=rspec} j = case balancecalc_ ropts of
390 CalcBudget -> do -- single or multi period budget report
391 let rspan = fst $ reportSpan j rspec
392 budgetreport = styleAmounts styles $ budgetReport rspec (balancingopts_ $ inputopts_ opts) rspan j
393 render = case fmt of
394 "txt" -> budgetReportAsText ropts
395 "json" -> (<>"\n") . toJsonText
396 "csv" -> printCSV . budgetReportAsCsv ropts
397 "tsv" -> printTSV . budgetReportAsCsv ropts
398 "html" -> (<>"\n") . htmlAsLazyText .
399 styledTableHtml . map (map (fmap toHtml)) . budgetReportAsSpreadsheet oneLineNoCostFmt ropts
400 "fods" -> printFods IO.localeEncoding .
401 Map.singleton "Budget Report" . (,) (1,0) . budgetReportAsSpreadsheet oneLineNoCostFmt ropts
402 _ -> error' $ unsupportedOutputFormatError fmt
403 writeOutputLazyText opts $ render budgetreport
404
405 _ | multiperiod -> do -- multi period balance report
406 let report = styleAmounts styles $ multiBalanceReport rspec j
407 render = case fmt of
408 "txt" -> multiBalanceReportAsText ropts
409 "csv" -> printCSV . multiBalanceReportAsCsv ropts
410 "tsv" -> printTSV . multiBalanceReportAsCsv ropts
411 "html" -> (<>"\n") . htmlAsLazyText . multiBalanceReportAsHtml ropts
412 "json" -> (<>"\n") . toJsonText
413 "fods" -> printFods IO.localeEncoding .
414 Map.singleton "Multi-period Balance Report" . multiBalanceReportAsSpreadsheet ropts
415 _ -> const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:
416 writeOutputLazyText opts $ render report
417
418 _ -> do -- single period simple balance report
419 let report = styleAmounts styles $ balanceReport rspec j -- simple Ledger-style balance report
420 render = case fmt of
421 "txt" -> TB.toLazyText . balanceReportAsText ropts
422 "csv" -> printCSV . balanceReportAsCsv ropts
423 "tsv" -> printTSV . balanceReportAsCsv ropts
424 "html" -> (<>"\n") . htmlAsLazyText .
425 styledTableHtml . map (map (fmap toHtml)) . balanceReportAsSpreadsheet ropts
426 "json" -> (<>"\n") . toJsonText
427 "fods" -> printFods IO.localeEncoding . Map.singleton "Balance Report" . (,) (1,0) . balanceReportAsSpreadsheet ropts
428 _ -> error' $ unsupportedOutputFormatError fmt -- PARTIAL:
429 writeOutputLazyText opts $ render report
430 where
431 styles = journalCommodityStylesWith HardRounding j
432 ropts =
433 let ropts0 = _rsReportOpts rspec in
434 ropts0 {
435 -- tidy csv is defined externally and must not include totals or averages
436 no_total_ = no_total_ ropts0 || layout_ ropts0 == LayoutTidy
437 }
438 -- Tidy csv/tsv should be consistent between single period and multiperiod reports.
439 multiperiod = interval_ ropts /= NoInterval || (layout_ ropts == LayoutTidy && delimited)
440 delimited = fmt == "csv" || fmt == "tsv"
441 fmt = outputFormatFromOpts opts
442
443 -- Rendering
444
445 data RowClass = Value | Total
446 deriving (Eq, Ord, Enum, Bounded, Show)
447
448 amountClass :: RowClass -> Ods.Class
449 amountClass rc =
450 Ods.Class $
451 case rc of Value -> "amount"; Total -> "amount coltotal"
452
453 budgetClass :: RowClass -> Ods.Class
454 budgetClass rc =
455 Ods.Class $
456 case rc of Value -> "budget"; Total -> "budget coltotal"
457
458 rowTotalClass :: RowClass -> Ods.Class
459 rowTotalClass rc =
460 Ods.Class $
461 case rc of Value -> "amount rowtotal"; Total -> "amount coltotal"
462
463 rowAverageClass :: RowClass -> Ods.Class
464 rowAverageClass rc =
465 Ods.Class $
466 case rc of Value -> "amount rowaverage"; Total -> "amount colaverage"
467
468 budgetTotalClass :: RowClass -> Ods.Class
469 budgetTotalClass rc =
470 Ods.Class $
471 case rc of Value -> "budget rowtotal"; Total -> "budget coltotal"
472
473 budgetAverageClass :: RowClass -> Ods.Class
474 budgetAverageClass rc =
475 Ods.Class $
476 case rc of Value -> "budget rowaverage"; Total -> "budget colaverage"
477
478 -- What to show as heading for the totals row in balance reports ?
479 -- Currently nothing in terminal, Total: in HTML, FODS and xSV output.
480 totalRowHeadingText = ""
481 totalRowHeadingSpreadsheet = "Total:"
482 totalRowHeadingBudgetText = ""
483 totalRowHeadingBudgetCsv = "Total:"
484
485 -- Single-column balance reports
486
487 -- | Render a single-column balance report as CSV.
488 balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV
489 balanceReportAsCsv opts =
490 rawTableContent . balanceReportAsSpreadsheet opts
491
492 -- | Render a single-column balance report as plain text.
493 balanceReportAsText :: ReportOpts -> BalanceReport -> TB.Builder
494 balanceReportAsText opts ((items, total)) = case layout_ opts of
495 LayoutBare | iscustom -> error' "Custom format not supported with commodity columns" -- PARTIAL:
496 LayoutBare -> bareLayoutBalanceReportAsText opts ((items, total))
497 _ -> unlinesB ls <> unlinesB (if no_total_ opts then [] else [overline, totalLines])
498 where
499 (ls, sizes) = unzip $ map (balanceReportItemAsText opts) items
500 -- abuse renderBalanceReportItem to render the total with similar format
501 (totalLines, _) = renderBalanceReportItem opts ("",0,total)
502 -- with a custom format, extend the line to the full report width;
503 -- otherwise show the usual 20-char line for compatibility
504 iscustom = case format_ opts of
505 OneLine ((FormatField _ _ _ TotalField):_) -> False
506 TopAligned ((FormatField _ _ _ TotalField):_) -> False
507 BottomAligned ((FormatField _ _ _ TotalField):_) -> False
508 _ -> True
509 overlinewidth = if iscustom then sum (map maximum' $ transpose sizes) else 20
510 overline = TB.fromText $ T.replicate overlinewidth "-"
511
512 -- | Render a single-column balance report as plain text with a separate commodity column (--layout=bare)
513 bareLayoutBalanceReportAsText :: ReportOpts -> BalanceReport -> TB.Builder
514 bareLayoutBalanceReportAsText opts (items, total) =
515 unlinesB .
516 map
517 (renderColumns def{tableBorders=singleColumnTableOuterBorder} sizes .
518 Group singleColumnTableInterColumnBorder . map Header) $
519 ls ++ concat [[[overline], totalline] | not (no_total_ opts)]
520 where
521 render (_, acctname, dep, amt) =
522 [ Cell TopRight damts
523 , Cell TopLeft (fmap wbFromText cs)
524 , Cell TopLeft (replicate (length damts - 1) mempty ++ [wbFromText dispname]) ]
525 where dopts = oneLineNoCostFmt{displayCommodity=layout_ opts /= LayoutBare, displayCommodityOrder=Just cs, displayColour=color_ opts}
526 cs = if mixedAmountLooksZero amt then [""] else S.toList $ maCommodities amt
527 dispname = T.replicate ((dep - 1) * 2) " " <> acctname
528 damts = showMixedAmountLinesB dopts amt
529 ls = fmap render items
530 totalline = render ("", "", 0, total)
531 sizes = fromMaybe 0 . maximumMay . map cellWidth <$>
532 transpose ([totalline | not (no_total_ opts)] ++ ls)
533 overline = Cell TopLeft . pure . wbFromText . flip T.replicate "-" . fromMaybe 0 $ headMay sizes
534 singleColumnTableOuterBorder = pretty_ opts
535 singleColumnTableInterColumnBorder = if pretty_ opts then SingleLine else NoLine
536
537 {-
538 This implementation turned out to be a bit convoluted but implements the following algorithm for formatting:
539
540 - If there is a single amount, print it with the account name directly:
541 - Otherwise, only print the account name on the last line.
542
543 a USD 1 ; Account 'a' has a single amount
544 EUR -1
545 b USD -1 ; Account 'b' has two amounts. The account name is printed on the last line.
546 -}
547 -- | Render one balance report line item as plain text suitable for console output (or
548 -- whatever string format is specified). Note, prices will not be rendered, and
549 -- differently-priced quantities of the same commodity will appear merged.
550 -- The output will be one or more lines depending on the format and number of commodities.
551 balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> (TB.Builder, [Int])
552 balanceReportItemAsText opts (_, accountName, dep, amt) =
553 renderBalanceReportItem opts (accountName, dep, amt)
554
555 -- | Render a balance report item, using the StringFormat specified by --format.
556 --
557 renderBalanceReportItem :: ReportOpts -> (AccountName, Int, MixedAmount) -> (TB.Builder, [Int])
558 renderBalanceReportItem opts (acctname, dep, total) =
559 case format_ opts of
560 OneLine comps -> renderRowFromComponents $ renderComponents True True comps
561 TopAligned comps -> renderRowFromComponents $ renderComponents True False comps
562 BottomAligned comps -> renderRowFromComponents $ renderComponents False False comps
563
564 where
565 -- Combine the rendered component cells horizontally, as a possibly multi-line text (builder),
566 -- aligned in borderless columns (? XXX). Also returns the rendered width of each cell.
567 renderRowFromComponents :: [Cell] -> (TB.Builder, [Int])
568 renderRowFromComponents cs =
569 ( renderRowB def{tableBorders=False, borderSpaces=False} . Group NoLine $ map Header cs
570 , map cellWidth cs
571 )
572
573 -- Render each of the given StringFormat components for the balance report item,
574 -- returning each as a Cell.
575 renderComponents :: Bool -> Bool -> [StringFormatComponent] -> [Cell]
576 renderComponents topaligned oneline = map (renderComponent topaligned oneline opts (acctname, dep, total))
577
578 -- Render one StringFormat component for a balance report item.
579 -- Returns a Cell, containing 0 or more lines of text (as builders).
580 renderComponent :: Bool -> Bool -> ReportOpts -> (AccountName, Int, MixedAmount) -> StringFormatComponent -> Cell
581 renderComponent _ _ _ _ (FormatLiteral s) = textCell TopLeft s
582 renderComponent topaligned oneline opts (acctname, dep, total) (FormatField ljust mmin mmax field) = case field of
583 DepthSpacerField -> Cell align [WideBuilder (TB.fromText $ T.replicate d " ") d]
584 where d = maybe id min mmax $ dep * fromMaybe 1 mmin
585 AccountField -> textCell align $ formatText ljust mmin mmax acctname
586 TotalField -> Cell align . pure $ showMixedAmountB dopts total
587 _ -> Cell align [mempty]
588 where
589 align | topaligned && ljust = TopLeft
590 | topaligned = TopRight
591 | ljust = BottomLeft
592 | otherwise = BottomRight
593 dopts = noCostFmt{displayCommodity = layout_ opts /= LayoutBare
594 ,displayOneLine = oneline
595 ,displayMinWidth = mmin
596 ,displayMaxWidth = mmax
597 ,displayColour = color_ opts
598 }
599
600
601 simpleDateSpanCell :: DateSpan -> Ods.Cell Ods.NumLines Text
602 simpleDateSpanCell = Ods.defaultCell . showDateSpan
603
604 addTotalBorders :: [[Ods.Cell border text]] -> [[Ods.Cell Ods.NumLines text]]
605 addTotalBorders =
606 zipWith
607 (\border ->
608 map (\c -> c {
609 Ods.cellStyle = Ods.Body Ods.Total,
610 Ods.cellBorder = Ods.noBorder {Ods.borderTop = border}}))
611 (Ods.DoubleLine : repeat Ods.NoLine)
612
613
614 -- | Render a single-column balance report as FODS.
615 balanceReportAsSpreadsheet ::
616 ReportOpts -> BalanceReport -> [[Ods.Cell Ods.NumLines Text]]
617 balanceReportAsSpreadsheet opts (items, total) =
618 (if transpose_ opts then Ods.transpose else id) $
619 headers :
620 concatMap (rows Value) items ++
621 if no_total_ opts then []
622 else addTotalBorders $
623 rows Total (totalRowHeadingSpreadsheet, totalRowHeadingSpreadsheet, 0, total)
624 where
625 cell = Ods.defaultCell
626 headers =
627 addHeaderBorders $ map headerCell $
628 "account" : case layout_ opts of
629 LayoutBare -> ["commodity", "balance"]
630 _ -> ["balance"]
631 rows ::
632 RowClass -> BalanceReportItem ->
633 [[Ods.Cell Ods.NumLines Text]]
634 rows rc (name, dispName, dep, ma) =
635 let accountCell =
636 setAccountAnchor
637 (guard (rc==Value) >> balance_base_url_ opts)
638 (querystring_ opts) name $
639 cell $ renderBalanceAcct opts nbsp (name, dispName, dep) in
640 addRowSpanHeader accountCell $
641 case layout_ opts of
642 LayoutBare ->
643 map (\a -> [cell $ acommodity a, renderAmount rc $ mixedAmount a])
644 . amounts $ mixedAmountStripCosts ma
645 _ -> [[renderAmount rc ma]]
646
647 renderAmount rc mixedAmt =
648 wbToText <$> cellFromMixedAmount bopts (amountClass rc, mixedAmt)
649 where
650 bopts = machineFmt{displayCommodity=showcomm, displayCommodityOrder = commorder}
651 (showcomm, commorder)
652 | layout_ opts == LayoutBare = (False, Just $ S.toList $ maCommodities mixedAmt)
653 | otherwise = (True, Nothing)
654
655
656
657 -- Multi-column balance reports
658
659 -- | Render a multi-column balance report as CSV.
660 -- The CSV will always include the initial headings row,
661 -- and will include the final totals row unless --no-total is set.
662 multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV
663 multiBalanceReportAsCsv opts@ReportOpts{..} report =
664 (if transpose_ then transpose else id) $
665 rawTableContent $ header : body ++ totals
666 where
667 (header, body, totals) =
668 multiBalanceReportAsSpreadsheetParts machineFmt opts report
669
670 -- | Render the Spreadsheet table rows (CSV, ODS, HTML) for a MultiBalanceReport.
671 -- Returns the heading row, 0 or more body rows, and the totals row if enabled.
672 multiBalanceReportAsSpreadsheetParts ::
673 AmountFormat -> ReportOpts -> MultiBalanceReport ->
674 ([Ods.Cell Ods.NumLines Text],
675 [[Ods.Cell Ods.NumLines Text]],
676 [[Ods.Cell Ods.NumLines Text]])
677 multiBalanceReportAsSpreadsheetParts fmt opts@ReportOpts{..} (PeriodicReport colspans items tr) =
678 (headers, concatMap fullRowAsTexts items, addTotalBorders totalrows)
679 where
680 accountCell label =
681 (Ods.defaultCell label) {Ods.cellClass = Ods.Class "account"}
682 hCell cls label = (headerCell label) {Ods.cellClass = Ods.Class cls}
683 headers =
684 addHeaderBorders $
685 hCell "account" "account" :
686 case layout_ of
687 LayoutTidy -> map headerCell tidyColumnLabels
688 LayoutBare -> headerCell "commodity" : dateHeaders
689 _ -> dateHeaders
690 dateHeaders =
691 (if not summary_only_ then map (headerDateSpanCell balance_base_url_ querystring_) colspans else [] )++
692 [hCell "rowtotal" "total" | multiBalanceHasTotalsColumn opts] ++
693 [hCell "rowaverage" "average" | average_]
694 fullRowAsTexts row =
695 addRowSpanHeader anchorCell $
696 rowAsText Value (dateSpanCell balance_base_url_ querystring_ acctName) row
697 where acctName = prrFullName row
698 anchorCell =
699 setAccountAnchor balance_base_url_ querystring_ acctName $
700 accountCell $ renderPeriodicAcct opts nbsp row
701 totalrows =
702 if no_total_
703 then []
704 else addRowSpanHeader (accountCell totalRowHeadingSpreadsheet) $
705 rowAsText Total simpleDateSpanCell tr
706 rowAsText rc dsCell =
707 map (map (fmap wbToText)) .
708 multiBalanceRowAsCellBuilders fmt opts colspans rc dsCell
709
710 tidyColumnLabels :: [Text]
711 tidyColumnLabels =
712 ["period", "start_date", "end_date", "commodity", "value"]
713
714
715 -- | Render a multi-column balance report as HTML.
716 multiBalanceReportAsHtml :: ReportOpts -> MultiBalanceReport -> Html
717 multiBalanceReportAsHtml ropts mbr =
718 styledTableHtml . map (map (fmap toHtml)) $
719 snd $ multiBalanceReportAsSpreadsheet ropts mbr
720
721 -- | Render the ODS table rows for a MultiBalanceReport.
722 -- Returns the heading row, 0 or more body rows, and the totals row if enabled.
723 multiBalanceReportAsSpreadsheet ::
724 ReportOpts -> MultiBalanceReport ->
725 ((Int, Int), [[Ods.Cell Ods.NumLines Text]])
726 multiBalanceReportAsSpreadsheet ropts mbr =
727 let (header,body,total) =
728 multiBalanceReportAsSpreadsheetParts oneLineNoCostFmt ropts mbr
729 in (if transpose_ ropts then swap *** Ods.transpose else id) $
730 ((1, case layout_ ropts of LayoutWide _ -> 1; _ -> 0),
731 header : body ++ total)
732
733
734 -- | Render a multi-column balance report as plain text suitable for console output.
735 multiBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> TL.Text
736 multiBalanceReportAsText ropts@ReportOpts{..} r = TB.toLazyText $
737 TB.fromText title
738 <> TB.fromText "\n\n"
739 <> multiBalanceReportTableAsText ropts (multiBalanceReportAsTable ropts r)
740 where
741 title = mtitle <> " in " <> showDateSpan (periodicReportSpan r) <> valuationdesc <> ":"
742
743 mtitle = case (balancecalc_, balanceaccum_) of
744 (CalcValueChange, PerPeriod ) -> "Period-end value changes"
745 (CalcValueChange, Cumulative ) -> "Cumulative period-end value changes"
746 (CalcGain, PerPeriod ) -> "Incremental gain"
747 (CalcGain, Cumulative ) -> "Cumulative gain"
748 (CalcGain, Historical ) -> "Historical gain"
749 (_, PerPeriod ) -> "Balance changes"
750 (_, Cumulative ) -> "Ending balances (cumulative)"
751 (_, Historical) -> "Ending balances (historical)"
752 valuationdesc =
753 (case conversionop_ of
754 Just ToCost -> ", converted to cost"
755 _ -> "")
756 <> (case value_ of
757 Just (AtThen _mc) -> ", valued at posting date"
758 Just (AtEnd _mc) | changingValuation -> ""
759 Just (AtEnd _mc) -> ", valued at period ends"
760 Just (AtNow _mc) -> ", current value"
761 Just (AtDate d _mc) -> ", valued at " <> showDate d
762 Nothing -> "")
763
764 changingValuation = case (balancecalc_, balanceaccum_) of
765 (CalcValueChange, PerPeriod) -> True
766 (CalcValueChange, Cumulative) -> True
767 _ -> False
768
769 -- | Given a table representing a multi-column balance report,
770 -- render it in a format suitable for console output.
771 -- Amounts with more than two commodities will be elided unless --no-elide is used.
772 multiBalanceReportTableAsText :: ReportOpts -> Table T.Text T.Text WideBuilder -> TB.Builder
773 multiBalanceReportTableAsText ReportOpts{..} = renderTableByRowsB tableopts renderCh renderRow
774 where
775 tableopts = def{tableBorders=multiColumnTableOuterBorder, prettyTable=pretty_}
776 multiColumnTableOuterBorder = pretty_
777
778 renderCh :: [Text] -> [Cell]
779 renderCh
780 | layout_ /= LayoutBare || transpose_ = fmap (textCell TopRight)
781 | otherwise = zipWith ($) (textCell TopLeft : repeat (textCell TopRight))
782
783 renderRow :: (Text, [WideBuilder]) -> (Cell, [Cell])
784 renderRow (rh, row)
785 | layout_ /= LayoutBare || transpose_ =
786 (textCell TopLeft rh, fmap (Cell TopRight . pure) row)
787 | otherwise =
788 (textCell TopLeft rh, zipWith ($) (Cell TopLeft : repeat (Cell TopRight)) (fmap pure row))
789
790 -- | Build a 'Table' from a multi-column balance report.
791 multiBalanceReportAsTable :: ReportOpts -> MultiBalanceReport -> Table T.Text T.Text WideBuilder
792 multiBalanceReportAsTable opts@ReportOpts{summary_only_, average_, balanceaccum_}
793 (PeriodicReport spans items tr) =
794 maybetranspose $
795 addtotalrow $
796 Table
797 (Group multiColumnTableInterRowBorder $ map Header $ concat accts)
798 (Group multiColumnTableInterColumnBorder $ map Header colheadings)
799 (concat rows)
800 where
801 colheadings = ["Commodity" | layout_ opts == LayoutBare]
802 ++ (if not summary_only_ then map (reportPeriodName balanceaccum_ spans) spans else [])
803 ++ [" Total" | multiBalanceHasTotalsColumn opts]
804 ++ ["Average" | average_]
805 (accts, rows) = unzip $ fmap fullRowAsTexts items
806 where
807 fullRowAsTexts row = (replicate (length rs) (renderacct row), rs)
808 where
809 rs = multiBalanceRowAsText opts row
810 renderacct row' = T.replicate (prrIndent row' * 2) " " <> prrDisplayName row'
811 addtotalrow
812 | no_total_ opts = id
813 | otherwise =
814 let totalrows = multiBalanceRowAsText opts tr
815 rowhdrs = Group NoLine $ map Header $ totalRowHeadingText : replicate (length totalrows - 1) ""
816 colhdrs = Header [] -- unused, concatTables will discard
817 in (flip (concatTables SingleLine) $ Table rowhdrs colhdrs totalrows)
818 maybetranspose | transpose_ opts = \(Table rh ch vals) -> Table ch rh (transpose vals)
819 | otherwise = id
820 multiColumnTableInterRowBorder = NoLine
821 multiColumnTableInterColumnBorder = if pretty_ opts then SingleLine else NoLine
822
823 multiBalanceRowAsCellBuilders ::
824 AmountFormat -> ReportOpts -> [DateSpan] ->
825 RowClass -> (DateSpan -> Ods.Cell Ods.NumLines Text) ->
826 PeriodicReportRow a MixedAmount ->
827 [[Ods.Cell Ods.NumLines WideBuilder]]
828 multiBalanceRowAsCellBuilders bopts ropts@ReportOpts{..} colspans
829 rc renderDateSpanCell (PeriodicReportRow _acct as rowtot rowavg) =
830 case layout_ of
831 LayoutWide width -> [fmap (cellFromMixedAmount bopts{displayMaxWidth=width}) clsamts]
832 LayoutTall -> paddedTranspose Ods.emptyCell
833 . map (cellsFromMixedAmount bopts{displayMaxWidth=Nothing})
834 $ clsamts
835 LayoutBare -> zipWith (:) (map wbCell cs) -- add symbols
836 . transpose -- each row becomes a list of Text quantities
837 . map (cellsFromMixedAmount bopts{displayCommodity=False, displayCommodityOrder=Just cs, displayMinWidth=Nothing})
838 $ clsamts
839 LayoutTidy -> concat
840 . zipWith (map . addDateColumns) colspans
841 . map ( zipWith (\c a -> [wbCell c, a]) cs
842 . cellsFromMixedAmount bopts{displayCommodity=False, displayCommodityOrder=Just cs, displayMinWidth=Nothing})
843 $ classified
844 -- Do not include totals column or average for tidy output, as this
845 -- complicates the data representation and can be easily calculated
846 where
847 wbCell = Ods.defaultCell . wbFromText
848 wbDate content = (wbCell content) {Ods.cellType = Ods.TypeDate}
849 cs = if all mixedAmountLooksZero allamts then [""] else S.toList $ foldMap maCommodities allamts
850 classified = map ((,) (amountClass rc)) as
851 allamts = map snd clsamts
852 clsamts = (if not summary_only_ then classified else []) ++
853 [(rowTotalClass rc, rowtot) |
854 multiBalanceHasTotalsColumn ropts && not (null as)] ++
855 [(rowAverageClass rc, rowavg) | average_ && not (null as)]
856 addDateColumns spn@(DateSpan s e) remCols =
857 (wbFromText <$> renderDateSpanCell spn) :
858 wbDate (maybe "" showEFDate s) :
859 wbDate (maybe "" (showEFDate . modifyEFDay (addDays (-1))) e) :
860 remCols
861
862 paddedTranspose :: a -> [[a]] -> [[a]]
863 paddedTranspose _ [] = [[]]
864 paddedTranspose n as1 = take (maximum . map length $ as1) . trans $ as1
865 where
866 trans ([] : xss) = (n : map h xss) : trans ([n] : map t xss)
867 trans ((x : xs) : xss) = (x : map h xss) : trans (m xs : map t xss)
868 trans [] = []
869 h (x:_) = x
870 h [] = n
871 t (_:xs) = xs
872 t [] = [n]
873 m (x:xs) = x:xs
874 m [] = [n]
875
876
877 multiBalanceHasTotalsColumn :: ReportOpts -> Bool
878 multiBalanceHasTotalsColumn ropts =
879 row_total_ ropts && balanceaccum_ ropts `notElem` [Cumulative, Historical]
880
881 multiBalanceRowAsText :: ReportOpts -> PeriodicReportRow a MixedAmount -> [[WideBuilder]]
882 multiBalanceRowAsText opts =
883 rawTableContent .
884 multiBalanceRowAsCellBuilders oneLineNoCostFmt{displayColour=color_ opts} opts []
885 Value simpleDateSpanCell
886
887 multiBalanceRowAsCsvText :: ReportOpts -> [DateSpan] -> PeriodicReportRow a MixedAmount -> [[T.Text]]
888 multiBalanceRowAsCsvText opts colspans =
889 map (map (wbToText . Ods.cellContent)) .
890 multiBalanceRowAsCellBuilders machineFmt opts colspans
891 Value simpleDateSpanCell
892
893
894 -- Budget reports
895
896 -- A BudgetCell's data values rendered for display - the actual change amount,
897 -- the budget goal amount if any, and the corresponding goal percentage if possible.
898 type BudgetDisplayCell = (WideBuilder, Maybe (WideBuilder, Maybe WideBuilder))
899
900 -- | A row of rendered budget data cells.
901 type BudgetDisplayRow = [BudgetDisplayCell]
902
903 -- | An amount render helper for the budget report. Renders each commodity separately.
904 type BudgetShowAmountsFn = MixedAmount -> [WideBuilder]
905
906 -- | A goal percentage calculating helper for the budget report.
907 type BudgetCalcPercentagesFn = Change -> BudgetGoal -> [Maybe Percentage]
908
909 -- | Render a budget report as plain text suitable for console output.
910 budgetReportAsText :: ReportOpts -> BudgetReport -> TL.Text
911 budgetReportAsText ropts@ReportOpts{..} budgetr = TB.toLazyText $
912 TB.fromText title <> TB.fromText "\n\n" <>
913 multiBalanceReportTableAsText ropts (budgetReportAsTable ropts budgetr)
914 where
915 title = "Budget performance in " <> showDateSpan (periodicReportSpan budgetr)
916 <> (case conversionop_ of
917 Just ToCost -> ", converted to cost"
918 _ -> "")
919 <> (case value_ of
920 Just (AtThen _mc) -> ", valued at posting date"
921 Just (AtEnd _mc) -> ", valued at period ends"
922 Just (AtNow _mc) -> ", current value"
923 Just (AtDate d _mc) -> ", valued at " <> showDate d
924 Nothing -> "")
925 <> ":"
926
927 -- | Build a 'Table' from a multi-column balance report.
928 budgetReportAsTable :: ReportOpts -> BudgetReport -> Table Text Text WideBuilder
929 budgetReportAsTable ropts@ReportOpts{..} (PeriodicReport spans items totrow) =
930 maybetransposetable $
931 addtotalrow $
932 Table
933 (Group budgetTableInterRowBorder $ map Header accts)
934 (Group budgetTableInterColumnBorder $ map Header colheadings)
935 rows
936 where
937 budgetTableInterRowBorder = NoLine
938 budgetTableInterColumnBorder = if pretty_ then SingleLine else NoLine
939
940 maybetransposetable
941 | transpose_ = \(Table rh ch vals) -> Table ch rh (transpose vals)
942 | otherwise = id
943
944 addtotalrow
945 | no_total_ = id
946 | otherwise =
947 let
948 rowhdrs = Group NoLine $ map Header $ totalRowHeadingBudgetText : replicate (length totalrows - 1) ""
949 colhdrs = Header [] -- ignored by concatTables
950 in
951 (flip (concatTables SingleLine) $ Table rowhdrs colhdrs totalrows) -- XXX ?
952
953 colheadings = ["Commodity" | layout_ == LayoutBare]
954 ++ (if not summary_only_ then map (reportPeriodName balanceaccum_ spans) spans else [])
955 ++ [" Total" | row_total_]
956 ++ ["Average" | average_]
957
958 (accts, rows, totalrows) =
959 (accts'
960 ,maybecommcol itemscs $ showcells texts
961 ,maybecommcol totrowcs $ showtotrow totrowtexts)
962 where
963 -- If --layout=bare, prepend a commodities column.
964 maybecommcol :: [WideBuilder] -> [[WideBuilder]] -> [[WideBuilder]]
965 maybecommcol cs
966 | layout_ == LayoutBare = zipWith (:) cs
967 | otherwise = id
968
969 showcells, showtotrow :: [[BudgetDisplayCell]] -> [[WideBuilder]]
970 (showcells, showtotrow) =
971 (maybetranspose . map (zipWith showBudgetDisplayCell widths) . maybetranspose
972 ,maybetranspose . map (zipWith showBudgetDisplayCell totrowwidths) . maybetranspose)
973 where
974 -- | Combine a BudgetDisplayCell's rendered values into a "[PERCENT of GOAL]" rendering,
975 -- respecting the given widths.
976 showBudgetDisplayCell :: (Int, Int, Int) -> BudgetDisplayCell -> WideBuilder
977 showBudgetDisplayCell (actualwidth, budgetwidth, percentwidth) (actual, mbudget) =
978 flip WideBuilder (actualwidth + totalbudgetwidth) $
979 toPadded actual <> maybe emptycell showBudgetGoalAndPercentage mbudget
980
981 where
982 toPadded (WideBuilder b w) = (TB.fromText . flip T.replicate " " $ actualwidth - w) <> b
983
984 (totalpercentwidth, totalbudgetwidth) =
985 let totalpercentwidth' = if percentwidth == 0 then 0 else percentwidth + 5
986 in ( totalpercentwidth'
987 , if budgetwidth == 0 then 0 else budgetwidth + totalpercentwidth' + 3
988 )
989
990 emptycell :: TB.Builder
991 emptycell = TB.fromText $ T.replicate totalbudgetwidth " "
992
993 showBudgetGoalAndPercentage :: (WideBuilder, Maybe WideBuilder) -> TB.Builder
994 showBudgetGoalAndPercentage (goal, perc) =
995 let perct = case perc of
996 Nothing -> T.replicate totalpercentwidth " "
997 Just pct -> T.replicate (percentwidth - wbWidth pct) " " <> wbToText pct <> "% of "
998 in TB.fromText $ " [" <> perct <> T.replicate (budgetwidth - wbWidth goal) " " <> wbToText goal <> "]"
999
1000 -- | Build a list of widths for each column.
1001 -- When --transpose is used, the totals row must be included in this list.
1002 widths :: [(Int, Int, Int)]
1003 widths = zip3 actualwidths budgetwidths percentwidths
1004 where
1005 actualwidths = map (maximum' . map first3 ) $ cols
1006 budgetwidths = map (maximum' . map second3) $ cols
1007 percentwidths = map (maximum' . map third3 ) $ cols
1008 catcolumnwidths = foldl' (zipWith (++)) $ repeat []
1009 cols = maybetranspose $ catcolumnwidths $ map (cellswidth . rowToBudgetCells) items ++ [cellswidth $ rowToBudgetCells totrow]
1010
1011 cellswidth :: [BudgetCell] -> [[(Int, Int, Int)]]
1012 cellswidth row =
1013 let cs = budgetCellsCommodities row
1014 (showmixed, percbudget) = mkBudgetDisplayFns cs
1015 disp = showcell showmixed percbudget
1016 budgetpercwidth = wbWidth *** maybe 0 wbWidth
1017 cellwidth (am, bm) = let (bw, pw) = maybe (0, 0) budgetpercwidth bm in (wbWidth am, bw, pw)
1018 in map (map cellwidth . disp) row
1019
1020 totrowwidths :: [(Int, Int, Int)]
1021 totrowwidths
1022 | transpose_ = drop (length texts) widths
1023 | otherwise = widths
1024
1025 maybetranspose
1026 | transpose_ = transpose
1027 | otherwise = id
1028
1029 (accts', itemscs, texts) = unzip3 $ concat shownitems
1030 where
1031 shownitems :: [[(AccountName, WideBuilder, BudgetDisplayRow)]]
1032 shownitems =
1033 map (\i ->
1034 let
1035 addacctcolumn = map (\(cs, cvals) -> (renderPeriodicAcct ropts " " i, cs, cvals))
1036 isunbudgetedrow = displayFull (prrName i) == unbudgetedAccountName
1037 in addacctcolumn $ showrow isunbudgetedrow $ rowToBudgetCells i)
1038 items
1039
1040 (totrowcs, totrowtexts) = unzip $ concat showntotrow
1041 where
1042 showntotrow :: [[(WideBuilder, BudgetDisplayRow)]]
1043 showntotrow = [showrow False $ rowToBudgetCells totrow]
1044
1045 -- | Get the data cells from a row or totals row, maybe adding
1046 -- the row total and/or row average depending on options.
1047 rowToBudgetCells :: PeriodicReportRow a BudgetCell -> [BudgetCell]
1048 rowToBudgetCells (PeriodicReportRow _ as rowtot rowavg) =
1049 (if not summary_only_ then as else [])
1050 ++ [rowtot | row_total_ && not (null as)]
1051 ++ [rowavg | average_ && not (null as)]
1052
1053 -- | Render a row's data cells as "BudgetDisplayCell"s, and a rendered list of commodity symbols.
1054 -- Also requires a flag indicating whether this is the special <unbudgeted> row.
1055 -- (The types make that hard to check here.)
1056 showrow :: Bool -> [BudgetCell] -> [(WideBuilder, BudgetDisplayRow)]
1057 showrow isunbudgetedrow cells =
1058 let
1059 cs = budgetCellsCommodities cells
1060 -- #2071 If there are no commodities - because there are no actual or goal amounts -
1061 -- the zipped list would be empty, causing this row not to be shown.
1062 -- But rows like this sometimes need to be shown to preserve the account tree structure.
1063 -- So, ensure 0 will be shown as actual amount(s).
1064 -- Unfortunately this disables boring parent eliding, as if --no-elide had been used.
1065 -- (Just turning on --no-elide higher up doesn't work right.)
1066 -- Note, no goal amount will be shown for these rows,
1067 -- whereas --no-elide is likely to show a goal amount aggregated from children.
1068 cs1 = if null cs && not isunbudgetedrow then [""] else cs
1069 (showmixed, percbudget) = mkBudgetDisplayFns cs1
1070 in
1071 zip (map wbFromText cs1) $
1072 transpose $
1073 map (showcell showmixed percbudget)
1074 cells
1075
1076 budgetCellsCommodities :: [BudgetCell] -> [CommoditySymbol]
1077 budgetCellsCommodities = S.toList . foldl' S.union mempty . map budgetCellCommodities
1078 where
1079 budgetCellCommodities :: BudgetCell -> S.Set CommoditySymbol
1080 budgetCellCommodities (am, bm) = f am `S.union` f bm
1081 where f = maybe mempty maCommodities
1082
1083 -- | Render a "BudgetCell"'s amounts as "BudgetDisplayCell"s (one per commodity).
1084 showcell :: BudgetShowAmountsFn -> BudgetCalcPercentagesFn -> BudgetCell -> BudgetDisplayRow
1085 showcell showCommodityAmounts calcCommodityPercentages (mactual, mbudget) =
1086 zip actualamts budgetinfos
1087 where
1088 actual = fromMaybe nullmixedamt mactual
1089 actualamts = showCommodityAmounts actual
1090 budgetinfos =
1091 case mbudget of
1092 Nothing -> repeat Nothing
1093 Just goal -> map Just $ showGoalAmountsAndPercentages goal
1094 where
1095 showGoalAmountsAndPercentages :: MixedAmount -> [(WideBuilder, Maybe WideBuilder)]
1096 showGoalAmountsAndPercentages goal = zip amts mpcts
1097 where
1098 amts = showCommodityAmounts goal
1099 mpcts = map (showrounded <$>) $ calcCommodityPercentages actual goal
1100 where showrounded = wbFromText . T.pack . show . roundTo 0
1101
1102 -- | Make budget info display helpers that adapt to --layout=wide.
1103 mkBudgetDisplayFns :: [CommoditySymbol] -> (BudgetShowAmountsFn, BudgetCalcPercentagesFn)
1104 mkBudgetDisplayFns cs = case layout_ of
1105 LayoutWide width ->
1106 ( pure . showMixedAmountB oneLineNoCostFmt{displayMaxWidth=width, displayColour=color_}
1107 , \a -> pure . percentage a)
1108 _ -> ( showMixedAmountLinesB noCostFmt{displayCommodity=layout_/=LayoutBare, displayCommodityOrder=Just cs, displayMinWidth=Nothing, displayColour=color_}
1109 , \a b -> map (percentage' a b) cs)
1110 where
1111 -- | Calculate the percentage of actual change to budget goal to show, if any.
1112 -- If valuing at cost, both amounts are converted to cost before comparing.
1113 -- A percentage will not be shown if:
1114 --
1115 -- - actual or goal are not the same, single, commodity
1116 --
1117 -- - the goal is zero
1118 --
1119 percentage :: Change -> BudgetGoal -> Maybe Percentage
1120 percentage actual budget =
1121 case (costedAmounts actual, costedAmounts budget) of
1122 ([a], [b]) | (acommodity a == acommodity b || amountLooksZero a) && not (amountLooksZero b)
1123 -> Just $ 100 * aquantity a / aquantity b
1124 _ -> Nothing
1125 where
1126 costedAmounts = case conversionop_ of
1127 Just ToCost -> amounts . mixedAmountCost
1128 _ -> amounts . mixedAmountStripCosts -- strip any lingering cost info that would prevent unification
1129
1130 -- | Like percentage, but accept multicommodity actual and budget amounts,
1131 -- and extract the specified commodity from both.
1132 percentage' :: Change -> BudgetGoal -> CommoditySymbol -> Maybe Percentage
1133 percentage' am bm c = case ((,) `on` find ((==) c . acommodity) . amounts) am bm of
1134 (Just a, Just b) -> percentage (mixedAmount a) (mixedAmount b)
1135 _ -> Nothing
1136
1137 -- XXX generalise this with multiBalanceReportAsCsv ?
1138 -- | Render a budget report as CSV. Like multiBalanceReportAsCsv,
1139 -- but includes alternating actual and budget amount columns.
1140 budgetReportAsCsv :: ReportOpts -> BudgetReport -> [[Text]]
1141 budgetReportAsCsv ropts report
1142 = rawTableContent $
1143 budgetReportAsSpreadsheet machineFmt ropts report
1144
1145 budgetReportAsSpreadsheet ::
1146 AmountFormat -> ReportOpts -> BudgetReport -> [[Ods.Cell Ods.NumLines Text]]
1147 budgetReportAsSpreadsheet
1148 fmt
1149 ropts@ReportOpts{..}
1150 (PeriodicReport colspans items totrow)
1151 = (if transpose_ then Ods.transpose else id) $
1152
1153 -- heading row
1154 (addHeaderBorders $ map headerCell $
1155 "Account" :
1156 ["Commodity" | layout_ == LayoutBare ]
1157 ++ (if not summary_only_ then concatMap (\spn -> [showDateSpan spn, "budget"]) colspans else [])
1158 ++ concat [["Total" ,"budget"] | row_total_]
1159 ++ concat [["Average","budget"] | average_]
1160 ) :
1161
1162 -- account rows
1163 concatMap (\row -> rowAsTexts Value (accountCell row) row) items
1164
1165 -- totals row
1166 ++ addTotalBorders
1167 (concat [ rowAsTexts Total (cell totalRowHeadingBudgetCsv) totrow | not no_total_ ])
1168
1169 where
1170 cell = Ods.defaultCell
1171 accountCell row =
1172 let name = prrFullName row in
1173 setAccountAnchor (balance_base_url_) querystring_ name $
1174 cell $ renderPeriodicAcct ropts nbsp row
1175 {-
1176 ToDo: The chosen HTML cell class names are not put in stone.
1177 If you find you need more systematic names,
1178 feel free to develop a more sophisticated scheme.
1179 -}
1180 flattentuples rc tups =
1181 concat [[(amountClass rc, a),(budgetClass rc, b)] | (a,b) <- tups]
1182 showNorm (cls,mval) =
1183 maybe Ods.emptyCell (fmap wbToText . curry (cellFromMixedAmount fmt) cls) mval
1184
1185 rowAsTexts :: RowClass
1186 -> Ods.Cell Ods.NumLines Text
1187 -> PeriodicReportRow a BudgetCell
1188 -> [[Ods.Cell Ods.NumLines Text]]
1189 rowAsTexts rc acctCell (PeriodicReportRow _ as (rowtot,budgettot) (rowavg, budgetavg)) =
1190 addRowSpanHeader acctCell $
1191 case layout_ of
1192 LayoutBare ->
1193 zipWith (:) (map cell cs) -- add symbols
1194 . transpose -- each row becomes a list of Text quantities
1195 . map (map (fmap wbToText) . cellsFromMixedAmount dopts . second (fromMaybe nullmixedamt))
1196 $ vals
1197 _ -> [map showNorm vals]
1198 where
1199 cs = S.toList . mconcat . map maCommodities $ mapMaybe snd vals
1200 dopts = fmt{displayCommodity=layout_ /= LayoutBare, displayCommodityOrder=Just cs, displayMinWidth=Nothing}
1201 vals = flattentuples rc (if not summary_only_ then as else [])
1202 ++ concat [[(rowTotalClass rc, rowtot),
1203 (budgetTotalClass rc, budgettot)]
1204 | row_total_]
1205 ++ concat [[(rowAverageClass rc, rowavg),
1206 (budgetAverageClass rc, budgetavg)]
1207 | average_]
1208
1209
1210 nbsp :: Text
1211 nbsp = "\160"
1212
1213 renderBalanceAcct ::
1214 ReportOpts -> Text -> (AccountName, AccountName, Int) -> Text
1215 renderBalanceAcct opts space (fullName, displayName, dep) =
1216 case accountlistmode_ opts of
1217 ALTree -> T.replicate (dep*2) space <> displayName
1218 ALFlat -> accountNameDrop (drop_ opts) fullName
1219
1220 -- FIXME. Have to check explicitly for which to render here, since
1221 -- budgetReport sets accountlistmode to ALTree. Find a principled way to do
1222 -- this.
1223 renderPeriodicAcct ::
1224 ReportOpts -> Text -> PeriodicReportRow DisplayName a -> Text
1225 renderPeriodicAcct opts space row =
1226 renderBalanceAcct opts space
1227 (prrFullName row, prrDisplayName row, prrIndent row)
1228
1229
1230 -- tests
1231
1232 tests_Balance = testGroup "Balance" [
1233
1234 testGroup "balanceReportAsText" [
1235 testCase "unicode in balance layout" $ do
1236 j <- readJournal'' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"
1237 let rspec = defreportspec{_rsReportOpts=defreportopts{no_total_=True}}
1238 TB.toLazyText (balanceReportAsText (_rsReportOpts rspec) (balanceReport rspec{_rsDay=fromGregorian 2008 11 26} j))
1239 @?=
1240 TL.unlines
1241 [" -100 актив:наличные"
1242 ," 100 расходы:покупки"
1243 ]
1244 ]
1245
1246 ]