{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE LambdaCase #-}
{-|

Common helpers for making multi-section balance report commands
like balancesheet, cashflow, and incomestatement.

-}

module Hledger.Cli.CompoundBalanceCommand (
  CompoundBalanceCommandSpec(..)
 ,compoundBalanceCommandMode
 ,compoundBalanceCommand
 ,compoundBalanceReportTitle
 ,titleInterval
 ,applySubreportTitles
 ,compoundBalanceSectionTypes
 ,CompoundBalanceReportParts(..)
 ,compoundBalanceReportAsSpreadsheetParts
 ,allCommoditiesFromSubreports
) where

import Control.Monad (guard, unless, void)
import Data.Bifunctor (second)
import Data.Foldable (traverse_)
import Data.List.NonEmpty (NonEmpty((:|)))
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Safe (atMay)
import Data.Map qualified as Map
import Data.Set qualified as Set
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Data.Time.Calendar (Day, addDays)
import System.Console.CmdArgs.Explicit as C (Mode, 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 as Tabular hiding (render)

import Hledger.Utils.I18n qualified as I18n
import Hledger
import Hledger.Cli.Anchor (LinkOpts(..), headerDateSpanCell)
import Hledger.Cli.Chart (compoundChartFlag, chartRequested, chartWidthFlag, compoundBalanceReportAsChart, writeChart)
import Hledger.Cli.Commands.Balance
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText, warnIfLargeMultiPeriodReport)
import Hledger.Cli.Commands.Balance.Internal
import Hledger.Write.Csv (CSV, printCSV, printTSV)
import Hledger.Write.Html (formatRow, formatTitle, htmlAsLazyText, nl, Html, toHtml)
import Hledger.Write.Html.Attribute (stylesheet, tableStyle)
import Hledger.Write.Ods (printFods)
import Hledger.Write.Spreadsheet qualified as Spr

-- | Description of a compound balance report command,
-- from which we generate the command's cmdargs mode and IO action.
-- A compound balance report command shows one or more sections/subreports,
-- each with its own title and subtotals row, in a certain order,
-- plus a grand totals row if there's more than one section.
-- Examples are the balancesheet, cashflow and incomestatement commands.
--
-- Compound balance reports do sign normalisation: they show all account balances
-- as normally positive, unlike the ordinary BalanceReport and most hledger commands
-- which show income/liability/equity balances as normally negative.
-- Each subreport specifies the normal sign of its amounts, and whether
-- it should be added to or subtracted from the grand total.
--
data CompoundBalanceCommandSpec = CompoundBalanceCommandSpec {
  CompoundBalanceCommandSpec -> [Char]
cbcdoc      :: CommandHelpStr,                  -- ^ the command's name(s) and documentation
  CompoundBalanceCommandSpec -> Interval -> Text
cbctitle    :: Interval -> T.Text,              -- ^ overall report title, by reporting interval
  CompoundBalanceCommandSpec -> [CBCSubreportSpec DisplayName]
cbcqueries  :: [CBCSubreportSpec DisplayName],  -- ^ subreport details
  CompoundBalanceCommandSpec -> BalanceAccumulation
cbcaccum    :: BalanceAccumulation              -- ^ how to accumulate balances (per-period, cumulative, historical)
                                                  --   (overrides command line flags)
}

-- | Generate a cmdargs option-parsing mode from a compound balance command
-- specification.
compoundBalanceCommandMode :: CompoundBalanceCommandSpec -> Mode RawOpts
compoundBalanceCommandMode :: CompoundBalanceCommandSpec -> Mode RawOpts
compoundBalanceCommandMode CompoundBalanceCommandSpec{[Char]
[CBCSubreportSpec DisplayName]
BalanceAccumulation
Interval -> Text
cbcdoc :: CompoundBalanceCommandSpec -> [Char]
cbctitle :: CompoundBalanceCommandSpec -> Interval -> Text
cbcqueries :: CompoundBalanceCommandSpec -> [CBCSubreportSpec DisplayName]
cbcaccum :: CompoundBalanceCommandSpec -> BalanceAccumulation
cbcdoc :: [Char]
cbctitle :: Interval -> Text
cbcqueries :: [CBCSubreportSpec DisplayName]
cbcaccum :: BalanceAccumulation
..} =
  [Char]
-> [Flag RawOpts]
-> [([Char], [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
   [Char]
cbcdoc
   -- keep roughly consistent order with Balance.hs. XXX refactor
   (
    -- https://hledger.org/dev/hledger.html#calculation-mode :
    [[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"sum"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"sum")
      ([Char]
calcprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"show sum of posting amounts (default)")
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"valuechange"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"valuechange")
      ([Char]
calcprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"show total change of value of period-end historical balances (caused by deposits, withdrawals, market price fluctuations)")
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"gain"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"gain")
      ([Char]
calcprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"show unrealised capital gain/loss (historical balance value minus cost basis)")
  -- currently not supported by compound balance commands:
  --  ,flagNone ["budget"] (setboolopt "budget")
  --     (calcprefix ++ "show sum of posting amounts compared to budget goals defined by periodic transactions")
   ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"count"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"count") ([Char]
calcprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"show the count of postings")

    -- https://hledger.org/dev/hledger.html#accumulation-mode :
   ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"change"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"change")
      ([Char]
accumprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"accumulate amounts from column start to column end (in multicolumn reports)" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ BalanceAccumulation -> [Char]
defaultMarker BalanceAccumulation
PerPeriod)
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"cumulative"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"cumulative")
      ([Char]
accumprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"accumulate amounts from report start (specified by e.g. -b/--begin) to column end" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ BalanceAccumulation -> [Char]
defaultMarker BalanceAccumulation
Cumulative)
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"historical",[Char]
"H"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"historical")
      ([Char]
accumprefix [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"accumulate amounts from journal start to column end (includes postings before report start date)" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ BalanceAccumulation -> [Char]
defaultMarker BalanceAccumulation
Historical)
    ]

    [Flag RawOpts] -> [Flag RawOpts] -> [Flag RawOpts]
forall a. [a] -> [a] -> [a]
++ Bool -> [Flag RawOpts]
flattreeflags Bool
True [Flag RawOpts] -> [Flag RawOpts] -> [Flag RawOpts]
forall a. [a] -> [a] -> [a]
++
    [[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq  [[Char]
"drop"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"drop" [Char]
s RawOpts
opts) [Char]
"N" [Char]
"in list mode, omit N leading account name parts"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"declared"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"declared") [Char]
"include non-parent declared accounts (best used with -E)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"average",[Char]
"A"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"average") [Char]
"show a row average column (in multicolumn reports)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"row-total",[Char]
"T"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"row-total") [Char]
"show a row total column (in multicolumn reports)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"summary-only"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"summary-only") [Char]
"display only row summaries (e.g. row total, average) (in multicolumn reports)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"no-total",[Char]
"N"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"no-total") [Char]
"omit the final total row"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"no-elide"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"no-elide") [Char]
"in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"full-names"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"full-names") [Char]
"in tree mode, show full account names instead of indented leaf names"
    ,[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq  [[Char]
"format"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"format" [Char]
s RawOpts
opts) [Char]
"FORMATSTR" [Char]
"use this custom line format (in simple reports)"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"sort-amount",[Char]
"S"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"sort-amount") [Char]
"sort by amount instead of account code/name"
    ,[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"percent", [Char]
"%"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"percent") [Char]
"express values in percentage of each column's total"
    ,[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq  [[Char]
"layout"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"layout" [Char]
s RawOpts
opts) [Char]
"ARG"
      ([[Char]] -> [Char]
unlines
        [[Char]
"how to show multi-commodity amounts:"
        ,[Char]
"'wide[,WIDTH]': all commodities on one line"
        ,[Char]
"'tall'        : each commodity on a new line"
        ,[Char]
"'bare'        : bare numbers, symbols in a column"
        ])
    ,[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq  [[Char]
"base-url"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"base-url" [Char]
s RawOpts
opts) [Char]
"URLPREFIX" [Char]
"in html output, generate hyperlinks to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"

    ,[[Char]] -> Flag RawOpts
outputFormatFlag [[Char]
"txt",[Char]
"html",[Char]
"csv",[Char]
"tsv",[Char]
"json",[Char]
"svg"]
    ,Flag RawOpts
outputFileFlag
    ,Flag RawOpts
outputViewFlag
    ,Flag RawOpts
compoundChartFlag
    ,Flag RawOpts
chartWidthFlag

    ])
    [([Char], [Flag RawOpts])]
