{-|
Turning reports into charts ("Hledger.Write.Chart"), and the --chart option.

Each adapter here chooses a useful default chart for its report,
so that charts just work without configuration (see doc/SPEC-charts.md, "Smart defaults").
-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}

module Hledger.Cli.Chart (
  chartFlag,
  balanceChartFlag,
  compoundChartFlag,
  chartWidthFlag,
  ChartArg(..),
  parseChartArg,
  chartArg,
  chartArgFor,
  chartRequested,
  chartAsTextForOpts,
  writeChart,
  multiBalanceReportAsChart,
  balanceReportAsChart,
  compoundBalanceReportAsChart,
  accountTransactionsReportAsChart,
  postingsReportAsChart,
  unitAmount,
) where

import Data.List (elemIndex, find, intercalate, isPrefixOf, nub, partition, sort, sortOn, transpose)
import Data.List.Extra (nubSort, splitOn, trim)
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.Map qualified as M
import Data.Maybe (fromMaybe, isJust, mapMaybe)
import Data.Ord (Down(..))
import Data.Set qualified as S
import Control.Applicative ((<|>))
import Control.Monad (when)
import Data.Char (isDigit, toUpper)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Time (Day)
import GHC.IO.Encoding (getLocaleEncoding, textEncodingName)
import Safe (atMay, headMay, readMay)
import System.Console.CmdArgs.Explicit (Flag, flagOpt, flagReq)
import Text.Printf (printf)

import Hledger
import Hledger.Cli.CliOptions (CliOpts(..), outputFormatFromOpts, outputFormats)
import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText)
import Hledger.Utils.I18n qualified as I18n
import Hledger.Write.Chart
import Hledger.Write.Chart.Svg (chartAsSvg, chartAsSvgWith)
import Hledger.Write.Chart.Text
import Hledger.Write.Csv (printCSV, printTSV)
import Hledger.Write.Html (htmlAsLazyText, nl)
import Text.Blaze.Html5 ((!))
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A


-- | The chart kinds that --chart accepts: auto (the default chart for the report),
-- or diverging or grouped (the bar layout for reports with several groups of accounts, ie compound reports' sections;
-- diverging is the default). A kind that doesn't apply to a report is ignored.
chartKinds :: [String]
chartKinds :: [[Char]]
chartKinds = [[Char]
"auto", [Char]
"diverging", [Char]
"grouped"]

