{-|

The @holdings@ command shows a report of investment holdings (lot-tracked assets).

Work in progress; see doc/SPEC-holdings.md.
Currently it shows the Date, Age, Units, Unit/Avg cost, Price, Cost,
Value, Weight, UGain, UGain%, RGain and XIRR columns, one row per
account (or lot subaccount, with --lots) and held commodity. In tree
mode, positions are grouped into account sections: a heading row per
account showing its subtree's totals, its positions beneath it named
by their commodity, and with --lots each position's lots beneath it.

The report computation (holdingsReport) is exported for reuse by other
UIs; the holdings command renders it in the usual output formats.

-}

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands.Holdings (
  holdingsmode
 ,holdings
 ,HoldingsReport(..)
 ,HoldingsReportOpts(..)
 ,HoldingsTotals(..)
 ,HoldingsLine(..)
 ,Holding(..)
 ,holdingsReport
 ,holdingsReportAsChart
 ,holdingsReportsAsChart
 ,holdingsPeriodReports
 ,holdingsPeriodsTitle
 ,holdingsUnpricedNote
 ,holdingsClosedHidden
 ,holdingsClosedNote
 ,totalsLeftOut
 ,showage
 ,showPercentWith
) where

import Control.Applicative ((<|>))
import Control.Monad (guard)
import Data.Aeson (Value, object, (.=))
import Data.Decimal (roundTo)
import Data.Default (def)
import Data.List.Extra (find, intercalate, intersperse, minimumBy, nubSort, nubSortOn, sortOn, transpose)
import Data.Map.Strict qualified as M
import Data.Set qualified as S
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, maybeToList)
import Data.Ord (Down(..), comparing)
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Time.Calendar (Day, addDays, diffDays)
import System.Console.ANSI (Color(..), ColorIntensity(..))
import System.Console.CmdArgs.Explicit (flagNone, flagReq)
import Safe (headMay)
import Text.Printf (printf)

import Hledger
import Hledger.Cli.Chart (chartFlag, chartRequested, chartWidthFlag, unitAmount, writeChart)
import Hledger.Cli.CliOptions
import Hledger.Cli.CompoundBalanceCommand (titleInterval)
import Hledger.Cli.Commands.Balance.Internal (addTotalBorders)
import Hledger.Cli.Commands.Print (roundFromRawOpts)
import Hledger.Cli.Utils (unsupportedOutputFormatError, warnIfLargeMultiPeriodReport, writeOutputLazyText)
import Hledger.Cli.Xirr (xirr)
import Hledger.Utils.I18n qualified as I18n
import Hledger.Write.Chart (Chart(..), ChartLabel(..), Mark(..), Panel(..), BarLayout(..), Series(..), SeriesRole(..), XAxis(..))
import Hledger.Write.Csv (CSV, printCSV, printTSV)
import Hledger.Write.Html (Html, htmlAsLazyText, titledTableHtml, toHtml)
import Hledger.Write.Ods (printFods)
import Hledger.Write.Spreadsheet (addHeaderBorders, headerCell)
import Hledger.Write.Spreadsheet qualified as Ods
import System.IO qualified as IO
import Text.Blaze.Html5 ((!))
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A
import Text.Tabular.AsciiWide

-- | Command line options for this command.
holdingsmode :: Mode RawOpts
holdingsmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Holdings.txt")
  (Bool -> [Flag RawOpts]
flattreeflags Bool
True [Flag RawOpts] -> [Flag RawOpts] -> [Flag RawOpts]
forall a. [a] -> [a] -> [a]
++
   [[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"no-elide"] (String -> RawOpts -> RawOpts
setboolopt String
"no-elide") String
"in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"full-names"] (String -> RawOpts -> RawOpts
setboolopt String
"full-names") String
"in tree mode, show full account names instead of indented leaf names"
   ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"drop"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"drop" String
s RawOpts
opts) String
"N" String
"omit N leading account name parts; in tree mode, remove the first N levels"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"sort-amount",String
"S"] (String -> RawOpts -> RawOpts
setboolopt String
"sort-amount") String
"sort by value (or with -B, cost) instead of account name, largest first"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"no-total",String
"N"] (String -> RawOpts -> RawOpts
setboolopt String
"no-total") String
"omit the final total row"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"change"] (String -> RawOpts -> RawOpts
setboolopt String
"change") String
"show gains during the report period, or with a report interval, during each period (default with a start date and no interval)"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"cumulative"] (String -> RawOpts -> RawOpts
setboolopt String
"cumulative") String
"with a report interval, show gains from the report start date to each period's end"
   ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"historical",String
"H"] (String -> RawOpts -> RawOpts
setboolopt String
"historical") String
"show gains since acquisition, ignoring the report start date (default with a report interval)"
   ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq [String
"round"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"round" String
s RawOpts
opts) String
"TYPE" (String -> Flag RawOpts) -> String -> Flag RawOpts
forall a b. (a -> b) -> a -> b
$
     String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"\n"
     [String
"how much rounding or padding should be done when displaying amounts ?"
     ,String
"none - show original decimal digits"
     ,String
"soft - just add or remove decimal zeros"
     ,String
"       to match precision"
     ,String
"hard - round amounts to precision (default)"
     ,String
"all  - also round cost amounts to precision"
     ]
   ,Flag RawOpts
chartFlag
   ,Flag RawOpts
chartWidthFlag
   ,[String] -> Flag RawOpts
outputFormatFlag [String
"txt",String
"csv",String
"tsv",String
"html",String
"fods",String
"json",String
"svg"]
   ,Flag RawOpts
outputFileFlag
   ,Flag RawOpts
outputViewFlag])
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"[QUERY]")

-- | One holding: one commodity held in one displayed account (or lot
-- subaccount), with its report attributes. Each holding is one row of
-- the text/html/fods table and one record of the csv/tsv/json output.
-- A commodity fully disposed from a displayed account also gets a
-- holding, with zero units, so its realised gain stays visible.
data Holding = Holding {
   Holding -> Text
hAccount   :: AccountName
  ,Holding -> Text
hCommodity :: CommoditySymbol
  ,Holding -> Maybe Day
hDate      :: Maybe Day        -- ^ acquisition date, when the lots share one
  ,Holding -> Maybe Integer
hAge       :: Maybe Integer    -- ^ days held at the report date
  ,Holding -> Amount
hUnits     :: Amount           -- ^ units held, styled
  ,Holding -> Maybe Amount
hUnitCost  :: Maybe Amount     -- ^ unit or average cost
  ,Holding -> [Amount]
hPrice     :: [Amount]         -- ^ market price(s) at the valuation date (several if the lots' value commodities differ)
  ,Holding -> [Amount]
hCost      :: [Amount]         -- ^ total cost basis (multiple amounts if cost commodities are mixed)
  ,Holding -> [Amount]
hValue     :: [Amount]         -- ^ market value, when all lots are priced (multiple amounts if value commodities are mixed)
  ,Holding -> Maybe Quantity
hWeight    :: Maybe Quantity   -- ^ percentage of the portfolio's value, unrounded
  ,Holding -> [Amount]
hUgain     :: [Amount]         -- ^ unrealised gain, when values and costs cover the same commodities
  ,Holding -> Maybe Quantity
hUgainPct  :: Maybe Quantity   -- ^ unrealised gain percent, unrounded
  ,Holding -> [Amount]
hRgain     :: [Amount]         -- ^ realised gain, from disposals so far
  ,Holding -> Maybe Double
hXirr      :: Maybe Double     -- ^ annualised internal rate of return percent
  ,Holding -> [(Day, Amount)]
hFlows     :: [(Day, Amount)]  -- ^ its dated cashflows (negative = money invested), which XIRR is calculated from; not displayed
  }

-- Machine-readable fields for the csv/tsv output: full account name, age
-- in days, bare units and rounded gain percent numbers, machine-format
-- amounts (no digit group marks).
holdingCsv :: Holding -> [T.Text]
holdingCsv :: Holding -> [Text]
holdingCsv Holding
h =
  [Holding -> Text
hAccount Holding
h
  ,Holding -> Text
hCommodity Holding
h
  ,Text -> (Day -> Text) -> Maybe Day -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Day -> Text
showDate (Holding -> Maybe Day
hDate Holding
h)
  ,Text -> (Integer -> Text) -> Maybe Integer -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Integer -> String) -> Integer -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> String
forall a. Show a => a -> String
show) (Holding -> Maybe Integer
hAge Holding
h)
  ,String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> Amount -> String
showAmountWith AmountFormat
machineFmt{displayCommodity=False} (Holding -> Amount
hUnits Holding
h)
  ,Text -> (Amount -> Text) -> Maybe Amount -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Amount -> Text
showamt (Holding -> Maybe Amount
hUnitCost Holding
h)
  ,[Amount] -> Text
showamts (Holding -> [Amount]
hPrice Holding
h)
  ,String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
machineFmt (MixedAmount -> String) -> MixedAmount -> String
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed ([Amount] -> MixedAmount) -> [Amount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hCost Holding
h
  ,[Amount] -> Text
showamts (Holding -> [Amount]
hValue Holding
h)
  ,Text -> (Quantity -> Text) -> Maybe Quantity -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Quantity -> String) -> Quantity -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Quantity -> String
forall a. Show a => a -> String
show (Quantity -> String)
-> (Quantity -> Quantity) -> Quantity -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1) (Holding -> Maybe Quantity
hWeight Holding
h)
  ,[Amount] -> Text
showamts (Holding -> [Amount]
hUgain Holding
h)
  ,Text -> (Quantity -> Text) -> Maybe Quantity -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Quantity -> String) -> Quantity -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Quantity -> String
forall a. Show a => a -> String
show (Quantity -> String)
-> (Quantity -> Quantity) -> Quantity -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1) (Holding -> Maybe Quantity
hUgainPct Holding
h)
  ,[Amount] -> Text
showamts (Holding -> [Amount]
hRgain Holding
h)
  ,Text -> (Double -> Text) -> Maybe Double -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Double -> String) -> Double -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Double -> String
forall r. PrintfType r => String -> r
printf String
"%.1f") (Holding -> Maybe Double
hXirr Holding
h)
  ]
  where
    showamt :: Amount -> Text
showamt  = String -> Text
T.pack (String -> Text) -> (Amount -> String) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> Amount -> String
showAmountWith AmountFormat
machineFmt
    showamts :: [Amount] -> Text
showamts [] = Text
""
    showamts [Amount]
as = String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
machineFmt (MixedAmount -> String) -> MixedAmount -> String
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
as

-- | Machine-readable fields for a period's totals, in the csv/tsv output with a report interval: like 'holdingCsv'.
periodTotalsCsv :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> [T.Text]
periodTotalsCsv :: Day -> (Map Text AmountStyle, HoldingsTotals) -> [Text]
periodTotalsCsv Day
d (Map Text AmountStyle
_, HoldingsTotals
tot) =
  [Day -> Text
showDate Day
d
  ,Text -> (Amount -> Text) -> Maybe Amount -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Amount -> String) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> Amount -> String
showAmountWith AmountFormat
machineFmt{displayCommodity=False}) (HoldingsTotals -> Maybe Amount
htUnits HoldingsTotals
tot)
  ,Text -> (Amount -> Text) -> Maybe Amount -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Amount -> Text
showamt (HoldingsTotals -> Maybe Amount
htAvgCost HoldingsTotals
tot)
  ,Text -> (Amount -> Text) -> Maybe Amount -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Amount -> Text
showamt (HoldingsTotals -> Maybe Amount
htPrice HoldingsTotals
tot)
  ,[Amount] -> Text
showamts (HoldingsTotals -> [Amount]
htCost HoldingsTotals
tot)
  ,Text -> ([Amount] -> Text) -> Maybe [Amount] -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" [Amount] -> Text
showamts (HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
tot)
  ,Text -> ([Amount] -> Text) -> Maybe [Amount] -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" [Amount] -> Text
showamts (HoldingsTotals -> Maybe [Amount]
htUgain HoldingsTotals
tot)
  ,Text -> (Quantity -> Text) -> Maybe Quantity -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Quantity -> String) -> Quantity -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Quantity -> String
forall a. Show a => a -> String
show (Quantity -> String)
-> (Quantity -> Quantity) -> Quantity -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1) (HoldingsTotals -> Maybe Quantity
htUgainPct HoldingsTotals
tot)
  ,[Amount] -> Text
showamts (HoldingsTotals -> [Amount]
htRgain HoldingsTotals
tot)
  ,Text -> (Double -> Text) -> Maybe Double -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (String -> Text
T.pack (String -> Text) -> (Double -> String) -> Double -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Double -> String
forall r. PrintfType r => String -> r
printf String
"%.1f") (HoldingsTotals -> Maybe Double
htXirr HoldingsTotals
tot)
  ,Text -> [Text] -> Text
T.intercalate Text
", " (HoldingsTotals -> [Text]
htUnpriced HoldingsTotals
tot)
  ]
  where
    showamt :: Amount -> Text
showamt Amount
a = [Amount] -> Text
showamts [Amount
a]
    showamts :: [Amount] -> Text
showamts [] = Text
""
    showamts [Amount]
as = String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
machineFmt (MixedAmount -> String) -> MixedAmount -> String
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
as

-- | A period's totals, in the json output with a report interval: like 'holdingJson'.
periodTotalsJson :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> Value
periodTotalsJson :: Day -> (Map Text AmountStyle, HoldingsTotals) -> Value
periodTotalsJson Day
d (Map Text AmountStyle
_, HoldingsTotals
tot) = [Pair] -> Value
object
  [Key
"date"       Key -> Day -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Day
d
  ,Key
"units"      Key -> Maybe Quantity -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Amount -> Quantity
aquantity (Amount -> Quantity) -> Maybe Amount -> Maybe Quantity
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe Amount
htUnits HoldingsTotals
tot)
  ,Key
"avgcost"    Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ([Amount] -> Text
showamts ([Amount] -> Text) -> (Amount -> [Amount]) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> [Amount] -> [Amount]
forall a. a -> [a] -> [a]
:[]) (Amount -> Text) -> Maybe Amount -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe Amount
htAvgCost HoldingsTotals
tot)
  ,Key
"unitprice"  Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ([Amount] -> Text
showamts ([Amount] -> Text) -> (Amount -> [Amount]) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> [Amount] -> [Amount]
forall a. a -> [a] -> [a]
:[]) (Amount -> Text) -> Maybe Amount -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe Amount
htPrice HoldingsTotals
tot)
  ,Key
"totalcost"  Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Text
showamts (HoldingsTotals -> [Amount]
htCost HoldingsTotals
tot)
  ,Key
"totalvalue" Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ([Amount] -> Text
showamts ([Amount] -> Text) -> Maybe [Amount] -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
tot)
  ,Key
"ugain"      Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ([Amount] -> Text
showamts ([Amount] -> Text) -> Maybe [Amount] -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe [Amount]
htUgain HoldingsTotals
tot)
  ,Key
"ugainpct"   Key -> Maybe Quantity -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1 (Quantity -> Quantity) -> Maybe Quantity -> Maybe Quantity
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HoldingsTotals -> Maybe Quantity
htUgainPct HoldingsTotals
tot)
  ,Key
"rgain"      Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Maybe Text
mshowamts (HoldingsTotals -> [Amount]
htRgain HoldingsTotals
tot)
  ,Key
"xirr"       Key -> Maybe Double -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= HoldingsTotals -> Maybe Double
htXirr HoldingsTotals
tot
  ,Key
"unpriced"   Key -> [Text] -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= HoldingsTotals -> [Text]
htUnpriced HoldingsTotals
tot
  ]
  where
    showamts :: [Amount] -> Text
showamts = String -> Text
T.pack (String -> Text) -> ([Amount] -> String) -> [Amount] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
machineFmt (MixedAmount -> String)
-> ([Amount] -> MixedAmount) -> [Amount] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed
    mshowamts :: [Amount] -> Maybe Text
mshowamts [Amount]
as = case [Amount]
as of [] -> Maybe Text
forall a. Maybe a
Nothing; [Amount]
_ -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ [Amount] -> Text
showamts [Amount]
as

holdingJson :: Holding -> Value
holdingJson :: Holding -> Value
holdingJson Holding
h = [Pair] -> Value
object
  [Key
"account"   Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Holding -> Text
hAccount Holding
h
  ,Key
"commodity" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Holding -> Text
hCommodity Holding
h
  ,Key
"date"      Key -> Maybe Day -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Holding -> Maybe Day
hDate Holding
h
  ,Key
"age"       Key -> Maybe Integer -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Holding -> Maybe Integer
hAge Holding
h
  ,Key
"units"     Key -> Quantity -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Amount -> Quantity
aquantity (Holding -> Amount
hUnits Holding
h)
  ,Key
"unitcost"   Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Amount -> Text
showamt (Amount -> Text) -> Maybe Amount -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Holding -> Maybe Amount
hUnitCost Holding
h)
  ,Key
"unitprice"  Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Maybe Text
mshowamts (Holding -> [Amount]
hPrice Holding
h)
  ,Key
"totalcost"  Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Text
showamts (Holding -> [Amount]
hCost Holding
h)
  ,Key
"totalvalue" Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Maybe Text
mshowamts (Holding -> [Amount]
hValue Holding
h)
  ,Key
"weight"    Key -> Maybe Quantity -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1 (Quantity -> Quantity) -> Maybe Quantity -> Maybe Quantity
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Holding -> Maybe Quantity
hWeight Holding
h)
  ,Key
"ugain"     Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Maybe Text
mshowamts (Holding -> [Amount]
hUgain Holding
h)
  ,Key
"ugainpct"  Key -> Maybe Quantity -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1 (Quantity -> Quantity) -> Maybe Quantity -> Maybe Quantity
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Holding -> Maybe Quantity
hUgainPct Holding
h)
  ,Key
"rgain"     Key -> Maybe Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Amount] -> Maybe Text
mshowamts (Holding -> [Amount]
hRgain Holding
h)
  ,Key
"xirr"      Key -> Maybe Double -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Holding -> Maybe Double
hXirr Holding
h
  ]
  where
    showamt :: Amount -> Text
showamt  = String -> Text
T.pack (String -> Text) -> (Amount -> String) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> Amount -> String
showAmountWith AmountFormat
machineFmt
    showamts :: [Amount] -> Text
showamts = String -> Text
T.pack (String -> Text) -> ([Amount] -> String) -> [Amount] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
machineFmt (MixedAmount -> String)
-> ([Amount] -> MixedAmount) -> [Amount] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed
    mshowamts :: [Amount] -> Maybe Text
mshowamts [Amount]
as = case [Amount]
as of [] -> Maybe Text
forall a. Maybe a
Nothing; [Amount]
_ -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ [Amount] -> Text
showamts [Amount]
as

-- | Show an age in days compactly: in days, or if a year or more,
-- in years with one decimal digit (approximating years as 365 days):
-- eg 44d, 1.1y.
showage :: Integer -> T.Text
showage :: Integer -> Text
showage Integer
d
  | Integer
d Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
365  = String -> Text
T.pack (Quantity -> String
forall a. Show a => a -> String
show (Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
1 (Integer -> Quantity
forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
d Quantity -> Quantity -> Quantity
forall a. Fractional a => a -> a -> a
/ Quantity
365))) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"y"
  | Bool
otherwise = String -> Text
T.pack (Integer -> String
forall a. Show a => a -> String
show Integer
d) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"d"

-- | Show a percentage (eg for the Weight, UGain% and XIRR columns) as a
-- "%" commodity amount, using the given styles' display style for the
-- "%" commodity (eg from a commodity directive or -c, or
-- holdingsReport's default): eg 64.3%.
showPercentWith :: M.Map CommoditySymbol AmountStyle -> Quantity -> T.Text
showPercentWith :: Map Text AmountStyle -> Quantity -> Text
showPercentWith Map Text AmountStyle
styles Quantity
p =
  String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> Amount -> String
showAmountWith AmountFormat
noCostFmt{displayZeroCommodity=True} (Amount -> String) -> Amount -> String
forall a b. (a -> b) -> a -> b
$
  Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles Amount
nullamt{acommodity="%", aquantity=p}

-- | Options for the holdings report, besides the usual ReportSpec.
data HoldingsReportOpts = HoldingsReportOpts {
   HoldingsReportOpts -> Bool
hroLots     :: Bool      -- ^ show each lot (one row per lot subaccount) rather than aggregating them per account, like --lots
  ,HoldingsReportOpts -> Rounding
hroRounding :: Rounding  -- ^ how much rounding or padding to apply to displayed amounts, like --round
  ,HoldingsReportOpts -> Maybe PriceOracle
hroPriceOracle :: Maybe PriceOracle
     -- ^ the journal's price oracle, if already made (for the report options' --infer-market-prices),
     --   so that several reports can share it and its cache; otherwise the report makes one
  }

-- | The grand totals of a holdings report, summed over its topmost
-- displayed rows (which include everything below them) - except RGain
-- and XIRR, which cover all the lots within the query and end date,
-- including fully disposed lots, commodities and accounts, which have
-- no row unless -E is used; so the totals are the same in list or tree
-- mode, with or without --lots or -E (#2769). Absent components
-- (Nothing or empty) are shown as blank cells.
-- Units, and the average cost per unit, are present only when the
-- holdings are all in one commodity (a multi-commodity total would
-- widen the column for everyone, and a multi-commodity average is
-- not meaningful); the average also needs a single cost commodity.
-- Value and gains are absent unless all holdings have a market price.
data HoldingsTotals = HoldingsTotals {
   HoldingsTotals -> Maybe Amount
htUnits    :: Maybe Amount    -- ^ total units held, when all in one commodity
  ,HoldingsTotals -> Maybe Amount
htAvgCost  :: Maybe Amount    -- ^ their average unit cost, when also in one cost commodity
  ,HoldingsTotals -> Maybe Amount
htPrice    :: Maybe Amount    -- ^ their unit market price, when they are in one commodity with one price (shown with a report interval)
  ,HoldingsTotals -> [Amount]
htCost     :: [Amount]        -- ^ total cost basis, per cost commodity
  ,HoldingsTotals -> Maybe [Amount]
htValue    :: Maybe [Amount]  -- ^ total market value, per value commodity, of the holdings whose value is known (see htUnpriced)
  ,HoldingsTotals -> Maybe Quantity
htWeight   :: Maybe Quantity  -- ^ percent of the portfolio's value, unrounded
  ,HoldingsTotals -> Maybe [Amount]
htUgain    :: Maybe [Amount]  -- ^ total unrealised gain, when values and costs are comparable (of the holdings whose value is known)
  ,HoldingsTotals -> Maybe Quantity
htUgainPct :: Maybe Quantity  -- ^ total unrealised gain percent, unrounded (likewise)
  ,HoldingsTotals -> [Amount]
htRgain    :: [Amount]        -- ^ total realised gain, per cost commodity
  ,HoldingsTotals -> Maybe Double
htXirr     :: Maybe Double    -- ^ the portfolio's annualised internal rate of return percent (likewise)
  ,HoldingsTotals -> [(Day, Amount)]
htFlows    :: [(Day, Amount)] -- ^ the dated cashflows (negative = money invested) which XIRR is calculated from
                                 --   (of the holdings whose value is known); not displayed
  ,HoldingsTotals -> [Amount]
htValuedCost :: [Amount]      -- ^ the total cost of the holdings counted in the value; not displayed
  ,HoldingsTotals -> [Text]
htUnpriced :: [CommoditySymbol]
     -- ^ the commodities left out of the value, UGain, UGain%, XIRR and cashflows:
     --   those held with no market price for some lot, so whose value is unknown
     --   (and in period gains, those left out at the start or the end; see holdingsPeriodGains)
  }

-- | One display line of the holdings report.
data HoldingsLine
  -- | An account heading row (tree mode): an account with subaccounts
  -- or several commodities, showing its subtree's totals.
  = HoldingsHeading {
      HoldingsLine -> Int
hlIndent  :: Int             -- ^ tree indent depth, 0 at top level
     ,HoldingsLine -> Text
hlAccount :: AccountName     -- ^ the full account name
     ,HoldingsLine -> Text
hlDisplay :: T.Text          -- ^ the name to display: the leaf name, or a squashed chain like b:c
     ,HoldingsLine -> HoldingsTotals
hlTotals  :: HoldingsTotals  -- ^ the account's subtree totals (see hrAccountTotals)
    }
  -- | A holding's line: a position, lot, or depth-clipped aggregate,
  -- one line per held commodity.
  | HoldingsPosition {
      hlIndent  :: Int          -- ^ tree indent depth, 0 at top level and in list mode
     ,hlAccount :: AccountName  -- ^ the account (or lot subaccount) the line belongs to
     ,hlDisplay :: T.Text       -- ^ the name to display: the account name (list mode, or a combined tree row), its commodity (a position under its account's heading), or a lot's name
     ,HoldingsLine -> Bool
hlIsLot   :: Bool         -- ^ is this a lot subaccount's line ?
     ,HoldingsLine -> Holding
hlHolding :: Holding
    }

-- | A computed holdings report: the display lines and totals shown by
-- the holdings command, renderable by any UI.
data HoldingsReport = HoldingsReport {
   HoldingsReport -> Day
hrDate            :: Day     -- ^ the date holdings are shown at: the day before the (exclusive) report end date if specified, otherwise today
  ,HoldingsReport -> [HoldingsLine]
hrLines           :: [HoldingsLine]
     -- ^ the display lines in display order: flat holdings in list
     --   mode, or account sections in tree mode
  ,HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows            :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
     -- ^ the holdings as flat records, for machine-readable output:
     --   each holding, paired with its report row (a row holding
     --   several commodities repeats on several lines)
  ,HoldingsReport -> HoldingsTotals
hrTotals          :: HoldingsTotals  -- ^ the grand totals row's components
  ,HoldingsReport -> Text -> HoldingsTotals
hrAccountTotals   :: AccountName -> HoldingsTotals
     -- ^ the totals of the lots at or under any one account, computed
     --   like the grand totals row (eg for an account heading row);
     --   Weight is relative to the whole portfolio's value
  ,HoldingsReport -> [Text] -> HoldingsTotals
hrTotalsExcluding :: [CommoditySymbol] -> HoldingsTotals
     -- ^ the grand totals as computed (before any period gains), leaving
     --   these commodities out of the value, gains and cashflows too
     --   (as if unpriced; see htUnpriced)
  ,HoldingsReport -> [Text] -> Text -> HoldingsTotals
hrAccountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals
     -- ^ likewise for an account's totals
  ,HoldingsReport -> Text
hrUnitCostHeading :: T.Text  -- ^ what the unit cost column shows: "Unit cost", "Avg cost", or "Unit/Avg cost"
  ,HoldingsReport -> Map Text AmountStyle
hrStyles          :: M.Map CommoditySymbol AmountStyle
     -- ^ the journal's display styles with hroRounding applied, plus a
     --   style for the "%" commodity, for showing the percent columns
     --   (see showPercentWith)
  ,HoldingsReport -> Maybe DateSpan
hrGainsPeriod     :: Maybe DateSpan
     -- ^ when the report has a start date: the report period, from it to
     --   the report date (inclusive), which the gain columns (UGain, UGain%,
     --   RGain, XIRR) then cover instead of each holding's whole life
     --   (see holdingsPeriodGains)
  ,HoldingsReport -> (Text, Text) -> Bool
hrKeepLot         :: (AccountName, CommoditySymbol) -> Bool
     -- ^ which lots (lot subaccount, commodity) this report counts: all,
     --   or with change:/balance: terms, those of the lines shown
  }

-- | Chart a holdings report: a bar for each holding (a commodity in an account, or a lot), in each of its commodities' panels
-- (see 'holdingsBarsChart'). Holdings are labelled by account (with --drop applied) and commodity, also in tree mode,
-- since account headings are not drawn. Their values are not marked, since each bar's solid part reaches its value
-- (cost basis and gain, or the part of the cost basis still worth, with the part lost beyond it, hatched).
holdingsReportAsChart :: ReportOpts -> T.Text -> HoldingsReport -> Chart
holdingsReportAsChart :: ReportOpts -> Text -> HoldingsReport -> Chart
holdingsReportAsChart ReportOpts
ropts Text
title HoldingsReport
rpt =
  ReportOpts
-> Mark
-> Map Text AmountStyle
-> Text
-> XAxis
-> [([Amount], [Amount], [Amount])]
-> Chart
holdingsBarsChart ReportOpts
ropts Mark
MarkNone (HoldingsReport -> Map Text AmountStyle
hrStyles HoldingsReport
rpt) Text
title ([ChartLabel] -> XAxis
XCategories ([ChartLabel] -> XAxis) -> [ChartLabel] -> XAxis
forall a b. (a -> b) -> a -> b
$ ((Text, Bool, Holding) -> ChartLabel)
-> [(Text, Bool, Holding)] -> [ChartLabel]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Bool, Holding) -> ChartLabel
label [(Text, Bool, Holding)]
positions) [Holding -> ([Amount], [Amount], [Amount])
holdingBarParts Holding
h | (Text
_, Bool
_, Holding
h) <- [(Text, Bool, Holding)]
positions]
  where
    -- each holding's account, whether it is a lot, and the holding
    positions :: [(Text, Bool, Holding)]
positions = [(Text
a, Bool
islot, Holding
h) | HoldingsPosition{hlAccount :: HoldingsLine -> Text
hlAccount = Text
a, hlIsLot :: HoldingsLine -> Bool
hlIsLot = Bool
islot, hlHolding :: HoldingsLine -> Holding
hlHolding = Holding
h} <- HoldingsReport -> [HoldingsLine]
hrLines HoldingsReport
rpt]
    -- eg "assets:broker AAPL", or for a lot, "assets:broker AAPL {2024-01-10, $150}"
    label :: (Text, Bool, Holding) -> ChartLabel
label (Text
acct, Bool
islot, Holding
h) = Text
-> Text -> Int -> Maybe AccountType -> Bool -> [Text] -> ChartLabel
ChartLabel (Text -> Text
name Text
acct) (Text -> Text
name (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Int -> Text -> Text
accountNameDrop (ReportOpts -> Int
drop_ ReportOpts
ropts) Text
acct) Int
0 Maybe AccountType
forall a. Maybe a
Nothing Bool
True []
      where
        name :: Text -> Text
name Text
a
          | Bool
islot     = [Text] -> Text
T.unwords [Text -> Text
parentAccountName Text
a, Holding -> Text
hCommodity Holding
h, Text -> Text
accountLeafName Text
a]
          | Bool
otherwise = Text
a Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Holding -> Text
hCommodity Holding
h

-- | Chart holdings reports at the ends of some periods: a bar for each period, showing all the holdings then,
-- as their total cost basis and their net unrealised gain or loss (see 'holdingsBarsChart').
-- Periods are labelled by their end dates, the holdings' dates.
-- When the reports' gain columns cover each period, or the time since the first period's start
-- (see 'holdingsPeriodReports'), the chart shows those gains instead (see 'holdingsGainsChart'),
-- since the holdings' unrealised gains in this chart are always since acquisition.
-- As in the table, the periods whose values and gains exclude holdings with no market price are starred,
-- and a note says which.
holdingsReportsAsChart :: ReportOpts -> BalanceAccumulation -> T.Text -> [(DateSpan, HoldingsReport)] -> Chart
holdingsReportsAsChart :: ReportOpts
-> BalanceAccumulation
-> Text
-> [(DateSpan, HoldingsReport)]
-> Chart
holdingsReportsAsChart ReportOpts
ropts BalanceAccumulation
accum Text
title [(DateSpan, HoldingsReport)]
rpts = Chart
chart{chNotes = maybeToList note}
  where
    chart :: Chart
chart = case BalanceAccumulation
accum of
      BalanceAccumulation
Historical -> ReportOpts
-> Mark
-> Map Text AmountStyle
-> Text
-> XAxis
-> [([Amount], [Amount], [Amount])]
-> Chart
holdingsBarsChart ReportOpts
ropts Mark
MarkLine (Map Text AmountStyle
-> ((DateSpan, HoldingsReport) -> Map Text AmountStyle)
-> Maybe (DateSpan, HoldingsReport)
-> Map Text AmountStyle
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map Text AmountStyle
forall k a. Map k a
M.empty (HoldingsReport -> Map Text AmountStyle
hrStyles (HoldingsReport -> Map Text AmountStyle)
-> ((DateSpan, HoldingsReport) -> HoldingsReport)
-> (DateSpan, HoldingsReport)
-> Map Text AmountStyle
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DateSpan, HoldingsReport) -> HoldingsReport
forall a b. (a, b) -> b
snd) (Maybe (DateSpan, HoldingsReport) -> Map Text AmountStyle)
-> Maybe (DateSpan, HoldingsReport) -> Map Text AmountStyle
forall a b. (a -> b) -> a -> b
$ [(DateSpan, HoldingsReport)] -> Maybe (DateSpan, HoldingsReport)
forall a. [a] -> Maybe a
headMay [(DateSpan, HoldingsReport)]
rpts) Text
title XAxis
xaxis
                      [ [([Amount], [Amount], [Amount])] -> ([Amount], [Amount], [Amount])
forall a. Monoid a => [a] -> a
mconcat ([([Amount], [Amount], [Amount])]
 -> ([Amount], [Amount], [Amount]))
-> [([Amount], [Amount], [Amount])]
-> ([Amount], [Amount], [Amount])
forall a b. (a -> b) -> a -> b
$ ((PeriodicReportRow DisplayName MixedAmount, Holding)
 -> ([Amount], [Amount], [Amount]))
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-> [([Amount], [Amount], [Amount])]
forall a b. (a -> b) -> [a] -> [b]
map (Holding -> ([Amount], [Amount], [Amount])
holdingBarParts (Holding -> ([Amount], [Amount], [Amount]))
-> ((PeriodicReportRow DisplayName MixedAmount, Holding)
    -> Holding)
-> (PeriodicReportRow DisplayName MixedAmount, Holding)
-> ([Amount], [Amount], [Amount])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PeriodicReportRow DisplayName MixedAmount, Holding) -> Holding
forall a b. (a, b) -> b
snd) ([(PeriodicReportRow DisplayName MixedAmount, Holding)]
 -> [([Amount], [Amount], [Amount])])
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-> [([Amount], [Amount], [Amount])]
forall a b. (a -> b) -> a -> b
$ HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
r | (DateSpan
_, HoldingsReport
r) <- [(DateSpan, HoldingsReport)]
rpts ]
      BalanceAccumulation