cligeneralflagsgroups1
    ([Flag RawOpts]
hiddenflags [Flag RawOpts] -> [Flag RawOpts] -> [Flag RawOpts]
forall a. [a] -> [a] -> [a]
++
      [ [[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"commodity-column"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"commodity-column")
        [Char]
"show commodity symbols in a separate column, amounts as bare numbers, one row per commodity"
      ])
    ([], 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
$ [Char] -> Arg RawOpts
argsFlag [Char]
"[QUERY]")
 where
  calcprefix :: [Char]
calcprefix = [Char]
"calculation mode: "
  accumprefix :: [Char]
accumprefix = [Char]
"accumulation mode: "
  defaultMarker :: BalanceAccumulation -> String
  defaultMarker :: BalanceAccumulation -> [Char]
defaultMarker BalanceAccumulation
bacc | BalanceAccumulation
bacc BalanceAccumulation -> BalanceAccumulation -> Bool
forall a. Eq a => a -> a -> Bool
== BalanceAccumulation
cbcaccum = [Char]
" (default)"
                     | Bool
otherwise        = [Char]
""

-- | Generate a runnable command from a compound balance command specification.
compoundBalanceCommand :: CompoundBalanceCommandSpec -> (CliOpts -> Journal -> IO ())
compoundBalanceCommand :: CompoundBalanceCommandSpec -> CliOpts -> Journal -> IO ()
compoundBalanceCommand spec :: CompoundBalanceCommandSpec
spec@CompoundBalanceCommandSpec{[Char]
[CBCSubreportSpec DisplayName]
BalanceAccumulation
Interval -> Text
cbcdoc :: CompoundBalanceCommandSpec -> [Char]
cbctitle :: CompoundBalanceCommandSpec -> Interval -> Text
cbcqueries :: CompoundBalanceCommandSpec -> [CBCSubreportSpec DisplayName]
cbcaccum :: CompoundBalanceCommandSpec -> BalanceAccumulation
cbcdoc :: [Char]
cbctitle :: Interval -> Text
cbcqueries :: [CBCSubreportSpec DisplayName]
cbcaccum :: BalanceAccumulation
..} opts :: CliOpts
opts@CliOpts{reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec, rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
    ReportSpec -> Journal -> IO ()
warnIfLargeMultiPeriodReport ReportSpec
rspec Journal
j
    if CliOpts -> Bool
chartRequested CliOpts
opts
    then CliOpts -> Maybe Text -> Chart -> IO ()
writeChart CliOpts
opts (Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ CompoundPeriodicReport DisplayName MixedAmount -> Text
render (CompoundPeriodicReport DisplayName MixedAmount -> Text)
-> CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a b. (a -> b) -> a -> b
$ Map Text AmountStyle
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundPeriodicReport DisplayName MixedAmount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles CompoundPeriodicReport DisplayName MixedAmount
cbr) (Chart -> IO ()) -> Chart -> IO ()
forall a b. (a -> b) -> a -> b
$ (Text -> Maybe AccountType)
-> [Maybe AccountType]
-> ReportOpts
-> CompoundPeriodicReport DisplayName MixedAmount
-> Chart
compoundBalanceReportAsChart (Journal -> Text -> Maybe AccountType
journalAccountType Journal
j) [Maybe AccountType]
sectiontypes ReportOpts
ropts' (CompoundPeriodicReport DisplayName MixedAmount -> Chart)
-> CompoundPeriodicReport DisplayName MixedAmount -> Chart
forall a b. (a -> b) -> a -> b
$ Map Text AmountStyle
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundPeriodicReport DisplayName MixedAmount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles CompoundPeriodicReport DisplayName MixedAmount
cbr
    else CliOpts -> Text -> IO ()
writeOutputLazyText CliOpts
opts (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ CompoundPeriodicReport DisplayName MixedAmount -> Text
render (CompoundPeriodicReport DisplayName MixedAmount -> Text)
-> CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a b. (a -> b) -> a -> b
$ Map Text AmountStyle
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundPeriodicReport DisplayName MixedAmount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles CompoundPeriodicReport DisplayName MixedAmount
cbr
  where
    styles :: Map Text AmountStyle
styles = ReportOpts -> Journal -> Map Text AmountStyle
balanceReportStyles ReportOpts
ropts Journal
j
    ropts :: ReportOpts
ropts = ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec
    -- use the default balance type for this report, unless the user overrides
    mbalanceAccumulationOverride :: Maybe BalanceAccumulation
mbalanceAccumulationOverride = RawOpts -> Maybe BalanceAccumulation
balanceAccumulationOverride RawOpts
rawopts
    balanceaccumulation :: BalanceAccumulation
balanceaccumulation = BalanceAccumulation
-> Maybe BalanceAccumulation -> BalanceAccumulation
forall a. a -> Maybe a -> a
fromMaybe BalanceAccumulation
cbcaccum Maybe BalanceAccumulation
mbalanceAccumulationOverride
    -- Set balance type in the report options.
    ropts' :: ReportOpts
ropts' = ReportOpts
ropts{balanceaccum_=balanceaccumulation}
    tr :: Text -> Text
tr = Translations -> Text -> Text
I18n.tr (ReportOpts -> Translations
translations_ ReportOpts
ropts)

    -- make a CompoundBalanceReport. The default heading is the auto-generated
    -- title; --title=TEXT overrides it (and =empty suppresses).
    -- --subreport-titles=A|B|... overrides per-subreport titles.
    cbr' :: CompoundPeriodicReport DisplayName MixedAmount
cbr' = ReportSpec
-> Journal
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
forall a.
ReportSpec
-> Journal
-> [CBCSubreportSpec a]
-> CompoundPeriodicReport a MixedAmount
compoundBalanceReport ReportSpec
rspec{_rsReportOpts=ropts'} Journal
j [CBCSubreportSpec DisplayName]
cbcqueries
    cbr :: CompoundPeriodicReport DisplayName MixedAmount
cbr  = ReportOpts
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundPeriodicReport DisplayName MixedAmount
forall a b.
ReportOpts
-> CompoundPeriodicReport a b -> CompoundPeriodicReport a b
applySubreportTitles ReportOpts
ropts' (CompoundPeriodicReport DisplayName MixedAmount
 -> CompoundPeriodicReport DisplayName MixedAmount)
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundPeriodicReport DisplayName MixedAmount
forall a b. (a -> b) -> a -> b
$
           CompoundPeriodicReport DisplayName MixedAmount
cbr'{cbrTitle = effectiveTitle ropts' $ compoundBalanceReportTitle spec ropts mbalanceAccumulationOverride cbr'
               ,cbrSubreports = [ (tr t, r, b) | (t, r, b) <- cbrSubreports cbr' ]}

    sectiontypes :: [Maybe AccountType]
sectiontypes = [CBCSubreportSpec DisplayName] -> [Maybe AccountType]
forall a. [CBCSubreportSpec a] -> [Maybe AccountType]
compoundBalanceSectionTypes [CBCSubreportSpec DisplayName]
cbcqueries

    -- render appropriately
    render :: CompoundPeriodicReport DisplayName MixedAmount -> Text
render = case CliOpts -> [Char]
outputFormatFromOpts CliOpts
opts of
      [Char]
"txt"  -> ReportOpts
-> CompoundPeriodicReport DisplayName MixedAmount -> Text
compoundBalanceReportAsText ReportOpts
ropts'
      [Char]
"csv"  -> CSV -> Text
printCSV (CSV -> Text)
-> (CompoundPeriodicReport DisplayName MixedAmount -> CSV)
-> CompoundPeriodicReport DisplayName MixedAmount
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> CSV
compoundBalanceReportAsCsv ReportOpts
ropts' [CBCSubreportSpec DisplayName]
cbcqueries
      [Char]
"tsv"  -> CSV -> Text
printTSV (CSV -> Text)
-> (CompoundPeriodicReport DisplayName MixedAmount -> CSV)
-> CompoundPeriodicReport DisplayName MixedAmount
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> CSV
compoundBalanceReportAsCsv ReportOpts
ropts' [CBCSubreportSpec DisplayName]
cbcqueries
      [Char]
"html" -> (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text)
-> (CompoundPeriodicReport DisplayName MixedAmount -> Text)
-> CompoundPeriodicReport DisplayName MixedAmount
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MarkupM () -> Text
htmlAsLazyText (MarkupM () -> Text)
-> (CompoundPeriodicReport DisplayName MixedAmount -> MarkupM ())
-> CompoundPeriodicReport DisplayName MixedAmount
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> MarkupM ()
compoundBalanceReportAsHtml ReportOpts
ropts' [CBCSubreportSpec DisplayName]
cbcqueries
      [Char]
"fods" -> TextEncoding
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
printFods TextEncoding
IO.localeEncoding (Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text)
-> (CompoundPeriodicReport DisplayName MixedAmount
    -> Map Text ((Int, Int), [[Cell NumLines Text]]))
-> CompoundPeriodicReport DisplayName MixedAmount
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                (((Int, Int), NonEmpty [Cell NumLines Text])
 -> ((Int, Int), [[Cell NumLines Text]]))
-> Map Text ((Int, Int), NonEmpty [Cell NumLines Text])
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall a b. (a -> b) -> Map Text a -> Map Text b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((NonEmpty [Cell NumLines Text] -> [[Cell NumLines Text]])
-> ((Int, Int), NonEmpty [Cell NumLines Text])
-> ((Int, Int), [[Cell NumLines Text]])
forall b c a. (b -> c) -> (a, b) -> (a, c)
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second NonEmpty [Cell NumLines Text] -> [[Cell NumLines Text]]
forall a. NonEmpty a -> [a]
NonEmpty.toList) (Map Text ((Int, Int), NonEmpty [Cell NumLines Text])
 -> Map Text ((Int, Int), [[Cell NumLines Text]]))
-> (CompoundPeriodicReport DisplayName MixedAmount
    -> Map Text ((Int, Int), NonEmpty [Cell NumLines Text]))
-> CompoundPeriodicReport DisplayName MixedAmount
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text
 -> ((Int, Int), NonEmpty [Cell NumLines Text])
 -> Map Text ((Int, Int), NonEmpty [Cell NumLines Text]))
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
-> Map Text ((Int, Int), NonEmpty [Cell NumLines Text])
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Text
-> ((Int, Int), NonEmpty [Cell NumLines Text])
-> Map Text ((Int, Int), NonEmpty [Cell NumLines Text])
forall k a. k -> a -> Map k a
Map.singleton ((Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
 -> Map Text ((Int, Int), NonEmpty [Cell NumLines Text]))
-> (CompoundPeriodicReport DisplayName MixedAmount
    -> (Text, ((Int, Int), NonEmpty [Cell NumLines Text])))
-> CompoundPeriodicReport DisplayName MixedAmount
-> Map Text ((Int, Int), NonEmpty [Cell NumLines Text])
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                AmountFormat
-> Text
-> Maybe Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
compoundBalanceReportAsSpreadsheet
                    AmountFormat
oneLineNoCostFmt Text
"Account" (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"") ReportOpts
ropts' [CBCSubreportSpec DisplayName]
cbcqueries
      [Char]
"json" -> CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a. ToJSON a => a -> Text
toJsonText
      [Char]
x      -> [Char] -> CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a. [Char] -> a
error' ([Char] -> CompoundPeriodicReport DisplayName MixedAmount -> Text)
-> [Char] -> CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char]
unsupportedOutputFormatError [Char]
x

-- | The title of a compound balance report: the interval and report
-- name, the dates, a note when the accumulation mode was overridden or
-- the calculation is not the plain one, and the valuation. The report
-- options are the command line's, with any accumulation override given
-- separately, since the title says which it was.
compoundBalanceReportTitle ::
  CompoundBalanceCommandSpec -> ReportOpts -> Maybe BalanceAccumulation -> CompoundPeriodicReport a b -> T.Text
compoundBalanceReportTitle :: forall a b.
CompoundBalanceCommandSpec
-> ReportOpts
-> Maybe BalanceAccumulation
-> CompoundPeriodicReport a b
-> Text
compoundBalanceReportTitle CompoundBalanceCommandSpec{cbctitle :: CompoundBalanceCommandSpec -> Interval -> Text
cbctitle=Interval -> Text
cbctitle, cbcaccum :: CompoundBalanceCommandSpec -> BalanceAccumulation
cbcaccum=BalanceAccumulation
cbcaccum} ReportOpts{Bool
Int
[Text]
[Status]
SortSpec
Maybe Int
Maybe Text
Maybe NormalSign
Maybe ConversionOp
Maybe ValuationType
Interval
Period
DepthSpec
AccountListMode
BalanceAccumulation
BalanceCalculation
Layout
PeriodTitles
Translations
StringFormat
balanceaccum_ :: ReportOpts -> BalanceAccumulation
translations_ :: ReportOpts -> Translations
period_ :: Period
interval_ :: Interval
statuses_ :: [Status]
conversionop_ :: Maybe ConversionOp
value_ :: Maybe ValuationType
infer_prices_ :: Bool
depth_ :: DepthSpec
fold_depth_ :: Maybe Int
no_elide_ :: Bool
date2_ :: Bool
empty_ :: Bool
full_names_ :: Bool
real_ :: Bool
format_ :: StringFormat
balance_base_url_ :: Maybe Text
pretty_ :: Bool
querystring_ :: [Text]
average_ :: Bool
related_ :: Bool
sortspec_ :: SortSpec
txn_dates_ :: Bool
balancecalc_ :: BalanceCalculation
balanceaccum_ :: BalanceAccumulation
budgetpat_ :: Maybe Text
accountlistmode_ :: AccountListMode
drop_ :: Int
declared_ :: Bool
row_total_ :: Bool
no_total_ :: Bool
summary_only_ :: Bool
show_costs_ :: Bool
sort_amount_ :: Bool
percent_ :: Bool
invert_ :: Bool
normalbalance_ :: Maybe NormalSign
color_ :: Bool
transpose_ :: Bool
layout_ :: Layout
period_titles_ :: PeriodTitles
title_ :: Maybe Text
subreport_titles_ :: Maybe Text
translations_ :: Translations
accountlistmode_ :: ReportOpts -> AccountListMode
average_ :: ReportOpts -> Bool
balance_base_url_ :: ReportOpts -> Maybe Text
balancecalc_ :: ReportOpts -> BalanceCalculation
budgetpat_ :: ReportOpts -> Maybe Text
color_ :: ReportOpts -> Bool
conversionop_ :: ReportOpts -> Maybe ConversionOp
date2_ :: ReportOpts -> Bool
declared_ :: ReportOpts -> Bool
depth_ :: ReportOpts -> DepthSpec
drop_ :: ReportOpts -> Int
empty_ :: ReportOpts -> Bool
fold_depth_ :: ReportOpts -> Maybe Int
format_ :: ReportOpts -> StringFormat
full_names_ :: ReportOpts -> Bool
infer_prices_ :: ReportOpts -> Bool
interval_ :: ReportOpts -> Interval
invert_ :: ReportOpts -> Bool
layout_ :: ReportOpts -> Layout
no_elide_ :: ReportOpts -> Bool
no_total_ :: ReportOpts -> Bool
normalbalance_ :: ReportOpts -> Maybe NormalSign
percent_ :: ReportOpts -> Bool
period_ :: ReportOpts -> Period
period_titles_ :: ReportOpts -> PeriodTitles
pretty_ :: ReportOpts -> Bool
querystring_ :: ReportOpts -> [Text]
real_ :: ReportOpts -> Bool
related_ :: ReportOpts -> Bool
row_total_ :: ReportOpts -> Bool
show_costs_ :: ReportOpts -> Bool
sort_amount_ :: ReportOpts -> Bool
sortspec_ :: ReportOpts -> SortSpec
statuses_ :: ReportOpts -> [Status]
subreport_titles_ :: ReportOpts -> Maybe Text
summary_only_ :: ReportOpts -> Bool
title_ :: ReportOpts -> Maybe Text
transpose_ :: ReportOpts -> Bool
txn_dates_ :: ReportOpts -> Bool
value_ :: ReportOpts -> Maybe ValuationType
..} Maybe BalanceAccumulation
mbalanceAccumulationOverride CompoundPeriodicReport a b
cbr =
  -- TRANSLATORS: the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends".
  -- {clarification} brings its own leading space when present.
  Text -> [(Text, Text)] -> Text
trf Text
"{report} {dates}{clarification}{valuation}"
    [ (Text
"report",        Text -> Text
tr (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Interval -> Text
cbctitle (Interval -> Text) -> Interval -> Text
forall a b. (a -> b) -> a -> b
$ Interval -> Interval
titleInterval Interval
interval_)
    , (Text
"dates",         Text
titledatestr)
    , (Text
"clarification", Text -> (Text -> Text) -> Maybe Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) Maybe Text
mtitleclarification)
    , (Text
"valuation",     Text
valuationdesc)
    ]
  where
    tr :: Text -> Text
tr  = Translations -> Text -> Text
I18n.tr  Translations
translations_
    trf :: Text -> [(Text, Text)] -> Text
trf = Translations -> Text -> [(Text, Text)] -> Text
I18n.trf Translations
translations_
    balanceaccumulation :: BalanceAccumulation
balanceaccumulation = BalanceAccumulation
-> Maybe BalanceAccumulation -> BalanceAccumulation
forall a. a -> Maybe a -> a
fromMaybe BalanceAccumulation
cbcaccum Maybe BalanceAccumulation
mbalanceAccumulationOverride

    -- XXX #1078 the title of ending balance reports
    -- (Historical) should mention the end date(s) shown as
    -- column heading(s) (not the date span of the transactions).
    -- Also the dates should not be simplified (it should show
    -- "2008/01/01-2008/12/31", not "2008").
    titledatestr :: Text
titledatestr = case BalanceAccumulation
balanceaccumulation of
        BalanceAccumulation
Historical -> [Day] -> Text
showEndDates [Day]
enddates
        BalanceAccumulation
_          -> DateSpan -> Text
showDateSpan DateSpan
columnsspan
      where
        enddates :: [Day]
enddates = (Day -> Day) -> [Day] -> [Day]
forall a b. (a -> b) -> [a] -> [b]
map (Integer -> Day -> Day
addDays (-Integer
1)) ([Day] -> [Day]) -> ([DateSpan] -> [Day]) -> [DateSpan] -> [Day]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DateSpan -> Maybe Day) -> [DateSpan] -> [Day]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe DateSpan -> Maybe Day
spanEnd ([DateSpan] -> [Day]) -> [DateSpan] -> [Day]
forall a b. (a -> b) -> a -> b
$ CompoundPeriodicReport a b -> [DateSpan]
forall a b. CompoundPeriodicReport a b -> [DateSpan]
cbrDates CompoundPeriodicReport a b
cbr  -- these spans will always have a definite end date
        -- the span the columns cover: the requested span, widened to whole intervals
        columnsspan :: DateSpan
columnsspan = [DateSpan] -> DateSpan
spansSpan ([DateSpan] -> DateSpan) -> [DateSpan] -> DateSpan
forall a b. (a -> b) -> a -> b
$ CompoundPeriodicReport a b -> [DateSpan]
forall a b. CompoundPeriodicReport a b -> [DateSpan]
cbrDates CompoundPeriodicReport a b
cbr

    -- when user overrides, add an indication to the report title
    -- Do we need to deal with overridden BalanceCalculation?
    mtitleclarification :: Maybe Text
mtitleclarification = case (BalanceCalculation
balancecalc_, BalanceAccumulation
balanceaccumulation, Maybe BalanceAccumulation
mbalanceAccumulationOverride) of
        (BalanceCalculation
CalcValueChange, BalanceAccumulation
PerPeriod,  Maybe BalanceAccumulation
_              ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Period-End Value Changes)"
        (BalanceCalculation
CalcValueChange, BalanceAccumulation
Cumulative, Maybe BalanceAccumulation
_              ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Cumulative Period-End Value Changes)"
        (BalanceCalculation
CalcGain,        BalanceAccumulation
PerPeriod,  Maybe BalanceAccumulation
_              ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Incremental Gain)"
        (BalanceCalculation
CalcGain,        BalanceAccumulation
Cumulative, Maybe BalanceAccumulation
_              ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Cumulative Gain)"
        (BalanceCalculation
CalcGain,        BalanceAccumulation
Historical, Maybe BalanceAccumulation
_              ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Historical Gain)"
        (BalanceCalculation
_,               BalanceAccumulation
_,          Just BalanceAccumulation
PerPeriod ) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Balance Changes)"
        (BalanceCalculation
_,               BalanceAccumulation
_,          Just BalanceAccumulation
Cumulative) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Cumulative Ending Balances)"
        (BalanceCalculation
_,               BalanceAccumulation
_,          Just BalanceAccumulation
Historical) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
tr Text
"(Historical Ending Balances)"
        (BalanceCalculation, BalanceAccumulation,
 Maybe BalanceAccumulation)