-- | The words that --chart accepts before its SCALE amounts, in any order: a chart kind (see 'chartKinds'),
-- and net, which draws the total or net (as a line or marks), which charts otherwise leave out (text charts still show it as a number).
chartWords :: [String]
chartWords :: [[Char]]
chartWords = [[Char]]
chartKinds [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [[Char]
"net"]

-- | What --chart's value says: a chart kind, whether to draw the total or net, and scale amounts.
data ChartArg = ChartArg
  { ChartArg -> [Char]
caKind   :: String
  , ChartArg -> Bool
caNet    :: Bool
  , ChartArg -> [Amount]
caScales :: [Amount]
  }

-- | The --chart[=net,SCALE] option, for commands that can show a chart.
-- It also accepts a KIND, like 'compoundChartFlag', but it is ignored, so not mentioned.
chartFlag :: Flag RawOpts
chartFlag :: Flag RawOpts
chartFlag = [Char] -> [Char] -> Flag RawOpts
chartFlagWith [Char]
"net,SCALE" [Char]
""

-- | The --chart[=KIND,net,SCALE] option, for the balance command, whose charts can group accounts by type.
balanceChartFlag :: Flag RawOpts
balanceChartFlag :: Flag RawOpts
balanceChartFlag = [Char] -> [Char] -> Flag RawOpts
chartFlagWith [Char]
"KIND,net,SCALE"
  [Char]
"KIND: grouped (a bar per account type, side by side). "

-- | The --chart[=KIND,net,SCALE] option, for compound balance commands, whose sections a chart can arrange.
compoundChartFlag :: Flag RawOpts
compoundChartFlag :: Flag RawOpts
compoundChartFlag = [Char] -> [Char] -> Flag RawOpts
chartFlagWith [Char]
"KIND,net,SCALE"
  [Char]
"KIND: diverging (sections above and below zero; the default) or grouped (sections side by side). "

chartFlagWith :: String -> String -> Flag RawOpts
chartFlagWith :: [Char] -> [Char] -> Flag RawOpts
chartFlagWith [Char]
metavar [Char]
kindhelp = [Char]
-> [[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a.
[Char] -> [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagOpt [Char]
"auto" [[Char]
"chart"] Update RawOpts
setchart [Char]
metavar ([Char] -> Flag RawOpts) -> [Char] -> Flag RawOpts
forall a b. (a -> b) -> a -> b
$
  [Char]
"show a chart: instead of the table (txt), above it (html), or as data (csv, tsv, json). "
  [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
kindhelp
  [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"net: also draw the net total (a line, or marks in text charts). "
  [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"SCALE: the amount that fills the chart (eg 1000 or 1000 USD; one per commodity), for comparable charts."
  where
    setchart :: Update RawOpts
setchart [Char]
s RawOpts
opts = ([Char] -> Either [Char] RawOpts)
-> (ChartArg -> Either [Char] RawOpts)
-> Either [Char] ChartArg
-> Either [Char] RawOpts
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> Either [Char] RawOpts
forall a b. a -> Either a b
Left (Either [Char] RawOpts -> ChartArg -> Either [Char] RawOpts
forall a b. a -> b -> a
const (Either [Char] RawOpts -> ChartArg -> Either [Char] RawOpts)
-> Either [Char] RawOpts -> ChartArg -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ 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]
"chart" [Char]
s RawOpts
opts) (Either [Char] ChartArg -> Either [Char] RawOpts)
-> Either [Char] ChartArg -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ Map AccountName AmountStyle -> [Char] -> Either [Char] ChartArg
parseChartArg Map AccountName AmountStyle
forall k a. Map k a
M.empty [Char]
s

-- | Parse the value of --chart: comma-separated parts, which are optional words (an optional chart kind, default auto,
-- and net, in any order), followed by optional scale amounts (see 'setChartScales'), read with these commodity styles
-- (so that eg 10.000 EUR is ten thousand when EUR is written with a decimal comma).
-- Since commas separate the parts, a comma between digits (a decimal comma, or a digit group mark) is an error.
parseChartArg :: M.Map CommoditySymbol AmountStyle -> String -> Either String ChartArg
parseChartArg :: Map AccountName AmountStyle -> [Char] -> Either [Char] ChartArg
parseChartArg Map AccountName AmountStyle
styles [Char]
s
  | [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Char -> Bool
isDigit Char
a Bool -> Bool -> Bool
&& Char
b Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',' Bool -> Bool -> Bool
&& Char -> Bool
isDigit Char
c | (Char
a, Char
b, Char
c) <- [Char] -> [Char] -> [Char] -> [(Char, Char, Char)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [Char]
s (Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
drop Int
1 [Char]
s) (Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
drop Int
2 [Char]
s)] = [Char] -> Either [Char] ChartArg
forall a b. a -> Either a b
Left ([Char] -> Either [Char] ChartArg)
-> [Char] -> Either [Char] ChartArg
forall a b. (a -> b) -> a -> b
$
      [Char]
"--chart's SCALE amounts should be written without a comma (commas separate them; use . as decimal mark, eg 2.5 BTC,"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" and leave out digit group marks or use spaces, eg 10000 EUR or 10 000 EUR), but this was not: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
s
  | Bool
otherwise = do
      let ([[Char]]
ws, [[Char]]
rest) = ([Char] -> Bool) -> [[Char]] -> ([[Char]], [[Char]])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span ([Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
chartWords) ([[Char]] -> ([[Char]], [[Char]]))
-> [[Char]] -> ([[Char]], [[Char]])
forall a b. (a -> b) -> a -> b
$ ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> ([Char] -> Bool) -> [Char] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null) ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ ([Char] -> [Char]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map [Char] -> [Char]
trim ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> [[Char]]
forall a. (Partial, Eq a) => [a] -> [a] -> [[a]]
splitOn [Char]
"," [Char]
s
      kind <- case ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
filter ([Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
chartKinds) [[Char]]
ws of
        []  -> [Char] -> Either [Char] [Char]
forall a b. b -> Either a b
Right [Char]
"auto"
        [[Char]
k] -> [Char] -> Either [Char] [Char]
forall a b. b -> Either a b
Right [Char]
k
        [[Char]]
ks  -> [Char] -> Either [Char] [Char]
forall a b. a -> Either a b
Left ([Char] -> Either [Char] [Char]) -> [Char] -> Either [Char] [Char]
forall a b. (a -> b) -> a -> b
$ [Char]
"--chart's KIND should be given once, but these were given: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]] -> [Char]
forall a. [a] -> [[a]] -> [a]
intercalate [Char]
", " [[Char]]
ks
      scales <- mapM scale rest
      Right ChartArg{caKind = kind, caNet = "net" `elem` ws, caScales = scales}
  where
    scale :: [Char] -> Either [Char] Amount
scale [Char]
p
      | [Char]
p [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
chartWords = [Char] -> Either [Char] Amount
forall a b. a -> Either a b
Left ([Char] -> Either [Char] Amount) -> [Char] -> Either [Char] Amount
forall a b. (a -> b) -> a -> b
$ [Char]
"--chart's KIND and net should come before any SCALE amounts, but this did not: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
p
      | Right Amount
a <- Map AccountName AmountStyle
-> [Char] -> Either HledgerParseErrors Amount
parseamountWithStyles Map AccountName AmountStyle
styles [Char]
p, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0 = Amount -> Either [Char] Amount
forall a b. b -> Either a b
Right Amount
a
      | Bool
otherwise = [Char] -> Either [Char] Amount
forall a b. a -> Either a b
Left ([Char] -> Either [Char] Amount) -> [Char] -> Either [Char] Amount
forall a b. (a -> b) -> a -> b
$ [Char]
"--chart's value should be a chart KIND (" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]] -> [Char]
forall a. [a] -> [[a]] -> [a]
intercalate [Char]
", " [[Char]]
chartKinds
          [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
") and/or net, and/or non-zero SCALE amounts after them, separated by commas (and written without digit group marks), but this part was not: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
p

-- | What --chart's value says, reading its amounts with these commodity styles (by default, an auto chart).
chartArg :: M.Map CommoditySymbol AmountStyle -> CliOpts -> ChartArg
chartArg :: Map AccountName AmountStyle -> CliOpts -> ChartArg
chartArg Map AccountName AmountStyle
styles = ([Char] -> ChartArg)
-> (ChartArg -> ChartArg) -> Either [Char] ChartArg -> ChartArg
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (ChartArg -> [Char] -> ChartArg
forall a b. a -> b -> a
const (ChartArg -> [Char] -> ChartArg) -> ChartArg -> [Char] -> ChartArg
forall a b. (a -> b) -> a -> b
$ [Char] -> Bool -> [Amount] -> ChartArg
ChartArg [Char]
"auto" Bool
False []) ChartArg -> ChartArg
forall a. a -> a
id (Either [Char] ChartArg -> ChartArg)
-> (CliOpts -> Either [Char] ChartArg) -> CliOpts -> ChartArg
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map AccountName AmountStyle -> [Char] -> Either [Char] ChartArg
parseChartArg Map AccountName AmountStyle
styles ([Char] -> Either [Char] ChartArg)
-> (CliOpts -> [Char]) -> CliOpts -> Either [Char] ChartArg
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> Maybe [Char] -> [Char]
forall a. a -> Maybe a -> a
fromMaybe [Char]
"" (Maybe [Char] -> [Char])
-> (CliOpts -> Maybe [Char]) -> CliOpts -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> RawOpts -> Maybe [Char]
maybestringopt [Char]
"chart" (RawOpts -> Maybe [Char])
-> (CliOpts -> RawOpts) -> CliOpts -> Maybe [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CliOpts -> RawOpts
rawopts_

-- | What --chart's value says for this chart, reading its amounts with the chart's commodity styles.
chartArgFor :: CliOpts -> Chart -> ChartArg
chartArgFor :: CliOpts -> Chart -> ChartArg
chartArgFor CliOpts
opts Chart
chart = Map AccountName AmountStyle -> CliOpts -> ChartArg
chartArg ([(AccountName, AmountStyle)] -> Map AccountName AmountStyle
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(Amount -> AccountName
acommodity Amount
u, Amount -> AmountStyle
astyle Amount
u) | Panel{pnUnit :: Panel -> Amount
pnUnit = Amount
u} <- Chart -> [Panel]
chPanels Chart
chart]) CliOpts
opts

-- | Was a chart requested, with --chart or an output format that can only show charts (svg) ?
chartRequested :: CliOpts -> Bool
chartRequested :: CliOpts -> Bool
chartRequested CliOpts
opts = Maybe [Char] -> Bool
forall a. Maybe a -> Bool
isJust ([Char] -> RawOpts -> Maybe [Char]
maybestringopt [Char]
"chart" (RawOpts -> Maybe [Char]) -> RawOpts -> Maybe [Char]
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts) Bool -> Bool -> Bool
|| CliOpts -> [Char]
outputFormatFromOpts CliOpts
opts [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"svg"

-- | The --width option, for commands that can show a chart.
chartWidthFlag :: Flag RawOpts
chartWidthFlag :: Flag RawOpts
chartWidthFlag = [[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq [[Char]
"width",[Char]
"w"] Update RawOpts
forall {a}. IsString a => [Char] -> RawOpts -> Either a RawOpts
setwidth [Char]
"N"
  [Char]
"with --chart: draw the chart N characters wide (default: the terminal width)"
  where
    setwidth :: [Char] -> RawOpts -> Either a RawOpts
setwidth [Char]
s RawOpts
opts = case [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMay [Char]
s :: Maybe Int of
      Just Int
n | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> RawOpts -> Either a RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either a RawOpts) -> RawOpts -> Either a RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"width" [Char]
s RawOpts
opts
      Maybe Int
_              -> a -> Either a RawOpts
forall a b. a -> Either a b
Left a
"--width should be a positive whole number"

-- | Draw a chart as text, as the command line options say:
-- --width characters wide or the terminal width, with colour if enabled
-- (exact 24-bit colours, like SVG charts', if the terminal advertises support for them, otherwise the terminal's basic colours),
-- and with unicode block characters if the system's text encoding is UTF-8 (otherwise ASCII).
-- Also warns if the chart has many panels (one per commodity).
chartAsTextForOpts :: CliOpts -> Chart -> IO TL.Text
chartAsTextForOpts :: CliOpts -> Chart -> IO Text
chartAsTextForOpts CliOpts{Maybe [Char]
width_ :: Maybe [Char]
width_ :: CliOpts -> Maybe [Char]
width_, Int
available_width_ :: Int
available_width_ :: CliOpts -> Int
available_width_, ReportSpec
reportspec_ :: ReportSpec
reportspec_ :: CliOpts -> ReportSpec
reportspec_} Chart
chart = do
  unicode <- ([Char]
"UTF-8" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) ([Char] -> Bool)
-> (TextEncoding -> [Char]) -> TextEncoding -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Char) -> [Char] -> [Char]
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toUpper ([Char] -> [Char])
-> (TextEncoding -> [Char]) -> TextEncoding -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TextEncoding -> [Char]
textEncodingName (TextEncoding -> Bool) -> IO TextEncoding -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO TextEncoding
getLocaleEncoding
  let npanels = [Panel] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Panel] -> Int) -> [Panel] -> Int
forall a b. (a -> b) -> a -> b
$ Chart -> [Panel]
chPanels Chart
chart
  when (npanels > maxPanels) $ warnIO $ printf
    ("this chart has %d panels, one per commodity. To show fewer, convert to one commodity (eg -X USD)\n"
    <> "or select some (eg cur:USD).")
    npanels
  truecolour <- supportsTrueColor
  let colourmode
        | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Bool
color_ (ReportOpts -> Bool) -> ReportOpts -> Bool
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
reportspec_ = ColourMode
NoColour
        | Bool
truecolour = Bool -> ColourMode
RgbColour (Maybe Bool
terminalIsLight Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False)  -- light variants unless the background is known to be dark
        | Bool
otherwise  = ColourMode
BasicColour
  return $ styledLinesAsText colourmode $ chartAsStyledLines (TextChartOpts width unicode) chart
  where
    width :: Int
width = Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
available_width_ (Maybe [Char]
width_ Maybe [Char] -> ([Char] -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMay)
    maxPanels :: Int
maxPanels = Int
8 :: Int

-- | Write a chart in the output format and to the destination selected by the command line options:
-- as text (txt), as an SVG image (svg), as the chart's data (csv, tsv, json),
-- or as an SVG image above the report's html, collapsed, if that is provided (html).
-- Other formats give an error (before the chart is computed).
writeChart :: CliOpts -> Maybe TL.Text -> Chart -> IO ()
writeChart :: CliOpts -> Maybe Text -> Chart -> IO ()
writeChart CliOpts
opts Maybe Text
mreporthtml Chart
chart = do
  render <- case [Char]
fmt of
    [Char]
"txt"  -> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ CliOpts -> Chart -> IO Text
chartAsTextForOpts CliOpts
opts (Chart -> IO Text) -> (Chart -> Chart) -> Chart -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> Chart
withnet
    [Char]
"svg"  -> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> IO Text) -> (Chart -> Text) -> Chart -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> Text
chartAsSvg (Chart -> Text) -> (Chart -> Chart) -> Chart -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> Chart
withnet
    [Char]
"html" | Just Text
reporthtml <- Maybe Text
mreporthtml ->
      -- without the dark variant, since our html is always light
      (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ \Chart
c -> Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> IO Text) -> Text -> IO Text
forall a b. (a -> b) -> a -> b
$ Bool -> Chart -> Text
chartAsSvgWith Bool
False (Chart -> Chart
withnet Chart
c) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AccountName -> Text -> Text
collapsedHtml (Translations -> AccountName -> AccountName
I18n.tr Translations
trans AccountName
"Report details") Text
reporthtml
    [Char]
"csv"  -> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> IO Text) -> (Chart -> Text) -> Chart -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CSV -> Text
printCSV (CSV -> Text) -> (Chart -> CSV) -> Chart -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> CSV
chartAsCsv
    [Char]
"tsv"  -> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> IO Text) -> (Chart -> Text) -> Chart -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CSV -> Text
printTSV (CSV -> Text) -> (Chart -> CSV) -> Chart -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> CSV
chartAsCsv
    [Char]
"json" -> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Chart -> IO Text) -> IO (Chart -> IO Text))
-> (Chart -> IO Text) -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> IO Text) -> (Chart -> Text) -> Chart -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> (Chart -> Text) -> Chart -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Chart -> Text
forall a. ToJSON a => a -> Text
toJsonText
    [Char]
_ | [Char]
fmt [Char] -> [[Char]] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
outputFormats -> [Char] -> IO (Chart -> IO Text)
forall a. [Char] -> a
error' ([Char] -> IO (Chart -> IO Text))
-> [Char] -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ [Char]
"--chart does not yet support " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
fmt [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" output; try txt, svg, html, csv, tsv or json"  -- PARTIAL:
      | Bool
otherwise -> [Char] -> IO (Chart -> IO Text)
forall a. [Char] -> a
error' ([Char] -> IO (Chart -> IO Text))
-> [Char] -> IO (Chart -> IO Text)
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char]
unsupportedOutputFormatError [Char]
fmt  -- PARTIAL:
  render (setChartLayout barlayout $ setChartScales scales chart) >>= writeOutputLazyText opts
  where
    fmt :: [Char]
fmt = CliOpts -> [Char]
outputFormatFromOpts CliOpts
opts
    trans :: Translations
trans = ReportOpts -> Translations
translations_ (ReportOpts -> Translations) -> ReportOpts -> Translations
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
opts
    ChartArg{caKind :: ChartArg -> [Char]
caKind = [Char]
kind, caNet :: ChartArg -> Bool
caNet = Bool
net, caScales :: ChartArg -> [Amount]
caScales = [Amount]
scales} = CliOpts -> Chart -> ChartArg
chartArgFor CliOpts
opts Chart
chart
    -- charts draw the total or net only with --chart=net (otherwise text charts show it only as a number, and chart data always has it)
    withnet :: Chart -> Chart
withnet = if Bool
net then Chart -> Chart
forall a. a -> a
id else Chart -> Chart
chartWithoutTotalMarks
    barlayout :: Maybe BarLayout
barlayout = case [Char]
kind of
      [Char]
"grouped"   -> BarLayout -> Maybe BarLayout
forall a. a -> Maybe a
Just BarLayout
Grouped
      [Char]
"diverging" -> BarLayout -> Maybe BarLayout
forall a. a -> Maybe a
Just BarLayout
Diverging
      [Char]
_           -> Maybe BarLayout
forall a. Maybe a
Nothing

-- | Some html (eg a report's table) in a collapsed section with the given label, which can be clicked to show it.
-- Its report title is hidden, since the chart above shows the same title.
collapsedHtml :: Text -> TL.Text -> TL.Text
collapsedHtml :: AccountName -> Text -> Text
collapsedHtml AccountName
label Text
html = Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ do
  Html -> Html
H.style (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ AccountName -> Html
H.preEscapedText (AccountName -> Html) -> AccountName -> Html
forall a b. (a -> b) -> a -> b
$ [AccountName] -> AccountName
T.concat
    [ AccountName
"details.hledger-details{font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif;font-variant-numeric:tabular-nums}"
    , AccountName
"details.hledger-details>summary{width:fit-content;margin:8px 0;padding:2px 10px;border:1px solid #e1e0d9;border-radius:6px;color:#52514e;cursor:pointer}"
    , AccountName
"details.hledger-details>summary:hover{background:#f3f2ee;color:#0b0b0b}"
    , AccountName
"details.hledger-details .report-title{display:none}"
    ]
  Html
nl
  Html -> Html
H.details (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.class_ AttributeValue
"hledger-details" (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ do
    Html -> Html
H.summary (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ AccountName -> Html
forall a. ToMarkup a => a -> Html
H.toHtml AccountName
label
    Html
nl
    Text -> Html
H.preEscapedLazyText Text
html
  Html
nl

-- | The most series to show in each section of a compound report chart: four accounts and "other"
-- (fewer than the type's 'maxTints', to keep these charts simple).
maxSectionSeries :: Int
maxSectionSeries :: Int
maxSectionSeries = Int
5

-- | The most series to show in one panel. Beyond this, the smallest series are combined into one "other" series.
maxSeries :: Int
maxSeries :: Int
maxSeries = Int
8

-- | Chart a multi-period balance report.
--
-- Period changes (flows) are drawn as stacked bars, end balances (stocks, with --cumulative or --historical) as lines;
-- either way, the total is a line.
-- There is one panel per commodity, most-used commodity first.
-- In tree mode, each account's own amounts are charted, excluding its displayed subaccounts', so nothing is counted twice.
-- The total is omitted with -N, with --percent (where it is always 100), and when there is only one series.
-- Each series' group is its main account type (assets, liabilities, equity, revenues, expenses; then accounts of no known type),
-- so that the grouped layout (--chart=grouped) draws a bar per type, side by side, with the amounts' own signs.
multiBalanceReportAsChart :: (AccountName -> Maybe AccountType) -> ReportOpts -> Text -> MultiBalanceReport -> Chart
multiBalanceReportAsChart :: (AccountName -> Maybe AccountType)
-> ReportOpts -> AccountName -> MultiBalanceReport -> Chart
multiBalanceReportAsChart AccountName -> Maybe AccountType
accttype ropts :: ReportOpts
ropts@ReportOpts{BalanceAccumulation
balanceaccum_ :: BalanceAccumulation
balanceaccum_ :: ReportOpts -> BalanceAccumulation
balanceaccum_, BalanceCalculation
balancecalc_ :: BalanceCalculation
balancecalc_ :: ReportOpts -> BalanceCalculation
balancecalc_, AccountListMode
accountlistmode_ :: AccountListMode
accountlistmode_ :: ReportOpts -> AccountListMode
accountlistmode_, Bool
no_total_ :: Bool
no_total_ :: ReportOpts -> Bool
no_total_, Bool
percent_ :: Bool
percent_ :: ReportOpts -> Bool
percent_, Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} AccountName
title
  (PeriodicReport [DateSpan]
spans [PeriodicReportRow DisplayName MixedAmount]
rows PeriodicReportRow () MixedAmount
totals) =
  Chart
    { chTitle :: AccountName
chTitle  = AccountName
title
    -- with no report interval (a grouped chart of the whole report period), the title names the period
    , chXAxis :: XAxis
chXAxis  = [(DateSpan, AccountName)] -> XAxis
XPeriods [(DateSpan
s, if ReportOpts -> Interval
interval_ ReportOpts
ropts Interval -> Interval -> Bool
forall a. Eq a => a -> a -> Bool
== Interval
NoInterval then AccountName
"" else ReportOpts -> [DateSpan] -> DateSpan -> AccountName
reportPeriodName ReportOpts
ropts [DateSpan]
spans DateSpan
s) | DateSpan
s <- [DateSpan]
spans]
    , chPanels :: [Panel]
chPanels = (AccountName -> Maybe Panel) -> [AccountName] -> [Panel]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe AccountName -> Maybe Panel
panel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
cells
    , chNotes :: [AccountName]
chNotes  = []
    }
  where
    flow :: Bool
flow = BalanceAccumulation
balanceaccum_ BalanceAccumulation -> BalanceAccumulation -> Bool
forall a. Eq a => a -> a -> Bool
== BalanceAccumulation
PerPeriod
    mark :: Mark
mark = if Bool
flow then Mark
MarkBar else Mark
MarkLine
    rows' :: [PeriodicReportRow DisplayName MixedAmount]
rows' = if AccountListMode
accountlistmode_ AccountListMode -> AccountListMode -> Bool
forall a. Eq a => a -> a -> Bool
== AccountListMode
ALTree then [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
ownAmountRows [PeriodicReportRow DisplayName MixedAmount]
rows else [PeriodicReportRow DisplayName MixedAmount]
rows
    cells :: [MixedAmount]
cells = (PeriodicReportRow DisplayName MixedAmount -> [MixedAmount])
-> [PeriodicReportRow DisplayName MixedAmount] -> [MixedAmount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap PeriodicReportRow DisplayName MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts [PeriodicReportRow DisplayName MixedAmount]
rows
    allamts :: [Amount]
allamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
cells
    panel :: AccountName -> Maybe Panel
panel AccountName
c
      | [Series] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Series]
series = Maybe Panel
forall a. Maybe a
Nothing
      | Bool
otherwise = Panel -> Maybe Panel
forall a. a -> Maybe a
Just Panel
          { pnUnit :: Amount
pnUnit      = Amount
unit
          , pnSeries :: [Series]
pnSeries    = [Series
s{seGroup = fromMaybe 0 $ elemIndex (seriestype s) types} | Series
s <- [Series]
series] [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++ [Series]
total
          , pnGroupNames :: [AccountName]
pnGroupNames = (Maybe AccountType -> AccountName)
-> [Maybe AccountType] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map Maybe AccountType -> AccountName
typename [Maybe AccountType]
types
          , pnScale :: Maybe Quantity
pnScale = Maybe Quantity
forall a. Maybe a
Nothing
          , pnLayout :: BarLayout
pnLayout = BarLayout
Diverging
          , pnCounts :: Bool
pnCounts = BalanceCalculation -> Bool
balanceCalcIsCount BalanceCalculation
balancecalc_
          , pnSummary :: [Summary]
pnSummary = ReportOpts
-> Amount -> PeriodicReportRow () MixedAmount -> [Summary]
forall a.
ReportOpts
-> Amount -> PeriodicReportRow a MixedAmount -> [Summary]
rowSummaries ReportOpts
ropts Amount
unit PeriodicReportRow () MixedAmount
totals
          , pnValueLabels :: [Maybe AccountName]
pnValueLabels = []
          }
      where
        unit :: Amount
unit = AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
allamts
        series :: [Series]
series = Int
-> Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]
limitSeries Int
maxSeries Translations
translations_ Mark
mark
          [ ((AccountName -> Maybe AccountType) -> DisplayName -> ChartLabel
accountLabel AccountName -> Maybe AccountType
accttype (DisplayName -> ChartLabel) -> DisplayName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName MixedAmount -> DisplayName
forall a b. PeriodicReportRow a b -> a
prrName PeriodicReportRow DisplayName MixedAmount
r, [Quantity]
qs) | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
rows', let qs :: [Quantity]
qs = (MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) (PeriodicReportRow DisplayName MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts PeriodicReportRow DisplayName MixedAmount
r), (Quantity -> Bool) -> [Quantity] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) [Quantity]
qs ]
        totalqs :: [Quantity]
totalqs = (MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) ([MixedAmount] -> [Quantity]) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow () MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts PeriodicReportRow () MixedAmount
totals
        total :: [Series]
total =
          [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Translations -> AccountName -> AccountName
I18n.tr Translations
translations_ AccountName
"Total") SeriesRole
SeriesTotal Mark
MarkLine ((Quantity -> Maybe Quantity) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just [Quantity]
totalqs) Int
0 Int
0
          | [Series] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Series]
series Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1, Bool -> Bool
not Bool
no_total_, Bool -> Bool
not Bool
percent_ ]
        -- the main account types of this panel's series, in the usual order, with no known type last
        seriestype :: Series -> Maybe AccountType
seriestype = (AccountType -> AccountType)
-> Maybe AccountType -> Maybe AccountType
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap AccountType -> AccountType
mainAccountType (Maybe AccountType -> Maybe AccountType)
-> (Series -> Maybe AccountType) -> Series -> Maybe AccountType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChartLabel -> Maybe AccountType
lbType (ChartLabel -> Maybe AccountType)
-> (Series -> ChartLabel) -> Series -> Maybe AccountType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Series -> ChartLabel
seLabel
        types :: [Maybe AccountType]
types = [Maybe AccountType
t | Maybe AccountType
t <- (AccountType -> Maybe AccountType)
-> [AccountType] -> [Maybe AccountType]
forall a b. (a -> b) -> [a] -> [b]
map AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just [AccountType
Asset, AccountType
Liability, AccountType
Equity, AccountType
Revenue, AccountType
Expense] [Maybe AccountType] -> [Maybe AccountType] -> [Maybe AccountType]
forall a. [a] -> [a] -> [a]
++ [Maybe AccountType
forall a. Maybe a
Nothing], Maybe AccountType
t Maybe AccountType -> [Maybe AccountType] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (Series -> Maybe AccountType) -> [Series] -> [Maybe AccountType]
forall a b. (a -> b) -> [a] -> [b]
map Series -> Maybe AccountType
seriestype [Series]
series]
        typename :: Maybe AccountType -> AccountName
typename Maybe AccountType
t = case Maybe AccountType
t of
          Just AccountType
Asset     -> AccountName -> AccountName
tr AccountName
"Assets"
          Just AccountType
Liability -> AccountName -> AccountName
tr AccountName
"Liabilities"
          Just AccountType
Equity    -> AccountName -> AccountName
tr AccountName
"Equity"
          Just AccountType
Revenue   -> AccountName -> AccountName
tr AccountName
"Revenues"
          Just AccountType
Expense   -> AccountName -> AccountName
tr AccountName
"Expenses"
          -- TRANSLATORS: in a balance chart grouped by account type, the group of accounts with no known type.
          Maybe AccountType
_              -> AccountName -> AccountName
tr AccountName
"Other"
        tr :: AccountName -> AccountName
tr = Translations -> AccountName -> AccountName
I18n.tr Translations
translations_

-- | Chart a single-period balance report, as one bar per account (horizontal, since the accounts are categories).
-- There is one panel per commodity, most-used commodity first;
-- accounts with no amount in a panel's commodity have no value (a gap) there.
-- Unlike stacked charts, all rows are shown, with the report's indentation in tree mode.
-- The total, which belongs to no row (so is not drawn, even with --chart=net), is shown below the chart, as in the table;
-- not with -N or --percent.
balanceReportAsChart :: (AccountName -> Maybe AccountType) -> ReportOpts -> Text -> BalanceReport -> Chart
balanceReportAsChart :: (AccountName -> Maybe AccountType)
-> ReportOpts -> AccountName -> BalanceReport -> Chart
balanceReportAsChart AccountName -> Maybe AccountType
accttype ReportOpts{BalanceCalculation
balancecalc_ :: ReportOpts -> BalanceCalculation
balancecalc_ :: BalanceCalculation
balancecalc_, Bool
no_total_ :: ReportOpts -> Bool
no_total_ :: Bool
no_total_, Bool
percent_ :: ReportOpts -> Bool
percent_ :: Bool
percent_, Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} AccountName
title ([BalanceReportItem]
items, MixedAmount
total) =
  Chart
    { chTitle :: AccountName
chTitle  = AccountName
title
    , chXAxis :: XAxis
chXAxis  = [ChartLabel] -> XAxis
XCategories [AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
full AccountName
short Int
indent (AccountName -> Maybe AccountType
accttype AccountName
full) Bool
True [] | (AccountName
full, AccountName
short, Int
indent, MixedAmount
_) <- [BalanceReportItem]
items]
    , chPanels :: [Panel]
chPanels = (AccountName -> Panel) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> [a] -> [b]
map AccountName -> Panel
panel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
cells
    , chNotes :: [AccountName]
chNotes  = []
    }
  where
    cells :: [MixedAmount]
cells = [MixedAmount
ma | (AccountName
_, AccountName
_, Int
_, MixedAmount
ma) <- [BalanceReportItem]
items]
    allamts :: [Amount]
allamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
cells
    panel :: AccountName -> Panel
panel AccountName
c = Panel
      { pnUnit :: Amount
pnUnit      = Amount
unit
      , pnSeries :: [Series]
pnSeries    = [ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Translations -> AccountName -> AccountName
I18n.tr Translations
translations_ AccountName
"Balance") SeriesRole
SeriesItem Mark
MarkBar
                        [ if (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
c) (AccountName -> Bool) -> (Amount -> AccountName) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> AccountName
acommodity) (MixedAmount -> [Amount]
amountsRaw MixedAmount
ma) then Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c MixedAmount
ma) else Maybe Quantity
forall a. Maybe a
Nothing
                        | (AccountName
_, AccountName
_, Int
_, MixedAmount
ma) <- [BalanceReportItem]
items ] Int
0 Int
0]
      , pnGroupNames :: [AccountName]
pnGroupNames = []
      , pnScale :: Maybe Quantity
pnScale = Maybe Quantity
forall a. Maybe a
Nothing
      , pnLayout :: BarLayout
pnLayout = BarLayout
Diverging
      , pnCounts :: Bool
pnCounts = BalanceCalculation -> Bool
balanceCalcIsCount BalanceCalculation
balancecalc_
      , pnSummary :: [Summary]
pnSummary = [SummaryKind -> AccountName -> Amount -> Summary
Summary SummaryKind
SummaryTotal (Translations -> AccountName -> AccountName -> AccountName
I18n.trc Translations
translations_ AccountName
"column heading" AccountName
"Total") (Amount -> MixedAmount -> Amount
summaryAmount Amount
unit MixedAmount
total) | Bool -> Bool
not Bool
no_total_, Bool -> Bool
not Bool
percent_]
      , pnValueLabels :: [Maybe AccountName]
pnValueLabels = []
      }
      where unit :: Amount
unit = AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
allamts

-- | Chart a compound balance report (balancesheet, incomestatement, cashflow..): its sections' accounts, and the net total.
--
-- Amounts are shown as their contribution to the net total: positive for sections that add to it (eg revenues, assets),
-- negative for sections that subtract from it (eg expenses, liabilities). (The report's tables show both as positive.)
-- So bars above zero increase the net and bars below zero reduce it; eg a refund, which is a negative expense, is drawn above zero.
-- At each period, all sections' accounts are stacked in one diverging bar, positive amounts above zero and negative ones below
-- (the diverging layout, the default); or with --chart=grouped, each section's accounts are stacked in a bar of their own, side by side.
-- See 'setChartLayout', which also re-signs the data for the grouped layout.
-- Each series has its section (as its group) and the section's usual sign, so that renderers can show contra amounts (eg a refund) distinctly.
-- The net total is a line, for changes (eg incomestatement) as well as end balances (eg balancesheet),
-- so that all charts show their totals the same way.
-- A single-period report is drawn the same way, with one period. With -1 (depth 1), each section is a single bar.
-- There is one panel per commodity, most-used commodity first. Each section has at most 'maxSectionSeries' series,
-- the smallest accounts being combined into an "other" series. In tree mode, each account's own amounts are charted.
-- The net total is omitted with -N and with --percent.
--
-- The second argument gives each section's account type, if known (eg from the report's query for it); accounts with no
-- type of their own get their section's, for colouring. An account shown as "..." (eg with depth 0) is labelled with its section's title.
compoundBalanceReportAsChart :: (AccountName -> Maybe AccountType) -> [Maybe AccountType] -> ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> Chart
compoundBalanceReportAsChart :: (AccountName -> Maybe AccountType)
-> [Maybe AccountType]
-> ReportOpts
-> CompoundPeriodicReport DisplayName MixedAmount
-> Chart
compoundBalanceReportAsChart AccountName -> Maybe AccountType
accttype [Maybe AccountType]
sectiontypes ropts :: ReportOpts
ropts@ReportOpts{BalanceCalculation
balancecalc_ :: ReportOpts -> BalanceCalculation
balancecalc_ :: BalanceCalculation
balancecalc_, AccountListMode
accountlistmode_ :: ReportOpts -> AccountListMode
accountlistmode_ :: AccountListMode
accountlistmode_, Bool
no_total_ :: ReportOpts -> Bool
no_total_ :: Bool
no_total_, Bool
percent_ :: ReportOpts -> Bool
percent_ :: Bool
percent_, Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_}
  (CompoundPeriodicReport AccountName
title [DateSpan]
spans [(AccountName, MultiBalanceReport, Bool)]
subreports PeriodicReportRow () MixedAmount
totals) =
  Chart
    { chTitle :: AccountName
chTitle  = AccountName
title
    , chXAxis :: XAxis
chXAxis  = [(DateSpan, AccountName)] -> XAxis
XPeriods [(DateSpan
s, if [DateSpan] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [DateSpan]
spans Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 then AccountName
"" else ReportOpts -> [DateSpan] -> DateSpan -> AccountName
reportPeriodName ReportOpts
ropts [DateSpan]
spans DateSpan
s) | DateSpan
s <- [DateSpan]
spans]  -- the title names a single period
    , chPanels :: [Panel]
chPanels = (AccountName -> Maybe Panel) -> [AccountName] -> [Panel]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe AccountName -> Maybe Panel
panel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
cells
    , chNotes :: [AccountName]
chNotes  = []
    }
  where
    -- each section's sign (1 if it adds to the net total, -1 if it subtracts from it), and its account rows
    -- (in tree mode, with only their own amounts, so that nothing is counted twice)
    sections :: [((AccountName, Maybe AccountType), Quantity,
  [PeriodicReportRow DisplayName MixedAmount])]
sections = [ ((AccountName
t, Maybe AccountType
sectype), if Bool
increasestotal then Quantity
1 else -Quantity
1, if AccountListMode
accountlistmode_ AccountListMode -> AccountListMode -> Bool
forall a. Eq a => a -> a -> Bool
== AccountListMode
ALTree then [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
ownAmountRows (MultiBalanceReport -> [PeriodicReportRow DisplayName MixedAmount]
forall a b. PeriodicReport a b -> [PeriodicReportRow a b]
prRows MultiBalanceReport
r) else MultiBalanceReport -> [PeriodicReportRow DisplayName MixedAmount]
forall a b. PeriodicReport a b -> [PeriodicReportRow a b]
prRows MultiBalanceReport
r)
               | ((AccountName
t, MultiBalanceReport
r, Bool
increasestotal), Maybe AccountType
sectype) <- [(AccountName, MultiBalanceReport, Bool)]
-> [Maybe AccountType]
-> [((AccountName, MultiBalanceReport, Bool), Maybe AccountType)]
forall a b. [a] -> [b] -> [(a, b)]
zip [(AccountName, MultiBalanceReport, Bool)]
subreports ([Maybe AccountType]
sectiontypes [Maybe AccountType] -> [Maybe AccountType] -> [Maybe AccountType]
forall a. [a] -> [a] -> [a]
++ Maybe AccountType -> [Maybe AccountType]
forall a. a -> [a]
repeat Maybe AccountType
forall a. Maybe a
Nothing) ]
    -- an account's label, with its section's type if it has none, or its section's title if it's "..."
    sectionAccountLabel :: (AccountName, Maybe AccountType)
-> PeriodicReportRow DisplayName b -> ChartLabel
sectionAccountLabel (AccountName
t, Maybe AccountType
sectype) PeriodicReportRow DisplayName b
r
      | ChartLabel -> AccountName
lbFull ChartLabel
l AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
"..." = AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
t AccountName
t Int
0 Maybe AccountType
sectype Bool
True []
      | Bool
otherwise         = ChartLabel
l{lbType = lbType l <|> sectype}
      where l :: ChartLabel
l = (AccountName -> Maybe AccountType) -> DisplayName -> ChartLabel
accountLabel AccountName -> Maybe AccountType
accttype (DisplayName -> ChartLabel) -> DisplayName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName b -> DisplayName
forall a b. PeriodicReportRow a b -> a
prrName PeriodicReportRow DisplayName b
r
    -- a section's usual sign, for showing contra amounts; cash (cf's section) has none, since it flows both ways as usual
    usualSign :: (a, Maybe AccountType) -> a -> a
usualSign (a
_, Maybe AccountType
sectype) a
sign = if Maybe AccountType
sectype Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Cash then a
0 else a -> a
forall b. Integral b => a -> b
forall a b. (RealFrac a, Integral b) => a -> b
round a
sign
    nettotals :: [MixedAmount]
nettotals = PeriodicReportRow () MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts PeriodicReportRow () MixedAmount
totals
    showtotal :: Bool
showtotal = Bool -> Bool
not Bool
no_total_ Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
percent_
    -- the table's "Net:" label, without the colon
    netlabel :: AccountName
netlabel = (Char -> Bool) -> AccountName -> AccountName
T.dropWhileEnd (Char -> [Char] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
':', Char
'\xff1a']) (AccountName -> AccountName) -> AccountName -> AccountName
forall a b. (a -> b) -> a -> b
$ Translations -> AccountName -> AccountName
I18n.tr Translations
translations_ AccountName
"Net:"
    cells :: [MixedAmount]
cells = [[MixedAmount]] -> [MixedAmount]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [(PeriodicReportRow DisplayName MixedAmount -> [MixedAmount])
-> [PeriodicReportRow DisplayName MixedAmount] -> [MixedAmount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap PeriodicReportRow DisplayName MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts [PeriodicReportRow DisplayName MixedAmount]
rows | ((AccountName, Maybe AccountType)
_, Quantity
_, [PeriodicReportRow DisplayName MixedAmount]
rows) <- [((AccountName, Maybe AccountType), Quantity,
  [PeriodicReportRow DisplayName MixedAmount])]
sections] [MixedAmount] -> [MixedAmount] -> [MixedAmount]
forall a. [a] -> [a] -> [a]
++ [MixedAmount]
nettotals
    allamts :: [Amount]
allamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
cells
    panel :: AccountName -> Maybe Panel
panel AccountName
c
      | [Series] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Series]
series = Maybe Panel
forall a. Maybe a
Nothing
      | Bool
otherwise = Panel -> Maybe Panel
forall a. a -> Maybe a
Just Panel
          { pnUnit :: Amount
pnUnit   = Amount
unit
          , pnSeries :: [Series]
pnSeries = [Series]
series [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++
              [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName -> ChartLabel
plainLabel AccountName
netlabel) SeriesRole
SeriesTotal Mark
MarkLine ((Quantity -> Maybe Quantity) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just [Quantity]
netqs) Int
0 Int
0
              | Bool
showtotal ]
          , pnGroupNames :: [AccountName]
pnGroupNames = [AccountName
t | (AccountName
t, MultiBalanceReport
_, Bool
_) <- [(AccountName, MultiBalanceReport, Bool)]
subreports]
          , pnScale :: Maybe Quantity
pnScale = Maybe Quantity
forall a. Maybe a
Nothing
          , pnLayout :: BarLayout
pnLayout = BarLayout
Diverging
          , pnCounts :: Bool
pnCounts = BalanceCalculation -> Bool
balanceCalcIsCount BalanceCalculation
balancecalc_
          , pnSummary :: [Summary]
pnSummary = ReportOpts
-> Amount -> PeriodicReportRow () MixedAmount -> [Summary]
forall a.
ReportOpts
-> Amount -> PeriodicReportRow a MixedAmount -> [Summary]
rowSummaries ReportOpts
ropts Amount
unit PeriodicReportRow () MixedAmount
totals
          , pnValueLabels :: [Maybe AccountName]
pnValueLabels = []
          }
      where
        unit :: Amount
unit = AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
allamts
        netqs :: [Quantity]
netqs = (MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) [MixedAmount]
nettotals
        series :: [Series]
series = [[Series]] -> [Series]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
          [ [ Series
s{seGroup = k, seSign = usualSign section sign} | Series
s <- Int
-> Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]
limitSeries Int
maxSectionSeries Translations
translations_ Mark
MarkBar [(ChartLabel, [Quantity])]
accts ]
          | (Int
k, ((AccountName, Maybe AccountType)
section, Quantity
sign, [PeriodicReportRow DisplayName MixedAmount]
rows)) <- [Int]
-> [((AccountName, Maybe AccountType), Quantity,
     [PeriodicReportRow DisplayName MixedAmount])]
-> [(Int,
     ((AccountName, Maybe AccountType), Quantity,
      [PeriodicReportRow DisplayName MixedAmount]))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [((AccountName, Maybe AccountType), Quantity,
  [PeriodicReportRow DisplayName MixedAmount])]
sections
          , let accts :: [(ChartLabel, [Quantity])]
accts = [ ((AccountName, Maybe AccountType)
-> PeriodicReportRow DisplayName MixedAmount -> ChartLabel
forall {b}.
(AccountName, Maybe AccountType)
-> PeriodicReportRow DisplayName b -> ChartLabel
sectionAccountLabel (AccountName, Maybe AccountType)
section PeriodicReportRow DisplayName MixedAmount
r, [Quantity]
qs) | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
rows, let qs :: [Quantity]
qs = (MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map ((Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* Quantity
sign) (Quantity -> Quantity)
-> (MixedAmount -> Quantity) -> MixedAmount -> Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) (PeriodicReportRow DisplayName MixedAmount -> [MixedAmount]
forall a b. PeriodicReportRow a b -> [b]
prrAmounts PeriodicReportRow DisplayName MixedAmount
r), (Quantity -> Bool) -> [Quantity] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) [Quantity]
qs ]
          ]

-- | Chart an account register (aregister): the balance after each transaction
-- (or the running total or average, as the report shows), as a line over time.
-- The arguments are the title, the account's name, and a function giving a transaction's date in the register.
-- There is one panel per commodity, most-used commodity first.
accountTransactionsReportAsChart :: (AccountName -> Maybe AccountType) -> Text -> AccountName -> (Transaction -> Day) -> AccountTransactionsReport -> Chart
accountTransactionsReportAsChart :: (AccountName -> Maybe AccountType)
-> AccountName
-> AccountName
-> (Transaction -> Day)
-> AccountTransactionsReport
-> Chart
accountTransactionsReportAsChart AccountName -> Maybe AccountType
accttype AccountName
title AccountName
acct Transaction -> Day
txndate AccountTransactionsReport
items =
  Chart
    { chTitle :: AccountName
chTitle  = AccountName
title
    , chXAxis :: XAxis
chXAxis  = [Day] -> XAxis
XDates [Transaction -> Day
txndate Transaction
t | (Transaction
t, Transaction
_, Bool
_, [AccountName]
_, MixedAmount
_, MixedAmount
_) <- AccountTransactionsReport
items]
    , chPanels :: [Panel]
chPanels = (AccountName -> Panel) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> [a] -> [b]
map AccountName -> Panel
panel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
bals
    , chNotes :: [AccountName]
chNotes  = []
    }
  where
    bals :: [MixedAmount]
bals = [MixedAmount
b | (Transaction
_, Transaction
_, Bool
_, [AccountName]
_, MixedAmount
_, MixedAmount
b) <- AccountTransactionsReport
items]
    allamts :: [Amount]
allamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
bals
    panel :: AccountName -> Panel
panel AccountName
c = Panel
      { pnUnit :: Amount
pnUnit      = AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
allamts
      , pnSeries :: [Series]
pnSeries    = [ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
acct AccountName
acct Int
0 (AccountName -> Maybe AccountType
accttype AccountName
acct) Bool
True []) SeriesRole
SeriesItem Mark
MarkLine ((MixedAmount -> Maybe Quantity)
-> [MixedAmount] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity)
-> (MixedAmount -> Quantity) -> MixedAmount -> Maybe Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) [MixedAmount]
bals) Int
0 Int
0]
      , pnGroupNames :: [AccountName]
pnGroupNames = []
      , pnScale :: Maybe Quantity
pnScale = Maybe Quantity
forall a. Maybe a
Nothing
      , pnLayout :: BarLayout
pnLayout = BarLayout
Diverging
      , pnCounts :: Bool
pnCounts = Bool
False
      , pnSummary :: [Summary]
pnSummary = []
      , pnValueLabels :: [Maybe AccountName]
pnValueLabels = []
      }

-- | Chart a postings report (register).
-- With a report interval, each account's amount in each period is drawn as stacked bars, with the period's total as a line
-- (like a multi-period balance report; at most 'maxSeries' series, the smallest combined into "other").
-- Otherwise, the running total (or average) after each posting is drawn as a line over time;
-- and with postings to several accounts (and not --average), each account's own running total (from the report start) is drawn too,
-- in its account type's colour, with the overall running total in ink.
-- There is one panel per commodity, most-used commodity first.
--
-- The second argument gives the accounts' balances before the report period, if the running total includes them
-- (with --historical; see 'postingsReportStartBalances'), so that each account's running total starts from its balance.
postingsReportAsChart :: (AccountName -> Maybe AccountType) -> M.Map AccountName MixedAmount -> ReportOpts -> Text -> PostingsReport -> Chart
postingsReportAsChart :: (AccountName -> Maybe AccountType)
-> Map AccountName MixedAmount
-> ReportOpts
-> AccountName
-> PostingsReport
-> Chart
postingsReportAsChart AccountName -> Maybe AccountType
accttype Map AccountName MixedAmount
startbals ropts :: ReportOpts
ropts@ReportOpts{Bool
average_ :: Bool
average_ :: ReportOpts -> Bool
average_, Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} AccountName
title PostingsReport
items
  | [Period] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Period]