_          -> ReportOpts -> Text -> XAxis -> [([Amount], [Amount])] -> Chart
holdingsGainsChart ReportOpts
ropts Text
title XAxis
xaxis
                      [ ([Amount] -> Maybe [Amount] -> [Amount]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Amount] -> [Amount]) -> Maybe [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ HoldingsTotals -> Maybe [Amount]
htUgain HoldingsTotals
tot, HoldingsTotals -> [Amount]
htRgain HoldingsTotals
tot) | (DateSpan
_, HoldingsReport
r) <- [(DateSpan, HoldingsReport)]
rpts, let tot :: HoldingsTotals
tot = HoldingsReport -> HoldingsTotals
hrTotals HoldingsReport
r ]
    xaxis :: XAxis
xaxis = [(DateSpan, Text)] -> XAxis
XPeriods [(DateSpan
spn, Day -> Text
showDate (HoldingsReport -> Day
hrDate HoldingsReport
r) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> if [Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (HoldingsReport -> [Text]
leftout HoldingsReport
r) then Text
"" else Text
"*") | (DateSpan
spn, HoldingsReport
r) <- [(DateSpan, HoldingsReport)]
rpts]
    leftout :: HoldingsReport -> [Text]
leftout = HoldingsTotals -> [Text]
totalsLeftOut (HoldingsTotals -> [Text])
-> (HoldingsReport -> HoldingsTotals) -> HoldingsReport -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HoldingsReport -> HoldingsTotals
hrTotals
    note :: Maybe Text
note = case [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ ((DateSpan, HoldingsReport) -> [Text])
-> [(DateSpan, HoldingsReport)] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (HoldingsReport -> [Text]
leftout (HoldingsReport -> [Text])
-> ((DateSpan, HoldingsReport) -> HoldingsReport)
-> (DateSpan, HoldingsReport)
-> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DateSpan, HoldingsReport) -> HoldingsReport
forall a b. (a, b) -> b
snd) [(DateSpan, HoldingsReport)]
rpts of
      [] -> Maybe Text
forall a. Maybe a
Nothing
      [Text]
cs -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (Text
"* " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$
        -- TRANSLATORS: a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".
        Translations -> Text -> [(Text, Text)] -> Text
I18n.trf (ReportOpts -> Translations
translations_ ReportOpts
ropts) Text
"Values and gains exclude holdings with no market price: {commodities}"
          [(Text
"commodities", Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
quoteCommoditySymbolIfNeeded [Text]
cs)]

-- | A chart of holdings' gains at some x positions (eg period ends), from their unrealised and realised gains there:
-- a bar for each, in each commodity's panel, diverging from zero: gains (revenue colour) above, losses (expense colour) below,
-- the realised ones solid, the unrealised ones hatched, since they are not yet final. The net gain is their total,
-- drawn as a line over time, like other reports' totals.
holdingsGainsChart :: ReportOpts -> T.Text -> XAxis -> [([Amount], [Amount])] -> Chart
holdingsGainsChart :: ReportOpts -> Text -> XAxis -> [([Amount], [Amount])] -> Chart
holdingsGainsChart ReportOpts{Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} Text
title XAxis
xaxis [([Amount], [Amount])]
gains =
  Chart{chTitle :: Text
chTitle = Text
title, chXAxis :: XAxis
chXAxis = XAxis
xaxis, chPanels :: [Panel]
chPanels = (Text -> Panel) -> [Text] -> [Panel]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Panel
panel ([Text] -> [Panel]) -> [Text] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Text]
commoditiesByUse [Amount]
amts, chNotes :: [Text]
chNotes = []}
  where
    amts :: [Amount]
amts = [[Amount]] -> [Amount]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Amount]
us [Amount] -> [Amount] -> [Amount]
forall a. [a] -> [a] -> [a]
++ [Amount]
rs | ([Amount]
us, [Amount]
rs) <- [([Amount], [Amount])]
gains]
    tr :: Text -> Text
tr = Translations -> Text -> Text
I18n.tr Translations
translations_
    panel :: Text -> Panel
panel Text
c = Panel
      { pnUnit :: Amount
pnUnit = Text -> [Amount] -> Amount
unitAmount Text
c [Amount]
amts
      , pnSeries :: [Series]
pnSeries = [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (Text
-> Text -> Int -> Maybe AccountType -> Bool -> [Text] -> ChartLabel
ChartLabel Text
name Text
name Int
0 Maybe AccountType
typ Bool
False []) SeriesRole
role Mark
mark [Maybe Quantity]
vals Int
0 Int
0
                   | (Text
name, Maybe AccountType
typ, SeriesRole
role, Mark
mark, Maybe Quantity -> Maybe Quantity -> Maybe Quantity
valueof) <- [(Text, Maybe AccountType, SeriesRole, Mark,
  Maybe Quantity -> Maybe Quantity -> Maybe Quantity)]
specs
                   , let vals :: [Maybe Quantity]
vals = [Maybe Quantity -> Maybe Quantity -> Maybe Quantity
valueof ([Amount] -> Maybe Quantity
quantityOf [Amount]
us) ([Amount] -> Maybe Quantity
quantityOf [Amount]
rs) | ([Amount]
us, [Amount]
rs) <- [([Amount], [Amount])]
gains]
                   , (Maybe Quantity -> Bool) -> [Maybe Quantity] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Maybe Quantity -> Bool
forall a. Maybe a -> Bool
isJust [Maybe Quantity]
vals ]
      , pnGroupNames :: [Text]
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 Text]
pnValueLabels = []
      }
      where
        -- each series: its name, type, role, mark, and value from the unrealised and realised gains, if any
        specs :: [(Text, Maybe AccountType, SeriesRole, Mark,
  Maybe Quantity -> Maybe Quantity -> Maybe Quantity)]
specs =
          [ (Text -> Text
tr Text
"Realised gain",   AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Revenue, SeriesRole
SeriesItem,        Mark
MarkBar,    \Maybe Quantity
_ Maybe Quantity
r -> Maybe Quantity
r Maybe Quantity -> (Quantity -> Maybe Quantity) -> Maybe Quantity
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Quantity -> Maybe Quantity
forall {a}. (Ord a, Num a) => a -> Maybe a
positive)
          , (Text -> Text
tr Text
"Unrealised gain", AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Revenue, SeriesRole
SeriesProvisional, Mark
MarkBar,    \Maybe Quantity
u Maybe Quantity
_ -> Maybe Quantity
u Maybe Quantity -> (Quantity -> Maybe Quantity) -> Maybe Quantity
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Quantity -> Maybe Quantity
forall {a}. (Ord a, Num a) => a -> Maybe a
positive)
          , (Text -> Text
tr Text
"Realised loss",   AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Expense, SeriesRole
SeriesItem,        Mark
MarkBar,    \Maybe Quantity
_ Maybe Quantity
r -> Maybe Quantity
r Maybe Quantity -> (Quantity -> Maybe Quantity) -> Maybe Quantity
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Quantity -> Maybe Quantity
forall {a}. (Ord a, Num a) => a -> Maybe a
negative)
          , (Text -> Text
tr Text
"Unrealised loss", AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Expense, SeriesRole
SeriesProvisional, Mark
MarkBar,    \Maybe Quantity
u Maybe Quantity
_ -> Maybe Quantity
u Maybe Quantity -> (Quantity -> Maybe Quantity) -> Maybe Quantity
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Quantity -> Maybe Quantity
forall {a}. (Ord a, Num a) => a -> Maybe a
negative)
          , (Text -> Text
tr Text
"Net gain",        Maybe AccountType
forall a. Maybe a
Nothing,      SeriesRole
SeriesTotal,       Mark
MarkLine,   \Maybe Quantity
u Maybe Quantity
r -> if Maybe Quantity -> Bool
forall a. Maybe a -> Bool
isJust Maybe Quantity
u Bool -> Bool -> Bool
|| Maybe Quantity -> Bool
forall a. Maybe a -> Bool
isJust Maybe Quantity
r then Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity -> Quantity
forall a. a -> Maybe a -> a
fromMaybe Quantity
0 Maybe Quantity
u Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
+ Quantity -> Maybe Quantity -> Quantity
forall a. a -> Maybe a -> a
fromMaybe Quantity
0 Maybe Quantity
r) else Maybe Quantity
forall a. Maybe a
Nothing)
          ]
        positive :: a -> Maybe a
positive a
q = if a
q a -> a -> Bool
forall a. Ord a => a -> a -> Bool
> a
0 then a -> Maybe a
forall a. a -> Maybe a
Just a
q else Maybe a
forall a. Maybe a
Nothing
        negative :: a -> Maybe a
negative a
q = if a
q a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
0 then a -> Maybe a
forall a. a -> Maybe a
Just a
q else Maybe a
forall a. Maybe a
Nothing
        quantityOf :: [Amount] -> Maybe Quantity
quantityOf [Amount]
as = case [Amount -> Quantity
aquantity Amount
a | Amount
a <- [Amount]
as, Amount -> Text
acommodity Amount
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
c] of
          [] -> Maybe Quantity
forall a. Maybe a
Nothing
          [Quantity]
qs -> Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity) -> Quantity -> Maybe Quantity
forall a b. (a -> b) -> a -> b
$ [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Quantity]
qs

-- | The commodities of these amounts, most used first (then by name): a chart's panels, in order.
commoditiesByUse :: [Amount] -> [CommoditySymbol]
commoditiesByUse :: [Amount] -> [Text]
commoditiesByUse [Amount]
amts = ((Text, Int) -> Text) -> [(Text, Int)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Int) -> Text
forall a b. (a, b) -> a
fst ([(Text, Int)] -> [Text]) -> [(Text, Int)] -> [Text]
forall a b. (a -> b) -> a -> b
$ ((Text, Int) -> (Down Int, Text)) -> [(Text, Int)] -> [(Text, Int)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\(Text
c, Int
n) -> (Int -> Down Int
forall a. a -> Down a
Down Int
n, Text
c)) ([(Text, Int)] -> [(Text, Int)]) -> [(Text, Int)] -> [(Text, Int)]
forall a b. (a -> b) -> a -> b
$ Map Text Int -> [(Text, Int)]
forall k a. Map k a -> [(k, a)]
M.toList (Map Text Int -> [(Text, Int)]) -> Map Text Int -> [(Text, Int)]
forall a b. (a -> b) -> a -> b
$ (Int -> Int -> Int) -> [(Text, Int)] -> Map Text 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
(+) [(Amount -> Text
acommodity Amount
a, Int
1 :: Int) | Amount
a <- [Amount]
amts]

-- | A holding's amounts, for a bar in a holdings chart: its market value and cost basis, if it has a market price
-- (or if its value is not comparable with its cost basis, its value twice, as having no gain or loss);
-- and its cost basis, if it has no market price.
holdingBarParts :: Holding -> ([Amount], [Amount], [Amount])
holdingBarParts :: Holding -> ([Amount], [Amount], [Amount])
holdingBarParts Holding
h
  | [Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Holding -> [Amount]
hValue Holding
h) = ([], [], Holding -> [Amount]
hCost Holding
h)
  | Bool
comparable      = (Holding -> [Amount]
hValue Holding
h, Holding -> [Amount]
hCost Holding
h, [])
  | Bool
otherwise       = (Holding -> [Amount]
hValue Holding
h, Holding -> [Amount]
hValue Holding
h, [])
  where
    -- the value and cost are in the same commodities (as for UGain, which can't be
    -- checked instead, since with a start date it can be blank for another reason)
    comparable :: Bool
comparable = Bool -> Bool
not ([Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([Amount] -> Bool) -> [Amount] -> Bool
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hCost Holding
h) Bool -> Bool -> Bool
&& [Amount] -> [Text]
commodities (Holding -> [Amount]
hValue Holding
h) [Text] -> [Text] -> Bool
forall a. Eq a => a -> a -> Bool
== [Amount] -> [Text]
commodities (Holding -> [Amount]
hCost Holding
h)
    commodities :: [Amount] -> [Text]
commodities = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> ([Amount] -> [Text]) -> [Amount] -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Text
acommodity

-- | A chart of holdings: a bar at each x position, in each commodity's panel, from the market value, cost basis
-- and cost basis without a market price, of one or more holdings there (see 'holdingBarParts').
-- Holdings with a market price are drawn as their cost basis and their unrealised gain, stacked, reaching their value;
-- or with an unrealised loss, as the part of their cost basis they are worth, and the part lost (hatched), reaching their cost basis.
-- Holdings without a market price are drawn as their cost basis, beyond those, in a muted colour.
-- The market values are the chart's total, drawn with the given mark: none for separate holdings, whose bars' solid parts
-- reach their values (shown as text), or a line over time, like other reports' totals. Graphical charts show the unrealised gain percents
-- instead (with these styles, for the % commodity), where there is a market price, since the axis shows the values.
holdingsBarsChart :: ReportOpts -> Mark -> M.Map CommoditySymbol AmountStyle -> T.Text -> XAxis -> [([Amount], [Amount], [Amount])] -> Chart
holdingsBarsChart :: ReportOpts
-> Mark
-> Map Text AmountStyle
-> Text
-> XAxis
-> [([Amount], [Amount], [Amount])]
-> Chart
holdingsBarsChart ReportOpts{Translations
translations_ :: ReportOpts -> Translations
translations_ :: Translations
translations_} Mark
totalmark Map Text AmountStyle
styles Text
title XAxis
xaxis [([Amount], [Amount], [Amount])]
parts =
  Chart{chTitle :: Text
chTitle = Text
title, chXAxis :: XAxis
chXAxis = XAxis
xaxis, chPanels :: [Panel]
chPanels = (Text -> Panel) -> [Text] -> [Panel]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Panel
panel ([Text] -> [Panel]) -> [Text] -> [Panel]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Text]
commoditiesByUse [Amount]
amts, chNotes :: [Text]
chNotes = []}
  where
    amts :: [Amount]
amts = [[Amount]] -> [Amount]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Amount]
vs [Amount] -> [Amount] -> [Amount]
forall a. [a] -> [a] -> [a]
++ [Amount]
ks [Amount] -> [Amount] -> [Amount]
forall a. [a] -> [a] -> [a]
++ [Amount]
us | ([Amount]
vs, [Amount]
ks, [Amount]
us) <- [([Amount], [Amount], [Amount])]
parts]
    tr :: Text -> Text
tr = Translations -> Text -> Text
I18n.tr Translations
translations_
    panel :: Text -> Panel
panel Text
c = Panel
      { pnUnit :: Amount
pnUnit = Text -> [Amount] -> Amount
unitAmount Text
c [Amount]
amts
      , pnSeries :: [Series]
pnSeries = [ ChartLabel
-> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
Series (Text
-> Text -> Int -> Maybe AccountType -> Bool -> [Text] -> ChartLabel
ChartLabel Text
name Text
name Int
0 Maybe AccountType
typ Bool
False []) SeriesRole
role Mark
mark [Maybe Quantity]
vals Int
0 Int
0
                   | ((Text
name, Maybe AccountType
typ, SeriesRole
role, Mark
mark), [Maybe Quantity]
vals) <- [(Text, Maybe AccountType, SeriesRole, Mark)]
-> [[Maybe Quantity]]
-> [((Text, Maybe AccountType, SeriesRole, Mark),
     [Maybe Quantity])]
forall a b. [a] -> [b] -> [(a, b)]
zip [(Text, Maybe AccountType, SeriesRole, Mark)]
specs ([[Maybe Quantity]]
 -> [((Text, Maybe AccountType, SeriesRole, Mark),
      [Maybe Quantity])])
-> [[Maybe Quantity]]
-> [((Text, Maybe AccountType, SeriesRole, Mark),
     [Maybe Quantity])]
forall a b. (a -> b) -> a -> b
$ [[Maybe Quantity]] -> [[Maybe Quantity]]
forall a. [[a]] -> [[a]]
transpose [[Amount] -> [Amount] -> [Amount] -> [Maybe Quantity]
barValues [Amount]
vs [Amount]
ks [Amount]
us | ([Amount]
vs, [Amount]
ks, [Amount]
us) <- [([Amount], [Amount], [Amount])]
parts]
                   , (Maybe Quantity -> Bool) -> [Maybe Quantity] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Maybe Quantity -> Bool
forall a. Maybe a -> Bool
isJust [Maybe Quantity]
vals Bool -> Bool -> Bool
|| SeriesRole
role SeriesRole -> SeriesRole -> Bool
forall a. Eq a => a -> a -> Bool
== SeriesRole
SeriesTotal ]  -- the values, even if none, so that a cost is not shown as one
      , pnGroupNames :: [Text]
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 Text]
pnValueLabels = [Maybe Quantity -> Maybe Quantity -> Maybe Text
gainPercent ([Amount] -> Maybe Quantity
quantityOf [Amount]
vs) ([Amount] -> Maybe Quantity
quantityOf [Amount]
ks) | ([Amount]
vs, [Amount]
ks, [Amount]
_) <- [([Amount], [Amount], [Amount])]
parts]
      }
      where
        -- eg +12.5%, -3.0%
        gainPercent :: Maybe Quantity -> Maybe Quantity -> Maybe Text
gainPercent Maybe Quantity
mv Maybe Quantity
mk = case (Maybe Quantity
mv, Maybe Quantity
mk) of
          (Just Quantity
v, Just Quantity
k) | Quantity
k Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0 -> let p :: Quantity
p = (Quantity
v Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
k) Quantity -> Quantity -> Quantity
forall a. Fractional a => a -> a -> a
/ Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
k Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* Quantity
100 in Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (if Quantity
p Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 then Text
"+" else Text
"") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Map Text AmountStyle -> Quantity -> Text
showPercentWith Map Text AmountStyle
styles Quantity
p
          (Maybe Quantity, Maybe Quantity)
_ -> Maybe Text
forall a. Maybe a
Nothing
        specs :: [(Text, Maybe AccountType, SeriesRole, Mark)]
specs =
          [ (Text -> Text
tr Text
"Cost", AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Asset, SeriesRole
SeriesItem, Mark
MarkBar)
          , (Text -> Text
tr Text
"Unrealised gain", AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Revenue, SeriesRole
SeriesItem, Mark
MarkBar)
          , (Text -> Text
tr Text
"Unrealised loss", AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Expense, SeriesRole
SeriesShortfall, Mark
MarkBar)
          , (Text -> Text
tr Text
"No market price", Maybe AccountType
forall a. Maybe a
Nothing, SeriesRole
SeriesOther, Mark
MarkBar)
          , (Text -> Text
tr Text
"Value", Maybe AccountType
forall a. Maybe a
Nothing, SeriesRole
SeriesTotal, Mark
totalmark)
          ]
        -- A bar's values for those series, in this commodity: the value and cost basis, the smaller of them
        -- stacked with the difference, a gain or loss; then the cost basis without a market price.
        -- (Values and costs are of one sign, negative for a short position, whose gain is a smaller value.)
        barValues :: [Amount] -> [Amount] -> [Amount] -> [Maybe Quantity]
barValues [Amount]
vs [Amount]
ks [Amount]
us = case ([Amount] -> Maybe Quantity
quantityOf [Amount]
vs, [Amount] -> Maybe Quantity
quantityOf [Amount]
ks) of
          (Just Quantity
v, Just Quantity
k) ->
            let (Quantity
base, Quantity
end) = if Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
v Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
<= Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
k then (Quantity
v, Quantity
k) else (Quantity
k, Quantity
v)
                ugain :: Quantity
ugain = Quantity
v Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
k
            in [Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just Quantity
base, Bool -> Quantity -> Maybe Quantity
forall {a}. (Eq a, Num a) => Bool -> a -> Maybe a
nonzero (Quantity
ugain Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0) (Quantity
end Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
base), Bool -> Quantity -> Maybe Quantity
forall {a}. (Eq a, Num a) => Bool -> a -> Maybe a
nonzero (Quantity
ugain Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0) (Quantity
end Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
base), [Amount] -> Maybe Quantity
quantityOf [Amount]
us, Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just Quantity
v]
          (Maybe Quantity, Maybe Quantity)
_ -> [Maybe Quantity
forall a. Maybe a
Nothing, Maybe Quantity
forall a. Maybe a
Nothing, Maybe Quantity
forall a. Maybe a
Nothing, [Amount] -> Maybe Quantity
quantityOf [Amount]
us, Maybe Quantity
forall a. Maybe a
Nothing]
        quantityOf :: [Amount] -> Maybe Quantity
quantityOf [Amount]
as = case [Amount -> Quantity
aquantity Amount
a | Amount
a <- [Amount]
as, Amount -> Text
acommodity Amount
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
c] of
          [] -> Maybe Quantity
forall a. Maybe a
Nothing
          [Quantity]
qs -> Quantity -> Maybe Quantity
forall a. a -> Maybe a
Just (Quantity -> Maybe Quantity) -> Quantity -> Maybe Quantity
forall a b. (a -> b) -> a -> b
$ [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Quantity]
qs
        nonzero :: Bool -> a -> Maybe a
nonzero Bool
ok a
q = if Bool
ok Bool -> Bool -> Bool
&& a
q a -> a -> Bool
forall a. Eq a => a -> a -> Bool
/= a
0 then a -> Maybe a
forall a. a -> Maybe a
Just a
q else Maybe a
forall a. Maybe a
Nothing

-- | Compute the holdings report: the assets held in lot-tracked accounts
-- as of the report end date, one line per account (or per lot, with
-- hroLots) and held commodity, plus grand totals. In tree mode the
-- display lines are instead account sections (see holdingsTreeLines),
-- while the flat records (hrRows) keep the list-mode shape.
--
-- The journal must have its lot detail (lot subaccounts and synthetic
-- postings) uncollapsed, as the holdings command receives it
-- (see maybePrepareLotDetail); this report aggregates lots itself.
-- A --value=then valuation strategy is not supported; callers reject it.
holdingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport HoldingsReportOpts
hro0 rspec :: ReportSpec
rspec@ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts'} Journal
j'
  | ReportOpts -> AccountListMode
accountlistmode_ ReportOpts
ropts' AccountListMode -> AccountListMode -> Bool
forall a. Eq a => a -> a -> Bool
== AccountListMode
ALTree = HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
treeHoldingsReport HoldingsReportOpts
hro ReportSpec
rspec Journal
j'
  | Bool
otherwise                         = HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport HoldingsReportOpts
hro ReportSpec
rspec Journal
j'
  where
    -- one price oracle for all the flat reports this needs (making one, and
    -- filling its cache, is costly with many prices)
    hro :: HoldingsReportOpts
hro = HoldingsReportOpts
hro0{hroPriceOracle = hroPriceOracle hro0 <|> Just (journalPriceOracle (infer_prices_ ropts') j')}

-- | -S's sort key for a holding, or an account's holdings, with this
-- market value (empty if unpriced) and cost: priced things first, largest
-- value first, then unpriced things, largest cost first; or at cost
-- (-B), everything by cost. Amounts of different commodities are
-- compared, and summed, by their quantities alone.
holdingsSortKey :: Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)
holdingsSortKey :: Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)
holdingsSortKey Bool
atcost [Amount]
val [Amount]
cost
  | Bool
atcost    = (Bool
False, Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity) -> Quantity -> Down Quantity
forall a b. (a -> b) -> a -> b
$ [Amount] -> Quantity
sumq [Amount]
cost)
  | [Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Amount]
val  = (Bool
True,  Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity) -> Quantity -> Down Quantity
forall a b. (a -> b) -> a -> b
$ [Amount] -> Quantity
sumq [Amount]
cost)
  | Bool
otherwise = (Bool
False, Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity) -> Quantity -> Down Quantity
forall a b. (a -> b) -> a -> b
$ [Amount] -> Quantity
sumq [Amount]
val)
  where sumq :: [Amount] -> Quantity