_                                              -> Maybe Text
forall a. Maybe a
Nothing

    valuationdesc :: Text
valuationdesc =
      (case Maybe ConversionOp
conversionop_ of
           Just ConversionOp
ToCost -> Text -> Text
tr Text
", converted to cost"
           Maybe ConversionOp
_           -> Text
"")
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (case Maybe ValuationType
value_ of
           Just (AtThen Maybe Text
_mc)       -> Text -> Text
tr Text
", valued at posting date"
           Just (AtEnd Maybe Text
_mc) | Bool
changingValuation -> Text
""
           Just (AtEnd Maybe Text
_mc)        -> Text -> Text
tr Text
", valued at period ends"
           Just (AtNow Maybe Text
_mc)        -> Text -> Text
tr Text
", current value"
           Just (AtDate Day
today Maybe Text
_mc) -> Text -> [(Text, Text)] -> Text
trf Text
", valued at {date}" [(Text
"date", Day -> Text
showDate Day
today)]
           Maybe ValuationType
Nothing                 -> Text
"")

    changingValuation :: Bool
changingValuation = case (BalanceCalculation
balancecalc_, BalanceAccumulation
balanceaccum_) of
        (BalanceCalculation
CalcValueChange, BalanceAccumulation
PerPeriod)  -> Bool
True
        (BalanceCalculation
CalcValueChange, BalanceAccumulation
Cumulative) -> Bool
True
        (BalanceCalculation, BalanceAccumulation)