periods =
      let totals :: [MixedAmount]
totals = [MixedAmount
t | (Maybe Day
_, Maybe Period
_, Maybe AccountName
_, Posting
_, MixedAmount
t) <- PostingsReport
items]
          totalamts :: [Amount]
totalamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
totals
          totalseries :: AccountName -> SeriesRole -> Series
totalseries AccountName
c SeriesRole
role = ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series ((AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Translations -> AccountName -> AccountName
I18n.tr Translations
translations_ AccountName
"Total"){lbType = commontype}) SeriesRole
role Mark
MarkLine ((MixedAmount -> Maybe Quantity)
-> [MixedAmount] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity)
-> (MixedAmount -> Quantity) -> MixedAmount -> Maybe Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) [MixedAmount]
totals) Int
0 Int
0
          -- with postings to several accounts (and not --average), each account's running total as a line, and the overall running total;
          -- otherwise just the running total (labelled with the account, if there's one, so that it has the account's colour)
          linespanel :: AccountName -> Panel
linespanel AccountName
c
            | Bool
average_ = Amount
-> [Series]
-> [AccountName]
-> Maybe Quantity
-> BarLayout
-> Bool
-> [Summary]
-> [Maybe AccountName]
-> Panel
Panel (AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
totalamts) [AccountName -> SeriesRole -> Series
totalseries AccountName
c SeriesRole
SeriesItem] [] Maybe Quantity
forall a. Maybe a
Nothing BarLayout
Diverging Bool
False [] []
            | [AccountName
a] <- AccountName -> [AccountName]
runningTotalAccounts AccountName
c = Amount
-> [Series]
-> [AccountName]
-> Maybe Quantity
-> BarLayout
-> Bool
-> [Summary]
-> [Maybe AccountName]
-> Panel
Panel (AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
totalamts) [(AccountName -> SeriesRole -> Series
totalseries AccountName
c SeriesRole
SeriesItem){seLabel = ChartLabel a a 0 (accttype a) True []}] [] Maybe Quantity
forall a. Maybe a
Nothing BarLayout
Diverging Bool
False [] []
            | [AccountName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (AccountName -> [AccountName]
runningTotalAccounts AccountName
c) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 = Amount
-> [Series]
-> [AccountName]
-> Maybe Quantity
-> BarLayout
-> Bool
-> [Summary]
-> [Maybe AccountName]
-> Panel
Panel (AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
totalamts) [AccountName -> SeriesRole -> Series
totalseries AccountName
c SeriesRole
SeriesItem] [] Maybe Quantity
forall a. Maybe a
Nothing BarLayout
Diverging Bool
False [] []
            | Bool
otherwise = Amount
-> [Series]
-> [AccountName]
-> Maybe Quantity
-> BarLayout
-> Bool
-> [Summary]
-> [Maybe AccountName]
-> Panel
Panel (AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
totalamts) (AccountName -> [Series]
accountRunningTotals AccountName
c [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++ [AccountName -> SeriesRole -> Series
totalseries AccountName
c SeriesRole
SeriesTotal]) [] Maybe Quantity
forall a. Maybe a
Nothing BarLayout
Diverging Bool
False [] []
      in Chart
        { chTitle :: AccountName
chTitle  = AccountName
title
        , chXAxis :: XAxis
chXAxis  = [Day] -> XAxis
XDates [WhichDate -> Posting -> Day
postingDateOrDate2 (ReportOpts -> WhichDate
whichDate ReportOpts
ropts) Posting
p | Posting
p <- [Posting]
postings]
        , chPanels :: [Panel]
chPanels = (AccountName -> Panel) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> [a] -> [b]
map AccountName -> Panel
linespanel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
totals
        , chNotes :: [AccountName]
chNotes  = []
        }
  | Bool
otherwise =
      Chart
        { chTitle :: AccountName
chTitle  = AccountName
title
        , chXAxis :: XAxis
chXAxis  = [(DateSpan, AccountName)] -> XAxis
XPeriods [(DateSpan
s, ReportOpts -> [DateSpan] -> DateSpan -> AccountName
reportPeriodName ReportOpts
ropts{balanceaccum_ = PerPeriod} [DateSpan]
spans DateSpan
s) | DateSpan
s <- [DateSpan]
spans]
        , chPanels :: [Panel]
chPanels = (AccountName -> Maybe Panel) -> [AccountName] -> [Panel]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe AccountName -> Maybe Panel
panel ([AccountName] -> [Panel]) -> [AccountName] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
cells
        , chNotes :: [AccountName]
chNotes  = []
        }
  where
    postings :: [Posting]
postings = [Posting
p | (Maybe Day
_, Maybe Period
_, Maybe AccountName
_, Posting
p, MixedAmount
_) <- PostingsReport
items]
    -- Running totals (from the report start) of the postings' accounts in one commodity, as lines:
    -- for at most 'maxSeries' accounts, the largest by total absolute posting amount (in name order), and the rest combined as "other".
    -- (Only these are computed, since there can be many accounts and postings.)
    -- Each account starts from its balance before the report period, if any.
    accountRunningTotals :: AccountName -> [Series]
accountRunningTotals AccountName
c =
      [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
a AccountName
a Int
0 (AccountName -> Maybe AccountType
accttype AccountName
a) Bool
True []) SeriesRole
SeriesItem Mark
MarkLine ((AccountName -> Bool) -> [Maybe Quantity]
runningTotal (AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
a)) Int
0 Int
0 | AccountName
a <- [AccountName]
kept ]
      [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++ [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (Translations -> Int -> [(AccountName, Quantity)] -> ChartLabel
otherLabel Translations
translations_ ([[(AccountName, Quantity)]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[(AccountName, Quantity)]]
othergroups) [(AccountName, Quantity)]
grp){lbType = accttype . fst =<< headMay grp} SeriesRole
SeriesOther Mark
MarkLine
             ((AccountName -> Bool) -> [Maybe Quantity]
runningTotal (AccountName -> Set AccountName -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` [AccountName] -> Set AccountName
forall a. Ord a => [a] -> Set a
S.fromList (((AccountName, Quantity) -> AccountName)
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName, Quantity) -> AccountName
forall a b. (a, b) -> a
fst [(AccountName, Quantity)]
grp))) Int
0 Int
0
         | [(AccountName, Quantity)]
grp <- [[(AccountName, Quantity)]]
othergroups ]
      where
        sizes :: [(AccountName, Quantity)]
sizes = Map AccountName Quantity -> [(AccountName, Quantity)]
forall k a. Map k a -> [(k, a)]
M.toList (Map AccountName Quantity -> [(AccountName, Quantity)])
-> Map AccountName Quantity -> [(AccountName, Quantity)]
forall a b. (a -> b) -> a -> b
$ AccountName -> Map AccountName Quantity
accountSizes AccountName
c
        ([Int]
keptis, [[Int]]
othergroupis) = Int -> [(Maybe AccountType, Quantity)] -> ([Int], [[Int]])
chooseSeries Int
maxSeries [(AccountType -> AccountType
mainAccountType (AccountType -> AccountType)
-> Maybe AccountType -> Maybe AccountType
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AccountName -> Maybe AccountType
accttype AccountName
a, Quantity
q) | (AccountName
a, Quantity
q) <- [(AccountName, Quantity)]
sizes]
        kept :: [AccountName]
kept = ((AccountName, Quantity) -> AccountName)
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName, Quantity) -> AccountName
forall a b. (a, b) -> a
fst ([(AccountName, Quantity)] -> [AccountName])
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> a -> b
$ (Int -> Maybe (AccountName, Quantity))
-> [Int] -> [(AccountName, Quantity)]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ([(AccountName, Quantity)] -> Int -> Maybe (AccountName, Quantity)
forall a. [a] -> Int -> Maybe a
atMay [(AccountName, Quantity)]
sizes) [Int]
keptis
        othergroups :: [[(AccountName, Quantity)]]
othergroups = ([Int] -> [(AccountName, Quantity)])
-> [[Int]] -> [[(AccountName, Quantity)]]
forall a b. (a -> b) -> [a] -> [b]
map ((Int -> Maybe (AccountName, Quantity))
-> [Int] -> [(AccountName, Quantity)]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ([(AccountName, Quantity)] -> Int -> Maybe (AccountName, Quantity)
forall a. [a] -> Int -> Maybe a
atMay [(AccountName, Quantity)]
sizes)) [[Int]]
othergroupis
        runningTotal :: (AccountName -> Bool) -> [Maybe Quantity]
runningTotal AccountName -> Bool
match =
          (Quantity -> Maybe Quantity) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just ([Quantity] -> [Maybe Quantity]) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> a -> b
$ Int -> [Quantity] -> [Quantity]
forall a. Int -> [a] -> [a]
drop Int
1 ([Quantity] -> [Quantity]) -> [Quantity] -> [Quantity]
forall a b. (a -> b) -> a -> b
$ (Quantity -> Quantity -> Quantity)
-> Quantity -> [Quantity] -> [Quantity]
forall b a. (b -> a -> b) -> b -> [a] -> [b]
scanl Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
(+) ([Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [AccountName -> AccountName -> Quantity
startIn AccountName
c AccountName
a | AccountName
a <- Map AccountName MixedAmount -> [AccountName]
forall k a. Map k a -> [k]
M.keys Map AccountName MixedAmount
startbals, AccountName -> Bool
match AccountName
a])
            [if AccountName -> Bool
match (Posting -> AccountName
paccount Posting
p) then AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c (Posting -> MixedAmount
pamount Posting
p) else Quantity
0 | Posting
p <- [Posting]
postings]
    -- the accounts with postings, or a starting balance, in this commodity, with their total absolute amount (for ranking)
    accountSizes :: AccountName -> Map AccountName Quantity
accountSizes AccountName
c = (Quantity -> Bool)
-> Map AccountName Quantity -> Map AccountName Quantity
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Map AccountName Quantity -> Map AccountName Quantity)
-> Map AccountName Quantity -> Map AccountName Quantity
forall a b. (a -> b) -> a -> b
$ (Quantity -> Quantity -> Quantity)
-> Map AccountName Quantity
-> Map AccountName Quantity
-> Map AccountName Quantity
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
(+)
      ((Quantity -> Quantity -> Quantity)
-> [(AccountName, Quantity)] -> Map AccountName Quantity
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
(+) [(Posting -> AccountName
paccount Posting
p, Quantity -> Quantity
forall a. Num a => a -> a
abs (Quantity -> Quantity) -> Quantity -> Quantity
forall a b. (a -> b) -> a -> b
$ AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c (MixedAmount -> Quantity) -> MixedAmount -> Quantity
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p) | Posting
p <- [Posting]
postings])
      ([(AccountName, Quantity)] -> Map AccountName Quantity
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(AccountName
a, Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
q) | AccountName
a <- Map AccountName MixedAmount -> [AccountName]
forall k a. Map k a -> [k]
M.keys Map AccountName MixedAmount
startbals, let q :: Quantity
q = AccountName -> AccountName -> Quantity
startIn AccountName
c AccountName
a, Quantity
q Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0])
    runningTotalAccounts :: AccountName -> [AccountName]
runningTotalAccounts AccountName
c = Map AccountName Quantity -> [AccountName]
forall k a. Map k a -> [k]
M.keys (Map AccountName Quantity -> [AccountName])
-> Map AccountName Quantity -> [AccountName]
forall a b. (a -> b) -> a -> b
$ AccountName -> Map AccountName Quantity
accountSizes AccountName
c
    startIn :: AccountName -> AccountName -> Quantity
startIn AccountName
c AccountName
a = Quantity
-> (MixedAmount -> Quantity) -> Maybe MixedAmount -> Quantity
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Quantity
0 (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) (Maybe MixedAmount -> Quantity) -> Maybe MixedAmount -> Quantity
forall a b. (a -> b) -> a -> b
$ AccountName -> Map AccountName MixedAmount -> Maybe MixedAmount
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup AccountName
a Map AccountName MixedAmount
startbals
    -- the main account type of all the postings' accounts, if they have one
    commontype :: Maybe AccountType
commontype = case [AccountType] -> [AccountType]
forall a. Ord a => [a] -> [a]
nubSort [AccountType -> AccountType
mainAccountType AccountType
t | (Maybe Day
_, Maybe Period
_, Maybe AccountName
_, Posting
p, MixedAmount
_) <- PostingsReport
items, Just AccountType
t <- [AccountName -> Maybe AccountType
accttype (AccountName -> Maybe AccountType)
-> AccountName -> Maybe AccountType
forall a b. (a -> b) -> a -> b
$ Posting -> AccountName
paccount Posting
p]] of
      [AccountType
t] | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Maybe AccountType -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AccountType -> Bool)
-> (Posting -> Maybe AccountType) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountName -> Maybe AccountType
accttype (AccountName -> Maybe AccountType)
-> (Posting -> AccountName) -> Posting -> Maybe AccountType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> AccountName
paccount) [Posting
p | (Maybe Day
_, Maybe Period
_, Maybe AccountName
_, Posting
p, MixedAmount
_) <- PostingsReport
items] -> AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
t
      [AccountType]
_ -> Maybe AccountType
forall a. Maybe a
Nothing
    periods :: [Period]
periods = [Period] -> [Period]
forall a. Ord a => [a] -> [a]
nubSort [Period
prd | (Maybe Day
_, Just Period
prd, Maybe AccountName
_, Posting
_, MixedAmount
_) <- PostingsReport
items]
    spans :: [DateSpan]
spans = (Period -> DateSpan) -> [Period] -> [DateSpan]
forall a b. (a -> b) -> [a] -> [b]
map Period -> DateSpan
periodAsDateSpan [Period]
periods
    -- each account's amount in each period
    acctamts :: M.Map AccountName (M.Map Period MixedAmount)
    acctamts :: Map AccountName (Map Period MixedAmount)
acctamts = (Map Period MixedAmount
 -> Map Period MixedAmount -> Map Period MixedAmount)
-> [(AccountName, Map Period MixedAmount)]
-> Map AccountName (Map Period MixedAmount)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith ((MixedAmount -> MixedAmount -> MixedAmount)
-> Map Period MixedAmount
-> Map Period MixedAmount
-> Map Period MixedAmount
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith MixedAmount -> MixedAmount -> MixedAmount
forall a. Semigroup a => a -> a -> a
(<>)) [(Posting -> AccountName
paccount Posting
p, Period -> MixedAmount -> Map Period MixedAmount
forall k a. k -> a -> Map k a
M.singleton Period
prd (Posting -> MixedAmount
pamount Posting
p)) | (Maybe Day
_, Just Period
prd, Maybe AccountName
_, Posting
p, MixedAmount
_) <- PostingsReport
items]
    rows :: [(AccountName, [MixedAmount])]
rows = [(AccountName
a, [MixedAmount -> Period -> Map Period MixedAmount -> MixedAmount
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault MixedAmount
nullmixedamt Period
prd Map Period MixedAmount
m | Period
prd <- [Period]
periods]) | (AccountName
a, Map Period MixedAmount
m) <- Map AccountName (Map Period MixedAmount)
-> [(AccountName, Map Period MixedAmount)]
forall k a. Map k a -> [(k, a)]
M.toList Map AccountName (Map Period MixedAmount)
acctamts]
    cells :: [MixedAmount]
cells = ((AccountName, [MixedAmount]) -> [MixedAmount])
-> [(AccountName, [MixedAmount])] -> [MixedAmount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (AccountName, [MixedAmount]) -> [MixedAmount]
forall a b. (a, b) -> b
snd [(AccountName, [MixedAmount])]
rows
    allamts :: [Amount]
allamts = (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw [MixedAmount]
cells
    panel :: AccountName -> Maybe Panel
panel AccountName
c
      | [Series] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Series]
series = Maybe Panel
forall a. Maybe a
Nothing
      | Bool
otherwise = Panel -> Maybe Panel
forall a. a -> Maybe a
Just Panel{pnUnit :: Amount
pnUnit = AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
allamts, pnSeries :: [Series]
pnSeries = [Series]
series [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++ [Series]
total, pnGroupNames :: [AccountName]
pnGroupNames = [], pnScale :: Maybe Quantity
pnScale = Maybe Quantity
forall a. Maybe a
Nothing, pnLayout :: BarLayout
pnLayout = BarLayout
Diverging, pnCounts :: Bool
pnCounts = Bool
False, pnSummary :: [Summary]
pnSummary = [], pnValueLabels :: [Maybe AccountName]
pnValueLabels = []}
      where
        series :: [Series]
series = Int
-> Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]
limitSeries Int
maxSeries Translations
translations_ Mark
MarkBar
          [ (AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
a AccountName
a Int
0 (AccountName -> Maybe AccountType
accttype AccountName
a) Bool
True [], [Quantity]
qs) | (AccountName
a, [MixedAmount]
amts) <- [(AccountName, [MixedAmount])]
rows, let qs :: [Quantity]
qs = (MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) [MixedAmount]
amts, (Quantity -> Bool) -> [Quantity] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) [Quantity]
qs ]
        totalqs :: [Quantity]
totalqs = ([Quantity] -> Quantity) -> [[Quantity]] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([[Quantity]] -> [Quantity]) -> [[Quantity]] -> [Quantity]
forall a b. (a -> b) -> a -> b
$ [[Quantity]] -> [[Quantity]]
forall a. [[a]] -> [[a]]
transpose [(MixedAmount -> Quantity) -> [MixedAmount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c) [MixedAmount]
amts | (AccountName
_, [MixedAmount]
amts) <- [(AccountName, [MixedAmount])]
rows]
        total :: [Series]
total =
          [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Translations -> AccountName -> AccountName
I18n.tr Translations
translations_ AccountName
"Total") SeriesRole
SeriesTotal Mark
MarkLine ((Quantity -> Maybe Quantity) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just [Quantity]
totalqs) Int
0 Int
0
          | [Series] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Series]
series Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1 ]

-- Helpers

-- | Keep at most this many series. If there are more, keep the largest (by total absolute value) in their original order,
-- and combine the rest into a final "other" series.
limitSeries :: Int -> I18n.Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]
limitSeries :: Int
-> Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]
limitSeries Int
maxn Translations
t Mark
mark [(ChartLabel, [Quantity])]
items =
  [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series ChartLabel
l SeriesRole
SeriesItem Mark
mark ((Quantity -> Maybe Quantity) -> [Quantity] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just [Quantity]
qs) Int
0 Int
0 | Int
i <- [Int]
kept, Just (ChartLabel
l, [Quantity]
qs) <- [[(ChartLabel, [Quantity])]
items [(ChartLabel, [Quantity])] -> Int -> Maybe (ChartLabel, [Quantity])
forall a. [a] -> Int -> Maybe a
`atMay` Int
i] ]
  [Series] -> [Series] -> [Series]
forall a. [a] -> [a] -> [a]
++ [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (Translations -> Int -> [(AccountName, Quantity)] -> ChartLabel
otherLabel Translations
t ([[Int]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[Int]]
othergroups) [(ChartLabel -> AccountName
lbFull ChartLabel
l, [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Quantity] -> Quantity) -> [Quantity] -> Quantity
forall a b. (a -> b) -> a -> b
$ (Quantity -> Quantity) -> [Quantity] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Quantity
forall a. Num a => a -> a
abs [Quantity]
qs) | (ChartLabel
l, [Quantity]
qs) <- [(ChartLabel, [Quantity])]
grp]){lbType = lbType . fst =<< headMay grp} SeriesRole
SeriesOther Mark
mark
         (([Quantity] -> Maybe Quantity) -> [[Quantity]] -> [Maybe Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity)
-> ([Quantity] -> Quantity) -> [Quantity] -> Maybe Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum) ([[Quantity]] -> [Maybe Quantity])
-> [[Quantity]] -> [Maybe Quantity]
forall a b. (a -> b) -> a -> b
$ [[Quantity]] -> [[Quantity]]
forall a. [[a]] -> [[a]]
transpose ([[Quantity]] -> [[Quantity]]) -> [[Quantity]] -> [[Quantity]]
forall a b. (a -> b) -> a -> b
$ ((ChartLabel, [Quantity]) -> [Quantity])
-> [(ChartLabel, [Quantity])] -> [[Quantity]]
forall a b. (a -> b) -> [a] -> [b]
map (ChartLabel, [Quantity]) -> [Quantity]
forall a b. (a, b) -> b
snd [(ChartLabel, [Quantity])]
grp) Int
0 Int
0
     | [(ChartLabel, [Quantity])]
grp <- ([Int] -> [(ChartLabel, [Quantity])])
-> [[Int]] -> [[(ChartLabel, [Quantity])]]
forall a b. (a -> b) -> [a] -> [b]
map ((Int -> Maybe (ChartLabel, [Quantity]))
-> [Int] -> [(ChartLabel, [Quantity])]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ([(ChartLabel, [Quantity])]
items [(ChartLabel, [Quantity])] -> Int -> Maybe (ChartLabel, [Quantity])
forall a. [a] -> Int -> Maybe a
`atMay`)) [[Int]]
othergroups ]
  where
    ([Int]
kept, [[Int]]
othergroups) = Int -> [(Maybe AccountType, Quantity)] -> ([Int], [[Int]])
chooseSeries Int
maxn [(AccountType -> AccountType
mainAccountType (AccountType -> AccountType)
-> Maybe AccountType -> Maybe AccountType
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ChartLabel -> Maybe AccountType
lbType ChartLabel
l, [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Quantity] -> Quantity) -> [Quantity] -> Quantity
forall a b. (a -> b) -> a -> b
$ (Quantity -> Quantity) -> [Quantity] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Quantity -> Quantity
forall a. Num a => a -> a
abs [Quantity]
qs) | (ChartLabel
l, [Quantity]
qs) <- [(ChartLabel, [Quantity])]
items]

-- | Choose which of these items (given as their account type, if known, and size) to show as series of their own,
-- when at most n series can be shown: all of them if they fit; otherwise the largest, but at least the largest of each
-- account type, with the rest of each type to be combined into an "other" series (so accounts of different types,
-- eg assets and liabilities, are never combined). A type with just one item left over shows that item instead.
-- Returns the positions of the items to show (in order), and of each type's items to combine (each at least two).
chooseSeries :: Int -> [(Maybe AccountType, Quantity)] -> ([Int], [[Int]])
chooseSeries :: Int -> [(Maybe AccountType, Quantity)] -> ([Int], [[Int]])
chooseSeries Int
n [(Maybe AccountType, Quantity)]
items
  | [(Maybe AccountType, Quantity)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Maybe AccountType, Quantity)]
items Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
n = ([Int]
positions, [])
  | Bool
otherwise = ([Int] -> [Int]
forall a. Ord a => [a] -> [a]
sort ([Int] -> [Int]) -> [Int] -> [Int]
forall a b. (a -> b) -> a -> b
$ Set Int -> [Int]
forall a. Set a -> [a]
S.toList Set Int
keptset [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [[Int]] -> [Int]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Int]]
singles, [[Int]]
multiples)
  where
    positions :: [Int]
positions = [Int
0 .. [(Maybe AccountType, Quantity)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Maybe AccountType, Quantity)]
items Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
    typeAt :: Int -> Maybe AccountType
typeAt Int
i = Maybe AccountType
-> ((Maybe AccountType, Quantity) -> Maybe AccountType)
-> Maybe (Maybe AccountType, Quantity)
-> Maybe AccountType
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Maybe AccountType
forall a. Maybe a
Nothing (Maybe AccountType, Quantity) -> Maybe AccountType
forall a b. (a, b) -> a
fst ([(Maybe AccountType, Quantity)]
items [(Maybe AccountType, Quantity)]
-> Int -> Maybe (Maybe AccountType, Quantity)
forall a. [a] -> Int -> Maybe a
`atMay` Int
i)
    sizeAt :: Int -> Quantity
sizeAt Int
i = Quantity
-> ((Maybe AccountType, Quantity) -> Quantity)
-> Maybe (Maybe AccountType, Quantity)
-> Quantity
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Quantity
0 (Maybe AccountType, Quantity) -> Quantity
forall a b. (a, b) -> b
snd ([(Maybe AccountType, Quantity)]
items [(Maybe AccountType, Quantity)]
-> Int -> Maybe (Maybe AccountType, Quantity)
forall a. [a] -> Int -> Maybe a
`atMay` Int
i)
    types :: [Maybe AccountType]
types = [Maybe AccountType] -> [Maybe AccountType]
forall a. Eq a => [a] -> [a]
nub ([Maybe AccountType] -> [Maybe AccountType])
-> [Maybe AccountType] -> [Maybe AccountType]
forall a b. (a -> b) -> a -> b
$ (Int -> Maybe AccountType) -> [Int] -> [Maybe AccountType]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Maybe AccountType
typeAt [Int]
positions
    ranked :: [Int]
ranked = (Int -> Down Quantity) -> [Int] -> [Int]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity)
-> (Int -> Quantity) -> Int -> Down Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Quantity
sizeAt) [Int]
positions
    -- the largest of each type, then more by size while they fit, with a series for each type's leftovers
    guaranteed :: Set Int
guaranteed = [Int] -> Set Int
forall a. Ord a => [a] -> Set a
S.fromList [Int
i | Maybe AccountType
ty <- [Maybe AccountType]
types, Just Int
i <- [(Int -> Bool) -> [Int] -> Maybe Int
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe AccountType
ty) (Maybe AccountType -> Bool)
-> (Int -> Maybe AccountType) -> Int -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Maybe AccountType
typeAt) [Int]
ranked]]
    keptset :: Set Int
keptset = (Set Int -> Int -> Set Int) -> Set Int -> [Int] -> Set Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\Set Int
ks Int
i -> let ks' :: Set Int
ks' = Int -> Set Int -> Set Int
forall a. Ord a => a -> Set a -> Set a
S.insert Int
i Set Int
ks in if Set Int -> Bool
fits Set Int
ks' then Set Int
ks' else Set Int
ks) Set Int
guaranteed [Int]
ranked
    fits :: Set Int -> Bool
fits Set Int
ks = Set Int -> Int
forall a. Set a -> Int
S.size Set Int
ks Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [[Int]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (([Int] -> Bool) -> [[Int]] -> [[Int]]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> ([Int] -> Bool) -> [Int] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null) ([[Int]] -> [[Int]]) -> [[Int]] -> [[Int]]
forall a b. (a -> b) -> a -> b
$ Set Int -> [[Int]]
leftovers Set Int
ks) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
n
    leftovers :: Set Int -> [[Int]]
leftovers Set Int
ks = [[Int
i | Int
i <- [Int]
positions, Int -> Maybe AccountType
typeAt Int
i Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe AccountType
ty, Int
i Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.notMember` Set Int
ks] | Maybe AccountType
ty <- [Maybe AccountType]
types]
    ([[Int]]
singles, [[Int]]
multiples) = ([Int] -> Bool) -> [[Int]] -> ([[Int]], [[Int]])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ((Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1) (Int -> Bool) -> ([Int] -> Int) -> [Int] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length) ([[Int]] -> ([[Int]], [[Int]])) -> [[Int]] -> ([[Int]], [[Int]])
forall a b. (a -> b) -> a -> b
$ ([Int] -> Bool) -> [[Int]] -> [[Int]]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> ([Int] -> Bool) -> [Int] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null) ([[Int]] -> [[Int]]) -> [[Int]] -> [[Int]]
forall a b. (a -> b) -> a -> b
$ Set Int -> [[Int]]
leftovers Set Int
keptset

-- | The label for an "other" series combining these accounts (given with their sizes), whose tooltips list them,
-- largest first, up to ten. When there are several "other" series, it names the accounts' common parent,
-- if they have one, to tell them apart.
otherLabel :: I18n.Translations -> Int -> [(AccountName, Quantity)] -> ChartLabel
otherLabel :: Translations -> Int -> [(AccountName, Quantity)] -> ChartLabel
otherLabel Translations
t Int
nothers [(AccountName, Quantity)]
sized = ChartLabel
label{lbTipLines = take maxlisted members ++ more}
  where
    maxlisted :: Int
maxlisted = Int
10
    members :: [AccountName]
members = ((AccountName, Quantity) -> AccountName)
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName, Quantity) -> AccountName
forall a b. (a, b) -> a
fst ([(AccountName, Quantity)] -> [AccountName])
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> a -> b
$ ((AccountName, Quantity) -> Down Quantity)
-> [(AccountName, Quantity)] -> [(AccountName, Quantity)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity)
-> ((AccountName, Quantity) -> Quantity)
-> (AccountName, Quantity)
-> Down Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AccountName, Quantity) -> Quantity
forall a b. (a, b) -> b
snd) [(AccountName, Quantity)]
sized
    nmore :: Int