sumq = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Quantity] -> Quantity)
-> ([Amount] -> [Quantity]) -> [Amount] -> Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> Quantity) -> [Amount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Quantity
aquantity

-- | The tree-mode holdings report: the flat report, with its display
-- lines grouped into account sections. With hroLots, a second flat
-- report gives each position's lots, shown beneath it, and provides
-- the flat records and unit cost heading, as list mode would.
treeHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
treeHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
treeHoldingsReport HoldingsReportOpts
hro rspec :: ReportSpec
rspec@ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts'} Journal
j' =
  HoldingsReport
prpt{ hrLines = holdingsTreeLines ropts' prpt mlrpt
      , hrRows  = hrRows mrpt
      , hrUnitCostHeading = hrUnitCostHeading mrpt
      }
  where
    flatrspec :: ReportSpec
flatrspec = ReportSpec
rspec{_rsReportOpts = ropts'{accountlistmode_ = ALFlat}}
    prpt :: HoldingsReport
prpt = HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport HoldingsReportOpts
hro{hroLots = False} ReportSpec
flatrspec Journal
j'
    mlrpt :: Maybe HoldingsReport
mlrpt | HoldingsReportOpts -> Bool
hroLots HoldingsReportOpts
hro = HoldingsReport -> Maybe HoldingsReport
forall a. a -> Maybe a
Just (HoldingsReport -> Maybe HoldingsReport)
-> HoldingsReport -> Maybe HoldingsReport
forall a b. (a -> b) -> a -> b
$ HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport HoldingsReportOpts
hro{hroLots = True} ReportSpec
flatrspec Journal
j'
          | Bool
otherwise   = Maybe HoldingsReport
forall a. Maybe a
Nothing
    mrpt :: HoldingsReport
mrpt = HoldingsReport -> Maybe HoldingsReport -> HoldingsReport
forall a. a -> Maybe a -> a
fromMaybe HoldingsReport
prpt Maybe HoldingsReport
mlrpt

-- | Group a flat holdings report's lines into account sections, as tree
-- mode displays them: an account with subaccounts or several
-- commodities is a heading line showing its subtree's totals, with its
-- own positions beneath it named by their commodity, then its
-- subaccounts; an account holding one commodity with no subaccounts is
-- a single combined line carrying its figures. Boring parents - those
-- with no positions of their own and a single child - are squashed into
-- their child like the balance reports' tree mode, unless no-elide is
-- set; only accounts with holdings exist here, so the squashing
-- considers holding rows alone (#2779). With a lots report given, each
-- position's lots are beneath it. Sibling accounts, the top level
-- included, are in account name order, or with -S, sorted by their
-- subtree's totals, as on their headings (see holdingsSortKey); an
-- account's positions, and their lots, keep the flat report's order.
-- --drop removes the first N levels: the tree's roots are the accounts
-- at level N+1 (a shallower account's own positions, a rare case, show
-- as top-level rows).
holdingsTreeLines :: ReportOpts -> HoldingsReport -> Maybe HoldingsReport -> [HoldingsLine]
holdingsTreeLines :: ReportOpts
-> HoldingsReport -> Maybe HoldingsReport -> [HoldingsLine]
holdingsTreeLines ReportOpts
ropts HoldingsReport
prpt Maybe HoldingsReport
mlrpt =
    ((Text, Bool) -> [HoldingsLine])
-> [(Text, Bool)] -> [HoldingsLine]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Text, Bool) -> [HoldingsLine]
node ([(Text, Bool)] -> [HoldingsLine])
-> [(Text, Bool)] -> [HoldingsLine]
forall a b. (a -> b) -> a -> b
$ ((Text, Bool) -> (Maybe (Bool, Down Quantity), Maybe Int))
-> [(Text, Bool)] -> [(Text, Bool)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Text -> (Maybe (Bool, Down Quantity), Maybe Int)
acctOrder (Text -> (Maybe (Bool, Down Quantity), Maybe Int))
-> ((Text, Bool) -> Text)
-> (Text, Bool)
-> (Maybe (Bool, Down Quantity), Maybe Int)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, Bool) -> Text
forall a b. (a, b) -> a
fst) ([(Text, Bool)] -> [(Text, Bool)])
-> [(Text, Bool)] -> [(Text, Bool)]
forall a b. (a -> b) -> a -> b
$
      [(Text
a, Bool
False) | Text
a <- [Text]
allaccts, Text -> Int
accountNameLevel Text
a Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
dropn Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1] [(Text, Bool)] -> [(Text, Bool)] -> [(Text, Bool)]
forall a. [a] -> [a] -> [a]
++
      [(Text
a, Bool
True)  | Int
dropn Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0, Text
a <- Map Text [Holding] -> [Text]
forall k a. Map k a -> [k]
M.keys Map Text [Holding]
posByAcct, Text -> Int
accountNameLevel Text
a Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
dropn]
  where
    dropn :: Int
dropn = ReportOpts -> Int
drop_ ReportOpts
ropts
    noelide :: Bool
noelide = ReportOpts -> Bool
no_elide_ ReportOpts
ropts
    -- sibling accounts' order: with -S, by their subtree's totals; then
    -- by their first row in the flat report (without -S, account name order)
    acctOrder :: Text -> (Maybe (Bool, Down Quantity), Maybe Int)
acctOrder Text
a = (Maybe (Bool, Down Quantity)
subtreeSortKey, Text -> Map Text Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
a Map Text Int
subtreeIxMap)
      where
        subtreeSortKey :: Maybe (Bool, Down Quantity)
subtreeSortKey
          | ReportOpts -> Bool
sort_amount_ ReportOpts
ropts = (Bool, Down Quantity) -> Maybe (Bool, Down Quantity)
forall a. a -> Maybe a
Just ((Bool, Down Quantity) -> Maybe (Bool, Down Quantity))
-> (Bool, Down Quantity) -> Maybe (Bool, Down Quantity)
forall a b. (a -> b) -> a -> b
$ Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)
holdingsSortKey (ReportOpts -> Maybe ConversionOp
conversionop_ ReportOpts
ropts Maybe ConversionOp -> Maybe ConversionOp -> Bool
forall a. Eq a => a -> a -> Bool
== ConversionOp -> Maybe ConversionOp
forall a. a -> Maybe a
Just ConversionOp
ToCost) ([Amount] -> Maybe [Amount] -> [Amount]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Amount] -> [Amount]) -> Maybe [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
t) (HoldingsTotals -> [Amount]
htCost HoldingsTotals
t)
          | Bool
otherwise          = Maybe (Bool, Down Quantity)
forall a. Maybe a
Nothing
          where t :: HoldingsTotals
t = HoldingsReport -> Text -> HoldingsTotals
hrAccountTotals HoldingsReport
prpt Text
a
    node :: (Text, Bool) -> [HoldingsLine]
node (Text
a, Bool
False) = Int -> Text -> [HoldingsLine]
treeNode Int
0 Text
a
    node (Text
a, Bool
True)  =
      [[HoldingsLine]] -> [HoldingsLine]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [ Int -> Text -> Text -> Bool -> Holding -> HoldingsLine
HoldingsPosition Int
0 Text
a (Int -> Text -> Text
accountNameDrop Int
dropn Text
a) Bool
False Holding
h HoldingsLine -> [HoldingsLine] -> [HoldingsLine]
forall a. a -> [a] -> [a]
: Int -> Text -> Holding -> [HoldingsLine]
lotLines Int
1 Text
a Holding
h
             | Holding
h <- [Holding] -> Text -> Map Text [Holding] -> [Holding]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
a Map Text [Holding]
posByAcct ]
    posByAcct :: Map Text [Holding]
posByAcct = ([Holding] -> [Holding] -> [Holding])
-> [(Text, [Holding])] -> Map Text [Holding]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith (([Holding] -> [Holding] -> [Holding])
-> [Holding] -> [Holding] -> [Holding]
forall a b c. (a -> b -> c) -> b -> a -> c
flip [Holding] -> [Holding] -> [Holding]
forall a. [a] -> [a] -> [a]
(++)) [(Holding -> Text
hAccount Holding
h, [Holding
h]) | (PeriodicReportRow DisplayName MixedAmount
_, Holding
h) <- HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
prpt]
    lotsByPos :: Map (Text, Text) [Holding]
lotsByPos = case Maybe HoldingsReport
mlrpt of
      Maybe HoldingsReport
Nothing -> Map (Text, Text) [Holding]
forall k a. Map k a
M.empty
      Just HoldingsReport
lr -> ([Holding] -> [Holding] -> [Holding])
-> [((Text, Text), [Holding])] -> Map (Text, Text) [Holding]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith (([Holding] -> [Holding] -> [Holding])
-> [Holding] -> [Holding] -> [Holding]
forall a b c. (a -> b -> c) -> b -> a -> c
flip [Holding] -> [Holding] -> [Holding]
forall a. [a] -> [a] -> [a]
(++))
        [ ((Text -> Text
lotBaseAccount Text
a, Holding -> Text
hCommodity Holding
h), [Holding
h])
        | (PeriodicReportRow DisplayName MixedAmount
_, Holding
h) <- HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
lr, let a :: Text
a = Holding -> Text
hAccount Holding
h, Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Text -> Maybe Text
lotSubaccountName Text
a) ]
    -- each account's subtree's first flat row, ordering subtrees as the
    -- flat report's sort ordered their rows
    subtreeIxMap :: Map Text Int
subtreeIxMap = (Int -> Int -> Int) -> [(Text, Int)] -> Map Text Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Int -> Int -> Int
forall a. Ord a => a -> a -> a
min
      [(Text
a, Int
ix) | (Int
ix, (PeriodicReportRow DisplayName MixedAmount
_, Holding
h)) <- [Int]
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-> [(Int, (PeriodicReportRow DisplayName MixedAmount, Holding))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] (HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
prpt), Text
a <- Text -> [Text]
expandAccountName (Holding -> Text
hAccount Holding
h)]
    allaccts :: [Text]
allaccts = Map Text Int -> [Text]
forall k a. Map k a -> [k]
M.keys Map Text Int
subtreeIxMap
    kidsMap :: Map Text [Text]
kidsMap = ([Text] -> [Text]) -> Map Text [Text] -> Map Text [Text]
forall a b k. (a -> b) -> Map k a -> Map k b
M.map ((Text -> (Maybe (Bool, Down Quantity), Maybe Int))
-> [Text] -> [Text]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Text -> (Maybe (Bool, Down Quantity), Maybe Int)
acctOrder) (Map Text [Text] -> Map Text [Text])
-> Map Text [Text] -> Map Text [Text]
forall a b. (a -> b) -> a -> b
$ ([Text] -> [Text] -> [Text]) -> [(Text, [Text])] -> Map Text [Text]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
(++)
      [(Text -> Text
parentAccountName Text
a, [Text
a]) | Text
a <- [Text]
allaccts, Text -> Int
accountNameLevel Text
a Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1]
    kidsOf :: Text -> [Text]
kidsOf Text
a = [Text] -> Text -> Map Text [Text] -> [Text]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
a Map Text [Text]
kidsMap
    -- squash boring parents into their child
    elide :: Text -> Text -> (Text, Text)
elide Text
disp Text
acct
      | Bool -> Bool
not Bool
noelide, Text -> Map Text [Holding] -> Bool
forall k a. Ord k => k -> Map k a -> Bool
M.notMember Text
acct Map Text [Holding]
posByAcct, [Text
c] <- Text -> [Text]
kidsOf Text
acct =
          Text -> Text -> (Text, Text)
elide (Text
disp Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
accountLeafName Text
c) Text
c
      | Bool
otherwise = (Text
disp, Text
acct)
    treeNode :: Int -> Text -> [HoldingsLine]
treeNode Int
d Text
acct0 = case ([Holding] -> Text -> Map Text [Holding] -> [Holding]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [Holding]
posByAcct, Text -> [Text]
kidsOf Text
acct) of
      ([Holding
h], []) -> Int -> Text -> Text -> Bool -> Holding -> HoldingsLine
HoldingsPosition Int
d Text
acct Text
disp Bool
False Holding
h HoldingsLine -> [HoldingsLine] -> [HoldingsLine]
forall a. a -> [a] -> [a]
: Int -> Text -> Holding -> [HoldingsLine]
lotLines (Int
dInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) Text
acct Holding
h
      ([Holding]
own, [Text]
kids) ->
        Int -> Text -> Text -> HoldingsTotals -> HoldingsLine
HoldingsHeading Int
d Text
acct Text
disp (HoldingsReport -> Text -> HoldingsTotals
hrAccountTotals HoldingsReport
prpt Text
acct) HoldingsLine -> [HoldingsLine] -> [HoldingsLine]
forall a. a -> [a] -> [a]
:
        [[HoldingsLine]] -> [HoldingsLine]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [ Int -> Text -> Text -> Bool -> Holding -> HoldingsLine
HoldingsPosition (Int
dInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) Text
acct (Holding -> Text
hCommodity Holding
h) Bool
False Holding
h HoldingsLine -> [HoldingsLine] -> [HoldingsLine]
forall a. a -> [a] -> [a]
: Int -> Text -> Holding -> [HoldingsLine]
lotLines (Int
dInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
2) Text
acct Holding
h
               | Holding
h <- [Holding]
own ] [HoldingsLine] -> [HoldingsLine] -> [HoldingsLine]
forall a. [a] -> [a] -> [a]
++
        (Text -> [HoldingsLine]) -> [Text] -> [HoldingsLine]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Int -> Text -> [HoldingsLine]
treeNode (Int
dInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1)) [Text]
kids
      where (Text
disp, Text
acct) = Text -> Text -> (Text, Text)
elide (Text -> Text
accountLeafName Text
acct0) Text
acct0
    lotLines :: Int -> Text -> Holding -> [HoldingsLine]
lotLines Int
d Text
acct Holding
h =
      [ Int -> Text -> Text -> Bool -> Holding -> HoldingsLine
HoldingsPosition Int
d (Holding -> Text
hAccount Holding
lh) (Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe (Holding -> Text
hAccount Holding
lh) (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
lotSubaccountName (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Holding -> Text
hAccount Holding
lh) Bool
True Holding
lh
      | Holding
lh <- [Holding]
-> (Text, Text) -> Map (Text, Text) [Holding] -> [Holding]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] (Text
acct, Holding -> Text
hCommodity Holding
h) Map (Text, Text) [Holding]
lotsByPos ]

-- | The flat (list-mode) holdings report; also the building block of
-- the tree-mode report. When the query has a start date, the gain
-- columns cover the report period (see holdingsPeriodGains); this needs
-- a second report, of the same lots as of the day before the start date.
flatHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport HoldingsReportOpts
hro rspec :: ReportSpec
rspec@ReportSpec{_rsQuery :: ReportSpec -> Query
_rsQuery=Query
q, _rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts} Journal
j =
  case Bool -> Query -> Maybe Day
queryStartDate Bool
False Query
q of
    Maybe Day
Nothing    -> HoldingsReport
endrpt
    Just Day
start -> Day -> HoldingsReport -> HoldingsReport -> HoldingsReport
holdingsPeriodGains Day
start HoldingsReport
startrpt HoldingsReport
endrpt
      where
        startrpt :: HoldingsReport
startrpt = Maybe ((Text, Text) -> Bool)
-> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReportAt (((Text, Text) -> Bool) -> Maybe ((Text, Text) -> Bool)
forall a. a -> Maybe a
Just (((Text, Text) -> Bool) -> Maybe ((Text, Text) -> Bool))
-> ((Text, Text) -> Bool) -> Maybe ((Text, Text) -> Bool)
forall a b. (a -> b) -> a -> b
$ HoldingsReport -> (Text, Text) -> Bool
hrKeepLot HoldingsReport
endrpt) HoldingsReportOpts
hro ReportSpec
startrspec Journal
j
        -- empty_, so that holdings sold off before the start date are seen too
        startrspec :: ReportSpec
startrspec = ReportSpec
rspec{ _rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Just $ Exact start)]
                          , _rsRowQuery = Any
                          , _rsReportOpts = ropts{empty_ = True} }
  where
    endrpt :: HoldingsReport
endrpt = Maybe ((Text, Text) -> Bool)
-> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReportAt Maybe ((Text, Text) -> Bool)
forall a. Maybe a
Nothing HoldingsReportOpts
hro ReportSpec
rspec Journal
j

-- | Make a holdings report's gain columns cover the period since this
-- start date, given the report of the same lots as of the day before it:
--
-- - UGain is the change in unrealised gain during the period
--
-- - UGain% is that as a percentage of the value at the start plus the
--   net cost added since (so with nothing held at the start, it is the
--   usual gain relative to cost)
--
-- - XIRR is the annualised rate of return over the period, counting the
--   value at the start as money invested then.
--
-- (RGain and the cashflows are already limited to the period, by
-- flatHoldingsReportAt.) These are left blank when a value needed is not
-- known (no market price) or the amounts are in several commodities.
holdingsPeriodGains :: Day -> HoldingsReport -> HoldingsReport -> HoldingsReport
holdingsPeriodGains :: Day -> HoldingsReport -> HoldingsReport -> HoldingsReport
holdingsPeriodGains Day
start HoldingsReport
startrpt HoldingsReport
rpt = HoldingsReport
rpt
  { hrLines         = map periodLine $ hrLines rpt
  , hrRows          = [(r, periodHolding h) | (r, h) <- hrRows rpt]
  , hrTotals        = periodTotals (hrTotalsExcluding startrpt) (hrTotalsExcluding rpt)
  , hrAccountTotals = accountPeriodTotals
  , hrGainsPeriod   = Just $ DateSpan (Just $ Exact start) (Just $ Exact $ addDays 1 $ hrDate rpt)
  }
  where
    periodLine :: HoldingsLine -> HoldingsLine
periodLine l :: HoldingsLine
l@HoldingsHeading{}  = HoldingsLine
l{hlTotals = accountPeriodTotals $ hlAccount l}
    periodLine l :: HoldingsLine
l@HoldingsPosition{} = HoldingsLine
l{hlHolding = periodHolding $ hlHolding l}

    startholdings :: Map (Text, Text) Holding
startholdings = [((Text, Text), Holding)] -> Map (Text, Text) Holding
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [((Holding -> Text
hAccount Holding
h, Holding -> Text
hCommodity Holding
h), Holding
h) | (PeriodicReportRow DisplayName MixedAmount
_, Holding
h) <- HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
startrpt]

    periodHolding :: Holding -> Holding
periodHolding Holding
h = Holding
h{hUgain = fromMaybe [] mugain, hUgainPct = mpct, hXirr = mxirr}
      where
        (Maybe [Amount]
mugain, Maybe Quantity
mpct, Maybe Double
mxirr) = Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> [(Day, Amount)]
-> (Maybe [Amount], Maybe Quantity, Maybe Double)
periodFigures Maybe [Amount]
mstartvalue Maybe [Amount]
mstartugain ([Amount] -> (Holding -> [Amount]) -> Maybe Holding -> [Amount]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Holding -> [Amount]
hCost Maybe Holding
mstarth) Maybe [Amount]
mendvalue Maybe [Amount]
mendugain (Holding -> [Amount]
hCost Holding
h) (Holding -> [(Day, Amount)]
hFlows Holding
h)
        mstarth :: Maybe Holding
mstarth = (Text, Text) -> Map (Text, Text) Holding -> Maybe Holding
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Holding -> Text
hAccount Holding
h, Holding -> Text
hCommodity Holding
h) Map (Text, Text) Holding
startholdings
        (Maybe [Amount]
mstartvalue, Maybe [Amount]
mstartugain) = (Maybe [Amount], Maybe [Amount])
-> (Holding -> (Maybe [Amount], Maybe [Amount]))
-> Maybe Holding
-> (Maybe [Amount], Maybe [Amount])
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [], [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just []) Holding -> (Maybe [Amount], Maybe [Amount])
valueAndUgain Maybe Holding
mstarth
        (Maybe [Amount]
mendvalue, Maybe [Amount]
mendugain) = Holding -> (Maybe [Amount], Maybe [Amount])
valueAndUgain Holding
h
        -- a holding's value and unrealised gain, if known; nothing held is worth nothing
        valueAndUgain :: Holding -> (Maybe [Amount], Maybe [Amount])
valueAndUgain Holding
h'
          | Amount -> Bool
amountLooksZero (Holding -> Amount
hUnits Holding
h') = ([Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [], [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [])
          | Bool
otherwise = ([Amount] -> Maybe [Amount]
forall {t :: * -> *} {a}. Foldable t => t a -> Maybe (t a)
nonEmpty ([Amount] -> Maybe [Amount]) -> [Amount] -> Maybe [Amount]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hValue Holding
h', [Amount] -> Maybe [Amount]
forall {t :: * -> *} {a}. Foldable t => t a -> Maybe (t a)
nonEmpty ([Amount] -> Maybe [Amount]) -> [Amount] -> Maybe [Amount]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hUgain Holding
h')
        nonEmpty :: t a -> Maybe (t a)
nonEmpty t a
as = if t a -> Bool
forall a. t a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null t a
as then Maybe (t a)
forall a. Maybe a
Nothing else t a -> Maybe (t a)
forall a. a -> Maybe a
Just t a
as

    -- Period totals from the start and end totals leaving out some
    -- commodities. Both leave out the same ones, those whose value is
    -- unknown at the start or the end, so the period's figures compare
    -- the same holdings.
    periodTotals :: ([Text] -> HoldingsTotals)
-> ([Text] -> HoldingsTotals) -> HoldingsTotals
periodTotals [Text] -> HoldingsTotals
stx [Text] -> HoldingsTotals
tx = HoldingsTotals
t{htUgain = mugain, htUgainPct = mpct, htXirr = mxirr}
      where
        excl :: [Text]
excl = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ HoldingsTotals -> [Text]
htUnpriced ([Text] -> HoldingsTotals
stx []) [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ HoldingsTotals -> [Text]
htUnpriced ([Text] -> HoldingsTotals
tx [])
        st :: HoldingsTotals
st = [Text] -> HoldingsTotals
stx [Text]
excl
        t :: HoldingsTotals
t  = [Text] -> HoldingsTotals
tx [Text]
excl
        (Maybe [Amount]
mugain, Maybe Quantity
mpct, Maybe Double
mxirr) = Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> [(Day, Amount)]
-> (Maybe [Amount], Maybe Quantity, Maybe Double)
periodFigures (HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
st) (HoldingsTotals -> Maybe [Amount]
totalUgain HoldingsTotals
st) (HoldingsTotals -> [Amount]
htValuedCost HoldingsTotals
st) (HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
t) (HoldingsTotals -> Maybe [Amount]
totalUgain HoldingsTotals
t) (HoldingsTotals -> [Amount]
htValuedCost HoldingsTotals
t) (HoldingsTotals -> [(Day, Amount)]
htFlows HoldingsTotals
t)
        totalUgain :: HoldingsTotals -> Maybe [Amount]
totalUgain HoldingsTotals
t'
          | HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
t' Maybe [Amount] -> Maybe [Amount] -> Bool
forall a. Eq a => a -> a -> Bool
== [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [] Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Amount -> Bool
amountLooksZero (HoldingsTotals -> [Amount]
htValuedCost HoldingsTotals
t') = [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just []  -- nothing (valued) held
          | Bool
otherwise = HoldingsTotals -> Maybe [Amount]
htUgain HoldingsTotals
t'
    accountPeriodTotals :: Text -> HoldingsTotals
accountPeriodTotals Text
a = ([Text] -> HoldingsTotals)
-> ([Text] -> HoldingsTotals) -> HoldingsTotals
periodTotals (\[Text]
x -> HoldingsReport -> [Text] -> Text -> HoldingsTotals
hrAccountTotalsExcluding HoldingsReport
startrpt [Text]
x Text
a) (\[Text]
x -> HoldingsReport -> [Text] -> Text -> HoldingsTotals
hrAccountTotalsExcluding HoldingsReport
rpt [Text]
x Text
a)

    -- From the value and unrealised gain (when known) and the cost, at the
    -- start and at the end, and the period's cashflows: the period's UGain,
    -- UGain% and XIRR.
    periodFigures :: Maybe [Amount] -> Maybe [Amount] -> [Amount] -> Maybe [Amount] -> Maybe [Amount] -> [Amount] -> [(Day, Amount)]
                  -> (Maybe [Amount], Maybe Quantity, Maybe Double)
    periodFigures :: Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> Maybe [Amount]
-> Maybe [Amount]
-> [Amount]
-> [(Day, Amount)]
-> (Maybe [Amount], Maybe Quantity, Maybe Double)
periodFigures Maybe [Amount]
mv0 Maybe [Amount]
mu0 [Amount]
cost0 Maybe [Amount]
mv1 Maybe [Amount]
mu1 [Amount]
cost1 [(Day, Amount)]
flows = (Maybe [Amount]
mugain, Maybe Quantity
mpct, Maybe Double
mxirr)
      where
        mugain :: Maybe [Amount]
mugain = do
          u0 <- Maybe [Amount]
mu0
          u1 <- mu1
          Just $ case u1 ++ map negate u0 of
            [] -> []
            [Amount]
as -> MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
as
        mpct :: Maybe Quantity
mpct = do
          [g] <- Maybe [Amount]
mugain
          v0 <- mv0
          let costs = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount]
cost0 [Amount] -> [Amount] -> [Amount]
forall a. [a] -> [a] -> [a]
++ [Amount]
cost1
              total = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Quantity] -> Quantity)
-> ([Amount] -> [Quantity]) -> [Amount] -> Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> Quantity) -> [Amount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Quantity
aquantity
          guard $ all ((== acommodity g) . acommodity) $ v0 ++ costs
          let base = [Amount] -> Quantity
total [Amount]
v0 Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
+ [Amount] -> Quantity
total [Amount]
cost1 Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- [Amount] -> Quantity
total [Amount]
cost0
          guard $ base /= 0
          Just $ 100 * aquantity g / abs base
        mxirr :: Maybe Double
mxirr = do
          v0 <- Maybe [Amount]
mv0
          opening <- case filter (not . amountLooksZero) v0 of
            []  -> [(Day, Amount)] -> Maybe [(Day, Amount)]
forall a. a -> Maybe a
Just []
            [Amount
v] -> [(Day, Amount)] -> Maybe [(Day, Amount)]
forall a. a -> Maybe a
Just [(Integer -> Day -> Day
addDays (-Integer
1) Day
start, Amount -> Amount
forall a. Num a => a -> a
negate Amount
v)]
            [Amount]
_   -> Maybe [(Day, Amount)]
forall a. Maybe a
Nothing
          let flows' = [(Day, Amount)]
opening [(Day, Amount)] -> [(Day, Amount)] -> [(Day, Amount)]
forall a. [a] -> [a] -> [a]
++ [(Day, Amount)]
flows
          -- the value at the end; nothing held is worth zero of the cashflows' commodity
          v1 <- case (mv1, flows') of
            (Just [Amount
v], [(Day, Amount)]
_)          -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
v
            (Just [], (Day
_, Amount
a):[(Day, Amount)]
_)    -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
a{aquantity = 0}
            (Maybe [Amount], [(Day, Amount)])
_                      -> Maybe Amount
forall a. Maybe a
Nothing
          holdingsXirr (hrDate rpt) flows' v1

-- | The annualised internal rate of return, as a percentage, implied by
-- dated cashflows (negative = money invested) plus a final value amount
-- at the report date, when they are all in one commodity. Calculated
-- like roi's IRR (see xirr for the special cases, eg -100% when nothing
-- is left of the money invested). Nothing if it has no solution (eg an
-- infinite rate) or can not be solved.
-- Not for a short position, whose flows are a long position's with the
-- signs reversed: the rate solving those is the same, so it would report
-- a winning short as a loss. A short is recognised by a negative final
-- value (units owed), or when closed, by money received rather than
-- invested in the earliest flow.
holdingsXirr :: Day -> [(Day, Amount)] -> Amount -> Maybe Double
holdingsXirr :: Day -> [(Day, Amount)] -> Amount -> Maybe Double
holdingsXirr Day
reportdate [(Day, Amount)]
flows Amount
finalv = do
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [(Day, Amount)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Day, Amount)]
flows
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ ((Day, Amount) -> Bool) -> [(Day, Amount)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Text
acommodity Amount
finalv) (Text -> Bool) -> ((Day, Amount) -> Text) -> (Day, Amount) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Text
acommodity (Amount -> Text)
-> ((Day, Amount) -> Amount) -> (Day, Amount) -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Day, Amount) -> Amount
forall a b. (a, b) -> b
snd) [(Day, Amount)]
flows
  let earliest :: Quantity
earliest = Amount -> Quantity
aquantity (Amount -> Quantity) -> Amount -> Quantity
forall a b. (a -> b) -> a -> b
$ (Day, Amount) -> Amount
forall a b. (a, b) -> b
snd ((Day, Amount) -> Amount) -> (Day, Amount) -> Amount
forall a b. (a -> b) -> a -> b
$ ((Day, Amount) -> (Day, Amount) -> Ordering)
-> [(Day, Amount)] -> (Day, Amount)
forall (t :: * -> *) a.
Foldable t =>
(a -> a -> Ordering) -> t a -> a
minimumBy (((Day, Amount) -> Day)
-> (Day, Amount) -> (Day, Amount) -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (Day, Amount) -> Day
forall a b. (a, b) -> a
fst) [(Day, Amount)]
flows
      isshort :: Bool
isshort = Amount -> Quantity
aquantity Amount
finalv Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0 Bool -> Bool -> Bool
|| (Amount -> Quantity
aquantity Amount
finalv Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
0 Bool -> Bool -> Bool
&& Quantity
earliest Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0)
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not Bool
isshort
  (IrrError -> Maybe Double)
-> (Double -> Maybe Double)
-> Either IrrError Double
-> Maybe Double
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Double -> IrrError -> Maybe Double
forall a b. a -> b -> a
const Maybe Double
forall a. Maybe a
Nothing) Double -> Maybe Double
forall a. a -> Maybe a
Just (Either IrrError Double -> Maybe Double)
-> Either IrrError Double -> Maybe Double
forall a b. (a -> b) -> a -> b
$ Day -> [(Day, Quantity)] -> Either IrrError Double
xirr Day
reportdate ([(Day, Quantity)] -> Either IrrError Double)
-> [(Day, Quantity)] -> Either IrrError Double
forall a b. (a -> b) -> a -> b
$ (Day
reportdate, Amount -> Quantity
aquantity Amount
finalv) (Day, Quantity) -> [(Day, Quantity)] -> [(Day, Quantity)]
forall a. a -> [a] -> [a]
: [(Day
d, Amount -> Quantity
aquantity Amount
a) | (Day
d, Amount
a) <- [(Day, Amount)]
flows]

-- | The flat holdings report with its gain columns covering each
-- holding's whole life up to the report end date - except RGain and the
-- cashflows (and so XIRR), which are limited to the report period when
-- the query has a start date (flatHoldingsReport then finishes the job).
-- If a lot filter is given, just those lots are counted, and the query's
-- change:/balance: terms are not consulted.
flatHoldingsReportAt :: Maybe ((AccountName, CommoditySymbol) -> Bool) -> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReportAt :: Maybe ((Text, Text) -> Bool)
-> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReportAt Maybe ((Text, Text) -> Bool)
mkeeplot HoldingsReportOpts{hroLots :: HoldingsReportOpts -> Bool
hroLots=Bool
showlots, hroRounding :: HoldingsReportOpts -> Rounding
hroRounding=Rounding
rounding, hroPriceOracle :: HoldingsReportOpts -> Maybe PriceOracle
hroPriceOracle=Maybe PriceOracle
mpriceoracle}
               rspec :: ReportSpec
rspec@ReportSpec{_rsQuery :: ReportSpec -> Query
_rsQuery=Query
q, _rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts} Journal
j =
  HoldingsReport
    { hrDate :: Day
hrDate            = Day
reportdate
    , hrLines :: [HoldingsLine]
hrLines           = [HoldingsLine]
displaylines
    , hrRows :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows            = [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines
    , hrTotals :: HoldingsTotals
hrTotals          = [Text] -> HoldingsTotals
totalsExcluding []
    , hrAccountTotals :: Text -> HoldingsTotals
hrAccountTotals   = [Text] -> Text -> HoldingsTotals
accountTotalsExcluding []
    , hrTotalsExcluding :: [Text] -> HoldingsTotals
hrTotalsExcluding = [Text] -> HoldingsTotals
totalsExcluding
    , hrAccountTotalsExcluding :: [Text] -> Text -> HoldingsTotals
hrAccountTotalsExcluding = [Text] -> Text -> HoldingsTotals
accountTotalsExcluding
    , hrUnitCostHeading :: Text
hrUnitCostHeading = Text
unitcostheading
    , hrStyles :: Map Text AmountStyle
hrStyles          = Map Text AmountStyle
pctstyles
    , hrGainsPeriod :: Maybe DateSpan
hrGainsPeriod     = Maybe DateSpan
forall a. Maybe a
Nothing
    , hrKeepLot :: (Text, Text) -> Bool
hrKeepLot         = (Text, Text) -> Bool
keeplot
    }
  where
    -- The date this report shows holdings at: the day before the (exclusive)
    -- report end date if specified, otherwise today.
    mend :: Maybe Day
mend = Bool -> Query -> Maybe Day
queryEndDate Bool
False Query
q
    reportdate :: Day
reportdate = Day -> (Day -> Day) -> Maybe Day -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ReportSpec -> Day
_rsDay ReportSpec
rspec) (Integer -> Day -> Day
addDays (-Integer
1)) Maybe Day
mend

    -- The report start date, if any. Realised gains and cashflows are
    -- limited to the period from then on.
    mstart :: Maybe Day