_                             -> Bool
False

-- | Apply --subreport-titles overrides to a compound report's subreports.
-- A `|`-separated argument overrides the corresponding subreport titles, in
-- order; subreports beyond the supplied list keep their default title. An
-- explicit empty argument suppresses all default subreport titles.
applySubreportTitles :: ReportOpts -> CompoundPeriodicReport a b -> CompoundPeriodicReport a b
applySubreportTitles :: forall a b.
ReportOpts
-> CompoundPeriodicReport a b -> CompoundPeriodicReport a b
applySubreportTitles ReportOpts
ropts cbr :: CompoundPeriodicReport a b
cbr@CompoundPeriodicReport{cbrSubreports :: forall a b.
CompoundPeriodicReport a b -> [(Text, PeriodicReport a b, Bool)]
cbrSubreports=[(Text, PeriodicReport a b, Bool)]
subs} =
  case ReportOpts -> Maybe Text
subreport_titles_ ReportOpts
ropts of
    Maybe Text
Nothing -> CompoundPeriodicReport a b
cbr
    Just Text
s
      | Text -> Bool
T.null Text
s  -> CompoundPeriodicReport a b
cbr{cbrSubreports = map (\(Text
_,PeriodicReport a b
r,Bool
b) -> (Text
"", PeriodicReport a b
r, Bool
b)) subs}
      | Bool
otherwise ->
          let custom :: [Text]
custom = HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"|" Text
s
              replace :: Int -> (Text, b, c) -> (Text, b, c)
replace Int
i (Text
old,b
r,c
b) = (Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
old ([Text] -> Int -> Maybe Text
forall a. [a] -> Int -> Maybe a
atMay [Text]
custom Int
i), b
r, c
b)
          in  CompoundPeriodicReport a b
cbr{cbrSubreports = zipWith replace [0..] subs}

-- | Each section's account type, from its query, if that is a simple type query (for colouring charts).
compoundBalanceSectionTypes :: [CBCSubreportSpec a] -> [Maybe AccountType]
compoundBalanceSectionTypes :: forall a. [CBCSubreportSpec a] -> [Maybe AccountType]
compoundBalanceSectionTypes [CBCSubreportSpec a]
specs = [case CBCSubreportSpec a -> Query
forall a. CBCSubreportSpec a -> Query
cbcsubreportquery CBCSubreportSpec a
q of Type (AccountType
t:[AccountType]
_) -> AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
t; Query
_ -> Maybe AccountType
forall a. Maybe a
Nothing | CBCSubreportSpec a
q <- [CBCSubreportSpec a]
specs]

-- | Merge the intervals that a report title does not distinguish:
-- twelve months is a year, and a quarter is three months.
titleInterval :: Interval -> Interval
titleInterval :: Interval -> Interval
titleInterval = \case
  Months Int
12  -> Int -> Interval
Years Int
1
  Quarters Int
1 -> Int -> Interval
Months Int
3
  Quarters Int
2 -> Int -> Interval
Months Int
6
  Interval
i          -> Interval
i

-- | Summarise one or more (inclusive) end dates, in a way that's
-- visually different from showDateSpan, suggesting discrete end dates
-- rather than a continuous span.
showEndDates :: [Day] -> T.Text
showEndDates :: [Day] -> Text
showEndDates [Day]
es = case [Day]
es of
  -- cf showPeriod
  (Day
e:Day
_:[Day]
_) -> Day -> Text
showDate Day
e Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".." Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Day -> Text
showDate ([Day] -> Day
forall a. HasCallStack => [a] -> a
last [Day]
es)
  [Day
e]     -> Day -> Text
showDate Day
e
  []      -> Text
""