nmore = [AccountName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [AccountName]
members Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
maxlisted
    -- TRANSLATORS: after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.
    more :: [AccountName]
more = [Translations -> Int -> AccountName -> AccountName -> AccountName
I18n.trn Translations
t Int
nmore AccountName
"…and {n} more" AccountName
"…and {n} more" | Int
nmore Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0]

    label :: ChartLabel
label
      | Int
nothers Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1, Bool -> Bool
not (AccountName -> Bool
T.null AccountName
parent) = AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Partial => AccountName -> AccountName -> AccountName -> AccountName
AccountName -> AccountName -> AccountName -> AccountName
T.replace AccountName
"{parent}" AccountName
parent (AccountName -> AccountName) -> AccountName -> AccountName
forall a b. (a -> b) -> a -> b
$ Translations -> Int -> AccountName -> AccountName -> AccountName
I18n.trn Translations
t Int
n AccountName
"other {parent} ({n} account)" AccountName
"other {parent} ({n} accounts)"
      | Bool
otherwise = AccountName -> ChartLabel
plainLabel (AccountName -> ChartLabel) -> AccountName -> ChartLabel
forall a b. (a -> b) -> a -> b
$ Translations -> Int -> AccountName -> AccountName -> AccountName
I18n.trn Translations
t Int
n AccountName
"other ({n} account)" AccountName
"other ({n} accounts)"
    accts :: [AccountName]
accts = ((AccountName, Quantity) -> AccountName)
-> [(AccountName, Quantity)] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName, Quantity) -> AccountName
forall a b. (a, b) -> a
fst [(AccountName, Quantity)]
sized
    n :: Int