mstart = Bool -> Query -> Maybe Day
queryStartDate Bool
False Query
q
    inperiod :: Day -> Bool
inperiod Day
d = Bool -> (Day -> Bool) -> Maybe Day -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>=) Maybe Day
mstart

    -- The query used to select lot subaccount postings: the report query
    -- without its date terms (holdings are cumulative to the end date,
    -- added here) and depth terms (--depth only clips the displayed rows;
    -- the lots beneath still count).
    endq :: Query
endq = [Query] -> Query
And [(Query -> Bool) -> Query -> Query
filterQuery (\Query
x -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Query -> Bool
queryIsDateOrDate2 Query
x Bool -> Bool -> Bool
|| Query -> Bool
queryIsDepth Query
x) Query
q
               ,DateSpan -> Query
Date (DateSpan -> Query) -> DateSpan -> Query
forall a b. (a -> b) -> a -> b
$ Maybe EFDay -> Maybe EFDay -> DateSpan
DateSpan Maybe EFDay
forall a. Maybe a
Nothing (Day -> EFDay
Exact (Day -> EFDay) -> Maybe Day -> Maybe EFDay
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Day
mend)]

    -- The postings contributing to each lot subaccount, keyed by account
    -- and commodity (so amounts in different commodities, not expected in
    -- a lot subaccount but possible, don't merge wrongly).
    lotpostings :: [((AccountName, CommoditySymbol), (Day, Amount))]
    lotpostings :: [((Text, Text), (Day, Amount))]
lotpostings =
      [ ((Posting -> Text
paccount Posting
p, Amount -> Text
acommodity Amount
a), (Posting -> Day
postingDate Posting
p, Amount
a))
      | Posting
p <- Journal -> [Posting]
journalPostings Journal
j
      , Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
lotSubaccountName (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
paccount Posting
p
      , Query
endq Query -> Posting -> Bool
`matchesPosting` Posting
p
      , Amount
a <- MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
      ]

    -- The units held in each lot subaccount.
    lotmap :: M.Map (AccountName, CommoditySymbol) Amount
    lotmap :: Map (Text, Text) Amount
lotmap = (Amount -> Amount -> Amount)
-> [((Text, Text), Amount)] -> Map (Text, Text) Amount
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Amount -> Amount -> Amount
forall a. Num a => a -> a -> a
(+) [((Text, Text)
k, Amount -> Amount
amountStripCost Amount
a) | ((Text, Text)
k, (Day
_, Amount
a)) <- [((Text, Text), (Day, Amount))]
lotpostings]

    -- Each lot subaccount's cashflows in the cost commodity, for XIRR:
    -- each posting's transacted cost if any (so, proceeds when disposing),
    -- otherwise its cost basis value. Negative = money invested.
    -- A posting with no transacted cost (eg a transfer between accounts, or
    -- an opening balance) is dated on its lot's acquisition date, not its own
    -- date, so that an account receiving lots measures from when they were
    -- acquired, like its UGain and Age (and the totals row, in which a
    -- transfer's two postings cancel). With a start date, no earlier than
    -- that, since gains are measured from then.
    flowmap :: M.Map (AccountName, CommoditySymbol) [(Day, Amount)]
    flowmap :: Map (Text, Text) [(Day, Amount)]
flowmap = Map (Text, Text) [(Day, Amount)]
-> Map (Text, Text) [(Day, Amount)]
forall v. Map (Text, Text) v -> Map (Text, Text) v
matchingLots (Map (Text, Text) [(Day, Amount)]
 -> Map (Text, Text) [(Day, Amount)])
-> Map (Text, Text) [(Day, Amount)]
-> Map (Text, Text) [(Day, Amount)]
forall a b. (a -> b) -> a -> b
$ ([(Day, Amount)] -> [(Day, Amount)] -> [(Day, Amount)])
-> [((Text, Text), [(Day, Amount)])]
-> Map (Text, Text) [(Day, Amount)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [(Day, Amount)] -> [(Day, Amount)] -> [(Day, Amount)]
forall a. [a] -> [a] -> [a]
(++)
      [ ((Text, Text)
k, [(Day
fd, Amount -> Amount
forall a. Num a => a -> a
negate Amount
flowamt)])
      | ((Text, Text)
k, (Day
d, Amount
a)) <- [((Text, Text), (Day, Amount))]
lotpostings
      , Day -> Bool
inperiod Day
d
      , Just (Day
fd, Amount
flowamt) <- [case Amount -> Maybe AmountCost
acost Amount
a of
          Just AmountCost
_  -> (Day, Amount) -> Maybe (Day, Amount)
forall a. a -> Maybe a
Just (Day
d, Amount -> Amount
amountCost Amount
a)
          Maybe AmountCost
Nothing -> do
            cb <- Amount -> Maybe CostBasis
acostbasis Amount
a
            c <- cbCost cb
            let acqdate = Day -> (Day -> Day) -> Maybe Day -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Day
d (\Day
acq -> Day -> (Day -> Day) -> Maybe Day -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Day
acq (Day -> Day -> Day
forall a. Ord a => a -> a -> a
max Day
acq) Maybe Day
mstart) (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ CostBasis -> Maybe Day
cbDate CostBasis
cb
            Just (acqdate, multiplyAmount (aquantity a) c)]
      ]

    -- Each lot subaccount's realised gains, in the cost commodity: for each
    -- dispose posting with a transacted price and a cost basis, its cost
    -- basis minus its transacted cost. For a sale (negative) that is the
    -- proceeds minus the basis of the units sold; for a short cover
    -- (positive, in a liability account) it is the short-sale basis minus
    -- the cost of buying the units back.
    -- The gains get their commodity's display style, since the cost bases
    -- they are derived from can have more precision (eg from inferred
    -- per-unit costs).
    rgainmap :: M.Map (AccountName, CommoditySymbol) Amount
    rgainmap :: Map (Text, Text) Amount
rgainmap = Map (Text, Text) Amount -> Map (Text, Text) Amount
forall v. Map (Text, Text) v -> Map (Text, Text) v
matchingLots Map (Text, Text) Amount
allrgainmap
    allrgainmap :: Map (Text, Text) Amount
allrgainmap = (Amount -> Amount)
-> Map (Text, Text) Amount -> Map (Text, Text) Amount
forall a b k. (a -> b) -> Map k a -> Map k b
M.map (Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles) (Map (Text, Text) Amount -> Map (Text, Text) Amount)
-> Map (Text, Text) Amount -> Map (Text, Text) Amount
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount -> Amount)
-> [((Text, Text), Amount)] -> Map (Text, Text) Amount
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Amount -> Amount -> Amount
forall a. Num a => a -> a -> a
(+)
      [ ((Posting -> Text
paccount Posting
p, Amount -> Text
acommodity Amount
a), Amount
basis Amount -> Amount -> Amount
forall a. Num a => a -> a -> a
- Amount
transacted)
      | Posting
p <- Journal -> [Posting]
journalPostings Journal
j
      , Posting -> Bool
isDisposePosting Posting
p
      , Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
lotSubaccountName (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
paccount Posting
p
      , Query
endq Query -> Posting -> Bool
`matchesPosting` Posting
p
      , Day -> Bool
inperiod (Day -> Bool) -> Day -> Bool
forall a b. (a -> b) -> a -> b
$ Posting -> Day
postingDate Posting
p
      , Amount
a <- MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
      , Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool) -> Maybe AmountCost -> Bool
forall a b. (a -> b) -> a -> b
$ Amount -> Maybe AmountCost
acost Amount
a
      , Maybe Amount -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Amount -> Bool) -> Maybe Amount -> Bool
forall a b. (a -> b) -> a -> b
$ CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Amount -> Maybe CostBasis
acostbasis Amount
a
      , let basis :: Amount
basis = Amount -> Amount
amountCostBasis Amount
a
            transacted :: Amount
transacted = Amount -> Amount
amountCost Amount
a
      , Amount -> Text
acommodity Amount
basis Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Text
acommodity Amount
transacted
      ]

    -- The current average unit cost of each AVERAGE/AVERAGEALL pool, as of
    -- the report end date, keyed by (base account, commodity). Computed
    -- from all of the pool's lot postings, whatever the query (see
    -- journalAveragePoolTotals). Used to fill in the cost missing from
    -- AVERAGE lots' costless subaccount names (see lotsUnder).
    poolavgmap :: M.Map (AccountName, CommoditySymbol) Amount
    poolavgmap :: Map (Text, Text) Amount
poolavgmap = ((Quantity, Amount) -> Amount)
-> Map (Text, Text) (Quantity, Amount) -> Map (Text, Text) Amount
forall a b k. (a -> b) -> Map k a -> Map k b
M.map (\(Quantity
units, Amount
costtot) -> Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount -> Amount
avgcost Amount
nullamt{aquantity=units} Amount
costtot)
                       (Journal -> Maybe Day -> Map (Text, Text) (Quantity, Amount)
journalAveragePoolTotals Journal
j Maybe Day
mend)

    -- The per-row lookups below (lotsOf, rgainsOf, flowsOf and the
    -- *Under forms) used to scan a whole per-lot map for every displayed
    -- row, making the report roughly O(rows × lots) (#2779). Instead,
    -- each map is indexed by account up front, in two groupings:
    --
    -- "under": a key's data appears under its account and every ancestor,
    -- answering "at or under this account" queries directly.
    --
    -- "own": a key's data appears under its owning row account - the
    -- deepest candidate row account at or above it, if any - answering
    -- "in this row's own scope" queries. This is what makes overlapping
    -- rows disjoint, eg when lots are held in both an account and its
    -- subaccount (each of which then gets its own row).
    --
    -- Each group keeps the map's ascending (account, commodity) key
    -- order, as the full scans produced.

    underIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]
    underIx :: forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) v
m = [(Text, (Text, v))] -> Map Text [(Text, v)]
forall a. [(Text, a)] -> Map Text [a]
groupIx [(Text
anc, (Text
c, v
v)) | ((Text
sub, Text
c), v
v) <- Map (Text, Text) v -> [((Text, Text), v)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map (Text, Text) v
m
                                       , Text
anc <- Text
sub Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Text -> [Text]
parentAccountNames Text
sub]

    ownIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]
    ownIx :: forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) v
m = [(Text, (Text, v))] -> Map Text [(Text, v)]
forall a. [(Text, a)] -> Map Text [a]
groupIx [(Text
owner, (Text
c, v
v)) | ((Text
sub, Text
c), v
v) <- Map (Text, Text) v -> [((Text, Text), v)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map (Text, Text) v
m
                                       , Just Text
owner <- [Text -> Maybe Text
ownerOf Text
sub]]

    -- Group an ascending association list by account, each group keeping
    -- the input order (fromListWith prepends, hence the reverse).
    groupIx :: [(AccountName, a)] -> M.Map AccountName [a]
    groupIx :: forall a. [(Text, a)] -> Map Text [a]
groupIx = ([a] -> [a] -> [a]) -> [(Text, [a])] -> Map Text [a]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
(++) ([(Text, [a])] -> Map Text [a])
-> ([(Text, a)] -> [(Text, [a])]) -> [(Text, a)] -> Map Text [a]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Text, [a])] -> [(Text, [a])]
forall a. [a] -> [a]
reverse ([(Text, [a])] -> [(Text, [a])])
-> ([(Text, a)] -> [(Text, [a])]) -> [(Text, a)] -> [(Text, [a])]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Text, a) -> (Text, [a])) -> [(Text, a)] -> [(Text, [a])]
forall a b. (a -> b) -> [a] -> [b]
map ((a -> [a]) -> (Text, a) -> (Text, [a])
forall a b. (a -> b) -> (Text, a) -> (Text, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (a -> [a] -> [a]
forall a. a -> [a] -> [a]
:[]))

    -- A lot subaccount's owning row account: the deepest candidate row
    -- account at or above it, if any.
    ownerOf :: AccountName -> Maybe AccountName
    ownerOf :: Text -> Maybe Text
ownerOf Text
sub = (Text -> Bool) -> [Text] -> Maybe Text
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Text -> Set Text -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Text
candaccset) (Text
sub Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Text -> [Text]
parentAccountNames Text
sub)
    candaccset :: Set Text
candaccset = [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList [Text]
candaccts

    ownFlowIx :: Map Text [(Text, [(Day, Amount)])]
ownFlowIx    = Map (Text, Text) [(Day, Amount)]
-> Map Text [(Text, [(Day, Amount)])]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) [(Day, Amount)]
flowmap
    ownRgainIx :: Map Text [(Text, Amount)]
ownRgainIx   = Map (Text, Text) Amount -> Map Text [(Text, Amount)]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) Amount
rgainmap
    underFlowIx :: Map Text [(Text, [(Day, Amount)])]
underFlowIx  = Map (Text, Text) [(Day, Amount)]
-> Map Text [(Text, [(Day, Amount)])]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) [(Day, Amount)]
flowmap
    underRgainIx :: Map Text [(Text, Amount)]
underRgainIx = Map (Text, Text) Amount -> Map Text [(Text, Amount)]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) Amount
rgainmap
    allUnderRgainIx :: Map Text [(Text, Amount)]
allUnderRgainIx = Map (Text, Text) Amount -> Map Text [(Text, Amount)]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) Amount
allrgainmap

    -- Narrow an indexed group to one held commodity, if specified.
    inComm :: Maybe CommoditySymbol -> [(CommoditySymbol, v)] -> [v]
    inComm :: forall v. Maybe Text -> [(Text, v)] -> [v]
inComm Maybe Text
mc [(Text, v)]
kvs = [v
v | (Text
c, v
v) <- [(Text, v)]
kvs, Bool -> (Text -> Bool) -> Maybe Text -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
c) Maybe Text
mc]

    -- The cashflows of the lots in a row account's own scope.
    flowsOf :: AccountName -> Maybe CommoditySymbol -> [(Day, Amount)]
    flowsOf :: Text -> Maybe Text -> [(Day, Amount)]
flowsOf Text
acct Maybe Text
mc = [[(Day, Amount)]] -> [(Day, Amount)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[(Day, Amount)]] -> [(Day, Amount)])
-> [[(Day, Amount)]] -> [(Day, Amount)]
forall a b. (a -> b) -> a -> b
$ Maybe Text -> [(Text, [(Day, Amount)])] -> [[(Day, Amount)]]
forall v. Maybe Text -> [(Text, v)] -> [v]
inComm Maybe Text
mc ([(Text, [(Day, Amount)])] -> [[(Day, Amount)]])
-> [(Text, [(Day, Amount)])] -> [[(Day, Amount)]]
forall a b. (a -> b) -> a -> b
$ [(Text, [(Day, Amount)])]
-> Text
-> Map Text [(Text, [(Day, Amount)])]
-> [(Text, [(Day, Amount)])]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, [(Day, Amount)])]
ownFlowIx

    -- The realised gains of the lots at or under an account, optionally of one held commodity.
    rgainsUnder :: AccountName -> Maybe CommoditySymbol -> [Amount]
    rgainsUnder :: Text -> Maybe Text -> [Amount]
rgainsUnder Text
acct Maybe Text
mc = Maybe Text -> [(Text, Amount)] -> [Amount]
forall v. Maybe Text -> [(Text, v)] -> [v]
inComm Maybe Text
mc ([(Text, Amount)] -> [Amount]) -> [(Text, Amount)] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [(Text, Amount)]
-> Text -> Map Text [(Text, Amount)] -> [(Text, Amount)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, Amount)]
underRgainIx

    -- The realised gains of the lots in a row account's own scope.
    rgainsOf :: AccountName -> Maybe CommoditySymbol -> [Amount]
    rgainsOf :: Text -> Maybe Text -> [Amount]
rgainsOf Text
acct Maybe Text
mc = Maybe Text -> [(Text, Amount)] -> [Amount]
forall v. Maybe Text -> [(Text, v)] -> [v]
inComm Maybe Text
mc ([(Text, Amount)] -> [Amount]) -> [(Text, Amount)] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [(Text, Amount)]
-> Text -> Map Text [(Text, Amount)] -> [(Text, Amount)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, Amount)]
ownRgainIx

    -- A lot subaccount's cost basis, parsed from its name
    -- (which by construction contains the acquisition date and unit cost).
    -- The cost gets its commodity's display style, including display
    -- precision (lot names can have more precision, eg from inferred
    -- per-unit costs), so derived amounts (Unit cost, Cost) are displayed
    -- with the standard display precision.
    lotBasis :: AccountName -> Maybe CostBasis
    lotBasis :: Text -> Maybe CostBasis
lotBasis Text
acct = do
      name <- Text -> Maybe Text
lotSubaccountName Text
acct
      cb <- either (const Nothing) Just $ parseLotName parseAmt name
      Just cb{cbCost = styleAmounts styles <$> cbCost cb}
      where parseAmt :: String -> Maybe Amount
parseAmt = (HledgerParseErrors -> Maybe Amount)
-> (Amount -> Maybe Amount)
-> Either HledgerParseErrors Amount
-> Maybe Amount
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Amount -> HledgerParseErrors -> Maybe Amount
forall a b. a -> b -> a
const Maybe Amount
forall a. Maybe a
Nothing) Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Either HledgerParseErrors Amount -> Maybe Amount)
-> (String -> Either HledgerParseErrors Amount)
-> String
-> Maybe Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either HledgerParseErrors Amount
parseamount

    -- Amounts are displayed normalised to their commodity's display
    -- precision by default; hroRounding can choose another rounding strategy.
    styles :: Map Text AmountStyle
styles = Rounding -> Journal -> Map Text AmountStyle
journalCommodityStylesWith Rounding
rounding Journal
j

    priceoracle :: PriceOracle
priceoracle = PriceOracle -> Maybe PriceOracle -> PriceOracle
forall a. a -> Maybe a -> a
fromMaybe (Bool -> Journal -> PriceOracle
journalPriceOracle (ReportOpts -> Bool
infer_prices_ ReportOpts
ropts) Journal
j) Maybe PriceOracle
mpriceoracle

    -- The valuation strategy requested with -V/-X/--value, if any.
    -- It selects the valuation date and/or the valuation commodity;
    -- --value=then is rejected above.
    mvalue :: Maybe ValuationType
mvalue = ReportOpts -> Maybe ValuationType
value_ ReportOpts
ropts
    (Day
valuationdate, Maybe Text
mtargetcomm) = case Maybe ValuationType
mvalue of
      Maybe ValuationType
Nothing            -> (Day
reportdate, Maybe Text
forall a. Maybe a
Nothing)
      Just (AtEnd  Maybe Text
mc)   -> (Day
reportdate, Maybe Text
mc)
      Just (AtNow  Maybe Text
mc)   -> (ReportSpec -> Day
_rsDay ReportSpec
rspec, Maybe Text
mc)
      Just (AtDate Day
d Maybe Text
mc) -> (Day
d, Maybe Text
mc)
      Just (AtThen Maybe Text
mc)   -> (Day
reportdate, Maybe Text
mc)  -- not supported, rejected above

    -- The valuation target commodity for a lot: the commodity requested
    -- with -V/-X/--value if any, otherwise the lot's own cost commodity
    -- when known, otherwise none (the price oracle picks a default).
    lotValuationComm :: Maybe CostBasis -> Maybe CommoditySymbol
    lotValuationComm :: Maybe CostBasis -> Maybe Text
lotValuationComm Maybe CostBasis
mcb = case Maybe ValuationType
mvalue of
      Maybe ValuationType
Nothing -> Amount -> Text
acommodity (Amount -> Text) -> Maybe Amount -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb)
      Just ValuationType
_  -> Maybe Text
mtargetcomm

    -- Value one lot at the valuation date: Just (unit price, total value)
    -- if it has a market price to its target commodity.
    lotValuation :: (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
    lotValuation :: (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
lotValuation (Amount
a, Maybe CostBasis
mcb) = do
      (pcomm, rate) <- PriceOracle
priceoracle (Day
valuationdate, Amount -> Text
acommodity Amount
a, Maybe CostBasis -> Maybe Text
lotValuationComm Maybe CostBasis
mcb)
      let mkamt Quantity
n = Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing
                      Amount
nullamt{acommodity=pcomm, aquantity=n}
      Just (mkamt rate, mkamt (rate * aquantity a))

    -- Value some lots at the valuation date: Just (their distinct unit
    -- prices, their total value per value commodity) if every lot has a
    -- market price, otherwise Nothing. Each lot is valued separately in
    -- its own target commodity, so values (and their sums, like the
    -- totals row) don't depend on how lots are grouped into display rows
    -- (by --depth, --pivot, tree mode etc).
    lotsValuation :: [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
    lotsValuation :: [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation [(Amount, Maybe CostBasis)]
lots = do
      pvs <- ((Amount, Maybe CostBasis) -> Maybe (Amount, Amount))
-> [(Amount, Maybe CostBasis)] -> Maybe [(Amount, Amount)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
lotValuation [(Amount, Maybe CostBasis)]
lots
      Just (nubSortOn (\Amount
a -> (Amount -> Text
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)) $ map fst pvs
           ,sumAmounts $ map snd pvs)

    -- The market value of the lots at or under an account whose value is
    -- known (see mvalueExcluding), per value commodity.
    mvalueUnder :: AccountName -> Maybe [Amount]
    mvalueUnder :: Text -> Maybe [Amount]
mvalueUnder Text
acct = [Text] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
mvalueExcluding ([(Amount, Maybe CostBasis)] -> [Text]
unpricedCommodities [(Amount, Maybe CostBasis)]
lots) [(Amount, Maybe CostBasis)]
lots
      where lots :: [(Amount, Maybe CostBasis)]
lots = Text -> [(Amount, Maybe CostBasis)]
lotsUnder Text
acct

    -- How to convert cost amounts (Cost, Unit/Avg cost, RGain, and the
    -- cost side of UGain) for display when -V/-X/--value is in effect:
    -- convert to the requested commodity, or to the given fallback
    -- commodity (the row's or portfolio's value commodity), at the
    -- valuation date. Costs already in the target commodity, or with no
    -- target or no market price, are left unchanged.
    costValuerTo :: Maybe CommoditySymbol -> Amount -> Amount
    costValuerTo :: Maybe Text -> Amount -> Amount
costValuerTo Maybe Text
mfallback = case Maybe ValuationType
mvalue of
      Maybe ValuationType
Nothing -> Amount -> Amount
forall a. a -> a
id
      Just ValuationType
_ -> case Maybe Text
mtargetcomm Maybe Text -> Maybe Text -> Maybe Text
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe Text
mfallback of
        Maybe Text
Nothing -> Amount -> Amount
forall a. a -> a
id
        -- styleAmounts is reapplied after conversion, since
        -- amountValueAtDate leaves full precision displayed
        Just Text
tc -> \Amount
a -> if Amount -> Text
acommodity Amount
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
tc then Amount
a
                         else Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$
                              PriceOracle
-> Map Text AmountStyle -> Maybe Text -> Day -> Amount -> Amount
amountValueAtDate PriceOracle
priceoracle Map Text AmountStyle
styles (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
tc) Day
valuationdate Amount
a

    rowCostValuer :: PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
    rowCostValuer :: PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer PeriodicReportRow DisplayName MixedAmount
r = Maybe Text -> Amount -> Amount
costValuerTo (Maybe Text -> Amount -> Amount) -> Maybe Text -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Maybe [Amount] -> Maybe Text
singleCommodity (Maybe [Amount] -> Maybe Text) -> Maybe [Amount] -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> Maybe [Amount]
mvalueUnder (PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r)

    xirrOf :: [(Day, Amount)] -> Amount -> Maybe Double
xirrOf = Day -> [(Day, Amount)] -> Amount -> Maybe Double
holdingsXirr Day
reportdate

    -- The total value of those lots which have a market price, per value
    -- commodity.
    pricedValue :: [(Amount, Maybe CostBasis)] -> [Amount]
    pricedValue :: [(Amount, Maybe CostBasis)] -> [Amount]
pricedValue [(Amount, Maybe CostBasis)]
lots = [Amount] -> [Amount]
sumAmounts [Amount
v | Just (Amount
_, Amount
v) <- ((Amount, Maybe CostBasis) -> Maybe (Amount, Amount))
-> [(Amount, Maybe CostBasis)] -> [Maybe (Amount, Amount)]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
lotValuation [(Amount, Maybe CostBasis)]
lots]

    -- The total value of all the priced holdings, including any lines
    -- hidden by change: or balance: terms. Weight is relative to this, so
    -- those terms hide lines without changing the others' weights, and
    -- unpriced holdings (which get no Weight) don't prevent the others'.
    wholevalue :: [Amount]
    wholevalue :: [Amount]
wholevalue = [(Amount, Maybe CostBasis)] -> [Amount]
pricedValue [(Amount, Maybe CostBasis)
l | ((Text
sub, Text
_), (Amount, Maybe CostBasis)
l) <- Map (Text, Text) (Amount, Maybe CostBasis)
-> [((Text, Text), (Amount, Maybe CostBasis))]
forall k a. Map k a -> [(k, a)]
M.toList Map (Text, Text) (Amount, Maybe CostBasis)
alllotbases, Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
ownerOf Text
sub]

    -- A value's percentage of the priced portfolio's value (wholevalue),
    -- when both are single amounts in the same commodity.
    weightPct :: [Amount] -> Maybe Quantity
    weightPct :: [Amount] -> Maybe Quantity
weightPct [Amount]
val = do
      [t] <- [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [Amount]
wholevalue
      [v] <- Just val
      guard $ acommodity v == acommodity t && aquantity t /= 0
      Just $ 100 * aquantity v / aquantity t

    -- The commodity display styles, plus a default style for the "%"
    -- commodity if none is declared or inferred: one decimal digit,
    -- and the % sign on the right with no space.
    pctstyles :: Map Text AmountStyle
pctstyles = Map Text AmountStyle
-> Map Text AmountStyle -> Map Text AmountStyle
forall k a. Ord k => Map k a -> Map k a -> Map k a
M.union Map Text AmountStyle
styles (Map Text AmountStyle -> Map Text AmountStyle)
-> Map Text AmountStyle -> Map Text AmountStyle
forall a b. (a -> b) -> a -> b
$ Text -> AmountStyle -> Map Text AmountStyle
forall k a. k -> a -> Map k a
M.singleton Text
"%" (AmountStyle -> Map Text AmountStyle)
-> AmountStyle -> Map Text AmountStyle
forall a b. (a -> b) -> a -> b
$
      AmountStyle
amountstyle{ascommodityside=R, asprecision=Precision 1, asrounding=HardRounding}

    -- The unrealised gains implied by value and cost amounts: value minus
    -- cost per commodity, when they cover exactly the same (nonempty) set
    -- of commodities; otherwise Nothing.
    gainAmounts :: [Amount] -> [Amount] -> Maybe [Amount]
    gainAmounts :: [Amount] -> [Amount] -> Maybe [Amount]
gainAmounts [Amount]
vals [Amount]
costs = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not ([Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Amount]
vs) Bool -> Bool -> Bool
&& (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Text
acommodity [Amount]
vs [Text] -> [Text] -> Bool
forall a. Eq a => a -> a -> Bool
== (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Text
acommodity [Amount]
cs
      [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just ([Amount] -> Maybe [Amount]) -> [Amount] -> Maybe [Amount]
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount -> Amount) -> [Amount] -> [Amount] -> [Amount]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Amount -> Amount -> Amount
gain1 [Amount]
vs [Amount]
cs
      where
        vs :: [Amount]
vs = [Amount] -> [Amount]
sumAmounts [Amount]
vals
        cs :: [Amount]
cs = [Amount] -> [Amount]
sumAmounts [Amount]
costs
        gain1 :: Amount -> Amount -> Amount
gain1 Amount
v Amount
c = Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing
                      Amount
nullamt{acommodity=acommodity v, aquantity=aquantity v - aquantity c}

    -- The percent gain, when the gains and the costs are single amounts
    -- in the same commodity and the cost is nonzero. Relative to the cost's
    -- magnitude, so a short position's gain (its cost being negative) keeps
    -- its sign.
    gainPct :: [Amount] -> [Amount] -> Maybe Quantity
    gainPct :: [Amount] -> [Amount] -> Maybe Quantity
gainPct [Amount]
gains [Amount]
costs = do
      [g] <- [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [Amount]
gains
      [c] <- Just $ sumAmounts costs
      guard $ acommodity g == acommodity c && aquantity c /= 0
      Just $ 100 * aquantity g / abs (aquantity c)

    -- A row's units of lot-tracked commodities: the sum of the lots in
    -- its own scope, one amount per commodity. (Not the row's report
    -- balance: a depth-clipped or pivoted row could also aggregate
    -- same-commodity balances from non-lot-tracked accounts, which would
    -- make Units inconsistent with the lot-derived Cost and gain columns.)
    rowUnitAmounts :: PeriodicReportRow DisplayName MixedAmount -> [Amount]
    rowUnitAmounts :: PeriodicReportRow DisplayName MixedAmount -> [Amount]
rowUnitAmounts PeriodicReportRow DisplayName MixedAmount
r =
      (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Amount]
sumAmounts ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$
      ((Amount, Maybe CostBasis) -> Amount)
-> [(Amount, Maybe CostBasis)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst ([(Amount, Maybe CostBasis)] -> [Amount])
-> [(Amount, Maybe CostBasis)] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Text -> [(Amount, Maybe CostBasis)]
lotsOf (Text -> [(Amount, Maybe CostBasis)])
-> Text -> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r

    -- The nonempty lots as (units, cost basis), keyed like lotmap.
    -- A lot's cost basis comes from its subaccount name, parsed once
    -- here; when the name has no cost part (AVERAGE lots' names omit it,
    -- staying stable across re-averaging), the pool's current average
    -- cost is filled in instead.
    alllotbases :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)
    alllotbases :: Map (Text, Text) (Amount, Maybe CostBasis)
alllotbases = ((Text, Text) -> Amount -> (Amount, Maybe CostBasis))
-> Map (Text, Text) Amount
-> Map (Text, Text) (Amount, Maybe CostBasis)
forall k a b. (k -> a -> b) -> Map k a -> Map k b
M.mapWithKey (Text, Text) -> Amount -> (Amount, Maybe CostBasis)
forall {b}. (Text, b) -> Amount -> (Amount, Maybe CostBasis)
mklot (Map (Text, Text) Amount
 -> Map (Text, Text) (Amount, Maybe CostBasis))
-> Map (Text, Text) Amount
-> Map (Text, Text) (Amount, Maybe CostBasis)
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool)
-> Map (Text, Text) Amount -> Map (Text, Text) Amount
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) Map (Text, Text) Amount
lotmap
    mklot :: (Text, b) -> Amount -> (Amount, Maybe CostBasis)
mklot (Text
sub, b
_) Amount
a = (Amount
a, Text -> Amount -> CostBasis -> CostBasis
addPoolAvg Text
sub Amount
a (CostBasis -> CostBasis) -> Maybe CostBasis -> Maybe CostBasis
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Maybe CostBasis
lotBasis Text
sub)
      where
        addPoolAvg :: Text -> Amount -> CostBasis -> CostBasis
addPoolAvg Text
sub' Amount
a' cb :: CostBasis
cb@CostBasis{cbCost :: CostBasis -> Maybe Amount
cbCost=Maybe Amount
Nothing} =
          CostBasis
cb{cbCost = M.lookup (lotBaseAccount sub', acommodity a') poolavgmap}
        addPoolAvg Text
_ Amount
_ CostBasis
cb = CostBasis
cb

    lotbases :: Map (Text, Text) (Amount, Maybe CostBasis)
lotbases = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map (Text, Text) (Amount, Maybe CostBasis)
forall v. Map (Text, Text) v -> Map (Text, Text) v
matchingLots Map (Text, Text) (Amount, Maybe CostBasis)
alllotbases

    underLotIx :: Map Text [(Text, (Amount, Maybe CostBasis))]
underLotIx = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map Text [(Text, (Amount, Maybe CostBasis))]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) (Amount, Maybe CostBasis)
lotbases
    ownLotIx :: Map Text [(Text, (Amount, Maybe CostBasis))]
ownLotIx   = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map Text [(Text, (Amount, Maybe CostBasis))]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) (Amount, Maybe CostBasis)
lotbases
    allUnderLotIx :: Map Text [(Text, (Amount, Maybe CostBasis))]
allUnderLotIx = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map Text [(Text, (Amount, Maybe CostBasis))]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
underIx Map (Text, Text) (Amount, Maybe CostBasis)
alllotbases
    allOwnLotIx :: Map Text [(Text, (Amount, Maybe CostBasis))]
allOwnLotIx   = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map Text [(Text, (Amount, Maybe CostBasis))]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) (Amount, Maybe CostBasis)
alllotbases

    -- The query's change: and balance: terms. In this report they test each
    -- displayed line: one commodity in one row account (see lineMatches).
    -- The lots, realised gains and cashflows of the other lines are left out
    -- (by matchingLots), so that the totals and tree mode's headings follow
    -- the lines shown (but Weight stays relative to all the holdings; see
    -- wholevalue). Row ownership is decided from all lots.
    rowq :: Query
rowq = ReportSpec -> Query
_rsRowQuery ReportSpec
rspec

    matchingLots :: M.Map (AccountName, CommoditySymbol) v -> M.Map (AccountName, CommoditySymbol) v
    matchingLots :: forall v. Map (Text, Text) v -> Map (Text, Text) v
matchingLots
      | Maybe ((Text, Text) -> Bool) -> Bool
forall a. Maybe a -> Bool
isJust Maybe ((Text, Text) -> Bool)
mkeeplot Bool -> Bool -> Bool
|| Bool -> Bool
not (Query -> Bool
queryIsNull Query
rowq) = ((Text, Text) -> v -> Bool)
-> Map (Text, Text) v -> Map (Text, Text) v
forall k a. (k -> a -> Bool) -> Map k a -> Map k a
M.filterWithKey (\(Text, Text)
k v
_ -> (Text, Text) -> Bool
keeplot (Text, Text)
k)
      | Bool
otherwise = Map (Text, Text) v -> Map (Text, Text) v
forall a. a -> a
id
    keeplot :: (AccountName, CommoditySymbol) -> Bool
    keeplot :: (Text, Text) -> Bool
keeplot = case Maybe ((Text, Text) -> Bool)
mkeeplot of
      Just (Text, Text) -> Bool
keep -> (Text, Text) -> Bool
keep
      Maybe ((Text, Text) -> Bool)
Nothing | Query -> Bool
queryIsNull Query
rowq -> Bool -> (Text, Text) -> Bool
forall a b. a -> b -> a
const Bool
True
              | Bool
otherwise        -> \(Text
sub, Text
c) -> Bool -> (Text -> Bool) -> Maybe Text -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (\Text
o -> (Text
o, Text
c) (Text, Text) -> Set (Text, Text) -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set (Text, Text)
matchinglines) (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
ownerOf Text
sub
    matchinglines :: Set (Text, Text)
matchinglines = [(Text, Text)] -> Set (Text, Text)
forall a. Ord a => [a] -> Set a
S.fromList
      [(Text
o, Text
c) | (Text
o, Text
c) <- [(Text, Text)] -> [(Text, Text)]
forall a. Ord a => [a] -> [a]
nubSort [(Text
o, Text
c) | (Text
sub, Text
c) <- Map (Text, Text) Amount -> [(Text, Text)]
forall k a. Map k a -> [k]
M.keys Map (Text, Text) Amount
lotmap, Just Text
o <- [Text -> Maybe Text
ownerOf Text
sub]], Text -> Text -> Bool
lineMatches Text
o Text
c]

    -- Each lot subaccount's change in units during the report period (all of
    -- its units, if the report has no start date), with its cost basis; the
    -- unchanged ones are left out.
    lotchanges :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)
    lotchanges :: Map (Text, Text) (Amount, Maybe CostBasis)
lotchanges = ((Text, Text) -> Amount -> (Amount, Maybe CostBasis))
-> Map (Text, Text) Amount
-> Map (Text, Text) (Amount, Maybe CostBasis)
forall k a b. (k -> a -> b) -> Map k a -> Map k b
M.mapWithKey (Text, Text) -> Amount -> (Amount, Maybe CostBasis)
forall {b}. (Text, b) -> Amount -> (Amount, Maybe CostBasis)
mklot (Map (Text, Text) Amount
 -> Map (Text, Text) (Amount, Maybe CostBasis))
-> Map (Text, Text) Amount
-> Map (Text, Text) (Amount, Maybe CostBasis)
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool)
-> Map (Text, Text) Amount -> Map (Text, Text) Amount
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) (Map (Text, Text) Amount -> Map (Text, Text) Amount)
-> Map (Text, Text) Amount -> Map (Text, Text) Amount
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount -> Amount)
-> [((Text, Text), Amount)] -> Map (Text, Text) Amount
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Amount -> Amount -> Amount
forall a. Num a => a -> a -> a
(+)
      [((Text, Text)
k, Amount -> Amount
amountStripCost Amount
a) | ((Text, Text)
k, (Day
d, Amount
a)) <- [((Text, Text), (Day, Amount))]
lotpostings, Day -> Bool
inperiod Day
d]
    ownLotChangeIx :: Map Text [(Text, (Amount, Maybe CostBasis))]