-- | Render a compound balance report as plain text suitable for console output.
{- Eg:
Balance Sheet

             ||  2017/12/31    Total  Average
=============++===============================
 Assets      ||
-------------++-------------------------------
 assets:b    ||           1        1        1
-------------++-------------------------------
             ||           1        1        1
=============++===============================
 Liabilities ||
-------------++-------------------------------
-------------++-------------------------------
             ||
=============++===============================
 Total       ||           1        1        1

-}
compoundBalanceReportAsText :: ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> TL.Text
compoundBalanceReportAsText :: ReportOpts
-> CompoundPeriodicReport DisplayName MixedAmount -> Text
compoundBalanceReportAsText ReportOpts
ropts (CompoundPeriodicReport Text
title [DateSpan]
_colspans [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports PeriodicReportRow () MixedAmount
totalsrow) =
  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
<>
    ReportOpts -> Table Text Text WideBuilder -> Builder
multiBalanceReportTableAsText ReportOpts
ropts Table Text Text WideBuilder
bigtablewithtotalsrow
  where
    titleBuilder :: Builder
titleBuilder | Text -> Bool
T.null Text
title = Builder
forall a. Monoid a => a
mempty
                 | Bool
otherwise    = Text -> Builder
TB.fromText Text
title Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Text -> Builder
TB.fromText Text
"\n\n"
    bigtable :: Table Text Text WideBuilder
bigtable =
      case ((Text, PeriodicReport DisplayName MixedAmount, Bool)
 -> Table Text Text WideBuilder)
-> [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
-> [Table Text Text WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map (ReportOpts
-> (Text, PeriodicReport DisplayName MixedAmount, Bool)
-> Table Text Text WideBuilder
forall {c}.
ReportOpts
-> (Text, PeriodicReport DisplayName MixedAmount, c)
-> Table Text Text WideBuilder
subreportAsTable ReportOpts
ropts) [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports of
        []   -> Table Text Text WideBuilder
forall rh ch a. Table rh ch a
Tabular.empty
        Table Text Text WideBuilder
r:[Table Text Text WideBuilder]
rs -> (Table Text Text WideBuilder
 -> Table Text Text WideBuilder -> Table Text Text WideBuilder)
-> Table Text Text WideBuilder
-> [Table Text Text WideBuilder]
-> Table Text Text WideBuilder
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
List.foldl' (Properties
-> Table Text Text WideBuilder
-> Table Text Text WideBuilder
-> Table Text Text WideBuilder
forall rh ch a ch2.
Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a
concatTables Properties
tableInterSubreportBorder) Table Text Text WideBuilder
r [Table Text Text WideBuilder]
rs
    bigtablewithtotalsrow :: Table Text Text WideBuilder
bigtablewithtotalsrow =
      if ReportOpts -> Bool
no_total_ ReportOpts
ropts Bool -> Bool -> Bool
|| [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
      then Table Text Text WideBuilder
bigtable
      else Properties
-> Table Text Text WideBuilder
-> Table Text [ZonkAny 0] WideBuilder
-> Table Text Text WideBuilder
forall rh ch a ch2.
Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a
concatTables Properties
tableGrandTotalsTopBorder Table Text Text WideBuilder
bigtable Table Text [ZonkAny 0] WideBuilder
forall {a}. Table Text [a] WideBuilder
totalstable
        where
          -- Append the report's grand column totals at the bottom of the table.
          -- Note "row" is confusingly overloaded here; *Report rows, Table rows,
          -- and visually apparent table rows are all distinct.
          -- With multiple currencies, in some layout modes, the column totals (a single report row)
          -- occupy multiple lines, which currently we put into multiple table rows,
          -- for convenience I guess, borderless so they look like a single visual row.
          --
          -- multiBalanceRowAsText gets a matrix of each line of each column total rendered as text
          -- (actually as WideBuilders), in line-major-order:
          --  [
          --   [COL1LINE1, COL2LINE1]
          --   [COL1LINE2, COL2LINE2]
          --  ]
          coltotalslines :: [[WideBuilder]]
coltotalslines = ReportOpts
-> [Text] -> PeriodicReportRow () MixedAmount -> [[WideBuilder]]
forall a.
ReportOpts
-> [Text] -> PeriodicReportRow a MixedAmount -> [[WideBuilder]]
multiBalanceRowAsText ReportOpts
ropts [Text]
allCommodities PeriodicReportRow () MixedAmount
totalsrow
          totalstable :: Table Text [a] WideBuilder
totalstable = Header Text
-> Header [a] -> [[WideBuilder]] -> Table Text [a] WideBuilder
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
            (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Text] -> Header Text) -> [Header Text] -> Header Text
forall a b. (a -> b) -> a -> b
$ (Text -> Header Text) -> [Text] -> [Header Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Header Text
forall h. h -> Header h
Header ([Text] -> [Header Text]) -> [Text] -> [Header Text]
forall a b. (a -> b) -> a -> b
$ Translations -> Text -> Text
I18n.tr (ReportOpts -> Translations
translations_ ReportOpts
ropts) Text
"Net:" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Int -> Text -> [Text]
forall a. Int -> a -> [a]
replicate ([[WideBuilder]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[WideBuilder]]
coltotalslines Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) Text
"")  -- row headers
            ([a] -> Header [a]
forall h. h -> Header h
Header [])     -- column headers, concatTables will discard these
            [[WideBuilder]]
coltotalslines  -- cell values         

    allCommodities :: [Text]
allCommodities = [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> [Text]
forall text a bool.
[(text, PeriodicReport a MixedAmount, bool)] -> [Text]
allCommoditiesFromSubreports [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports

    -- | Convert a named multi balance report to a table suitable for
    -- concatenating with others to make a compound balance report table.
    -- An empty subreport title is omitted entirely (no title row above the data).
    subreportAsTable :: ReportOpts
-> (Text, PeriodicReport DisplayName MixedAmount, c)
-> Table Text Text WideBuilder
subreportAsTable ReportOpts
ropts1 (Text
title1, PeriodicReport DisplayName MixedAmount
r, c
_) = Table Text Text WideBuilder
tablewithtitle
      where
        Table Header Text
lefthdrs Header Text
tophdrs [[WideBuilder]]
cells =
            ReportOpts
-> [Text]
-> PeriodicReport DisplayName MixedAmount
-> Table Text Text WideBuilder
multiBalanceReportAsPartTable ReportOpts
ropts1 [Text]
allCommodities PeriodicReport DisplayName MixedAmount
r
        tablewithtitle :: Table Text Text WideBuilder
tablewithtitle
          | Text -> Bool
T.null Text
title1 = Header Text
-> Header Text -> [[WideBuilder]] -> Table Text Text WideBuilder
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table Header Text
lefthdrs Header Text
tophdrs [[WideBuilder]]
cells
          | Bool
otherwise     = Header Text
-> Header Text -> [[WideBuilder]] -> Table Text Text WideBuilder
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
              (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
tableSubreportTitleBottomBorder [Text -> Header Text
forall h. h -> Header h
Header Text
title1, Header Text
lefthdrs])  -- row headers
              Header Text
tophdrs       -- column headers
              ([][WideBuilder] -> [[WideBuilder]] -> [[WideBuilder]]
forall a. a -> [a] -> [a]
:[[WideBuilder]]
cells)    -- cell values

    tableSubreportTitleBottomBorder :: Properties
tableSubreportTitleBottomBorder = Properties
SingleLine
    tableInterSubreportBorder :: Properties
tableInterSubreportBorder       = Properties
DoubleLine
    tableGrandTotalsTopBorder :: Properties
tableGrandTotalsTopBorder       = Properties
DoubleLine

-- | Render a compound balance report as CSV.
-- Subreports' CSV is concatenated, with the headings rows replaced by a
-- subreport title row, and an overall title row, one headings row, and an
-- optional overall totals row is added.
compoundBalanceReportAsCsv ::
  ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount -> CSV
compoundBalanceReportAsCsv :: ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> CSV
compoundBalanceReportAsCsv ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr =
    let spreadsheet :: NonEmpty [Cell NumLines Text]
spreadsheet =
            ((Int, Int), NonEmpty [Cell NumLines Text])
-> NonEmpty [Cell NumLines Text]
forall a b. (a, b) -> b
snd (((Int, Int), NonEmpty [Cell NumLines Text])
 -> NonEmpty [Cell NumLines Text])
-> ((Int, Int), NonEmpty [Cell NumLines Text])
-> NonEmpty [Cell NumLines Text]
forall a b. (a -> b) -> a -> b
$ (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
-> ((Int, Int), NonEmpty [Cell NumLines Text])
forall a b. (a, b) -> b
snd ((Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
 -> ((Int, Int), NonEmpty [Cell NumLines Text]))
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
-> ((Int, Int), NonEmpty [Cell NumLines Text])
forall a b. (a -> b) -> a -> b
$
            AmountFormat
-> Text
-> Maybe Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
compoundBalanceReportAsSpreadsheet
                AmountFormat
machineFmt Text
"Account" Maybe Text
forall a. Maybe a
Nothing ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr
        title :: Text
title = CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a b. CompoundPeriodicReport a b -> Text
cbrTitle CompoundPeriodicReport DisplayName MixedAmount
cbr
        titleRows :: [[Cell NumLines Text]]
titleRows | Text -> Bool
T.null Text
title = []
                  | Bool
otherwise =
                      [[Cell NumLines Text] -> Cell NumLines Text -> [Cell NumLines Text]
forall border text a.
(Lines border, Monoid text) =>
[a] -> Cell border text -> [Cell border text]
Spr.horizontalSpan (NonEmpty [Cell NumLines Text] -> [Cell NumLines Text]
forall a. NonEmpty a -> a
NonEmpty.head NonEmpty [Cell NumLines Text]
spreadsheet)
                         (Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell Text
title)]
    in  [[Cell NumLines Text]] -> CSV
forall (f :: * -> *) border text.
Functor f =>
[f (Cell border text)] -> [f text]
Spr.rawTableContent ([[Cell NumLines Text]] -> CSV) -> [[Cell NumLines Text]] -> CSV
forall a b. (a -> b) -> a -> b
$
        [[Cell NumLines Text]]
titleRows [[Cell NumLines Text]]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. [a] -> [a] -> [a]
++ NonEmpty [Cell NumLines Text] -> [[Cell NumLines Text]]
forall a. NonEmpty a -> [a]
NonEmpty.toList NonEmpty [Cell NumLines Text]
spreadsheet

-- | Render a compound balance report as HTML.
compoundBalanceReportAsHtml ::
  ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount -> Html
compoundBalanceReportAsHtml :: ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> MarkupM ()
compoundBalanceReportAsHtml ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr =
  let (Text
title, ((Int, Int)
_fixed, NonEmpty [Cell NumLines Text]
cells)) =
          AmountFormat
-> Text
-> Maybe Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
compoundBalanceReportAsSpreadsheet
              AmountFormat
oneLineNoCostFmt Text
"" (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
nbsp) ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr
  in 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
$ Text -> MarkupM ()
forall a. ToMarkup a => a -> MarkupM ()
preEscapedToHtml (Text -> MarkupM ()) -> Text -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ [(Text, Text)] -> Text
stylesheet ([(Text, Text)] -> Text) -> [(Text, Text)] -> Text
forall a b. (a -> b) -> a -> b
$
      [(Text, Text)]
tableStyle [(Text, Text)] -> [(Text, Text)] -> [(Text, Text)]
forall a. [a] -> [a] -> [a]
++ [
      (Text
"td:nth-child(1)", Text
"white-space:nowrap"),
      (Text
"tr:nth-child(odd) td", Text
"background-color:#eee")
      ]
    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
    Bool -> MarkupM () -> MarkupM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Text -> Bool
T.null Text
title) (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ Text -> MarkupM ()
formatTitle Text
title
    -- Do not use `styledTableHtml` here since that leads to nested `<table>`s.
    MarkupM () -> MarkupM ()
H.table (MarkupM () -> MarkupM ()) -> MarkupM () -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ MarkupM ()
nl MarkupM () -> MarkupM () -> MarkupM ()
forall a. Semigroup a => a -> a -> a
<> (([Cell NumLines (MarkupM ())] -> MarkupM ())
-> NonEmpty [Cell NumLines (MarkupM ())] -> MarkupM ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ [Cell NumLines (MarkupM ())] -> MarkupM ()
forall border.
Lines border =>
[Cell border (MarkupM ())] -> MarkupM ()
formatRow (NonEmpty [Cell NumLines (MarkupM ())] -> MarkupM ())
-> NonEmpty [Cell NumLines (MarkupM ())] -> MarkupM ()
forall a b. (a -> b) -> a -> b
$ ([Cell NumLines Text] -> [Cell NumLines (MarkupM ())])
-> NonEmpty [Cell NumLines Text]
-> NonEmpty [Cell NumLines (MarkupM ())]
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Cell NumLines Text -> Cell NumLines (MarkupM ()))
-> [Cell NumLines Text] -> [Cell NumLines (MarkupM ())]
forall a b. (a -> b) -> [a] -> [b]
map ((Text -> MarkupM ())
-> Cell NumLines Text -> 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 Text -> MarkupM ()
forall a. ToMarkup a => a -> MarkupM ()
toHtml)) NonEmpty [Cell NumLines Text]
cells)

-- | Render a compound balance report as Spreadsheet: the heading row,
-- then each section's title row, body rows, totals rows, and a blank row
-- for whitespace if wanted, then the net total rows.
compoundBalanceReportAsSpreadsheet ::
  AmountFormat -> T.Text -> Maybe T.Text ->
  ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount ->
  (T.Text, ((Int, Int), NonEmpty [Spr.Cell Spr.NumLines T.Text]))
compoundBalanceReportAsSpreadsheet :: AmountFormat
-> Text
-> Maybe Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> (Text, ((Int, Int), NonEmpty [Cell NumLines Text]))
compoundBalanceReportAsSpreadsheet AmountFormat
fmt Text
accountLabel Maybe Text
maybeBlank ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr =
  let
    CompoundBalanceReportParts{[[Cell NumLines Text]]
[(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
[Cell NumLines Text]
cbrpLeadingHeaders :: [Cell NumLines Text]
cbrpDataHeaders :: [Cell NumLines Text]
cbrpSections :: [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
cbrpNetRows :: [[Cell NumLines Text]]
cbrpNetRows :: CompoundBalanceReportParts -> [[Cell NumLines Text]]
cbrpSections :: CompoundBalanceReportParts
-> [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
cbrpDataHeaders :: CompoundBalanceReportParts -> [Cell NumLines Text]
cbrpLeadingHeaders :: CompoundBalanceReportParts -> [Cell NumLines Text]
..} = AmountFormat
-> Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundBalanceReportParts
compoundBalanceReportAsSpreadsheetParts AmountFormat
fmt Text
accountLabel ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr
    dataHeaders :: [Text]
dataHeaders = (Cell NumLines Text -> Text) -> [Cell NumLines Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Cell NumLines Text -> Text
forall border text. Cell border text -> text
Spr.cellContent [Cell NumLines Text]
cbrpDataHeaders
    headerrow :: [Cell NumLines Text]
headerrow =
      [Cell NumLines Text]
cbrpLeadingHeaders [Cell NumLines Text]
-> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. [a] -> [a] -> [a]
++
      (Cell NumLines Text -> [Cell NumLines Text])
-> [Cell NumLines Text] -> [Cell NumLines Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([()] -> Cell NumLines Text -> [Cell NumLines Text]
forall border text a.
(Lines border, Monoid text) =>
[a] -> Cell border text -> [Cell border text]
Spr.horizontalSpan [()]
subColumns) [Cell NumLines Text]
cbrpDataHeaders

    blankrow :: Maybe [Cell NumLines Text]
blankrow =
      (Text -> [Cell NumLines Text])
-> Maybe Text -> Maybe [Cell NumLines Text]
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ([Cell NumLines Text] -> Cell NumLines Text -> [Cell NumLines Text]
forall border text a.
(Lines border, Monoid text) =>
[a] -> Cell border text -> [Cell border text]
Spr.horizontalSpan [Cell NumLines Text]
headerrow (Cell NumLines Text -> [Cell NumLines Text])
-> (Text -> Cell NumLines Text) -> Text -> [Cell NumLines Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Cell NumLines Text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell) Maybe Text
maybeBlank
    subColumns :: [()]
subColumns =
        case ReportOpts -> Layout
layout_ ReportOpts
ropts of
            Layout
LayoutBareWide -> [Text] -> [()]
forall (f :: * -> *) a. Functor f => f a -> f ()
void [Text]
allCommodities
            Layout
_ -> [()]
    allCommodities :: [Text]
allCommodities = [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> [Text]
forall text a bool.
[(text, PeriodicReport a MixedAmount, bool)] -> [Text]
allCommoditiesFromSubreports ([(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> [Text])
-> [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> [Text]
forall a b. (a -> b) -> a -> b
$ CompoundPeriodicReport DisplayName MixedAmount
-> [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
forall a b.
CompoundPeriodicReport a b -> [(Text, PeriodicReport a b, Bool)]
cbrSubreports CompoundPeriodicReport DisplayName MixedAmount
cbr

    sectionrows :: (Text, [[Cell NumLines Text]], [[Cell NumLines Text]])
-> [[Cell NumLines Text]]
sectionrows (Text
subreporttitle, [[Cell NumLines Text]]
bodyrows, [[Cell NumLines Text]]
totalsrows) =
      let
        accountCell :: Cell NumLines Text
accountCell =
            (Text -> Cell NumLines Text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell Text
subreporttitle) {
                Spr.cellStyle = Spr.Body Spr.Total,
                Spr.cellClass = accountClass
            }
        titleRows :: [[Cell NumLines Text]]
titleRows
          | Text -> Bool
T.null Text
subreporttitle = []
          | Bool
otherwise =
              [case ReportOpts -> Layout
layout_ ReportOpts
ropts of
                  Layout
LayoutBareWide ->
                      Cell NumLines Text
accountCell Cell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:
                      (Text -> Cell NumLines Text) -> [Text] -> [Cell NumLines Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell ([Text]
dataHeaders [Text] -> [Text] -> [Text]
forall a b. [a] -> [b] -> [b]
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Text]
allCommodities)
                  Layout
_ -> [Cell NumLines Text] -> Cell NumLines Text -> [Cell NumLines Text]
forall border text a.
(Lines border, Monoid text) =>
[a] -> Cell border text -> [Cell border text]
Spr.horizontalSpan [Cell NumLines Text]
headerrow Cell NumLines Text
accountCell]
      in
        [[Cell NumLines Text]]
titleRows [[Cell NumLines Text]]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. [a] -> [a] -> [a]
++
        [[Cell NumLines Text]]
bodyrows [[Cell NumLines Text]]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. [a] -> [a] -> [a]
++
        [[Cell NumLines Text]]
totalsrows [[Cell NumLines Text]]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. [a] -> [a] -> [a]
++
        Maybe [Cell NumLines Text] -> [[Cell NumLines Text]]
forall a. Maybe a -> [a]
maybeToList Maybe [Cell NumLines Text]
blankrow

  in  (CompoundPeriodicReport DisplayName MixedAmount -> Text
forall a b. CompoundPeriodicReport a b -> Text
cbrTitle CompoundPeriodicReport DisplayName MixedAmount
cbr,
        ((Int
1, Layout -> Int
multiBalanceReportNumHeaderColumns (Layout -> Int) -> Layout -> Int
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Layout
layout_ ReportOpts
ropts),
            [Cell NumLines Text]
headerrow [Cell NumLines Text]
-> [[Cell NumLines Text]] -> NonEmpty [Cell NumLines Text]
forall a. a -> [a] -> NonEmpty a
:| ((Text, [[Cell NumLines Text]], [[Cell NumLines Text]])
 -> [[Cell NumLines Text]])
-> [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
-> [[Cell NumLines Text]]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Text, [[Cell NumLines Text]], [[Cell NumLines Text]])
-> [[Cell NumLines Text]]
sectionrows [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
cbrpSections [[Cell NumLines Text]]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. [a] -> [a] -> [a]
++ [[Cell NumLines Text]]
cbrpNetRows))

-- | The parts of a compound balance report as spreadsheet cells, to be
-- laid out as one table, or as a table with sections as hledger-web does.
data CompoundBalanceReportParts = CompoundBalanceReportParts {
    CompoundBalanceReportParts -> [Cell NumLines Text]
cbrpLeadingHeaders :: [Spr.Cell Spr.NumLines T.Text],
      -- ^ The heading row's first cell(s): the account column's, and the
      --   tidy and bare layouts' extra columns'.
    CompoundBalanceReportParts -> [Cell NumLines Text]
cbrpDataHeaders    :: [Spr.Cell Spr.NumLines T.Text],
      -- ^ Then a heading per data column: each period, linking to the
      --   register for it, then the row total and average when shown.
      --   In the bare-wide layout each of these spans the commodity columns.
    CompoundBalanceReportParts
-> [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
cbrpSections       :: [(T.Text, [[Spr.Cell Spr.NumLines T.Text]], [[Spr.Cell Spr.NumLines T.Text]])],
      -- ^ Each section's title, body rows, and totals rows.
    CompoundBalanceReportParts -> [[Cell NumLines Text]]
cbrpNetRows        :: [[Spr.Cell Spr.NumLines T.Text]]
      -- ^ The net total rows; none when there is one section or no totals.
}

-- | Render a compound balance report's parts as spreadsheet cells. The
-- subreport specs it was made from say how each section's figures link:
-- a section is rendered with its own report options, so that its links
-- say when its figures are negated, and its totals link to the registers
-- of its account types.
compoundBalanceReportAsSpreadsheetParts ::
  AmountFormat -> T.Text ->
  ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount ->
  CompoundBalanceReportParts
compoundBalanceReportAsSpreadsheetParts :: AmountFormat
-> Text
-> ReportOpts
-> [CBCSubreportSpec DisplayName]
-> CompoundPeriodicReport DisplayName MixedAmount
-> CompoundBalanceReportParts
compoundBalanceReportAsSpreadsheetParts AmountFormat
fmt Text
accountLabel ReportOpts
ropts [CBCSubreportSpec DisplayName]
specs CompoundPeriodicReport DisplayName MixedAmount
cbr =
  CompoundBalanceReportParts {
    cbrpLeadingHeaders :: [Cell NumLines Text]
cbrpLeadingHeaders = [Cell NumLines Text]
leadingHeaders,
    cbrpDataHeaders :: [Cell NumLines Text]
cbrpDataHeaders = [Cell NumLines Text]
dataHeaderCells,
    cbrpSections :: [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
cbrpSections = (CBCSubreportSpec DisplayName
 -> (Text, PeriodicReport DisplayName MixedAmount, Bool)
 -> (Text, [[Cell NumLines Text]], [[Cell NumLines Text]]))
-> [CBCSubreportSpec DisplayName]
-> [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
-> [(Text, [[Cell NumLines Text]], [[Cell NumLines Text]])]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith CBCSubreportSpec DisplayName
-> (Text, PeriodicReport DisplayName MixedAmount, Bool)
-> (Text, [[Cell NumLines Text]], [[Cell NumLines Text]])
forall {a} {a} {c}.
CBCSubreportSpec a
-> (a, PeriodicReport DisplayName MixedAmount, c)
-> (a, [[Cell NumLines Text]], [[Cell NumLines Text]])
section [CBCSubreportSpec DisplayName]
specs [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports,
    cbrpNetRows :: [[Cell NumLines Text]]
cbrpNetRows = [[Cell NumLines Text]]
netrows
  }
  where
    CompoundPeriodicReport Text
_ [DateSpan]
colspans [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports PeriodicReportRow () MixedAmount
totalrow = CompoundPeriodicReport DisplayName MixedAmount
cbr
    leadingHeaders :: [Cell NumLines Text]
leadingHeaders =
      Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell Text
accountLabel Cell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:
      case ReportOpts -> Layout
layout_ ReportOpts
ropts of
          Layout
LayoutTidy -> (Text -> Cell NumLines Text) -> [Text] -> [Cell NumLines Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell [Text]
tidyColumnLabels
          Layout
LayoutBare -> [Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell Text
"Commodity"]
          Layout
_ -> []
    -- A period heading links to the register for that period; its text
    -- is the period's end date in a historical report.
    dataHeaderCells :: [Cell NumLines Text]
dataHeaderCells =
      (Bool -> [()]
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ReportOpts -> Layout
layout_ ReportOpts
ropts Layout -> Layout -> Bool
forall a. Eq a => a -> a -> Bool
/= Layout
LayoutTidy) [()] -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a b. [a] -> [b] -> [b]
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>) ([Cell NumLines Text] -> [Cell NumLines Text])
-> [Cell NumLines Text] -> [Cell NumLines Text]
forall a b. (a -> b) -> a -> b
$
      [ (Bool
-> PeriodTitles -> Maybe Text -> [Text] -> DateSpan -> Cell () Text
headerDateSpanCell (ReportOpts -> Bool
date2_ ReportOpts
ropts) (ReportOpts -> PeriodTitles
period_titles_ ReportOpts
ropts) (ReportOpts -> Maybe Text
balance_base_url_ ReportOpts
ropts) (ReportOpts -> [Text]
querystring_ ReportOpts
ropts) DateSpan
spn) {
          Spr.cellBorder = Spr.noBorder,
          -- column headings stay English in these formats, month names included
          Spr.cellContent = reportPeriodName ropts{translations_ = I18n.noTranslations} colspans spn
        }
      | Bool -> Bool
not (ReportOpts -> Bool
summary_only_ ReportOpts
ropts), DateSpan
spn <- [DateSpan]
colspans ] [Cell NumLines Text]
-> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. [a] -> [a] -> [a]
++
      (Bool -> [()]
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ReportOpts -> Bool
multiBalanceHasTotalsColumn ReportOpts
ropts) [()] -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a b. [a] -> [b] -> [b]
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell Text
"Total"]) [Cell NumLines Text]
-> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. [a] -> [a] -> [a]
++
      (Bool -> [()]
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ReportOpts -> Bool
average_ ReportOpts
ropts) [()] -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a b. [a] -> [b] -> [b]
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Text -> Cell NumLines Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell Text
"Average"])
    allCommodities :: [Text]
allCommodities = [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> [Text]
forall text a bool.
[(text, PeriodicReport a MixedAmount, bool)] -> [Text]
allCommoditiesFromSubreports [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports

    -- The account type codes a section is selected by, which its totals'
    -- registers need; a section not selected by type gets no such links.
    typeCodes :: Query -> Maybe Text
typeCodes Query
q = case Query
q of
      Type [AccountType]
ts -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (AccountType -> Text) -> [AccountType] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map ([Char] -> Text
T.pack ([Char] -> Text) -> (AccountType -> [Char]) -> AccountType -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountType -> [Char]
forall a. Show a => a -> [Char]
show) [AccountType]
ts
      Query
_       -> Maybe Text
forall a. Maybe a
Nothing
    typeTerm :: Query -> Maybe Text
typeTerm = (Text -> Text) -> Maybe Text -> Maybe Text
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Text
"type:" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Maybe Text -> Maybe Text)
-> (Query -> Maybe Text) -> Query -> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Query -> Maybe Text
typeCodes
    -- Is a section shown with its figures negated, as normally negative
    -- accounts are ?
    negated :: CBCSubreportSpec a -> Bool
negated CBCSubreportSpec a
spec = ReportOpts -> Maybe NormalSign
normalbalance_ (CBCSubreportSpec a -> ReportOpts -> ReportOpts
forall a. CBCSubreportSpec a -> ReportOpts -> ReportOpts
cbcsubreportoptions CBCSubreportSpec a
spec ReportOpts
ropts) Maybe NormalSign -> Maybe NormalSign -> Bool
forall a. Eq a => a -> a -> Bool
== NormalSign -> Maybe NormalSign
forall a. a -> Maybe a
Just NormalSign
NormallyNegative
    unlinked :: [[Cell border text]] -> [[Cell border text]]
unlinked = ([Cell border text] -> [Cell border text])
-> [[Cell border text]] -> [[Cell border text]]
forall a b. (a -> b) -> [a] -> [b]
map ((Cell border text -> Cell border text)
-> [Cell border text] -> [Cell border text]
forall a b. (a -> b) -> [a] -> [b]
map (\Cell border text
c -> Cell border text
c {Spr.cellAnchor = mempty, Spr.cellTitle = mempty}))
    linkedWhen :: Maybe a -> [[Cell border text]] -> [[Cell border text]]
linkedWhen Maybe a
mterm [[Cell border text]]
rows = [[Cell border text]]
-> (a -> [[Cell border text]]) -> Maybe a -> [[Cell border text]]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([[Cell border text]] -> [[Cell border text]]
forall {border} {text}.
[[Cell border text]] -> [[Cell border text]]
unlinked [[Cell border text]]
rows) ([[Cell border text]] -> a -> [[Cell border text]]
forall a b. a -> b -> a
const [[Cell border text]]
rows) Maybe a
mterm

    -- A section's rows link with its type term as well, so that their
    -- registers exclude a subaccount of another type, as the figures do.
    section :: CBCSubreportSpec a
-> (a, PeriodicReport DisplayName MixedAmount, c)
-> (a, [[Cell NumLines Text]], [[Cell NumLines Text]])
section CBCSubreportSpec a
spec (a
subreporttitle, PeriodicReport DisplayName MixedAmount
mbr, c
_increasestotal) = (a
subreporttitle, [[Cell NumLines Text]]
bodyrows, [[Cell NumLines Text]]
totalsrows)
      where
        sropts :: ReportOpts
sropts = CBCSubreportSpec a -> ReportOpts -> ReportOpts
forall a. CBCSubreportSpec a -> ReportOpts -> ReportOpts
cbcsubreportoptions CBCSubreportSpec a
spec ReportOpts
ropts
        sectionterm :: Maybe Text
sectionterm = Query -> Maybe Text
typeTerm (Query -> Maybe Text) -> Query -> Maybe Text
forall a b. (a -> b) -> a -> b
$ CBCSubreportSpec a -> Query
forall a. CBCSubreportSpec a -> Query
cbcsubreportquery CBCSubreportSpec a
spec
        ([[Cell NumLines Text]]
_, [[Cell NumLines Text]]
bodyrows, [[Cell NumLines Text]]
_) =
          AmountFormat
-> ReportOpts
-> [Text]
-> PeriodicReport DisplayName MixedAmount
-> ([[Cell NumLines Text]], [[Cell NumLines Text]],
    [[Cell NumLines Text]])
balanceSubReportAsSpreadsheetParts AmountFormat
fmt
            ReportOpts
sropts{no_total_ = True, querystring_ = maybeToList sectionterm ++ querystring_ sropts}
            [Text]
allCommodities PeriodicReport DisplayName MixedAmount
mbr
        totalsrows :: [[Cell NumLines Text]]
totalsrows
          | ReportOpts -> Bool
no_total_ ReportOpts
ropts = []
          | Bool
otherwise =
              Maybe Text -> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall {a} {border} {text}.
Maybe a -> [[Cell border text]] -> [[Cell border text]]
linkedWhen Maybe Text
sectionterm ([[Cell NumLines Text]] -> [[Cell NumLines Text]])
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a b. (a -> b) -> a -> b
$
              AmountFormat
-> ReportOpts
-> LinkOpts
-> [Text]
-> [Text]
-> [DateSpan]
-> Text
-> PeriodicReportRow () MixedAmount
-> [[Cell NumLines Text]]
forall a.
AmountFormat
-> ReportOpts
-> LinkOpts
-> [Text]
-> [Text]
-> [DateSpan]
-> Text
-> PeriodicReportRow a MixedAmount
-> [[Cell NumLines Text]]
multiBalanceTotalsRows AmountFormat
fmt ReportOpts
sropts (ReportOpts -> [DateSpan] -> LinkOpts
reportLinkOpts ReportOpts
sropts (PeriodicReport DisplayName MixedAmount -> [DateSpan]
forall a b. PeriodicReport a b -> [DateSpan]
prDates PeriodicReport DisplayName MixedAmount
mbr)) (Maybe Text -> [Text]
forall a. Maybe a -> [a]
maybeToList Maybe Text
sectionterm)
                  [Text]
allCommodities (PeriodicReport DisplayName MixedAmount -> [DateSpan]
forall a b. PeriodicReport a b -> [DateSpan]
prDates PeriodicReport DisplayName MixedAmount
mbr) Text
totalRowHeadingSpreadsheet (PeriodicReport DisplayName MixedAmount
-> PeriodicReportRow () MixedAmount
forall a b. PeriodicReport a b -> PeriodicReportRow () b
prTotals PeriodicReport DisplayName MixedAmount
mbr)

    -- The net total's register is that of all the sections' account
    -- types. It shows the net with the opposite sign when a section's
    -- negation is not undone by subtracting it, as an income statement's
    -- revenues are added negated.
    netterm :: Maybe Text
netterm = ([Text] -> Text) -> Maybe [Text] -> Maybe Text
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Text
"type:" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Text -> Text) -> ([Text] -> Text) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Text
T.concat) (Maybe [Text] -> Maybe Text) -> Maybe [Text] -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (CBCSubreportSpec DisplayName -> Maybe Text)
-> [CBCSubreportSpec DisplayName] -> Maybe [Text]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Query -> Maybe Text
typeCodes (Query -> Maybe Text)
-> (CBCSubreportSpec DisplayName -> Query)
-> CBCSubreportSpec DisplayName
-> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CBCSubreportSpec DisplayName -> Query
forall a. CBCSubreportSpec a -> Query
cbcsubreportquery) [CBCSubreportSpec DisplayName]
specs
    netnegated :: Bool
netnegated = (CBCSubreportSpec DisplayName -> Bool)
-> [CBCSubreportSpec DisplayName] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\CBCSubreportSpec DisplayName
spec -> CBCSubreportSpec DisplayName -> Bool
forall {a}. CBCSubreportSpec a -> Bool
negated CBCSubreportSpec DisplayName
spec Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= Bool -> Bool
not (CBCSubreportSpec DisplayName -> Bool
forall {a}. CBCSubreportSpec a -> Bool
cbcsubreportincreasestotal CBCSubreportSpec DisplayName
spec)) [CBCSubreportSpec DisplayName]
specs
    netrows :: [[Cell NumLines Text]]
netrows =
      if ReportOpts -> Bool
no_total_ ReportOpts
ropts Bool -> Bool -> Bool
|| [(Text, PeriodicReport DisplayName MixedAmount, Bool)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Text, PeriodicReport DisplayName MixedAmount, Bool)]
subreports Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 then []
      else
        Maybe Text -> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall {a} {border} {text}.
Maybe a -> [[Cell border text]] -> [[Cell border text]]
linkedWhen Maybe Text
netterm ([[Cell NumLines Text]] -> [[Cell NumLines Text]])
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a b. (a -> b) -> a -> b
$
        AmountFormat
-> ReportOpts
-> LinkOpts
-> [Text]
-> [Text]
-> [DateSpan]
-> Text
-> PeriodicReportRow () MixedAmount
-> [[Cell NumLines Text]]
forall a.
AmountFormat
-> ReportOpts
-> LinkOpts
-> [Text]
-> [Text]
-> [DateSpan]
-> Text
-> PeriodicReportRow a MixedAmount
-> [[Cell NumLines Text]]
multiBalanceTotalsRows AmountFormat
fmt ReportOpts
ropts (ReportOpts -> [DateSpan] -> LinkOpts
reportLinkOpts ReportOpts
ropts [DateSpan]
colspans){loNegated = netnegated}
            (Maybe Text -> [Text]
forall a. Maybe a -> [a]
maybeToList Maybe Text
netterm) [Text]
allCommodities [DateSpan]
colspans Text
"Net:" PeriodicReportRow () MixedAmount
totalrow

-- | All commodities appearing in any of these subreports, sorted.
-- Used as the commodity column order for LayoutBareWide across the whole
-- compound report; it must cover every row rendered, including the totals
-- row, see 'setDisplayCommodityBare' in "Hledger.Cli.Commands.Balance.Internal".
allCommoditiesFromSubreports ::
    [(text, PeriodicReport a MixedAmount, bool)] -> [CommoditySymbol]
allCommoditiesFromSubreports :: forall text a bool.
[(text, PeriodicReport a MixedAmount, bool)] -> [Text]
allCommoditiesFromSubreports =
    Set Text -> [Text]
forall a. Set a -> [a]
Set.toAscList (Set Text -> [Text])
-> ([(text, PeriodicReport a MixedAmount, bool)] -> Set Text)
-> [(text, PeriodicReport a MixedAmount, bool)]
-> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
    ((text, PeriodicReport a MixedAmount, bool) -> Set Text)
-> [(text, PeriodicReport a MixedAmount, bool)] -> Set Text
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(text
_,PeriodicReport a MixedAmount
mbr,bool
_) ->
                (PeriodicReportRow a MixedAmount -> Set Text)
-> [PeriodicReportRow a MixedAmount] -> Set Text
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap ((MixedAmount -> Set Text) -> [MixedAmount] -> Set Text
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap MixedAmount -> Set Text
maCommodities ([MixedAmount] -> Set Text)
-> (PeriodicReportRow a MixedAmount -> [MixedAmount])
-> PeriodicReportRow a MixedAmount
-> Set Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicReportRow a MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts) ([PeriodicReportRow a MixedAmount] -> Set Text)
-> [PeriodicReportRow a MixedAmount] -> Set Text
forall a b. (a -> b) -> a -> b
$ PeriodicReport a MixedAmount -> [PeriodicReportRow a MixedAmount]
forall a b. PeriodicReport a b -> [PeriodicReportRow a b]
prRows PeriodicReport a MixedAmount
mbr)