n = [AccountName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [AccountName]
accts
    parent :: AccountName
parent = case (AccountName -> [AccountName]) -> [AccountName] -> CSV
forall a b. (a -> b) -> [a] -> [b]
map (Partial => AccountName -> AccountName -> [AccountName]
AccountName -> AccountName -> [AccountName]
T.splitOn AccountName
":") [AccountName]
accts of
      []     -> AccountName
""
      [AccountName]
p : CSV
ps -> AccountName -> [AccountName] -> AccountName
T.intercalate AccountName
":" ([AccountName] -> AccountName) -> [AccountName] -> AccountName
forall a b. (a -> b) -> a -> b
$ ([AccountName] -> [AccountName] -> [AccountName])
-> [AccountName] -> CSV -> [AccountName]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' [AccountName] -> [AccountName] -> [AccountName]
forall {b}. Eq b => [b] -> [b] -> [b]
commonPrefix [AccountName]
p CSV
ps
    commonPrefix :: [b] -> [b] -> [b]
commonPrefix [b]
a [b]
b = ((b, b) -> b) -> [(b, b)] -> [b]
forall a b. (a -> b) -> [a] -> [b]
map (b, b) -> b
forall a b. (a, b) -> a
fst ([(b, b)] -> [b]) -> [(b, b)] -> [b]
forall a b. (a -> b) -> a -> b
$ ((b, b) -> Bool) -> [(b, b)] -> [(b, b)]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile ((b -> b -> Bool) -> (b, b) -> Bool
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry b -> b -> Bool
forall a. Eq a => a -> a -> Bool
(==)) ([(b, b)] -> [(b, b)]) -> [(b, b)] -> [(b, b)]
forall a b. (a -> b) -> a -> b
$ [b] -> [b] -> [(b, b)]
forall a b. [a] -> [b] -> [(a, b)]
zip [b]
a [b]
b

-- | In tree mode, a parent account's row includes the amounts of its displayed subaccounts' rows.
-- Subtract those, leaving each row with only its own amounts.
ownAmountRows :: [MultiBalanceReportRow] -> [MultiBalanceReportRow]
ownAmountRows :: [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
ownAmountRows [PeriodicReportRow DisplayName MixedAmount]
rows = (PeriodicReportRow DisplayName MixedAmount
 -> PeriodicReportRow DisplayName MixedAmount)
-> [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map PeriodicReportRow DisplayName MixedAmount
-> PeriodicReportRow DisplayName MixedAmount
own [PeriodicReportRow DisplayName MixedAmount]
rows
  where
    fullname :: PeriodicReportRow DisplayName b -> AccountName
fullname = DisplayName -> AccountName
displayFull (DisplayName -> AccountName)
-> (PeriodicReportRow DisplayName b -> DisplayName)
-> PeriodicReportRow DisplayName b
-> AccountName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicReportRow DisplayName b -> DisplayName
forall a b. PeriodicReportRow a b -> a
prrName
    names :: Set AccountName
names = [AccountName] -> Set AccountName
forall a. Ord a => [a] -> Set a
S.fromList ([AccountName] -> Set AccountName)
-> [AccountName] -> Set AccountName
forall a b. (a -> b) -> a -> b
$ (PeriodicReportRow DisplayName MixedAmount -> AccountName)
-> [PeriodicReportRow DisplayName MixedAmount] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map PeriodicReportRow DisplayName MixedAmount -> AccountName
forall {b}. PeriodicReportRow DisplayName b -> AccountName
fullname [PeriodicReportRow DisplayName MixedAmount]
rows
    displayedParent :: PeriodicReportRow DisplayName b -> Maybe AccountName
displayedParent PeriodicReportRow DisplayName b
r = (AccountName -> Bool) -> [AccountName] -> Maybe AccountName
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (AccountName -> Set AccountName -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set AccountName
names) ([AccountName] -> Maybe AccountName)
-> [AccountName] -> Maybe AccountName
forall a b. (a -> b) -> a -> b
$ AccountName -> [AccountName]
parentAccountNames (AccountName -> [AccountName]) -> AccountName -> [AccountName]
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName b -> AccountName
forall {b}. PeriodicReportRow DisplayName b -> AccountName
fullname PeriodicReportRow DisplayName b
r
    children :: Map AccountName [PeriodicReportRow DisplayName MixedAmount]
children = ([PeriodicReportRow DisplayName MixedAmount]
 -> [PeriodicReportRow DisplayName MixedAmount]
 -> [PeriodicReportRow DisplayName MixedAmount])
-> [(AccountName, [PeriodicReportRow DisplayName MixedAmount])]
-> Map AccountName [PeriodicReportRow DisplayName MixedAmount]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
forall a. [a] -> [a] -> [a]
(++) [(AccountName
p, [PeriodicReportRow DisplayName MixedAmount
r]) | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
rows, Just AccountName
p <- [PeriodicReportRow DisplayName MixedAmount -> Maybe AccountName
forall {b}. PeriodicReportRow DisplayName b -> Maybe AccountName
displayedParent PeriodicReportRow DisplayName MixedAmount
r]]
    own :: PeriodicReportRow DisplayName MixedAmount
-> PeriodicReportRow DisplayName MixedAmount
own PeriodicReportRow DisplayName MixedAmount
r = case AccountName
-> Map AccountName [PeriodicReportRow DisplayName MixedAmount]
-> Maybe [PeriodicReportRow DisplayName MixedAmount]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (PeriodicReportRow DisplayName MixedAmount -> AccountName
forall {b}. PeriodicReportRow DisplayName b -> AccountName
fullname PeriodicReportRow DisplayName MixedAmount
r) Map AccountName [PeriodicReportRow DisplayName MixedAmount]
children of
      Maybe [PeriodicReportRow DisplayName MixedAmount]
Nothing -> PeriodicReportRow DisplayName MixedAmount
r
      Just [PeriodicReportRow DisplayName MixedAmount]
cs -> PeriodicReportRow DisplayName MixedAmount
r{prrAmounts = foldl' (zipWith maMinus) (prrAmounts r) (map prrAmounts cs)}

-- | The commodities with non-zero quantities in these report cells,
-- those in the most cells first, then alphabetically.
-- (Cells are counted, not amounts, since a cell can hold several amounts of one commodity with different costs.)
commoditiesByUse :: [MixedAmount] -> [CommoditySymbol]
commoditiesByUse :: [MixedAmount] -> [AccountName]
commoditiesByUse [MixedAmount]
cells =
  ((AccountName, Int) -> AccountName)
-> [(AccountName, Int)] -> [AccountName]
forall a b. (a -> b) -> [a] -> [b]
map (AccountName, Int) -> AccountName
forall a b. (a, b) -> a
fst ([(AccountName, Int)] -> [AccountName])
-> [(AccountName, Int)] -> [AccountName]
forall a b. (a -> b) -> a -> b
$ ((AccountName, Int) -> (Down Int, AccountName))
-> [(AccountName, Int)] -> [(AccountName, Int)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\(AccountName
c, Int
n) -> (Int -> Down Int
forall a. a -> Down a
Down Int
n, AccountName
c)) ([(AccountName, Int)] -> [(AccountName, Int)])
-> [(AccountName, Int)] -> [(AccountName, Int)]
forall a b. (a -> b) -> a -> b
$ Map AccountName Int -> [(AccountName, Int)]
forall k a. Map k a -> [(k, a)]
M.toList (Map AccountName Int -> [(AccountName, Int)])
-> Map AccountName Int -> [(AccountName, Int)]
forall a b. (a -> b) -> a -> b
$
  (Int -> Int -> Int) -> [(AccountName, Int)] -> Map AccountName Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) [(AccountName
c, Int
1 :: Int) | MixedAmount
ma <- [MixedAmount]
cells, AccountName
c <- Set AccountName -> [AccountName]
forall a. Set a -> [a]
S.toList (Set AccountName -> [AccountName])
-> Set AccountName -> [AccountName]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> Set AccountName
maCommodities MixedAmount
ma, AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c MixedAmount
ma Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0]

-- | A unit for values in this commodity: an amount of it from the list (for its display style),
-- with zero quantity and no cost.
unitAmount :: CommoditySymbol -> [Amount] -> Amount
unitAmount :: AccountName -> [Amount] -> Amount
unitAmount AccountName
c [Amount]
as = case (Amount -> Bool) -> [Amount] -> Maybe Amount
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
c) (AccountName -> Bool) -> (Amount -> AccountName) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> AccountName
acommodity) [Amount]
as of
  Just Amount
a  -> Amount
a{aquantity = 0, acost = Nothing, acostbasis = Nothing}
  Maybe Amount
Nothing -> Amount
nullamt{acommodity = c}

-- | With -T or -A: the total (in a chart of changes per period) and the average per period of the report's totals row,
-- in the given unit's commodity, labelled like the report table's columns.
-- In a chart of end balances, the average is of the period-end balances, and the total (the last balance) is left out.
-- Each keeps its own display style, eg an average of counts has a decimal place.
rowSummaries :: ReportOpts -> Amount -> PeriodicReportRow a MixedAmount -> [Summary]
rowSummaries :: forall a.
ReportOpts
-> Amount -> PeriodicReportRow a MixedAmount -> [Summary]
rowSummaries ReportOpts{BalanceAccumulation
balanceaccum_ :: ReportOpts -> BalanceAccumulation
balanceaccum_ :: BalanceAccumulation
balanceaccum_, Bool
row_total_ :: Bool
row_total_ :: ReportOpts -> Bool
row_total_, Bool
average_ :: ReportOpts -> Bool
average_ :: Bool
average_, Bool
percent_ :: ReportOpts -> Bool
percent_ :: Bool
percent_, Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} Amount
unit PeriodicReportRow a MixedAmount
totals
  | Bool
percent_ = []
  | Bool
otherwise =
      [SummaryKind -> AccountName -> Amount -> Summary
Summary SummaryKind
SummaryTotal (AccountName -> AccountName
heading AccountName
"Total") (Amount -> MixedAmount -> Amount
summaryAmount Amount
unit (MixedAmount -> Amount) -> MixedAmount -> Amount
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow a MixedAmount -> MixedAmount
forall a b. PeriodicReportRow a b -> b
prrTotal PeriodicReportRow a MixedAmount
totals) | Bool
row_total_, BalanceAccumulation
balanceaccum_ BalanceAccumulation -> BalanceAccumulation -> Bool
forall a. Eq a => a -> a -> Bool
== BalanceAccumulation
PerPeriod]
      [Summary] -> [Summary] -> [Summary]
forall a. [a] -> [a] -> [a]
++ [SummaryKind -> AccountName -> Amount -> Summary
Summary SummaryKind
SummaryAverage (AccountName -> AccountName
heading AccountName
"Average") (Amount -> MixedAmount -> Amount
summaryAmount Amount
unit (MixedAmount -> Amount) -> MixedAmount -> Amount
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow a MixedAmount -> MixedAmount
forall a b. PeriodicReportRow a b -> b
prrAverage PeriodicReportRow a MixedAmount
totals) | Bool
average_]
  where
    heading :: AccountName -> AccountName
heading = Translations -> AccountName -> AccountName -> AccountName
I18n.trc Translations
translations_ AccountName
"column heading"

-- | A mixed amount's quantity in the given unit's commodity, as that unit, with the amount's own display style if it has one.
summaryAmount :: Amount -> MixedAmount -> Amount
summaryAmount :: Amount -> MixedAmount -> Amount
summaryAmount Amount
unit MixedAmount
ma = case [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw MixedAmount
ma, Amount -> AccountName
acommodity Amount
a AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
c] of
  Amount
a:[Amount]
_ -> Amount
unit{aquantity = quantityIn c ma, astyle = astyle a}
  []  -> Amount
unit
  where c :: AccountName
c = Amount -> AccountName
acommodity Amount
unit

-- | The total quantity of this commodity in a mixed amount, ignoring costs.
quantityIn :: CommoditySymbol -> MixedAmount -> Quantity
quantityIn :: AccountName -> MixedAmount -> Quantity
quantityIn AccountName
c MixedAmount
ma = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Amount -> Quantity
aquantity Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw MixedAmount
ma, Amount -> AccountName
acommodity Amount
a AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
== AccountName
c]