ownLotChangeIx = Map (Text, Text) (Amount, Maybe CostBasis)
-> Map Text [(Text, (Amount, Maybe CostBasis))]
forall v. Map (Text, Text) v -> Map Text [(Text, v)]
ownIx Map (Text, Text) (Amount, Maybe CostBasis)
lotchanges

    -- Does a row account's line for this commodity match the change: and
    -- balance: terms ? A line has two balances, its units and their market
    -- value (if all are priced), and likewise two changes: its change in
    -- units during the report period, and that valued (at the valuation
    -- date, as in the balance reports). A term with no commodity symbol tests
    -- the units; one with a symbol tests whichever of the two amounts is in
    -- that commodity, so eg balance:'>$1000' tests the value, and doesn't
    -- match an unpriced line. With -B/--cost, the cost is tested instead of
    -- the value, as displayed in Total cost (the known costs; and with
    -- -V/-X, converted like the row's costs).
    lineMatches :: AccountName -> CommoditySymbol -> Bool
    lineMatches :: Text -> Text -> Bool
lineMatches Text
acct Text
c = Query -> Bool
go Query
rowq
      where
        (MixedAmount
balunits, MixedAmount
balvalue) = Map Text [(Text, (Amount, Maybe CostBasis))]
-> (MixedAmount, MixedAmount)
unitsAndValue Map Text [(Text, (Amount, Maybe CostBasis))]
allOwnLotIx
        (MixedAmount
chgunits, MixedAmount
chgvalue) = Map Text [(Text, (Amount, Maybe CostBasis))]
-> (MixedAmount, MixedAmount)
unitsAndValue Map Text [(Text, (Amount, Maybe CostBasis))]
ownLotChangeIx
        unitsAndValue :: Map Text [(Text, (Amount, Maybe CostBasis))]
-> (MixedAmount, MixedAmount)
unitsAndValue Map Text [(Text, (Amount, Maybe CostBasis))]
ix = ([Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed ([Amount] -> MixedAmount) -> [Amount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ ((Amount, Maybe CostBasis) -> Amount)
-> [(Amount, Maybe CostBasis)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst [(Amount, Maybe CostBasis)]
lots, if Bool
atcost then MixedAmount
cost else MixedAmount
mktvalue)
          where
            lots :: [(Amount, Maybe CostBasis)]
lots = [(Amount, Maybe CostBasis)
l | (Text
c', (Amount, Maybe CostBasis)
l) <- [(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
ix, Text
c' Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
c]
            mktvalue :: MixedAmount
mktvalue = MixedAmount
-> (([Amount], [Amount]) -> MixedAmount)
-> Maybe ([Amount], [Amount])
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount
nullmixedamt ([Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed ([Amount] -> MixedAmount)
-> (([Amount], [Amount]) -> [Amount])
-> ([Amount], [Amount])
-> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Amount], [Amount]) -> [Amount]
forall a b. (a, b) -> b
snd) (Maybe ([Amount], [Amount]) -> MixedAmount)
-> Maybe ([Amount], [Amount]) -> MixedAmount
forall a b. (a -> b) -> a -> b
$ [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation [(Amount, Maybe CostBasis)]
lots
            cost :: MixedAmount
cost = [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount -> Amount
costvaluer (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
a) Amount
cb | (Amount
a, Maybe CostBasis
mcb) <- [(Amount, Maybe CostBasis)]
lots, Just Amount
cb <- [CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb]]
        -- like rowCostValuer, but from all lots, since this decides which are kept
        costvaluer :: Amount -> Amount
costvaluer = Maybe Text -> Amount -> Amount
costValuerTo (Maybe Text -> Amount -> Amount) -> Maybe Text -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ case [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation ([(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount]))
-> [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
forall a b. (a -> b) -> a -> b
$ ((Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis))
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> [a] -> [b]
map (Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis)
forall a b. (a, b) -> b
snd ([(Text, (Amount, Maybe CostBasis))]
 -> [(Amount, Maybe CostBasis)])
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> a -> b
$ [(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
allUnderLotIx of
          Just ([Amount]
_, [Amount
v]) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Amount -> Text
acommodity Amount
v
          Maybe ([Amount], [Amount])
_             -> Maybe Text
forall a. Maybe a
Nothing
        go :: Query -> Bool
go (And [Query]
qs) = (Query -> Bool) -> [Query] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Query -> Bool
go [Query]
qs
        go (Not Query
t)  = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Query -> Bool
go Query
t
        go (Change  OrdPlus
ord Quantity
n Maybe Text
mc) = OrdPlus -> Quantity -> Maybe Text -> Query
Amt OrdPlus
ord Quantity
n Maybe Text
mc Query -> MixedAmount -> Bool
`matchesMixedAmount` Maybe Text -> MixedAmount -> MixedAmount -> MixedAmount
forall {a}. Maybe a -> MixedAmount -> MixedAmount -> MixedAmount
pick Maybe Text
mc MixedAmount
chgunits MixedAmount
chgvalue
        go (Balance OrdPlus
ord Quantity
n Maybe Text
mc) = OrdPlus -> Quantity -> Maybe Text -> Query
Amt OrdPlus
ord Quantity
n Maybe Text
mc Query -> MixedAmount -> Bool
`matchesMixedAmount` Maybe Text -> MixedAmount -> MixedAmount -> MixedAmount
forall {a}. Maybe a -> MixedAmount -> MixedAmount -> MixedAmount
pick Maybe Text
mc MixedAmount
balunits MixedAmount
balvalue
        go Query
_ = Bool
True
        pick :: Maybe a -> MixedAmount -> MixedAmount -> MixedAmount
pick Maybe a
Nothing MixedAmount
units MixedAmount
_     = MixedAmount
units
        pick Maybe a
_       MixedAmount
units MixedAmount
val = MixedAmount -> MixedAmount -> MixedAmount
maPlus MixedAmount
units MixedAmount
val

    -- The lots held at or under the given account, excluding empty ones.
    lotsUnder :: AccountName -> [(Amount, Maybe CostBasis)]
    lotsUnder :: Text -> [(Amount, Maybe CostBasis)]
lotsUnder Text
acct = ((Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis))
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> [a] -> [b]
map (Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis)
forall a b. (a, b) -> b
snd ([(Text, (Amount, Maybe CostBasis))]
 -> [(Amount, Maybe CostBasis)])
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> a -> b
$ [(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
underLotIx

    -- The lots in a row account's own scope, excluding empty ones.
    lotsOf :: AccountName -> [(Amount, Maybe CostBasis)]
    lotsOf :: Text -> [(Amount, Maybe CostBasis)]
lotsOf Text
acct = ((Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis))
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> [a] -> [b]
map (Text, (Amount, Maybe CostBasis)) -> (Amount, Maybe CostBasis)
forall a b. (a, b) -> b
snd ([(Text, (Amount, Maybe CostBasis))]
 -> [(Amount, Maybe CostBasis)])
-> [(Text, (Amount, Maybe CostBasis))]
-> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> a -> b
$ [(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
ownLotIx

    -- Report rows come from a single-period, end-balances multiBalanceReport:
    -- on the lot-detailed journal with --lots (rows are lot subaccounts),
    -- on the collapsed journal otherwise (rows are the base accounts).
    -- Non-holding accounts are filtered out.
    -- Cost conversion and valuation (-B/-V/--value) are disabled:
    -- holdings does its own valuation, and units should stay units.
    -- Nor does it apply the change:/balance: terms; they are tested here (see rowq).
    -- Its query has no start date, since holdings are cumulative (a start date
    -- after the last posting would otherwise leave an empty report span).
    mbr :: MultiBalanceReport
mbr = ReportSpec -> Journal -> MultiBalanceReport
multiBalanceReport ReportSpec
rspec' Journal
j'
      where
        rspec' :: ReportSpec
rspec' = ReportSpec
rspec{_rsRowQuery = Any
                      ,_rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Exact <$> mend)]
                      ,_rsReportOpts=ropts{balanceaccum_=Historical, interval_=NoInterval
                                          ,conversionop_=Just NoConversionOp, value_=Nothing
                                          ,sort_amount_=False}}  -- -S sorts by value/cost below, not by units
        j' :: Journal
j' = if Bool
showlots then Journal
j else Journal -> Journal
journalCollapseLotDetail Journal
j
    -- Candidate rows: those with lots at or beneath them; with -E/--empty,
    -- also those with realised gains at or beneath them (fully disposed
    -- accounts/lots, normally hidden).
    candidates :: [PeriodicReportRow DisplayName MixedAmount]
candidates = (PeriodicReportRow DisplayName MixedAmount -> Bool)
-> [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
forall a. (a -> Bool) -> [a] -> [a]
filter PeriodicReportRow DisplayName MixedAmount -> Bool
forall {a}. PeriodicReportRow DisplayName a -> Bool
isholdingrow ([PeriodicReportRow DisplayName MixedAmount]
 -> [PeriodicReportRow DisplayName MixedAmount])
-> [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
forall a b. (a -> b) -> a -> b
$ MultiBalanceReport -> [PeriodicReportRow DisplayName MixedAmount]
forall a b. PeriodicReport a b -> [PeriodicReportRow a b]
prRows MultiBalanceReport
mbr
      where
        isholdingrow :: PeriodicReportRow DisplayName a -> Bool
isholdingrow PeriodicReportRow DisplayName a
r = Bool -> Bool
not ([(Text, (Amount, Maybe CostBasis))] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
allUnderLotIx))
                      Bool -> Bool -> Bool
|| (ReportOpts -> Bool
empty_ ReportOpts
ropts Bool -> Bool -> Bool
&& ((Text, Amount) -> Bool) -> [(Text, Amount)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Bool
not (Bool -> Bool)
-> ((Text, Amount) -> Bool) -> (Text, Amount) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero (Amount -> Bool)
-> ((Text, Amount) -> Amount) -> (Text, Amount) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, Amount) -> Amount
forall a b. (a, b) -> b
snd) ([(Text, Amount)]
-> Text -> Map Text [(Text, Amount)] -> [(Text, Amount)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, Amount)]
allUnderRgainIx))
          where acct :: Text
acct = PeriodicReportRow DisplayName a -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName a
r
    candaccts :: [Text]
candaccts = (PeriodicReportRow DisplayName MixedAmount -> Text)
-> [PeriodicReportRow DisplayName MixedAmount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName [PeriodicReportRow DisplayName MixedAmount]
candidates

    -- Rows to display: the candidates, except those with nothing in
    -- their own scope (eg a base account row whose lots all appear in
    -- displayed lot subaccount rows). A row holding lots directly is
    -- kept even when a deeper row also displays; it shows just its own
    -- lots (see ownIx).
    rows :: [PeriodicReportRow DisplayName MixedAmount]
rows = (PeriodicReportRow DisplayName MixedAmount -> Bool)
-> [PeriodicReportRow DisplayName MixedAmount]
-> [PeriodicReportRow DisplayName MixedAmount]
forall a. (a -> Bool) -> [a] -> [a]
filter PeriodicReportRow DisplayName MixedAmount -> Bool
forall {a}. PeriodicReportRow DisplayName a -> Bool
keeprow [PeriodicReportRow DisplayName MixedAmount]
candidates
      where
        keeprow :: PeriodicReportRow DisplayName a -> Bool
keeprow PeriodicReportRow DisplayName a
r = Bool -> Bool
not ([(Amount, Maybe CostBasis)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Text -> [(Amount, Maybe CostBasis)]
lotsOf Text
acct))
                 Bool -> Bool -> Bool
|| (ReportOpts -> Bool
empty_ ReportOpts
ropts Bool -> Bool -> Bool
&& Bool -> Bool
not ([Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([Text] -> Bool) -> [Text] -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> [Text]
rgainOnlyCommodities Text
acct))
          where acct :: Text
acct = PeriodicReportRow DisplayName a -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName a
r

    -- The commodities with nonzero realised gains in this row account's own
    -- scope but no units held there (eg fully sold off).
    rgainOnlyCommodities :: AccountName -> [CommoditySymbol]
    rgainOnlyCommodities :: Text -> [Text]
rgainOnlyCommodities Text
acct =
      [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort [ Text
c | (Text
c, Amount
g) <- [(Text, Amount)]
-> Text -> Map Text [(Text, Amount)] -> [(Text, Amount)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, Amount)]
ownRgainIx, Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Amount -> Bool
amountLooksZero Amount
g
                  , Text
c Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` ((Text, (Amount, Maybe CostBasis)) -> Text)
-> [(Text, (Amount, Maybe CostBasis))] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, (Amount, Maybe CostBasis)) -> Text
forall a b. (a, b) -> a
fst ([(Text, (Amount, Maybe CostBasis))]
-> Text
-> Map Text [(Text, (Amount, Maybe CostBasis))]
-> [(Text, (Amount, Maybe CostBasis))]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, (Amount, Maybe CostBasis))]
allOwnLotIx) ]

    -- The topmost displayed rows: those not contained in another displayed
    -- row. Totals are computed from these, to avoid double counting.
    toprows :: [PeriodicReportRow DisplayName MixedAmount]
toprows = [ PeriodicReportRow DisplayName MixedAmount
r | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
rows
              , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Text -> Set Text -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Text
rowaccset) (Text -> [Text]
parentAccountNames (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r) ]
      where rowaccset :: Set Text
rowaccset = [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList ([Text] -> Set Text) -> [Text] -> Set Text
forall a b. (a -> b) -> a -> b
$ (PeriodicReportRow DisplayName MixedAmount -> Text)
-> [PeriodicReportRow DisplayName MixedAmount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName [PeriodicReportRow DisplayName MixedAmount]
rows

    -- With -B/--cost, -S sorts and the change:/balance: terms test cost instead of value.
    atcost :: Bool
atcost = ReportOpts -> Maybe ConversionOp
conversionop_ ReportOpts
ropts Maybe ConversionOp -> Maybe ConversionOp -> Bool
forall a. Eq a => a -> a -> Bool
== ConversionOp -> Maybe ConversionOp
forall a. a -> Maybe a
Just ConversionOp
ToCost

    -- The displayed table lines: each report row's holdings, one line per
    -- commodity, with the report row kept for rendering the account cell
    -- (repeated on each of its lines). They are in account name order, or
    -- with -S, each line is sorted by its own amounts (see
    -- holdingsSortKey), ties keeping the account name order. Tree mode
    -- groups these into account sections, keeping this order within each.
    rowlines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
    rowlines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines
      | ReportOpts -> Bool
sort_amount_ ReportOpts
ropts = ((PeriodicReportRow DisplayName MixedAmount, Holding)
 -> (Bool, Down Quantity))
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\(PeriodicReportRow DisplayName MixedAmount
_, Holding
h) -> Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)
holdingsSortKey Bool
atcost (Holding -> [Amount]
hValue Holding
h) (Holding -> [Amount]
hCost Holding
h)) [(PeriodicReportRow DisplayName MixedAmount, Holding)]
namelines
      | Bool
otherwise          = [(PeriodicReportRow DisplayName MixedAmount, Holding)]
namelines
      where namelines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
namelines = [(PeriodicReportRow DisplayName MixedAmount
r, Holding
h) | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
rows, Holding
h <- PeriodicReportRow DisplayName MixedAmount -> [Holding]
rowHoldings PeriodicReportRow DisplayName MixedAmount
r]

    -- One display line per report line.
    displaylines :: [HoldingsLine]
    displaylines :: [HoldingsLine]
displaylines =
      [ HoldingsPosition
          { hlIndent :: Int
hlIndent  = PeriodicReportRow DisplayName MixedAmount -> Int
forall a. PeriodicReportRow DisplayName a -> Int
prrIndent PeriodicReportRow DisplayName MixedAmount
r
          , hlAccount :: Text
hlAccount = PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r
          , hlDisplay :: Text
hlDisplay = PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrDisplayName PeriodicReportRow DisplayName MixedAmount
r
          , hlIsLot :: Bool
hlIsLot   = Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
lotSubaccountName (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r
          , hlHolding :: Holding
hlHolding = Holding
h }
      | (PeriodicReportRow DisplayName MixedAmount
r, Holding
h) <- [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines ]

    -- The cost column's heading matches what's shown: "Avg cost" on rows
    -- aggregating multiple lots (the default) or when the lots shown all
    -- belong to AVERAGE/AVERAGEALL pools (whose per-lot rows show the
    -- pool's average cost); "Unit cost" when each lot shows its own cost;
    -- "Unit/Avg cost" when both kinds of lot are shown.
    -- TRANSLATORS: the holdings table's cost column heading, translated where it is displayed.
    unitcostheading :: T.Text
    unitcostheading :: Text
unitcostheading
      | Bool -> Bool
not Bool
showlots Bool -> Bool -> Bool
|| Bool
allavg = Text -> Text
I18n.i18n Text
"Avg cost"
      | Bool
anyavg = Text -> Text
I18n.i18n Text
"Unit/Avg cost"
      | Bool
otherwise = Text -> Text
I18n.i18n Text
"Unit cost"
      where
        avgs :: [Bool]
avgs = [ (ReductionMethod, String) -> ReductionMethod
forall a b. (a, b) -> a
fst (Journal -> Text -> Text -> (ReductionMethod, String)
resolveReductionMethodForAccount Journal
j (Text -> Text
lotBaseAccount Text
sub) Text
c)
                 ReductionMethod -> [ReductionMethod] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ReductionMethod
AVERAGE, ReductionMethod
AVERAGEALL]
               | (Text
sub, Text
c) <- Map (Text, Text) Amount -> [(Text, Text)]
forall k a. Map k a -> [k]
M.keys Map (Text, Text) Amount
lotmap ]
        allavg :: Bool
allavg = Bool -> Bool
not ([Bool] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Bool]
avgs) Bool -> Bool -> Bool
&& [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [Bool]
avgs
        anyavg :: Bool
anyavg = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Bool]
avgs

    -- Sum amounts per commodity, keeping an empty list empty
    -- (unlike amounts . mixed, which would make it a single zero).
    sumAmounts :: [Amount] -> [Amount]
    sumAmounts :: [Amount] -> [Amount]
sumAmounts [] = []
    sumAmounts [Amount]
as = MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
as

    -- A report row's holdings, one per commodity, in the same order as its
    -- unit amounts. With -E/--empty, these are followed by a zero-units
    -- holding for each commodity no longer held at or under the row's
    -- account but with realised gains, keeping those visible (eg a
    -- commodity fully sold off); without -E such rows are hidden (their
    -- gains still count in the totals row).
    rowHoldings :: PeriodicReportRow DisplayName MixedAmount -> [Holding]
    rowHoldings :: PeriodicReportRow DisplayName MixedAmount -> [Holding]
rowHoldings PeriodicReportRow DisplayName MixedAmount
r = (Amount -> Holding) -> [Amount] -> [Holding]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Holding
rec ([Amount] -> [Holding]) -> [Amount] -> [Holding]
forall a b. (a -> b) -> a -> b
$ [Amount]
heldamts [Amount] -> [Amount] -> [Amount]
forall a. [a] -> [a] -> [a]
++ [Amount]
rgainonlyamts
      where
        acct :: Text
acct = PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r
        heldamts :: [Amount]
heldamts = PeriodicReportRow DisplayName MixedAmount -> [Amount]
rowUnitAmounts PeriodicReportRow DisplayName MixedAmount
r
        rgainonlyamts :: [Amount]
rgainonlyamts
          | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Bool
empty_ ReportOpts
ropts = []
          | Bool
otherwise = [Amount
nullamt{acommodity=c} | Text
c <- Text -> [Text]
rgainOnlyCommodities Text
acct]
        rec :: Amount -> Holding
rec Amount
qa = Holding
          { hAccount :: Text
hAccount   = Text
acct
          , hCommodity :: Text
hCommodity = Text
c
          , hDate :: Maybe Day
hDate      = Maybe Day
mdate
          , hAge :: Maybe Integer
hAge       = Day -> Day -> Integer
diffDays Day
reportdate (Day -> Integer) -> Maybe Day -> Maybe Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Day
mdate
          , hUnits :: Amount
hUnits     = Map Text AmountStyle -> Amount -> Amount
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles Amount
qa
          , hUnitCost :: Maybe Amount
hUnitCost  = Maybe Amount
mucost
          , hCost :: [Amount]
hCost      = [Amount] -> [Amount]
sumAmounts [Amount]
ccosts
          , hPrice :: [Amount]
hPrice     = [Amount]
prices
          , hValue :: [Amount]
hValue     = [Amount]
vals
          , hWeight :: Maybe Quantity
hWeight    = [Amount] -> Maybe Quantity
weightPct [Amount]
vals
          , hUgain :: [Amount]
hUgain     = [Amount]
gains
          , hUgainPct :: Maybe Quantity
hUgainPct  = [Amount] -> [Amount] -> Maybe Quantity
gainPct [Amount]
gains [Amount]
ccosts
          , hRgain :: [Amount]
hRgain     = [Amount] -> [Amount]
sumAmounts ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount) -> [Amount] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer PeriodicReportRow DisplayName MixedAmount
r) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text -> [Amount]
rgainsOf Text
acct (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
c)
          , hXirr :: Maybe Double
hXirr      = Maybe Double
mxirr
          , hFlows :: [(Day, Amount)]
hFlows     = Text -> Maybe Text -> [(Day, Amount)]
flowsOf Text
acct (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
c)
          }
          where
            c :: Text
c = Amount -> Text
acommodity Amount
qa
            clots :: [(Amount, Maybe CostBasis)]
clots = ((Amount, Maybe CostBasis) -> Bool)
-> [(Amount, Maybe CostBasis)] -> [(Amount, Maybe CostBasis)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
==Text
c) (Text -> Bool)
-> ((Amount, Maybe CostBasis) -> Text)
-> (Amount, Maybe CostBasis)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Text
acommodity (Amount -> Text)
-> ((Amount, Maybe CostBasis) -> Amount)
-> (Amount, Maybe CostBasis)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst) ([(Amount, Maybe CostBasis)] -> [(Amount, Maybe CostBasis)])
-> [(Amount, Maybe CostBasis)] -> [(Amount, Maybe CostBasis)]
forall a b. (a -> b) -> a -> b
$ Text -> [(Amount, Maybe CostBasis)]
lotsOf Text
acct
            dates :: [Maybe Day]
dates = [Maybe Day] -> [Maybe Day]
forall a. Ord a => [a] -> [a]
nubSort [CostBasis -> Maybe Day
cbDate (CostBasis -> Maybe Day) -> Maybe CostBasis -> Maybe Day
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb | (Amount
_, Maybe CostBasis
mcb) <- [(Amount, Maybe CostBasis)]
clots]
            mdate :: Maybe Day
mdate = case [Maybe Day]
dates of
              [Just Day
dt] -> Day -> Maybe Day
forall a. a -> Maybe a
Just Day
dt
              [Maybe Day]
_         -> Maybe Day
forall a. Maybe a
Nothing
            ccosts :: [Amount]
ccosts
              -- a line with no units held (shown for its realised gain) costs zero, in the gain's commodity
              | [(Amount, Maybe CostBasis)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Amount, Maybe CostBasis)]
clots = [Amount
g{aquantity = 0} | Amount
g <- Int -> [Amount] -> [Amount]
forall a. Int -> [a] -> [a]
take Int
1 ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text -> [Amount]
rgainsOf Text
acct (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
c)]
              | Bool
otherwise  = [PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer PeriodicReportRow DisplayName MixedAmount
r (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
a) Amount
cb | (Amount
a, Maybe CostBasis
mcb) <- [(Amount, Maybe CostBasis)]
clots, Just Amount
cb <- [CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb]]
            mucost :: Maybe Amount
mucost = case ([(Amount, Maybe CostBasis)]
clots, [Amount]
ccosts) of
              ([(Amount
_, Maybe CostBasis
mcb)], [Amount]
_) -> PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer PeriodicReportRow DisplayName MixedAmount
r (Amount -> Amount) -> Maybe Amount -> Maybe Amount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb)
              ([(Amount, Maybe CostBasis)]
_, Amount
_:[Amount]
_) | [Amount
totcost] <- MixedAmount -> [Amount]
amounts ([Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
ccosts)
                       , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Amount -> Bool
amountLooksZero Amount
qa
                       -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount) -> Amount -> Maybe Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount -> Amount
avgcost Amount
qa Amount
totcost
              ([(Amount, Maybe CostBasis)], [Amount])
_ -> Maybe Amount
forall a. Maybe a
Nothing
            -- The line's lots to value; a zero-units (rgain-only) line
            -- values a synthetic zero lot, so a market price and a zero
            -- value can still be shown.
            vlots :: [(Amount, Maybe CostBasis)]
vlots = if [(Amount, Maybe CostBasis)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Amount, Maybe CostBasis)]
clots then [(Amount
qa, Maybe CostBasis
forall a. Maybe a
Nothing)] else [(Amount, Maybe CostBasis)]
clots
            ([Amount]
prices, [Amount]
vals) = ([Amount], [Amount])
-> Maybe ([Amount], [Amount]) -> ([Amount], [Amount])
forall a. a -> Maybe a -> a
fromMaybe ([], []) (Maybe ([Amount], [Amount]) -> ([Amount], [Amount]))
-> Maybe ([Amount], [Amount]) -> ([Amount], [Amount])
forall a b. (a -> b) -> a -> b
$ [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation [(Amount, Maybe CostBasis)]
vlots
            gains :: [Amount]
gains = [Amount] -> Maybe [Amount] -> [Amount]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Amount] -> [Amount]) -> Maybe [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Amount] -> Maybe [Amount]
gainAmounts [Amount]
vals [Amount]
ccosts
            mxirr :: Maybe Double
mxirr = do
              [v] <- [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [Amount]
vals
              xirrOf (flowsOf acct (Just c)) v

    -- The grand totals, summed over the topmost displayed rows; the
    -- RGain and XIRR components cover all the lots within the query and
    -- end date, whatever rows are displayed (#2769; see HoldingsTotals).
    -- The value, gains and cashflows leave out the holdings whose value is
    -- unknown, and those of the given commodities (see htUnpriced).
    totalsExcluding :: [CommoditySymbol] -> HoldingsTotals
    totalsExcluding :: [Text] -> HoldingsTotals
totalsExcluding [Text]
excl0 = HoldingsTotals
      { htUnits :: Maybe Amount
htUnits    = case [Amount]
totunits of [Amount
u] -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
u; [Amount]
_ -> Maybe Amount
forall a. Maybe a
Nothing
      , htAvgCost :: Maybe Amount
htAvgCost  = case ([Amount]
totunits, [Amount] -> [Amount]
sumAmounts [Amount]
totcosts) of
          ([Amount
u], [Amount
c]) -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount) -> Amount -> Maybe Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount -> Amount
avgcost Amount
u Amount
c
          ([Amount], [Amount])
_          -> Maybe Amount
forall a. Maybe a
Nothing
      , htCost :: [Amount]
htCost     = MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
totcosts
      , htPrice :: Maybe Amount
htPrice    = [(Amount, Maybe CostBasis)] -> Maybe Amount
singlePrice [(Amount, Maybe CostBasis)]
toplots
      , htValue :: Maybe [Amount]
htValue    = Maybe [Amount]
mvalue'
      , htWeight :: Maybe Quantity
htWeight   = [Amount] -> Maybe Quantity
weightPct ([Amount] -> Maybe Quantity) -> [Amount] -> Maybe Quantity
forall a b. (a -> b) -> a -> b
$ [(Amount, Maybe CostBasis)] -> [Amount]
pricedValue [(Amount, Maybe CostBasis)]
toplots
      , htUgain :: Maybe [Amount]
htUgain    = Maybe [Amount]
mgains
      , htUgainPct :: Maybe Quantity
htUgainPct = [Amount] -> [Amount] -> Maybe Quantity
gainPct ([Amount] -> Maybe [Amount] -> [Amount]
forall a. a -> Maybe a -> a
fromMaybe [] Maybe [Amount]
mgains) [Amount]
valuedcosts
      , htRgain :: [Amount]
htRgain    = case (Amount -> Amount) -> [Amount] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Maybe Text -> Amount -> Amount
costValuerTo Maybe Text
mvaluecomm) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Map (Text, Text) Amount -> [Amount]
forall k a. Map k a -> [a]
M.elems Map (Text, Text) Amount
rgainmap of
          [] -> []
          [Amount]
rs -> MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
rs
      , htXirr :: Maybe Double
htXirr     = do
          [tv] <- Maybe [Amount]
mvalue'
          xirrOf flows tv
      , htFlows :: [(Day, Amount)]
htFlows    = [(Day, Amount)]
flows
      , htValuedCost :: [Amount]
htValuedCost = MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed [Amount]
valuedcosts
      , htUnpriced :: [Text]
htUnpriced = [Text]
excl
      }
      where
        toplots :: [(Amount, Maybe CostBasis)]
toplots = (PeriodicReportRow DisplayName MixedAmount
 -> [(Amount, Maybe CostBasis)])
-> [PeriodicReportRow DisplayName MixedAmount]
-> [(Amount, Maybe CostBasis)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Text -> [(Amount, Maybe CostBasis)]
lotsUnder (Text -> [(Amount, Maybe CostBasis)])
-> (PeriodicReportRow DisplayName MixedAmount -> Text)
-> PeriodicReportRow DisplayName MixedAmount
-> [(Amount, Maybe CostBasis)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName) [PeriodicReportRow DisplayName MixedAmount]
toprows
        excl :: [Text]
excl = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ [Text]
excl0 [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [(Amount, Maybe CostBasis)] -> [Text]
unpricedCommodities [(Amount, Maybe CostBasis)]
toplots
        mvalue' :: Maybe [Amount]
mvalue' = [Text] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
mvalueExcluding [Text]
excl [(Amount, Maybe CostBasis)]
toplots
        mvaluecomm :: Maybe Text
mvaluecomm = Maybe [Amount] -> Maybe Text
singleCommodity Maybe [Amount]
mvalue'
        totunits :: [Amount]
totunits = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Amount]
sumAmounts ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ ((Amount, Maybe CostBasis) -> Amount)
-> [(Amount, Maybe CostBasis)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst [(Amount, Maybe CostBasis)]
toplots
        -- each lot's cost, with its units
        lotcosts :: [(Amount, Amount)]
lotcosts = [ (Amount
a, PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer PeriodicReportRow DisplayName MixedAmount
r (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
a) Amount
c)
                   | PeriodicReportRow DisplayName MixedAmount
r <- [PeriodicReportRow DisplayName MixedAmount]
toprows, (Amount
a, Maybe CostBasis
mcb) <- Text -> [(Amount, Maybe CostBasis)]
lotsUnder (PeriodicReportRow DisplayName MixedAmount -> Text
forall a. PeriodicReportRow DisplayName a -> Text
prrFullName PeriodicReportRow DisplayName MixedAmount
r), Just Amount
c <- [CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb] ]
        totcosts :: [Amount]
totcosts = ((Amount, Amount) -> Amount) -> [(Amount, Amount)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Amount) -> Amount
forall a b. (a, b) -> b
snd [(Amount, Amount)]
lotcosts
        valuedcosts :: [Amount]
valuedcosts = [Amount
k | (Amount
a, Amount
k) <- [(Amount, Amount)]
lotcosts, Amount -> Text
acommodity Amount
a Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text]
excl]
        mgains :: Maybe [Amount]
mgains = Maybe [Amount]
mvalue' Maybe [Amount] -> ([Amount] -> Maybe [Amount]) -> Maybe [Amount]
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \[Amount]
v -> [Amount] -> [Amount] -> Maybe [Amount]
gainAmounts [Amount]
v [Amount]
valuedcosts
        flows :: [(Day, Amount)]
flows = [[(Day, Amount)]] -> [(Day, Amount)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[(Day, Amount)]
fs | ((Text
_, Text
c), [(Day, Amount)]
fs) <- Map (Text, Text) [(Day, Amount)]
-> [((Text, Text), [(Day, Amount)])]
forall k a. Map k a -> [(k, a)]
M.toList Map (Text, Text) [(Day, Amount)]
flowmap, Text
c Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text]
excl]

    -- The totals of the lots at or under one account, computed like the
    -- grand totals row: an account heading row's figures. Like those,
    -- RGain and XIRR cover all the subtree's lots within the query and
    -- end date, including fully disposed ones with no row (#2769), and
    -- the value, gains and cashflows leave out the holdings whose value is
    -- unknown, and those of the given commodities. Weight is relative to
    -- the whole portfolio's value.
    accountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals
    accountTotalsExcluding :: [Text] -> Text -> HoldingsTotals
accountTotalsExcluding [Text]
excl0 Text
acct = HoldingsTotals
      { htUnits :: Maybe Amount
htUnits    = case [Amount]
units of [Amount
u] -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
u; [Amount]
_ -> Maybe Amount
forall a. Maybe a
Nothing
      , htAvgCost :: Maybe Amount
htAvgCost  = case ([Amount]
units, [Amount] -> [Amount]
sumAmounts [Amount]
costs) of
          ([Amount
u], [Amount
c]) -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount) -> Amount -> Maybe Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount -> Amount
avgcost Amount
u Amount
c
          ([Amount], [Amount])
_          -> Maybe Amount
forall a. Maybe a
Nothing
      , htCost :: [Amount]
htCost     = [Amount] -> [Amount]
sumAmounts [Amount]
costs
      , htPrice :: Maybe Amount
htPrice    = [(Amount, Maybe CostBasis)] -> Maybe Amount
singlePrice [(Amount, Maybe CostBasis)]
lots
      , htValue :: Maybe [Amount]
htValue    = Maybe [Amount]
msubvalue
      , htWeight :: Maybe Quantity
htWeight   = [Amount] -> Maybe Quantity
weightPct ([Amount] -> Maybe Quantity) -> [Amount] -> Maybe Quantity
forall a b. (a -> b) -> a -> b
$ [(Amount, Maybe CostBasis)] -> [Amount]
pricedValue [(Amount, Maybe CostBasis)]
lots
      , htUgain :: Maybe [Amount]
htUgain    = Maybe [Amount]
mgains
      , htUgainPct :: Maybe Quantity
htUgainPct = [Amount] -> [Amount] -> Maybe Quantity
gainPct ([Amount] -> Maybe [Amount] -> [Amount]
forall a. a -> Maybe a -> a
fromMaybe [] Maybe [Amount]
mgains) [Amount]
valuedcosts
      , htRgain :: [Amount]
htRgain    = [Amount] -> [Amount]
sumAmounts ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount) -> [Amount] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Maybe Text -> Amount -> Amount
costValuerTo Maybe Text
msubvaluecomm) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text -> [Amount]
rgainsUnder Text
acct Maybe Text
forall a. Maybe a
Nothing
      , htXirr :: Maybe Double
htXirr     = do
          [v] <- Maybe [Amount]
msubvalue
          xirrOf flows v
      , htFlows :: [(Day, Amount)]
htFlows    = [(Day, Amount)]
flows
      , htValuedCost :: [Amount]
htValuedCost = [Amount] -> [Amount]
sumAmounts [Amount]
valuedcosts
      , htUnpriced :: [Text]
htUnpriced = [Text]
excl
      }
      where
        lots :: [(Amount, Maybe CostBasis)]
lots = Text -> [(Amount, Maybe CostBasis)]
lotsUnder Text
acct
        excl :: [Text]
excl = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ [Text]
excl0 [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [(Amount, Maybe CostBasis)] -> [Text]
unpricedCommodities [(Amount, Maybe CostBasis)]
lots
        units :: [Amount]
units = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountLooksZero) ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Amount] -> [Amount]
sumAmounts ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ ((Amount, Maybe CostBasis) -> Amount)
-> [(Amount, Maybe CostBasis)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst [(Amount, Maybe CostBasis)]
lots
        -- each lot's cost, with its units
        lotcosts :: [(Amount, Amount)]
lotcosts = [ (Amount
a, Maybe Text -> Amount -> Amount
costValuerTo Maybe Text
msubvaluecomm (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
a) Amount
c)
                   | (Amount
a, Maybe CostBasis
mcb) <- [(Amount, Maybe CostBasis)]
lots, Just Amount
c <- [CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Maybe CostBasis
mcb] ]
        costs :: [Amount]
costs = ((Amount, Amount) -> Amount) -> [(Amount, Amount)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Amount) -> Amount
forall a b. (a, b) -> b
snd [(Amount, Amount)]
lotcosts
        valuedcosts :: [Amount]
valuedcosts = [Amount
k | (Amount
a, Amount
k) <- [(Amount, Amount)]
lotcosts, Amount -> Text
acommodity Amount
a Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text]
excl]
        msubvalue :: Maybe [Amount]
msubvalue = [Text] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
mvalueExcluding [Text]
excl [(Amount, Maybe CostBasis)]
lots
        msubvaluecomm :: Maybe Text
msubvaluecomm = Maybe [Amount] -> Maybe Text
singleCommodity Maybe [Amount]
msubvalue
        mgains :: Maybe [Amount]
mgains = Maybe [Amount]
msubvalue Maybe [Amount] -> ([Amount] -> Maybe [Amount]) -> Maybe [Amount]
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \[Amount]
subvalue -> [Amount] -> [Amount] -> Maybe [Amount]
gainAmounts [Amount]
subvalue [Amount]
valuedcosts
        flows :: [(Day, Amount)]
flows = [[(Day, Amount)]] -> [(Day, Amount)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[(Day, Amount)]
fs | (Text
c, [(Day, Amount)]
fs) <- [(Text, [(Day, Amount)])]
-> Text
-> Map Text [(Text, [(Day, Amount)])]
-> [(Text, [(Day, Amount)])]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] Text
acct Map Text [(Text, [(Day, Amount)])]
underFlowIx, Text
c Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text]
excl]

    -- The commodities of these lots which have a lot with no market price,
    -- so whose holdings' value is unknown.
    unpricedCommodities :: [(Amount, Maybe CostBasis)] -> [CommoditySymbol]
    unpricedCommodities :: [(Amount, Maybe CostBasis)] -> [Text]
unpricedCommodities [(Amount, Maybe CostBasis)]
lots = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort [Amount -> Text
acommodity Amount
a | l :: (Amount, Maybe CostBasis)
l@(Amount
a, Maybe CostBasis
_) <- [(Amount, Maybe CostBasis)]
lots, Maybe (Amount, Amount) -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe (Amount, Amount) -> Bool) -> Maybe (Amount, Amount) -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
lotValuation (Amount, Maybe CostBasis)
l]

    -- The market value of these lots, per value commodity, leaving out
    -- those of the given commodities (eg the unpriced ones); Nothing if
    -- some of the others can't be valued.
    mvalueExcluding :: [CommoditySymbol] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
    mvalueExcluding :: [Text] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
mvalueExcluding [Text]
excl [(Amount, Maybe CostBasis)]
lots = ([Amount], [Amount]) -> [Amount]
forall a b. (a, b) -> b
snd (([Amount], [Amount]) -> [Amount])
-> Maybe ([Amount], [Amount]) -> Maybe [Amount]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation (((Amount, Maybe CostBasis) -> Bool)
-> [(Amount, Maybe CostBasis)] -> [(Amount, Maybe CostBasis)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text]
excl) (Text -> Bool)
-> ((Amount, Maybe CostBasis) -> Text)
-> (Amount, Maybe CostBasis)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Text
acommodity (Amount -> Text)
-> ((Amount, Maybe CostBasis) -> Amount)
-> (Amount, Maybe CostBasis)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst) [(Amount, Maybe CostBasis)]
lots)

    -- The commodity of a value, when it is a single amount.
    singleCommodity :: Maybe [Amount] -> Maybe CommoditySymbol
    singleCommodity :: Maybe [Amount] -> Maybe Text
singleCommodity Maybe [Amount]
mv = case Maybe [Amount]
mv of
      Just [Amount
v] -> Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Amount -> Text
acommodity Amount
v
      Maybe [Amount]
_        -> Maybe Text
forall a. Maybe a
Nothing

    -- The unit market price of some lots, when they are all of one commodity
    -- and have the same price.
    singlePrice :: [(Amount, Maybe CostBasis)] -> Maybe Amount
    singlePrice :: [(Amount, Maybe CostBasis)] -> Maybe Amount
singlePrice [(Amount, Maybe CostBasis)]
lots = do
      [_] <- [Text] -> Maybe [Text]
forall a. a -> Maybe a
Just ([Text] -> Maybe [Text]) -> [Text] -> Maybe [Text]
forall a b. (a -> b) -> a -> b
$ [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ ((Amount, Maybe CostBasis) -> Text)
-> [(Amount, Maybe CostBasis)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Amount -> Text
acommodity (Amount -> Text)
-> ((Amount, Maybe CostBasis) -> Amount)
-> (Amount, Maybe CostBasis)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, Maybe CostBasis) -> Amount
forall a b. (a, b) -> a
fst) [(Amount, Maybe CostBasis)]
lots
      ([p], _) <- lotsValuation lots
      Just p

    -- An average cost: total cost / total units, shown like other amounts
    -- in the cost commodity's display precision - but with at least 2
    -- decimal digits when the division is inexact and the display
    -- precision is less, so eg an average of $56.666... is not shown as
    -- the misleading $57.
    avgcost :: Amount -> Amount -> Amount
avgcost Amount
qtya Amount
costa = AmountPrecision -> Amount -> Amount
amountSetPrecision (Word8 -> AmountPrecision
Precision Word8
p) Amount
avg
      where
        avg :: Amount
avg  = Quantity -> Amount -> Amount
divideAmountAndUpdatePrecision (Amount -> Quantity
aquantity Amount
qtya) Amount
costa
        p :: Word8
p = Word8 -> Word8 -> Word8 -> Word8
forall {c}. Ord c => c -> c -> c -> c
clamp Word8
pstyle (Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
max Word8
2 Word8
pstyle) Word8
pdiv
        clamp :: c -> c -> c -> c
clamp c
lo c
hi = c -> c -> c
forall a. Ord a => a -> a -> a
max c
lo (c -> c) -> (c -> c) -> c -> c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. c -> c -> c
forall a. Ord a => a -> a -> a
min c
hi
        pdiv :: Word8
pdiv = case AmountStyle -> AmountPrecision
asprecision (Amount -> AmountStyle
astyle Amount
avg) of Precision Word8
n -> Word8
n; AmountPrecision
_ -> Word8
defaultMaxDisplayPrecision
        pstyle :: Word8
pstyle = case AmountStyle -> AmountPrecision
asprecision (Amount -> AmountStyle
astyle Amount
costa) of Precision Word8
n -> Word8
n; AmountPrecision
_ -> Word8
2

-- | The commodities whose holdings some totals leave out of their value, gains and XIRR,
-- having no market price, when they show those of other holdings. (When they show none,
-- those are simply blank.)
totalsLeftOut :: HoldingsTotals -> [CommoditySymbol]
totalsLeftOut :: HoldingsTotals -> [Text]
totalsLeftOut HoldingsTotals
tot = case HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
tot of
  Just (Amount
_:[Amount]
_) -> HoldingsTotals -> [Text]
htUnpriced HoldingsTotals
tot
  Maybe [Amount]
_          -> []

-- | A note saying which commodities' holdings the totals' value, gains and XIRR
-- leave out, having no market price (see 'htUnpriced'), if there are any.
holdingsUnpricedNote :: I18n.Translations -> [CommoditySymbol] -> Maybe T.Text
holdingsUnpricedNote :: Translations -> [Text] -> Maybe Text
holdingsUnpricedNote Translations
_ [] = Maybe Text
forall a. Maybe a
Nothing
holdingsUnpricedNote Translations
trs [Text]
cs = Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$
  -- TRANSLATORS: a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".
  Translations -> Text -> [(Text, Text)] -> Text
I18n.trf Translations
trs Text
"Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"
    [(Text
"commodities", Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
quoteCommoditySymbolIfNeeded [Text]
cs)]

-- | How many closed positions (an account's commodity, fully disposed, with
-- a realised gain) a holdings report of this spec and journal leaves out of its
-- rows, for lack of -E/--empty. The totals' RGain and XIRR still include them.
holdingsClosedHidden :: HoldingsReportOpts -> ReportSpec -> Journal -> Int
holdingsClosedHidden :: HoldingsReportOpts -> ReportSpec -> Journal -> Int
holdingsClosedHidden HoldingsReportOpts
hropts ReportSpec
rspec Journal
j
  | ReportOpts -> Bool
empty_ ReportOpts
ropts = Int
0
  | Bool
otherwise    = [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [() | (PeriodicReportRow DisplayName MixedAmount
_, Holding
h) <- HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
rpt, Amount -> Quantity
aquantity (Holding -> Amount
hUnits Holding
h) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
0]
  where
    ropts :: ReportOpts
ropts = ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec
    rpt :: HoldingsReport
rpt = HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport HoldingsReportOpts
hropts{hroLots = False} ReportSpec
rspec{_rsReportOpts = ropts{empty_ = True, sort_amount_ = False}} Journal
j

-- | A note saying how many closed positions are not shown, though the totals'
-- RGain and XIRR include them (see 'holdingsClosedHidden'), if there are any.
holdingsClosedNote :: I18n.Translations -> Int -> Maybe T.Text
holdingsClosedNote :: Translations -> Int -> Maybe Text
holdingsClosedNote Translations
_ Int
0 = Maybe Text
forall a. Maybe a
Nothing
holdingsClosedNote Translations
trs Int
n = Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$
  -- TRANSLATORS: a note below the holdings table; {n} is the number of closed (fully disposed) positions.
  Translations -> Int -> Text -> Text -> Text
I18n.trn Translations
trs Int
n Text
"RGain and XIRR totals include {n} closed position, not shown" Text
"RGain and XIRR totals include {n} closed positions, not shown"

-- | A report spec with these start and end dates in place of its query's dates
-- (Nothing for the end date keeps the query's end date).
holdingsSpecWithDates :: ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec
holdingsSpecWithDates :: ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec
holdingsSpecWithDates ReportSpec
rspec Maybe EFDay
mb Maybe EFDay
me =
  ReportSpec
rspec{_rsQuery = And [ filterQuery (not . queryIsDateOrDate2) $ _rsQuery rspec
                       , Date $ DateSpan mb (me <|> (Exact <$> queryEndDate False (_rsQuery rspec)))]}

-- | Holdings reports at the end of each of the report spec's periods (it should have a report interval),
-- like the single-date report computed at each period's end. Their gain columns cover the time since acquisition
-- (Historical), each period (PerPeriod), or the time since the first period's start (Cumulative).
-- List/tree mode and lots don't matter here (only the reports' totals are meant to be shown),
-- so these are flat and without lots.
holdingsPeriodReports :: HoldingsReportOpts -> BalanceAccumulation -> ReportSpec -> Journal -> [(DateSpan, HoldingsReport)]
holdingsPeriodReports :: HoldingsReportOpts
-> BalanceAccumulation
-> ReportSpec
-> Journal
-> [(DateSpan, HoldingsReport)]
holdingsPeriodReports HoldingsReportOpts
hropts BalanceAccumulation
accum ReportSpec
rspec Journal
j =
  [ (DateSpan
spn, HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport HoldingsReportOpts
hropts{hroLots = False} (Maybe EFDay -> EFDay -> ReportSpec
rspecFor Maybe EFDay
mb EFDay
e) Journal
j)
  | spn :: DateSpan
spn@(DateSpan Maybe EFDay
mb (Just EFDay
e)) <- [DateSpan]
periodspans ]
  where
    -- each period's report: as of its end, with gains since acquisition, or
    -- during the period, or since the first period's start
    rspecFor :: Maybe EFDay -> EFDay -> ReportSpec
rspecFor Maybe EFDay
mb EFDay
e = (ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec
holdingsSpecWithDates ReportSpec
rspec Maybe EFDay
mstart (EFDay -> Maybe EFDay
forall a. a -> Maybe a
Just EFDay
e)){_rsReportOpts = (_rsReportOpts rspec){accountlistmode_ = ALFlat}}
      where mstart :: Maybe EFDay
mstart = case BalanceAccumulation
accum of
              BalanceAccumulation
Historical -> Maybe EFDay
forall a. Maybe a
Nothing
              BalanceAccumulation
PerPeriod  -> Maybe EFDay
mb
              BalanceAccumulation
Cumulative -> Maybe EFDay
mfirststart
    mfirststart :: Maybe EFDay
mfirststart = case [DateSpan]
periodspans of
      DateSpan Maybe EFDay
mb Maybe EFDay
_ : [DateSpan]
_ -> Maybe EFDay
mb
      []                -> Maybe EFDay
forall a. Maybe a
Nothing
    -- The periods: as usual (with no end date, ending with the journal's last
    -- postings), but since values change with market prices, with no end date
    -- they always extend to today, and the period containing today ends today,
    -- like the single-date report. (Periods after it, from future-dated
    -- postings, are kept.)
    periodspans :: [DateSpan]
periodspans
      | Maybe Day -> Bool
forall a. Maybe a -> Bool
isJust (Bool -> Query -> Maybe Day
queryEndDate Bool
False (Query -> Maybe Day) -> Query -> Maybe Day
forall a b. (a -> b) -> a -> b
$ ReportSpec -> Query
_rsQuery ReportSpec
rspec) = [DateSpan]
defspans
      | [DateSpan] -> Bool
reachestoday [DateSpan]
defspans = (DateSpan -> DateSpan) -> [DateSpan] -> [DateSpan]
forall a b. (a -> b) -> [a] -> [b]
map DateSpan -> DateSpan
clip [DateSpan]
defspans
      | Bool
otherwise = (DateSpan -> DateSpan) -> [DateSpan] -> [DateSpan]
forall a b. (a -> b) -> [a] -> [b]
map DateSpan -> DateSpan
clip ([DateSpan] -> [DateSpan]) -> [DateSpan] -> [DateSpan]
forall a b. (a -> b) -> a -> b
$ ReportSpec -> [DateSpan]
spansOf ReportSpec
rspec{_rsQuery = And [_rsQuery rspec, Date $ DateSpan Nothing (Just $ Exact tomorrow)]}
      where
        spansOf :: ReportSpec -> [DateSpan]
spansOf = Maybe DayPartition -> [DateSpan]
maybeDayPartitionToDateSpans (Maybe DayPartition -> [DateSpan])
-> (ReportSpec -> Maybe DayPartition) -> ReportSpec -> [DateSpan]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DateSpan, Maybe DayPartition) -> Maybe DayPartition
forall a b. (a, b) -> b
snd ((DateSpan, Maybe DayPartition) -> Maybe DayPartition)
-> (ReportSpec -> (DateSpan, Maybe DayPartition))
-> ReportSpec
-> Maybe DayPartition
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)
reportSpanBothDates Journal
j
        defspans :: [DateSpan]
defspans = ReportSpec -> [DateSpan]
spansOf ReportSpec
rspec
        tomorrow :: Day
tomorrow = Integer -> Day -> Day
addDays Integer
1 (Day -> Day) -> Day -> Day
forall a b. (a -> b) -> a -> b
$ ReportSpec -> Day
_rsDay ReportSpec
rspec
        reachestoday :: [DateSpan] -> Bool
reachestoday = (DateSpan -> Bool) -> [DateSpan] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(DateSpan Maybe EFDay
_ Maybe EFDay
me) -> Bool -> (EFDay -> Bool) -> Maybe EFDay -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>= Day
tomorrow) (Day -> Bool) -> (EFDay -> Day) -> EFDay -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EFDay -> Day
fromEFDay) Maybe EFDay
me)
        clip :: DateSpan -> DateSpan
clip spn :: DateSpan
spn@(DateSpan Maybe EFDay
mb (Just EFDay
e))
          | EFDay -> Day
fromEFDay EFDay
e Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
> Day
tomorrow Bool -> Bool -> Bool
&& Bool -> (EFDay -> Bool) -> Maybe EFDay -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True ((Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
< Day
tomorrow) (Day -> Bool) -> (EFDay -> Day) -> EFDay -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EFDay -> Day
fromEFDay) Maybe EFDay
mb = Maybe EFDay -> Maybe EFDay -> DateSpan
DateSpan Maybe EFDay
mb (EFDay -> Maybe EFDay
forall a. a -> Maybe a
Just (EFDay -> Maybe EFDay) -> EFDay -> Maybe EFDay
forall a b. (a -> b) -> a -> b
$ Day -> EFDay
Exact Day
tomorrow)
          | Bool
otherwise = DateSpan
spn
        clip DateSpan
spn = DateSpan
spn

-- | The default title of some holdings reports at period ends (see 'holdingsPeriodReports'),
-- saying their interval, which dates they cover and what their gain columns cover.
holdingsPeriodsTitle :: I18n.Translations -> Interval -> BalanceAccumulation -> [(DateSpan, HoldingsReport)] -> T.Text
holdingsPeriodsTitle :: Translations
-> Interval
-> BalanceAccumulation
-> [(DateSpan, HoldingsReport)]
-> Text
holdingsPeriodsTitle Translations
trs Interval
ivl BalanceAccumulation
accum [(DateSpan, HoldingsReport)]
rpts = case (((DateSpan, HoldingsReport) -> Day)
-> [(DateSpan, HoldingsReport)] -> [Day]
forall a b. (a -> b) -> [a] -> [b]
map (HoldingsReport -> Day
hrDate (HoldingsReport -> Day)
-> ((DateSpan, HoldingsReport) -> HoldingsReport)
-> (DateSpan, HoldingsReport)
-> Day
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DateSpan, HoldingsReport) -> HoldingsReport
forall a b. (a, b) -> b
snd) [(DateSpan, HoldingsReport)]
rpts, BalanceAccumulation
accum) of
  ([], BalanceAccumulation
_) -> Text
ivltitle
  -- TRANSLATORS: the title of the holdings report with a report interval; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.
  ([Day]
ds, BalanceAccumulation
Historical) -> Text -> [(Text, Text)] -> Text
trf Text
"{holdings}, {dates}" [(Text
"holdings", Text
ivltitle), (Text
"dates", [Day] -> Text
forall {t :: * -> *}. Foldable t => t Day -> Text
showdates [Day]
ds)]
  -- TRANSLATORS: the title of the holdings report with a report interval and --change; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.
  ([Day]
ds, BalanceAccumulation
PerPeriod)  -> Text -> [(Text, Text)] -> Text
trf Text
"{holdings}, {dates}, gains in each period" [(Text
"holdings", Text
ivltitle), (Text
"dates", [Day] -> Text
forall {t :: * -> *}. Foldable t => t Day -> Text
showdates [Day]
ds)]
  -- TRANSLATORS: the title of the holdings report with a report interval and --cumulative; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30, {start} the report start date.
  ([Day]
ds, BalanceAccumulation
Cumulative) -> Text -> [(Text, Text)] -> Text
trf Text
"{holdings}, {dates}, gains since {start}" [(Text
"holdings", Text
ivltitle), (Text
"dates", [Day] -> Text
forall {t :: * -> *}. Foldable t => t Day -> Text
showdates [Day]
ds), (Text
"start", Text -> (EFDay -> Text) -> Maybe EFDay -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (Day -> Text
showDate (Day -> Text) -> (EFDay -> Day) -> EFDay -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EFDay -> Day
fromEFDay) Maybe EFDay
mfirststart)]
  where
    trf :: Text -> [(Text, Text)] -> Text
trf = Translations -> Text -> [(Text, Text)] -> Text
I18n.trf Translations
trs
    ivltitle :: Text
ivltitle = Translations -> Text -> Text
I18n.tr Translations
trs (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Interval -> Text
holdingsIntervalTitle (Interval -> Text) -> Interval -> Text
forall a b. (a -> b) -> a -> b
$ Interval -> Interval
titleInterval Interval
ivl
    showdates :: t Day -> Text
showdates t Day
ds = Day -> Text
showDate (t Day -> Day
forall a. Ord a => t a -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
minimum t Day
ds) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".." Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Day -> Text
showDate (t Day -> Day
forall a. Ord a => t a -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum t Day
ds)
    mfirststart :: Maybe EFDay
mfirststart = case [(DateSpan, HoldingsReport)]
rpts of
      (DateSpan Maybe EFDay
mb Maybe EFDay
_, HoldingsReport
_) : [(DateSpan, HoldingsReport)]
_ -> Maybe EFDay
mb
      []                     -> Maybe EFDay
forall a. Maybe a
Nothing

-- | The start of the holdings report's title with a report interval.
holdingsIntervalTitle :: Interval -> T.Text
holdingsIntervalTitle :: Interval -> Text
holdingsIntervalTitle = \case
  -- TRANSLATORS: the start of the holdings report's title, with its reporting interval. Each is a
  -- whole phrase, so put the words in the order and form your language needs.
  Days Int
1   -> Text -> Text
I18n.i18n Text
"Daily holdings"
  Weeks Int
1  -> Text -> Text
I18n.i18n Text
"Weekly holdings"
  Weeks Int
2  -> Text -> Text
I18n.i18n Text
"Biweekly holdings"
  Months Int
1 -> Text -> Text
I18n.i18n Text
"Monthly holdings"
  Months Int
2 -> Text -> Text
I18n.i18n Text
"Bimonthly holdings"
  Months Int
3 -> Text -> Text
I18n.i18n Text
"Quarterly holdings"
  Months Int
6 -> Text -> Text
I18n.i18n Text
"Half-yearly holdings"
  Years Int
1  -> Text -> Text
I18n.i18n Text
"Yearly holdings"
  Years Int
2  -> Text -> Text
I18n.i18n Text
"Biennial holdings"
  Interval
_        -> Text -> Text
I18n.i18n Text
"Periodic holdings"

-- | Show the holdings report: the assets held in lot-tracked accounts
-- as of the report end date, one row per account (or per lot, with --lots).
--
-- This command receives the journal with lot detail (lot subaccounts and
-- synthetic postings) uncollapsed, regardless of --lots
-- (see maybePrepareLotDetail); holdingsReport aggregates lots itself.
holdings :: CliOpts -> Journal -> IO ()
holdings :: CliOpts -> Journal -> IO ()
holdings opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts, reportspec_ :: CliOpts -> ReportSpec
reportspec_=rspec :: ReportSpec
rspec@ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ReportOpts
ropts}} Journal
j = do
  ReportSpec -> Journal -> IO ()
warnIfLargeMultiPeriodReport ReportSpec
rspec Journal
j
  if (case ReportOpts -> Maybe ValuationType
value_ ReportOpts
ropts of Just (AtThen Maybe Text
_) -> Bool
True; Maybe ValuationType
_ -> Bool
False)
  then String -> IO ()
forall a. String -> a
error' String
"holdings: --value=then is not supported"
  else Rounding
rounding Rounding -> IO () -> IO ()
forall a b. a -> b -> b
`seq`  -- validate the --round value before any output
    if | CliOpts -> Bool
chartRequested CliOpts
opts Bool -> Bool -> Bool
&& Bool
periodic ->
           CliOpts -> Maybe Text -> Chart -> IO ()
writeChart CliOpts
opts (Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> [[Cell NumLines Html]] -> Html
forall border. Lines border => Text -> [[Cell border Html]] -> Html
titledTableHtml Text
ptitle [[Cell NumLines Html]]
phtmltable Html -> Html -> Html
forall a. Semigroup a => a -> a -> a
<> Maybe Text -> Html
htmlnote ((Text
"* " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Text
pnote))) (Chart -> IO ()) -> Chart -> IO ()
forall a b. (a -> b) -> a -> b
$ ReportOpts
-> BalanceAccumulation
-> Text
-> [(DateSpan, HoldingsReport)]
-> Chart
holdingsReportsAsChart ReportOpts
ropts BalanceAccumulation
paccum Text
ptitle [(DateSpan, HoldingsReport)]
periodrpts
       | CliOpts -> Bool
chartRequested CliOpts
opts ->
           CliOpts -> Maybe Text -> Chart -> IO ()
writeChart CliOpts
opts (Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> [[Cell NumLines Html]] -> Html
forall border. Lines border => Text -> [[Cell border Html]] -> Html
titledTableHtml Text
title [[Cell NumLines Html]]
htmltable Html -> Html -> Html
forall a. Semigroup a => a -> a -> a
<> (Text -> Html) -> [Text] -> Html
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Maybe Text -> Html
htmlnote (Maybe Text -> Html) -> (Text -> Maybe Text) -> Text -> Html
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Maybe Text
forall a. a -> Maybe a
Just) [Text]
notes)) (Chart -> IO ()) -> Chart -> IO ()
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Text -> HoldingsReport -> Chart
holdingsReportAsChart ReportOpts
ropts Text
title HoldingsReport
rpt
       | Bool
periodic -> CliOpts -> Text -> IO ()
writeOutputLazyText CliOpts
opts (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ case CliOpts -> String
outputFormatFromOpts CliOpts
opts of
           String
"txt"  -> Text
ptxtoutput
           String
"csv"  -> CSV -> Text
printCSV CSV
pcsvoutput
           String
"tsv"  -> CSV -> Text
printTSV CSV
pcsvoutput
           String
"html" -> (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> [[Cell NumLines Html]] -> Html
forall border. Lines border => Text -> [[Cell border Html]] -> Html
titledTableHtml Text
ptitle [[Cell NumLines Html]]
phtmltable Html -> Html -> Html
forall a. Semigroup a => a -> a -> a
<> Maybe Text -> Html
htmlnote ((Text
"* " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Text
pnote))
           String
"fods" -> TextEncoding
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
printFods TextEncoding
IO.localeEncoding (Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text)
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
forall a b. (a -> b) -> a -> b
$ Text
-> ((Int, Int), [[Cell NumLines Text]])
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall k a. k -> a -> Map k a
M.singleton (Text -> Text
tr Text
"Holdings") ((Int
1,Int
0), [[Cell NumLines Text]]
pfodstable)
           String
"json" -> (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ [Value] -> Text
forall a. ToJSON a => a -> Text
toJsonText ([Value] -> Text) -> [Value] -> Text
forall a b. (a -> b) -> a -> b
$ ((Day, (Map Text AmountStyle, HoldingsTotals)) -> Value)
-> [(Day, (Map Text AmountStyle, HoldingsTotals))] -> [Value]
forall a b. (a -> b) -> [a] -> [b]
map ((Day -> (Map Text AmountStyle, HoldingsTotals) -> Value)
-> (Day, (Map Text AmountStyle, HoldingsTotals)) -> Value
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Day -> (Map Text AmountStyle, HoldingsTotals) -> Value
periodTotalsJson) [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals
           String
fmt    -> String -> Text
forall a. String -> a
error' (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String -> String
unsupportedOutputFormatError String
fmt
       | Bool
otherwise -> CliOpts -> Text -> IO ()
writeOutputLazyText CliOpts
opts (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ case CliOpts -> String
outputFormatFromOpts CliOpts
opts of
           String
"txt"  -> Text
txtoutput
           String
"csv"  -> CSV -> Text
printCSV CSV
csvoutput
           String
"tsv"  -> CSV -> Text
printTSV CSV
csvoutput
           String
"html" -> (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> [[Cell NumLines Html]] -> Html
forall border. Lines border => Text -> [[Cell border Html]] -> Html
titledTableHtml Text
title [[Cell NumLines Html]]
htmltable Html -> Html -> Html
forall a. Semigroup a => a -> a -> a
<> (Text -> Html) -> [Text] -> Html
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Maybe Text -> Html
htmlnote (Maybe Text -> Html) -> (Text -> Maybe Text) -> Text -> Html
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Maybe Text
forall a. a -> Maybe a
Just) [Text]
notes)
           String
"fods" -> TextEncoding
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
printFods TextEncoding
IO.localeEncoding (Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text)
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
forall a b. (a -> b) -> a -> b
$ Text
-> ((Int, Int), [[Cell NumLines Text]])
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall k a. k -> a -> Map k a
M.singleton (Text -> Text
tr Text
"Holdings") ((Int
1,Int
0), [[Cell NumLines Text]]
fodstable)
           String
"json" -> (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ [Value] -> Text
forall a. ToJSON a => a -> Text
toJsonText ([Value] -> Text) -> [Value] -> Text
forall a b. (a -> b) -> a -> b
$ (Holding -> Value) -> [Holding] -> [Value]
forall a b. (a -> b) -> [a] -> [b]
map Holding -> Value
holdingJson [Holding]
holdingrecords
           String
fmt    -> String -> Text
forall a. String -> a
error' (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String -> String
unsupportedOutputFormatError String
fmt
  where
    -- Amounts are displayed normalised to their commodity's display
    -- precision by default; --round can choose another rounding strategy.
    rounding :: Rounding
rounding = Rounding -> Maybe Rounding -> Rounding
forall a. a -> Maybe a -> a
fromMaybe Rounding
HardRounding (Maybe Rounding -> Rounding) -> Maybe Rounding -> Rounding
forall a b. (a -> b) -> a -> b
$ RawOpts -> Maybe Rounding
roundFromRawOpts RawOpts
rawopts
    tr :: Text -> Text
tr = Translations -> Text -> Text
I18n.tr (ReportOpts -> Translations
translations_ ReportOpts
ropts)
    trf :: Text -> [(Text, Text)] -> Text
trf = Translations -> Text -> [(Text, Text)] -> Text
I18n.trf (ReportOpts -> Translations
translations_ ReportOpts
ropts)

    rpt :: HoldingsReport
rpt = HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport HoldingsReportOpts
hropts ReportSpec
rptspec Journal
j
    hropts :: HoldingsReportOpts
hropts = HoldingsReportOpts{hroLots :: Bool
hroLots = String -> RawOpts -> Bool
boolopt String
"lots" RawOpts
rawopts, hroRounding :: Rounding
hroRounding = Rounding
rounding, hroPriceOracle :: Maybe PriceOracle
hroPriceOracle = PriceOracle -> Maybe PriceOracle
forall a. a -> Maybe a
Just PriceOracle
priceoracle}
    rptspec :: ReportSpec
rptspec = if Maybe BalanceAccumulation
maccum Maybe BalanceAccumulation -> Maybe BalanceAccumulation -> Bool
forall a. Eq a => a -> a -> Bool
== BalanceAccumulation -> Maybe BalanceAccumulation
forall a. a -> Maybe a
Just BalanceAccumulation
Historical then ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec
holdingsSpecWithDates ReportSpec
rspec Maybe EFDay
forall a. Maybe a
Nothing Maybe EFDay
forall a. Maybe a
Nothing else ReportSpec
rspec

    -- --change, --cumulative or --historical/-H, if specified: which period the
    -- gain columns cover. In the single-date report, a start date gives the gains
    -- during the report period (--change, or the same, --cumulative), unless
    -- --historical asks for the gains since acquisition. With a report interval,
    -- the default is --historical.
    maccum :: Maybe BalanceAccumulation
maccum = RawOpts -> Maybe BalanceAccumulation
balanceAccumulationOverride RawOpts
rawopts

    -- one price oracle for all the reports (eg one per period)
    priceoracle :: PriceOracle
priceoracle = Bool -> Journal -> PriceOracle
journalPriceOracle (ReportOpts -> Bool
infer_prices_ ReportOpts
ropts) Journal
j
    paccum :: BalanceAccumulation
paccum = BalanceAccumulation
-> Maybe BalanceAccumulation -> BalanceAccumulation
forall a. a -> Maybe a -> a
fromMaybe BalanceAccumulation
Historical Maybe BalanceAccumulation
maccum

    rowlines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines = HoldingsReport
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
hrRows HoldingsReport
rpt
    reportdate :: Day
reportdate = HoldingsReport -> Day
hrDate HoldingsReport
rpt

    -- With a report interval, the holdings at the end of each period (their totals, in a row per period).
    periodic :: Bool
periodic = ReportOpts -> Interval
interval_ ReportOpts
ropts Interval -> Interval -> Bool
forall a. Eq a => a -> a -> Bool
/= Interval
NoInterval
    periodrpts :: [(DateSpan, HoldingsReport)]
periodrpts = HoldingsReportOpts
-> BalanceAccumulation
-> ReportSpec
-> Journal
-> [(DateSpan, HoldingsReport)]
holdingsPeriodReports
      HoldingsReportOpts{hroLots :: Bool
hroLots = Bool
False, hroRounding :: Rounding
hroRounding = Rounding
rounding, hroPriceOracle :: Maybe PriceOracle
hroPriceOracle = PriceOracle -> Maybe PriceOracle
forall a. a -> Maybe a
Just PriceOracle
priceoracle} BalanceAccumulation
paccum ReportSpec
rspec Journal
j
    ptotals :: [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals = [(HoldingsReport -> Day
hrDate HoldingsReport
r, (HoldingsReport -> Map Text AmountStyle
hrStyles HoldingsReport
r, HoldingsReport -> HoldingsTotals
hrTotals HoldingsReport
r)) | (DateSpan
_, HoldingsReport
r) <- [(DateSpan, HoldingsReport)]
periodrpts]
    ptitle :: Text
ptitle = ReportOpts -> Text -> Text
effectiveTitle ReportOpts
ropts (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Translations
-> Interval
-> BalanceAccumulation
-> [(DateSpan, HoldingsReport)]
-> Text
holdingsPeriodsTitle (ReportOpts -> Translations
translations_ ReportOpts
ropts) (ReportOpts -> Interval
interval_ ReportOpts
ropts) BalanceAccumulation
paccum [(DateSpan, HoldingsReport)]
periodrpts
    -- The Units, Avg cost and Unit price columns are shown only when some period has a single commodity
    -- (they are blank otherwise); Weight is always 100%, and Date and Age don't apply.
    showunits :: Bool
showunits = ((Day, (Map Text AmountStyle, HoldingsTotals)) -> Bool)
-> [(Day, (Map Text AmountStyle, HoldingsTotals))] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe Amount -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Amount -> Bool)
-> ((Day, (Map Text AmountStyle, HoldingsTotals)) -> Maybe Amount)
-> (Day, (Map Text AmountStyle, HoldingsTotals))
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HoldingsTotals -> Maybe Amount
htUnits (HoldingsTotals -> Maybe Amount)
-> ((Day, (Map Text AmountStyle, HoldingsTotals))
    -> HoldingsTotals)
-> (Day, (Map Text AmountStyle, HoldingsTotals))
-> Maybe Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map Text AmountStyle, HoldingsTotals) -> HoldingsTotals
forall a b. (a, b) -> b
snd ((Map Text AmountStyle, HoldingsTotals) -> HoldingsTotals)
-> ((Day, (Map Text AmountStyle, HoldingsTotals))
    -> (Map Text AmountStyle, HoldingsTotals))
-> (Day, (Map Text AmountStyle, HoldingsTotals))
-> HoldingsTotals
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Day, (Map Text AmountStyle, HoldingsTotals))
-> (Map Text AmountStyle, HoldingsTotals)
forall a b. (a, b) -> b
snd) [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals
    pcolheadings :: [Text]
pcolheadings = [Text
h | (Text
h, Bool
shown) <- [Text] -> [Bool] -> [(Text, Bool)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Text]
allpcolheadings [Bool]
pcolshown, Bool
shown]
    allpcolheadings :: [Text]
allpcolheadings = [Text -> Text
tr Text
"Units", Text -> Text
tr Text
"Avg cost", Text -> Text
tr Text
"Unit price", Text -> Text
tr Text
"Total cost", Text -> Text
tr Text
"Total value", Text -> Text
tr Text
"UGain", Text -> Text
tr Text
"UGain%", Text -> Text
tr Text
"RGain", Text -> Text
tr Text
"XIRR"]
    pcolshown :: [Bool]
pcolshown = Int -> Bool -> [Bool]
forall a. Int -> a -> [a]
replicate Int
3 Bool
showunits [Bool] -> [Bool] -> [Bool]
forall a. [a] -> [a] -> [a]
++ Int -> Bool -> [Bool]
forall a. Int -> a -> [a]
replicate Int
6 Bool
True
    -- a period's cells: those of the totals row's cells which make sense over time, and its unit price
    periodcells :: Bool -> (Map Text AmountStyle, HoldingsTotals) -> [[WideBuilder]]
periodcells Bool
c (Map Text AmountStyle
styles, HoldingsTotals
tot) = [[WideBuilder]
ps | ([WideBuilder]
ps, Bool
shown) <- [[WideBuilder]] -> [Bool] -> [([WideBuilder], Bool)]
forall a b. [a] -> [b] -> [(a, b)]
zip (Int -> [[WideBuilder]] -> [[WideBuilder]]
forall a. Int -> [a] -> [a]
take Int
2 [[WideBuilder]]
cells [[WideBuilder]] -> [[WideBuilder]] -> [[WideBuilder]]
forall a. [a] -> [a] -> [a]
++ [[WideBuilder]
price] [[WideBuilder]] -> [[WideBuilder]] -> [[WideBuilder]]
forall a. [a] -> [a] -> [a]
++ Int -> [[WideBuilder]] -> [[WideBuilder]]
forall a. Int -> [a] -> [a]
drop Int
2 [[WideBuilder]]
cells) [Bool]
pcolshown, Bool
shown]
      where
        cells :: [[WideBuilder]]
cells = [[WideBuilder]
ps | (Int
i, [WideBuilder]
ps) <- [Int] -> [[WideBuilder]] -> [(Int, [WideBuilder])]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] (Bool -> Map Text AmountStyle -> HoldingsTotals -> [[WideBuilder]]
totalsCellParts Bool
c Map Text AmountStyle
styles HoldingsTotals
tot), Int
i Int -> [Int] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Int
2, Int
3, Int
5, Int
6, Int
8, Int
9, Int
10, Int
11]]
        price :: [WideBuilder]
price = [WideBuilder]
-> (Amount -> [WideBuilder]) -> Maybe Amount -> [WideBuilder]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((WideBuilder -> [WideBuilder] -> [WideBuilder]
forall a. a -> [a] -> [a]
:[]) (WideBuilder -> [WideBuilder])
-> (Amount -> WideBuilder) -> Amount -> [WideBuilder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
noCostFmt) (HoldingsTotals -> Maybe Amount
htPrice HoldingsTotals
tot)
    -- for the html and fods tables: whether each shown column is an amount, and its class
    pcolinfo :: [(Bool, Text)]
pcolinfo = [(Bool, Text)
ci | ((Bool, Text)
ci, Bool
shown) <- [(Bool, Text)] -> [Bool] -> [((Bool, Text), Bool)]
forall a b. [a] -> [b] -> [(a, b)]
zip [(Bool
True,Text
"units"),(Bool
True,Text
"unitcost"),(Bool
True,Text
"unitprice"),(Bool
True,Text
"totalcost"),(Bool
True,Text
"totalvalue"),(Bool
True,Text
"ugain"),(Bool
False,Text
"ugainpct"),(Bool
True,Text
"rgain"),(Bool
False,Text
"xirr")] [Bool]
pcolshown, Bool
shown]
    ptxtoutput :: Text
ptxtoutput =
      (case Text
ptitle of
         Text
"" -> Text
""
         Text
t  -> Text -> Text
TL.fromStrict Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n\n")
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
      if [(Day, (Map Text AmountStyle, HoldingsTotals))] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals
      then Text -> Text
TL.fromStrict (Text -> Text
tr Text
"(no holdings)") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n"
      else TableOpts
-> (Text -> Cell)
-> (Text -> Cell)
-> (WideBuilder -> Cell)
-> Table Text Text WideBuilder
-> Text
forall a rh ch.
Show a =>
TableOpts
-> (rh -> Cell)
-> (ch -> Cell)
-> (a -> Cell)
-> Table rh ch a
-> Text
renderTable TableOpts
forall a. Default a => a
def{tableBorders=False} (Align -> Text -> Cell
textCell Align
TopLeft) (Align -> Text -> Cell
textCell Align
TopRight) (Align -> [WideBuilder] -> Cell
Cell Align
TopRight ([WideBuilder] -> Cell)
-> (WideBuilder -> [WideBuilder]) -> WideBuilder -> Cell
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WideBuilder -> [WideBuilder]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure) (Header Text
-> Header Text -> [[WideBuilder]] -> Table Text Text WideBuilder
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
        (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine [Text -> Header Text
forall h. h -> Header h
Header (Text -> Header Text) -> Text -> Header Text
forall a b. (a -> b) -> a -> b
$ Day -> (Map Text AmountStyle, HoldingsTotals) -> Text
forall {a}. Day -> (a, HoldingsTotals) -> Text
pdate Day
d (Map Text AmountStyle, HoldingsTotals)
st | (Day
d, (Map Text AmountStyle, HoldingsTotals)
st) <- [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals])
        (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Text] -> Header Text) -> [Header Text] -> Header Text
forall a b. (a -> b) -> a -> b
$ (Text -> Header Text) -> [Text] -> [Header Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Header Text
forall h. h -> Header h
Header [Text]
pcolheadings)
        [([WideBuilder] -> WideBuilder) -> [[WideBuilder]] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map [WideBuilder] -> WideBuilder
joinParts ([[WideBuilder]] -> [WideBuilder])
-> [[WideBuilder]] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Bool -> (Map Text AmountStyle, HoldingsTotals) -> [[WideBuilder]]
periodcells (ReportOpts -> Bool
color_ ReportOpts
ropts) (Map Text AmountStyle, HoldingsTotals)
st | (Day
_, (Map Text AmountStyle, HoldingsTotals)
st) <- [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals])
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Maybe Text -> Text
txtnote ((Text
"* " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Text
pnote)
    -- A period's date, starred if its totals leave out unpriced holdings,
    -- which the note below the table names.
    pdate :: Day -> (a, HoldingsTotals) -> Text
pdate Day
d (a
_, HoldingsTotals
tot) = Day -> Text
showDate Day
d Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> if [Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (HoldingsTotals -> [Text]
totalsLeftOut HoldingsTotals
tot) then Text
"" else Text
"*"
    pnote :: Maybe Text
pnote = Translations -> [Text] -> Maybe Text
holdingsUnpricedNote (ReportOpts -> Translations
translations_ ReportOpts
ropts) ([Text] -> Maybe Text) -> [Text] -> Maybe Text
forall a b. (a -> b) -> a -> b
$ [Text] -> [Text]
forall a. Ord a => [a] -> [a]
nubSort ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ ((Day, (Map Text AmountStyle, HoldingsTotals)) -> [Text])
-> [(Day, (Map Text AmountStyle, HoldingsTotals))] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (HoldingsTotals -> [Text]
totalsLeftOut (HoldingsTotals -> [Text])
-> ((Day, (Map Text AmountStyle, HoldingsTotals))
    -> HoldingsTotals)
-> (Day, (Map Text AmountStyle, HoldingsTotals))
-> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map Text AmountStyle, HoldingsTotals) -> HoldingsTotals
forall a b. (a, b) -> b
snd ((Map Text AmountStyle, HoldingsTotals) -> HoldingsTotals)
-> ((Day, (Map Text AmountStyle, HoldingsTotals))
    -> (Map Text AmountStyle, HoldingsTotals))
-> (Day, (Map Text AmountStyle, HoldingsTotals))
-> HoldingsTotals
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Day, (Map Text AmountStyle, HoldingsTotals))
-> (Map Text AmountStyle, HoldingsTotals)
forall a b. (a, b) -> b
snd) [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals
    pcsvoutput :: CSV
    pcsvoutput :: CSV
pcsvoutput = [Text
"date",Text
"units",Text
"avgcost",Text
"unitprice",Text
"totalcost",Text
"totalvalue",Text
"ugain",Text
"ugainpct",Text
"rgain",Text
"xirr",Text
"unpriced"] [Text] -> CSV -> CSV
forall a. a -> [a] -> [a]
: ((Day, (Map Text AmountStyle, HoldingsTotals)) -> [Text])
-> [(Day, (Map Text AmountStyle, HoldingsTotals))] -> CSV
forall a b. (a -> b) -> [a] -> [b]
map ((Day -> (Map Text AmountStyle, HoldingsTotals) -> [Text])
-> (Day, (Map Text AmountStyle, HoldingsTotals)) -> [Text]
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Day -> (Map Text AmountStyle, HoldingsTotals) -> [Text]
periodTotalsCsv) [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals
    -- spreadsheet-shaped tables for the html and fods output, like the text table
    pspreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content) -> [[Ods.Cell Ods.NumLines content]]
    pspreadsheetWith :: forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
pspreadsheetWith Text -> content
plain Bool -> [Text] -> content
parts =
      [Cell () content] -> [Cell NumLines content]
forall (f :: * -> *) text.
Functor f =>
f (Cell () text) -> f (Cell NumLines text)
addHeaderBorders [Text -> content
plain (Text -> content) -> Cell () Text -> Cell () content
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> Cell () Text
forall borders. Lines borders => Text -> Cell borders Text
headerCell Text
t){Ods.cellClass = Ods.Class cls} | (Text
t, Text
cls) <- [Text] -> [Text] -> [(Text, Text)]
forall a b. [a] -> [b] -> [(a, b)]
zip (Text -> Text
tr Text
"Date" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
pcolheadings) (Text
"date" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: ((Bool, Text) -> Text) -> [(Bool, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Bool, Text) -> Text
forall a b. (a, b) -> b
snd [(Bool, Text)]
pcolinfo)]
      [Cell NumLines content]
-> [[Cell NumLines content]] -> [[Cell NumLines content]]
forall a. a -> [a] -> [a]
: [ (content -> Cell NumLines content
forall border text. Lines border => text -> Cell border text
Ods.defaultCell (Text -> content
plain (Text -> content) -> Text -> content
forall a b. (a -> b) -> a -> b
$ Day -> (Map Text AmountStyle, HoldingsTotals) -> Text
forall {a}. Day -> (a, HoldingsTotals) -> Text
pdate Day
d (Map Text AmountStyle, HoldingsTotals)
st)){Ods.cellType = Ods.TypeString, Ods.cellClass = Ods.Class "date"}
          Cell NumLines content
-> [Cell NumLines content] -> [Cell NumLines content]
forall a. a -> [a] -> [a]
: [ (content -> Cell NumLines content
forall border text. Lines border => text -> Cell border text
Ods.defaultCell (Bool -> [Text] -> content
parts Bool
isamount [Text]
ps)){Ods.cellType = Ods.TypeMixedAmount, Ods.cellClass = Ods.Class cls}
            | ((Bool
isamount, Text
cls), [Text]
ps) <- [(Bool, Text)] -> CSV -> [((Bool, Text), [Text])]
forall a b. [a] -> [b] -> [(a, b)]
zip [(Bool, Text)]
pcolinfo ([[WideBuilder]] -> CSV
textParts ([[WideBuilder]] -> CSV) -> [[WideBuilder]] -> CSV
forall a b. (a -> b) -> a -> b
$ Bool -> (Map Text AmountStyle, HoldingsTotals) -> [[WideBuilder]]
periodcells Bool
False (Map Text AmountStyle, HoldingsTotals)
st) ]
        | (Day
d, (Map Text AmountStyle, HoldingsTotals)
st) <- [(Day, (Map Text AmountStyle, HoldingsTotals))]
ptotals ]
    phtmltable :: [[Cell NumLines Html]]
phtmltable = (Text -> Html)
-> (Bool -> [Text] -> Html) -> [[Cell NumLines Html]]
forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
pspreadsheetWith Text -> Html
forall a. ToMarkup a => a -> Html
toHtml Bool -> [Text] -> Html
htmlParts
    pfodstable :: [[Cell NumLines Text]]
pfodstable = (Text -> Text)
-> (Bool -> [Text] -> Text) -> [[Cell NumLines Text]]
forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
pspreadsheetWith Text -> Text
forall a. a -> a
id (\Bool
_ -> Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> ([Text] -> [Text]) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null))

    -- The default title can be customised or suppressed with --title.
    -- TRANSLATORS: the holdings report's title; {date} is the report date, {period} the report period (eg 2026-11, or 2026-11-01..2026-11-14) if it has a start date.
    title :: Text
title = ReportOpts -> Text -> Text
effectiveTitle ReportOpts
ropts (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ case HoldingsReport -> Maybe DateSpan
hrGainsPeriod HoldingsReport
rpt of
      Maybe DateSpan
Nothing  -> Text -> [(Text, Text)] -> Text
trf Text
"Holdings on {date}" [(Text
"date", Day -> Text
showDate Day
reportdate)]
      Just DateSpan
spn -> Text -> [(Text, Text)] -> Text
trf Text
"Holdings on {date}, gains in {period}" [(Text
"date", Day -> Text
showDate Day
reportdate), (Text
"period", DateSpan -> Text
showDateSpan DateSpan
spn)]
    txtoutput :: Text
txtoutput =
      (case Text
title of
         Text
"" -> Text
""
         Text
t  -> Text -> Text
TL.fromStrict Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n\n")
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
      if [(PeriodicReportRow DisplayName MixedAmount, Holding)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines
      then Text -> Text
TL.fromStrict (Text -> Text
tr Text
"(no holdings)") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n"
      else TableOpts
-> (Text -> Cell)
-> (Text -> Cell)
-> (WideBuilder -> Cell)
-> Table Text Text WideBuilder
-> Text
forall a rh ch.
Show a =>
TableOpts
-> (rh -> Cell)
-> (ch -> Cell)
-> (a -> Cell)
-> Table rh ch a
-> Text
renderTable
        TableOpts
forall a. Default a => a
def{tableBorders=False}
        (Align -> Text -> Cell
textCell Align
TopLeft)
        (Align -> Text -> Cell
textCell Align
TopRight)
        (Align -> [WideBuilder] -> Cell
Cell Align
TopRight ([WideBuilder] -> Cell)
-> (WideBuilder -> [WideBuilder]) -> WideBuilder -> Cell
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WideBuilder -> [WideBuilder]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure)
        Table Text Text WideBuilder
tbl
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (Text -> Text) -> [Text] -> Text
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Maybe Text -> Text
txtnote (Maybe Text -> Text) -> (Text -> Maybe Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Maybe Text
forall a. a -> Maybe a
Just) [Text]
notes

    -- Notes about the totals, when there are totals (a totals row, or
    -- tree mode's headings): that they leave out unpriced holdings, if
    -- any, and that their RGain and XIRR include closed positions which
    -- are not shown, if any.
    notes :: [Text]
notes
      | ReportOpts -> Bool
no_total_ ReportOpts
ropts Bool -> Bool -> Bool
&& ReportOpts -> AccountListMode
accountlistmode_ ReportOpts
ropts AccountListMode -> AccountListMode -> Bool
forall a. Eq a => a -> a -> Bool
/= AccountListMode
ALTree = []
      | Bool
otherwise = [Maybe Text] -> [Text]
forall a. [Maybe a] -> [a]
catMaybes
          [ Translations -> [Text] -> Maybe Text
holdingsUnpricedNote (ReportOpts -> Translations
translations_ ReportOpts
ropts) ([Text] -> Maybe Text) -> [Text] -> Maybe Text
forall a b. (a -> b) -> a -> b
$ HoldingsTotals -> [Text]
totalsLeftOut (HoldingsTotals -> [Text]) -> HoldingsTotals -> [Text]
forall a b. (a -> b) -> a -> b
$ HoldingsReport -> HoldingsTotals
hrTotals HoldingsReport
rpt
            -- TRANSLATORS: follows the holdings report's closed positions note, naming the flag that shows them.
          , (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
tr Text
"(see -E)") (Text -> Text) -> Maybe Text -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Translations -> Int -> Maybe Text
holdingsClosedNote (ReportOpts -> Translations
translations_ ReportOpts
ropts) (HoldingsReportOpts -> ReportSpec -> Journal -> Int
holdingsClosedHidden HoldingsReportOpts
hropts ReportSpec
rptspec Journal
j)
          ]
    -- A note below a text table, after a blank line.
    txtnote :: Maybe Text -> Text
txtnote = Text -> (Text -> Text) -> Maybe Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (\Text
n -> Text
"\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
TL.fromStrict Text
n Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n")
    -- A note below an html table.
    htmlnote :: Maybe T.Text -> Html
    htmlnote :: Maybe Text -> Html
htmlnote = Html -> (Text -> Html) -> Maybe Text -> Html
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Html
forall a. Monoid a => a
mempty (Html -> Html
H.p (Html -> Html) -> (Text -> Html) -> Text -> Html
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Html
forall a. ToMarkup a => a -> Html
toHtml)

    tbl :: Table Text Text WideBuilder
tbl = (Table Text Text WideBuilder -> Table Text Text WideBuilder)
-> ([WideBuilder]
    -> Table Text Text WideBuilder -> Table Text Text WideBuilder)
-> Maybe [WideBuilder]
-> Table Text Text WideBuilder
-> Table Text Text WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Table Text Text WideBuilder -> Table Text Text WideBuilder
forall a. a -> a
id [WideBuilder]
-> Table Text Text WideBuilder -> Table Text Text WideBuilder
forall {rh} {a} {ch}.
IsString rh =>
[a] -> Table rh ch a -> Table rh ch a
addtotalrow (([WideBuilder] -> WideBuilder) -> [[WideBuilder]] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map [WideBuilder] -> WideBuilder
joinParts ([[WideBuilder]] -> [WideBuilder])
-> Maybe [[WideBuilder]] -> Maybe [WideBuilder]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Bool -> Maybe [[WideBuilder]]
mtotalrowparts (ReportOpts -> Bool
color_ ReportOpts
ropts)) (Table Text Text WideBuilder -> Table Text Text WideBuilder)
-> Table Text Text WideBuilder -> Table Text Text WideBuilder
forall a b. (a -> b) -> a -> b
$ Header Text
-> Header Text -> [[WideBuilder]] -> Table Text Text WideBuilder
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
      (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Text] -> Header Text) -> [Header Text] -> Header Text
forall a b. (a -> b) -> a -> b
$ (HoldingsLine -> Header Text) -> [HoldingsLine] -> [Header Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Header Text
forall h. h -> Header h
Header (Text -> Header Text)
-> (HoldingsLine -> Text) -> HoldingsLine -> Header Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HoldingsLine -> Text
lineacct) [HoldingsLine]
displaylines)
      (Properties -> [Header Text] -> Header Text
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Text] -> Header Text) -> [Header Text] -> Header Text
forall a b. (a -> b) -> a -> b
$ (Text -> Header Text) -> [Text] -> [Header Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Header Text
forall h. h -> Header h
Header [Text]
colheadings)
      ((HoldingsLine -> [WideBuilder])
-> [HoldingsLine] -> [[WideBuilder]]
forall a b. (a -> b) -> [a] -> [b]
map (([WideBuilder] -> WideBuilder) -> [[WideBuilder]] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map [WideBuilder] -> WideBuilder
joinParts ([[WideBuilder]] -> [WideBuilder])
-> (HoldingsLine -> [[WideBuilder]])
-> HoldingsLine
-> [WideBuilder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> HoldingsLine -> [[WideBuilder]]
linecells (ReportOpts -> Bool
color_ ReportOpts
ropts)) [HoldingsLine]
displaylines)
      where
        addtotalrow :: [a] -> Table rh ch a -> Table rh ch a
addtotalrow [a]
totalrow Table rh ch a
tbl' = Properties
-> Table rh ch a -> Table rh [ZonkAny 0] a -> Table rh ch a
forall rh ch a ch2.
Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a
concatTables Properties
SingleLine Table rh ch a
tbl' (Table rh [ZonkAny 0] a -> Table rh ch a)
-> Table rh [ZonkAny 0] a -> Table rh ch a
forall a b. (a -> b) -> a -> b
$
          Header rh -> Header [ZonkAny 0] -> [[a]] -> Table rh [ZonkAny 0] a
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table (Properties -> [Header rh] -> Header rh
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine [rh -> Header rh
forall h. h -> Header h
Header rh
""]) ([ZonkAny 0] -> Header [ZonkAny 0]
forall h. h -> Header h
Header []) [[a]
totalrow]
    -- TRANSLATORS: the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".
    colheadings :: [Text]
colheadings = [Text -> Text
tr Text
"Date", Text -> Text
tr Text
"Age", Text -> Text
tr Text
"Units", Text -> Text
tr (HoldingsReport -> Text
hrUnitCostHeading HoldingsReport
rpt), Text -> Text
tr Text
"Unit price", Text -> Text
tr Text
"Total cost", Text -> Text
tr Text
"Total value", Text -> Text
tr Text
"Weight", Text -> Text
tr Text
"UGain", Text -> Text
tr Text
"UGain%", Text -> Text
tr Text
"RGain", Text -> Text
tr Text
"XIRR"]
    displaylines :: [HoldingsLine]
displaylines = HoldingsReport -> [HoldingsLine]
hrLines HoldingsReport
rpt

    -- A display line's account cell: indented display names in tree
    -- mode, full (possibly dropped) account names otherwise.
    lineacct :: HoldingsLine -> T.Text
    lineacct :: HoldingsLine -> Text
lineacct HoldingsLine
l
      | ReportOpts -> AccountListMode
accountlistmode_ ReportOpts
ropts AccountListMode -> AccountListMode -> Bool
forall a. Eq a => a -> a -> Bool
== AccountListMode
ALTree Bool -> Bool -> Bool
&& Bool -> Bool
not (ReportOpts -> Bool
full_names_ ReportOpts
ropts) =
          Int -> Text -> Text
T.replicate (HoldingsLine -> Int
hlIndent HoldingsLine
l Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
2) Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> HoldingsLine -> Text
hlDisplay HoldingsLine
l
      | Bool
otherwise = Int -> Text -> Text
accountNameDrop (ReportOpts -> Int
drop_ ReportOpts
ropts) (HoldingsLine -> Text
hlAccount HoldingsLine
l)

    -- A display line's data cells, each as a list of parts,
    -- with gains and losses coloured if the flag is true (see gainColour).
    linecells :: Bool -> HoldingsLine -> [[WideBuilder]]
    linecells :: Bool -> HoldingsLine -> [[WideBuilder]]
linecells Bool
c HoldingsHeading{HoldingsTotals
hlTotals :: HoldingsLine -> HoldingsTotals
hlTotals :: HoldingsTotals
hlTotals}   = Bool -> Map Text AmountStyle -> HoldingsTotals -> [[WideBuilder]]
totalsCellParts Bool
c (HoldingsReport -> Map Text AmountStyle
hrStyles HoldingsReport
rpt) HoldingsTotals
hlTotals
    linecells Bool
c HoldingsPosition{Holding
hlHolding :: HoldingsLine -> Holding
hlHolding :: Holding
hlHolding} = Bool -> Holding -> [[WideBuilder]]
holdingCellParts Bool
c Holding
hlHolding

    -- A text table cell from its parts, comma-separated.
    joinParts :: [WideBuilder] -> WideBuilder
    joinParts :: [WideBuilder] -> WideBuilder
joinParts = [WideBuilder] -> WideBuilder
forall a. Monoid a => [a] -> a
mconcat ([WideBuilder] -> WideBuilder)
-> ([WideBuilder] -> [WideBuilder]) -> [WideBuilder] -> WideBuilder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WideBuilder -> [WideBuilder] -> [WideBuilder]
forall a. a -> [a] -> [a]
intersperse (Text -> WideBuilder
wbFromText Text
", ")
    -- Cells' parts as plain text, for the html and fods tables.
    textParts :: [[WideBuilder]] -> [[T.Text]]
    textParts :: [[WideBuilder]] -> CSV
textParts = ([WideBuilder] -> [Text]) -> [[WideBuilder]] -> CSV
forall a b. (a -> b) -> [a] -> [b]
map ((WideBuilder -> Text) -> [WideBuilder] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map WideBuilder -> Text
wbToText)

    -- Colour a gain (or the like, eg an XIRR) green if positive and a loss red, if the flag is true.
    -- Colouring a WideBuilder keeps its width, so text tables stay aligned.
    gainColour :: Bool -> Quantity -> WideBuilder -> WideBuilder
    gainColour :: Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c Quantity
q
      | Bool
c Bool -> Bool -> Bool
&& Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 = ColorIntensity -> Color -> WideBuilder -> WideBuilder
colorB ColorIntensity
Dull Color
Green
      | Bool
c Bool -> Bool -> Bool
&& Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0 = ColorIntensity -> Color -> WideBuilder -> WideBuilder
colorB ColorIntensity
Dull Color
Red
      | Bool
otherwise  = WideBuilder -> WideBuilder
forall a. a -> a
id

    showpct :: Quantity -> Text
showpct = Map Text AmountStyle -> Quantity -> Text
showPercentWith (HoldingsReport -> Map Text AmountStyle
hrStyles HoldingsReport
rpt)
    -- Show an XIRR percentage, like showpct: eg 12.3%.
    showxirr :: Double -> T.Text
    showxirr :: Double -> Text
showxirr = Quantity -> Text
showpct (Quantity -> Text) -> (Double -> Quantity) -> Double -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Double -> Quantity
forall a b. (Real a, Fractional b) => a -> b
realToFrac

    -- A holding's cells, each as a list of parts: possibly several in Cost
    -- and RGain (when cost commodities are mixed), at most one elsewhere.
    -- Units show a commodity symbol even when zero (for rgain-only rows).
    holdingCellParts :: Bool -> Holding -> [[WideBuilder]]
    holdingCellParts :: Bool -> Holding -> [[WideBuilder]]
holdingCellParts Bool
c Holding
h =
      [ [Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> (Day -> Text) -> Maybe Day -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Day -> Text
showDate (Holding -> Maybe Day
hDate Holding
h)]
      , [Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> (Integer -> Text) -> Maybe Integer -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Integer -> Text
showage (Holding -> Maybe Integer
hAge Holding
h)]
      , [Amount -> WideBuilder
showamtz (Holding -> Amount
hUnits Holding
h)]
      , [WideBuilder
-> (Amount -> WideBuilder) -> Maybe Amount -> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty Amount -> WideBuilder
showamt (Holding -> Maybe Amount
hUnitCost Holding
h)]
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> WideBuilder
showamt ([Amount] -> [WideBuilder]) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hPrice Holding
h
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> WideBuilder
showamtz ([Amount] -> [WideBuilder]) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hCost Holding
h
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> WideBuilder
showamtz ([Amount] -> [WideBuilder]) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hValue Holding
h
      , [Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> (Quantity -> Text) -> Maybe Quantity -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Quantity -> Text
showpct (Holding -> Maybe Quantity
hWeight Holding
h)]
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map ((Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
showamtz) ([Amount] -> [WideBuilder]) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hUgain Holding
h
      , [WideBuilder
-> (Quantity -> WideBuilder) -> Maybe Quantity -> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty (\Quantity
p -> Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c Quantity
p (WideBuilder -> WideBuilder) -> WideBuilder -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Quantity -> Text
showpct Quantity
p) (Holding -> Maybe Quantity
hUgainPct Holding
h)]
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map ((Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
showamt) ([Amount] -> [WideBuilder]) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Holding -> [Amount]
hRgain Holding
h
      , [WideBuilder
-> (Double -> WideBuilder) -> Maybe Double -> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty (\Double
x -> Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c (Double -> Quantity
forall a b. (Real a, Fractional b) => a -> b
realToFrac Double
x) (WideBuilder -> WideBuilder) -> WideBuilder -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Double -> Text
showxirr Double
x) (Holding -> Maybe Double
hXirr Holding
h)]
      ]
      where
        showamt :: Amount -> WideBuilder
showamt  = AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
noCostFmt
        showamtz :: Amount -> WideBuilder
showamtz = AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
noCostFmt{displayZeroCommodity=True}
        gainamt :: (Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
sh Amount
a = Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c (Amount -> Quantity
aquantity Amount
a) (Amount -> WideBuilder
sh Amount
a)

    -- A totals row's cells (the grand total, or an account heading row
    -- in tree mode), each as a list of parts like holdingCellParts.
    totalsCellParts :: Bool -> M.Map CommoditySymbol AmountStyle -> HoldingsTotals -> [[WideBuilder]]
    totalsCellParts :: Bool -> Map Text AmountStyle -> HoldingsTotals -> [[WideBuilder]]
totalsCellParts Bool
c Map Text AmountStyle
styles HoldingsTotals
tot =
      [ []
      , []
      , [WideBuilder]
-> (Amount -> [WideBuilder]) -> Maybe Amount -> [WideBuilder]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((WideBuilder -> [WideBuilder] -> [WideBuilder]
forall a. a -> [a] -> [a]
:[]) (WideBuilder -> [WideBuilder])
-> (Amount -> WideBuilder) -> Amount -> [WideBuilder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> WideBuilder
showamt) (HoldingsTotals -> Maybe Amount
htUnits HoldingsTotals
tot)
      , [WideBuilder]
-> (Amount -> [WideBuilder]) -> Maybe Amount -> [WideBuilder]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((WideBuilder -> [WideBuilder] -> [WideBuilder]
forall a. a -> [a] -> [a]
:[]) (WideBuilder -> [WideBuilder])
-> (Amount -> WideBuilder) -> Amount -> [WideBuilder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> WideBuilder
showamt) (HoldingsTotals -> Maybe Amount
htAvgCost HoldingsTotals
tot)
      , []
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> WideBuilder
showamt (HoldingsTotals -> [Amount]
htCost HoldingsTotals
tot)
      , [WideBuilder]
-> ([Amount] -> [WideBuilder]) -> Maybe [Amount] -> [WideBuilder]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> WideBuilder
showamt) (HoldingsTotals -> Maybe [Amount]
htValue HoldingsTotals
tot)
      , [Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> (Quantity -> Text) -> Maybe Quantity -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Quantity -> Text
pct (HoldingsTotals -> Maybe Quantity
htWeight HoldingsTotals
tot)]
      , [WideBuilder]
-> ([Amount] -> [WideBuilder]) -> Maybe [Amount] -> [WideBuilder]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map ((Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
showamtz)) (HoldingsTotals -> Maybe [Amount]
htUgain HoldingsTotals
tot)
      , [WideBuilder
-> (Quantity -> WideBuilder) -> Maybe Quantity -> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty (\Quantity
p -> Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c Quantity
p (WideBuilder -> WideBuilder) -> WideBuilder -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Quantity -> Text
pct Quantity
p) (HoldingsTotals -> Maybe Quantity
htUgainPct HoldingsTotals
tot)]
      , (Amount -> WideBuilder) -> [Amount] -> [WideBuilder]
forall a b. (a -> b) -> [a] -> [b]
map ((Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
showamt) (HoldingsTotals -> [Amount]
htRgain HoldingsTotals
tot)
      , [WideBuilder
-> (Double -> WideBuilder) -> Maybe Double -> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty (\Double
x -> Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c (Double -> Quantity
forall a b. (Real a, Fractional b) => a -> b
realToFrac Double
x) (WideBuilder -> WideBuilder) -> WideBuilder -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Text -> WideBuilder
wbFromText (Text -> WideBuilder) -> Text -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Quantity -> Text
pct (Quantity -> Text) -> Quantity -> Text
forall a b. (a -> b) -> a -> b
$ Double -> Quantity
forall a b. (Real a, Fractional b) => a -> b
realToFrac Double
x) (HoldingsTotals -> Maybe Double
htXirr HoldingsTotals
tot)]
      ]
      where
        pct :: Quantity -> Text
pct = Map Text AmountStyle -> Quantity -> Text
showPercentWith Map Text AmountStyle
styles
        showamt :: Amount -> WideBuilder
showamt  = AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
noCostFmt
        showamtz :: Amount -> WideBuilder
showamtz = AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
noCostFmt{displayZeroCommodity=True}
        gainamt :: (Amount -> WideBuilder) -> Amount -> WideBuilder
gainamt Amount -> WideBuilder
sh Amount
a = Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour Bool
c (Amount -> Quantity
aquantity Amount
a) (Amount -> WideBuilder
sh Amount
a)

    -- The grand totals row as cell parts (coloured if the flag is true), unless --no-total is in effect.
    mtotalrowparts :: Bool -> Maybe [[WideBuilder]]
    mtotalrowparts :: Bool -> Maybe [[WideBuilder]]
mtotalrowparts Bool
c
      | ReportOpts -> Bool
no_total_ ReportOpts
ropts = Maybe [[WideBuilder]]
forall a. Maybe a
Nothing
      | Bool
otherwise = [[WideBuilder]] -> Maybe [[WideBuilder]]
forall a. a -> Maybe a
Just ([[WideBuilder]] -> Maybe [[WideBuilder]])
-> [[WideBuilder]] -> Maybe [[WideBuilder]]
forall a b. (a -> b) -> a -> b
$ Bool -> Map Text AmountStyle -> HoldingsTotals -> [[WideBuilder]]
totalsCellParts Bool
c (HoldingsReport -> Map Text AmountStyle
hrStyles HoldingsReport
rpt) (HoldingsTotals -> [[WideBuilder]])
-> HoldingsTotals -> [[WideBuilder]]
forall a b. (a -> b) -> a -> b
$ HoldingsReport -> HoldingsTotals
hrTotals HoldingsReport
rpt

    -- Spreadsheet-shaped tables for the html and fods output: like the
    -- text table, but with single-line cells, an Account column heading,
    -- and a Total: row heading. Parameterised on how to convert plain
    -- text, and a cell's list of (possibly amount) parts, to content.
    spreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content)
                    -> [[Ods.Cell Ods.NumLines content]]
    spreadsheetWith :: forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
spreadsheetWith Text -> content
plain Bool -> [Text] -> content
parts =
      [Cell () content] -> [Cell NumLines content]
forall (f :: * -> *) text.
Functor f =>
f (Cell () text) -> f (Cell NumLines text)
addHeaderBorders ((Text -> Text -> Cell () content)
-> [Text] -> [Text] -> [Cell () content]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Text -> Text -> Cell () content
forall {border}.
Lines border =>
Text -> Text -> Cell border content
hcell [Text]
colclasses (Text -> Text
tr Text
"Account" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
colheadings))
      [Cell NumLines content]
-> [[Cell NumLines content]] -> [[Cell NumLines content]]
forall a. a -> [a] -> [a]
: [ (Int -> Text -> content -> Cell NumLines content)
-> [Int] -> [Text] -> [content] -> [Cell NumLines content]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 Int -> Text -> content -> Cell NumLines content
forall border content'.
Lines border =>
Int -> Text -> content' -> Cell border content'
bodycell [Int
0..] (HoldingsLine -> [Text]
lineclasses HoldingsLine
l)
            (Text -> content
plain (HoldingsLine -> Text
acctcell HoldingsLine
l) content -> [content] -> [content]
forall a. a -> [a] -> [a]
: (Bool -> [Text] -> content) -> [Bool] -> CSV -> [content]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Bool -> [Text] -> content
parts [Bool]
amountcols ([[WideBuilder]] -> CSV
textParts ([[WideBuilder]] -> CSV) -> [[WideBuilder]] -> CSV
forall a b. (a -> b) -> a -> b
$ Bool -> HoldingsLine -> [[WideBuilder]]
linecells Bool
False HoldingsLine
l))
        | HoldingsLine
l <- [HoldingsLine]
displaylines ]
      [[Cell NumLines content]]
-> [[Cell NumLines content]] -> [[Cell NumLines content]]
forall a. [a] -> [a] -> [a]
++ [[Cell NumLines content]]
-> ([[WideBuilder]] -> [[Cell NumLines content]])
-> Maybe [[WideBuilder]]
-> [[Cell NumLines content]]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\[[WideBuilder]]
tot -> [[Cell () content]] -> [[Cell NumLines content]]
forall (f :: * -> *) border text.
Functor f =>
[f (Cell border text)] -> [f (Cell NumLines text)]
addTotalBorders
           [(Int -> Text -> content -> Cell () content)
-> [Int] -> [Text] -> [content] -> [Cell () content]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 Int -> Text -> content -> Cell () content
forall border content'.
Lines border =>
Int -> Text -> content' -> Cell border content'
totalcell [Int
0..] [Text]
colclasses
              (Text -> content
plain (Text -> Text
tr Text
"Total:") content -> [content] -> [content]
forall a. a -> [a] -> [a]
: (Bool -> [Text] -> content) -> [Bool] -> CSV -> [content]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Bool -> [Text] -> content
parts [Bool]
amountcols ([[WideBuilder]] -> CSV
textParts [[WideBuilder]]
tot)) :: [Ods.Cell () content]])
           (Bool -> Maybe [[WideBuilder]]
mtotalrowparts Bool
False)
      where
        -- per-column css classes, so the html cells can be styled
        colclasses :: [Text]
colclasses = [Text
"account",Text
"date",Text
"age",Text
"units",Text
"unitcost",Text
"unitprice",Text
"totalcost",Text
"totalvalue",Text
"weight",Text
"ugain",Text
"ugainpct",Text
"rgain",Text
"xirr"]
        -- which of the other columns' cell parts are amounts
        amountcols :: [Bool]
amountcols = [Bool
False, Bool
False, Bool
True, Bool
True, Bool
True, Bool
True, Bool
True, Bool
False, Bool
True, Bool
False, Bool
True, Bool
False]
        hcell :: Text -> Text -> Cell border content
hcell Text
cls Text
t = Text -> content
plain (Text -> content) -> Cell border Text -> Cell border content
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> Cell border Text
forall borders. Lines borders => Text -> Cell borders Text
headerCell Text
t){Ods.cellClass = Ods.Class cls}
        -- account heading rows get an extra class, so html can style them
        lineclasses :: HoldingsLine -> [Text]
lineclasses HoldingsHeading{}  = Text
"account acctheading" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Int -> [Text] -> [Text]
forall a. Int -> [a] -> [a]
drop Int
1 [Text]
colclasses
        lineclasses HoldingsPosition{} = [Text]
colclasses
        -- body cells are right-aligned, except the first two columns
        -- (Account and Date); headings are unaffected
        bodycell :: Ods.Lines border => Int -> T.Text -> content' -> Ods.Cell border content'
        bodycell :: forall border content'.
Lines border =>
Int -> Text -> content' -> Cell border content'
bodycell Int
i Text
cls content'
t = (content' -> Cell border content'
forall border text. Lines border => text -> Cell border text
Ods.defaultCell content'
t)
          {Ods.cellType = if i < 2 then Ods.TypeString else Ods.TypeMixedAmount
          ,Ods.cellClass = Ods.Class cls}
        totalcell :: Int -> Text -> content' -> Cell border content'
totalcell Int
i Text
cls = Int -> Text -> content' -> Cell border content'
forall border content'.
Lines border =>
Int -> Text -> content' -> Cell border content'
bodycell Int
i (Text
cls Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" coltotal")
        -- indent tree-mode account names with no-break spaces
        acctcell :: HoldingsLine -> Text
acctcell HoldingsLine
l = Int -> Text -> Text
T.replicate (HoldingsLine -> Int
hlIndent HoldingsLine
l Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
2) Text
"\160" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> HoldingsLine -> Text
hlDisplay HoldingsLine
l

    -- Each commodity amount gets its own span with an "amount" class,
    -- so eg wrapping within amounts can be prevented with css.
    htmltable :: [[Ods.Cell Ods.NumLines Html]]
    htmltable :: [[Cell NumLines Html]]
htmltable = (Text -> Html)
-> (Bool -> [Text] -> Html) -> [[Cell NumLines Html]]
forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
spreadsheetWith Text -> Html
forall a. ToMarkup a => a -> Html
toHtml Bool -> [Text] -> Html
htmlParts
    htmlParts :: Bool -> [Text] -> Html
htmlParts Bool
isamount [Text]
parts =
      [Html] -> Html
forall a. Monoid a => [a] -> a
mconcat ([Html] -> Html) -> [Html] -> Html
forall a b. (a -> b) -> a -> b
$ Html -> [Html] -> [Html]
forall a. a -> [a] -> [a]
intersperse (Text -> Html
forall a. ToMarkup a => a -> Html
toHtml (Text
", "::T.Text)) ([Html] -> [Html]) -> [Html] -> [Html]
forall a b. (a -> b) -> a -> b
$
      (Text -> Html) -> [Text] -> [Html]
forall a b. (a -> b) -> [a] -> [b]
map (\Text
p -> if Bool
isamount then (Html -> Html
H.span (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.class_ AttributeValue
"amount") (Text -> Html
forall a. ToMarkup a => a -> Html
toHtml Text
p) else Text -> Html
forall a. ToMarkup a => a -> Html
toHtml Text
p) ([Text] -> [Html]) -> [Text] -> [Html]
forall a b. (a -> b) -> a -> b
$
      (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) [Text]
parts

    fodstable :: [[Ods.Cell Ods.NumLines T.Text]]
    fodstable :: [[Cell NumLines Text]]
fodstable = (Text -> Text)
-> (Bool -> [Text] -> Text) -> [[Cell NumLines Text]]
forall content.
(Text -> content)
-> (Bool -> [Text] -> content) -> [[Cell NumLines content]]
spreadsheetWith Text -> Text
forall a. a -> a
id (\Bool
_ -> Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> ([Text] -> [Text]) -> [Text] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null))

    -- Machine-readable records for the csv/tsv/json output, one per
    -- displayed table line. No totals records.
    holdingrecords :: [Holding]
    holdingrecords :: [Holding]
holdingrecords = ((PeriodicReportRow DisplayName MixedAmount, Holding) -> Holding)
-> [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-> [Holding]
forall a b. (a -> b) -> [a] -> [b]
map (PeriodicReportRow DisplayName MixedAmount, Holding) -> Holding
forall a b. (a, b) -> b
snd [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines

    csvoutput :: CSV
    csvoutput :: CSV
csvoutput =
      [Text
"account",Text
"commodity",Text
"date",Text
"age",Text
"units",Text
"unitcost",Text
"unitprice",Text
"totalcost",Text
"totalvalue",Text
"weight",Text
"ugain",Text
"ugainpct",Text
"rgain",Text
"xirr"]
      [Text] -> CSV -> CSV
forall a. a -> [a] -> [a]
: (Holding -> [Text]) -> [Holding] -> CSV
forall a b. (a -> b) -> [a] -> [b]
map Holding -> [Text]
holdingCsv [Holding]
holdingrecords