-- | A label for an account (or accounts, eg a depth-clipped one), from a report row's name.
-- A "..." row (all accounts, eg with depth 0) is labelled as not an account, like a total, so that alone it is drawn neutral.
accountLabel :: (AccountName -> Maybe AccountType) -> DisplayName -> ChartLabel
accountLabel :: (AccountName -> Maybe AccountType) -> DisplayName -> ChartLabel
accountLabel AccountName -> Maybe AccountType
accttype DisplayName{AccountName
displayFull :: DisplayName -> AccountName
displayFull :: AccountName
displayFull, AccountName
displayName :: AccountName
displayName :: DisplayName -> AccountName
displayName, Int
displayIndent :: Int
displayIndent :: DisplayName -> Int
displayIndent} =
  AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
displayFull AccountName
displayName Int
displayIndent (AccountName -> Maybe AccountType
accttype AccountName
displayFull) (AccountName
displayFull AccountName -> AccountName -> Bool
forall a. Eq a => a -> a -> Bool
/= AccountName
"...") []

-- | A label for something other than an account, eg a total.
plainLabel :: Text -> ChartLabel
plainLabel :: AccountName -> ChartLabel
plainLabel AccountName
t = AccountName
-> AccountName
-> Int
-> Maybe AccountType
-> Bool
-> [AccountName]
-> ChartLabel
ChartLabel AccountName
t AccountName
t Int
0 Maybe AccountType
forall a. Maybe a
Nothing Bool
False []