{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}
{-# LANGUAGE NamedFieldPuns #-}

module Hledger.Cli.Commands.Prices (
  pricesmode
 ,prices
)
where

import Data.List
import Data.Set qualified as S
import Data.Text qualified as T
import Data.Time.Calendar (Day, DayOfWeek(..), dayOfWeek)
import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils (writeOutputWithTitle)
import System.Console.CmdArgs.Explicit
import Data.Maybe (mapMaybe)
import Data.Function ((&))
import Text.Printf (printf)

pricesmode :: Mode RawOpts
pricesmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Prices.txt")
  [[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"show-reverse"] (String -> RawOpts -> RawOpts
setboolopt String
"show-reverse") String
"also show the prices inferred by reversing known prices"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"show-aliases"] (String -> RawOpts -> RawOpts
setboolopt String
"show-aliases") String
"also show the exchange rates provided by commodity aliases"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"summary"] (String -> RawOpts -> RawOpts
setboolopt String
"summary") String
"summarise declared prices per commodity instead of listing them"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"locations"] (String -> RawOpts -> RawOpts
setboolopt String
"locations") String
"also show where prices where declared"
  ]
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  ([Flag RawOpts]
hiddenflags [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
"costs"]                (String -> RawOpts -> RawOpts
setboolopt String
"infer-market-prices") String
"deprecated, use --infer-market-prices instead"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"inverted-costs"]       (String -> RawOpts -> RawOpts
setboolopt String
"show-reverse") String
"deprecated, use --show-reverse instead"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"infer-reverse-prices"] (String -> RawOpts -> RawOpts
setboolopt String
"show-reverse") String
"deprecated, use --show-reverse instead"
  ])
  ([], 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]")

instance HasAmounts PriceDirective where
  styleAmounts :: Map CommoditySymbol AmountStyle -> PriceDirective -> PriceDirective
styleAmounts Map CommoditySymbol AmountStyle
styles PriceDirective
pd = PriceDirective
pd{pdamount=styleAmounts styles $ pdamount pd}

-- List market prices.
prices :: CliOpts -> Journal -> IO ()
prices CliOpts
opts Journal
j = do
  let
    q :: Query
q       = ReportSpec -> Query
_rsQuery (ReportSpec -> Query) -> ReportSpec -> Query
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
opts
    showloc :: Bool
showloc = String -> RawOpts -> Bool
boolopt String
"locations" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)
    styles :: Map CommoditySymbol AmountStyle
styles  = Journal -> Map CommoditySymbol AmountStyle
journalCommodityStyles Journal
j
    render :: PriceDirective -> CommoditySymbol
render PriceDirective
pd =
      PriceDirective -> CommoditySymbol
showPriceDirective (Map CommoditySymbol AmountStyle -> PriceDirective -> PriceDirective
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles PriceDirective
pd)
      CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> [CommoditySymbol] -> CommoditySymbol
comment ([CommoditySymbol
"commodity alias" | PriceDirective -> Bool
isAliasRate PriceDirective
pd] [CommoditySymbol] -> [CommoditySymbol] -> [CommoditySymbol]
forall a. Semigroup a => a -> a -> a
<> [CommoditySymbol
loc | Bool
showloc, Just CommoditySymbol
loc <- [PriceDirective -> Maybe CommoditySymbol
locationTag PriceDirective
pd]])

    -- XXX duplicates logic in Hledger.Data.Valuation.makePriceGraph, keep synced

    declaredprices :: [PriceDirective]
declaredprices =
      -- dbg0 "declaredprices" $
      Journal -> [PriceDirective]
jpricedirectives Journal
j

    -- Use the location-preserving helper only when --locations is set,
    -- to avoid the per-directive record update otherwise.
    pricesfromcosts :: [PriceDirective]
pricesfromcosts =
      -- dbg0 "pricesfromcosts" $
      (Posting -> [PriceDirective]) -> [Posting] -> [PriceDirective]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (if Bool
showloc then Posting -> [PriceDirective]
postingPriceDirectivesWithLoc
                            else Posting -> [PriceDirective]
postingPriceDirectivesFromCost) ([Posting] -> [PriceDirective]) -> [Posting] -> [PriceDirective]
forall a b. (a -> b) -> a -> b
$
      Journal -> [Posting]
journalPostings Journal
j

    marketprices :: [PriceDirective]
marketprices =
      -- dbg0 "marketprices" $
      if String -> RawOpts -> Bool
boolopt String
"infer-market-prices" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)
      then [PriceDirective]
declaredprices [PriceDirective] -> [PriceDirective] -> [PriceDirective]
`mergePriceDirectives` [PriceDirective]
pricesfromcosts
      else [PriceDirective]
declaredprices

    -- Commodity alias rates, between commodities with no market prices between them
    -- (as in Hledger.Data.Valuation.buildPriceIndexes).
    aliasprices :: [PriceDirective]
aliasprices =
      if String -> RawOpts -> Bool
boolopt String
"show-aliases" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)
      then [ PriceDirective
pd | PriceDirective
pd <- Journal -> [PriceDirective]
journalAliasPriceDirectives Journal
j, let (CommoditySymbol
f, CommoditySymbol
t) = PriceDirective -> (CommoditySymbol, CommoditySymbol)
pricePair PriceDirective
pd
                , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol, CommoditySymbol)
-> Set (CommoditySymbol, CommoditySymbol) -> Bool
forall a. Ord a => a -> Set a -> Bool
S.member (CommoditySymbol
f, CommoditySymbol
t) Set (CommoditySymbol, CommoditySymbol)
marketpairs, Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol, CommoditySymbol)
-> Set (CommoditySymbol, CommoditySymbol) -> Bool
forall a. Ord a => a -> Set a -> Bool
S.member (CommoditySymbol
t, CommoditySymbol
f) Set (CommoditySymbol, CommoditySymbol)
marketpairs ]
      else []
      where marketpairs :: Set (CommoditySymbol, CommoditySymbol)
marketpairs = [(CommoditySymbol, CommoditySymbol)]
-> Set (CommoditySymbol, CommoditySymbol)
forall a. Ord a => [a] -> Set a
S.fromList ([(CommoditySymbol, CommoditySymbol)]
 -> Set (CommoditySymbol, CommoditySymbol))
-> [(CommoditySymbol, CommoditySymbol)]
-> Set (CommoditySymbol, CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ (PriceDirective -> (CommoditySymbol, CommoditySymbol))
-> [PriceDirective] -> [(CommoditySymbol, CommoditySymbol)]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> (CommoditySymbol, CommoditySymbol)
pricePair [PriceDirective]
marketprices
    aliaspairs :: Set (CommoditySymbol, CommoditySymbol)
aliaspairs = [(CommoditySymbol, CommoditySymbol)]
-> Set (CommoditySymbol, CommoditySymbol)
forall a. Ord a => [a] -> Set a
S.fromList ([(CommoditySymbol, CommoditySymbol)]
 -> Set (CommoditySymbol, CommoditySymbol))
-> [(CommoditySymbol, CommoditySymbol)]
-> Set (CommoditySymbol, CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ (PriceDirective -> (CommoditySymbol, CommoditySymbol))
-> [PriceDirective] -> [(CommoditySymbol, CommoditySymbol)]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> (CommoditySymbol, CommoditySymbol)
pricePair [PriceDirective]
aliasprices
    pricePair :: PriceDirective -> (CommoditySymbol, CommoditySymbol)
pricePair PriceDirective
pd = (PriceDirective -> CommoditySymbol
pdcommodity PriceDirective
pd, Amount -> CommoditySymbol
acommodity (Amount -> CommoditySymbol) -> Amount -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ PriceDirective -> Amount
pdamount PriceDirective
pd)
    -- An alias rate, or its reverse ?
    isAliasRate :: PriceDirective -> Bool
isAliasRate PriceDirective
pd = let (CommoditySymbol
f, CommoditySymbol
t) = PriceDirective -> (CommoditySymbol, CommoditySymbol)
pricePair PriceDirective
pd in (CommoditySymbol, CommoditySymbol)
-> Set (CommoditySymbol, CommoditySymbol) -> Bool
forall a. Ord a => a -> Set a -> Bool
S.member (CommoditySymbol
f, CommoditySymbol
t) Set (CommoditySymbol, CommoditySymbol)
aliaspairs Bool -> Bool -> Bool
|| (CommoditySymbol, CommoditySymbol)
-> Set (CommoditySymbol, CommoditySymbol) -> Bool
forall a. Ord a => a -> Set a -> Bool
S.member (CommoditySymbol
t, CommoditySymbol
f) Set (CommoditySymbol, CommoditySymbol)
aliaspairs

    forwardprices :: [PriceDirective]
forwardprices = [PriceDirective]
marketprices [PriceDirective] -> [PriceDirective] -> [PriceDirective]
forall a. Semigroup a => a -> a -> a
<> [PriceDirective]
aliasprices

    reverseprices :: [PriceDirective]
reverseprices =
      -- dbg0 "reverseprices" $
      (PriceDirective -> Maybe PriceDirective)
-> [PriceDirective] -> [PriceDirective]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe PriceDirective -> Maybe PriceDirective
reversePriceDirective [PriceDirective]
forwardprices

    allprices :: [PriceDirective]
allprices =
      -- dbg0 "allprices" $
      if String -> RawOpts -> Bool
boolopt String
"show-reverse" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)
      then [PriceDirective]
forwardprices [PriceDirective] -> [PriceDirective] -> [PriceDirective]
`mergePriceDirectives` [PriceDirective]
reverseprices
      else [PriceDirective]
forwardprices

    filteredprices :: [PriceDirective]
filteredprices =
      -- dbg0 "filtered unsorted" $
      (PriceDirective -> Bool) -> [PriceDirective] -> [PriceDirective]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> PriceDirective -> Bool
matchesPriceDirective Query
q) [PriceDirective]
allprices

  CliOpts -> CommoditySymbol -> IO ()
writeOutputWithTitle CliOpts
opts (CommoditySymbol -> IO ()) -> CommoditySymbol -> IO ()
forall a b. (a -> b) -> a -> b
$
    if String -> RawOpts -> Bool
boolopt String
"summary" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)
    then Journal -> Query -> [PriceDirective] -> CommoditySymbol
pricesSummary Journal
j Query
q ((PriceDirective -> Bool) -> [PriceDirective] -> [PriceDirective]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> PriceDirective -> Bool
matchesPriceDirective Query
q) [PriceDirective]
declaredprices)
    else [CommoditySymbol] -> CommoditySymbol
T.unlines ([CommoditySymbol] -> CommoditySymbol)
-> [CommoditySymbol] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (PriceDirective -> CommoditySymbol)
-> [PriceDirective] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> CommoditySymbol
render ([PriceDirective] -> [CommoditySymbol])
-> [PriceDirective] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (PriceDirective -> Day) -> [PriceDirective] -> [PriceDirective]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn PriceDirective -> Day
pddate [PriceDirective]
filteredprices

-- | Like 'postingPriceDirectivesFromCost', but tags each inferred
-- price directive with the source position of the parent transaction
-- (if known) so it can be reported by --locations.
postingPriceDirectivesWithLoc :: Posting -> [PriceDirective]
postingPriceDirectivesWithLoc :: Posting -> [PriceDirective]
postingPriceDirectivesWithLoc Posting
p =
  [ PriceDirective
pd{pdsourcepos = pos} | PriceDirective
pd <- Posting -> [PriceDirective]
postingPriceDirectivesFromCost Posting
p ]
  where
    pos :: SourcePos
pos = SourcePos
-> (Transaction -> SourcePos) -> Maybe Transaction -> SourcePos
forall b a. b -> (a -> b) -> Maybe a -> b
maybe SourcePos
nullsourcepos ((SourcePos, SourcePos) -> SourcePos
forall a b. (a, b) -> a
fst ((SourcePos, SourcePos) -> SourcePos)
-> (Transaction -> (SourcePos, SourcePos))
-> Transaction
-> SourcePos
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> (SourcePos, SourcePos)
tsourcepos) (Posting -> Maybe Transaction
ptransaction Posting
p)

-- | A trailing journal comment containing these items, if any.
comment :: [T.Text] -> T.Text
comment :: [CommoditySymbol] -> CommoditySymbol
comment [] = CommoditySymbol
""
comment [CommoditySymbol]
xs = CommoditySymbol
"  ; " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol -> [CommoditySymbol] -> CommoditySymbol
T.intercalate CommoditySymbol
", " [CommoditySymbol]
xs

-- | A location tag showing the file and line where a price directive was declared or inferred
-- (or for a commodity alias rate, the commodity directive declaring it).
-- Reversed prices inherit the source position of the directive they were derived from.
-- Nothing only when no source position is available.
locationTag :: PriceDirective -> Maybe T.Text
locationTag :: PriceDirective -> Maybe CommoditySymbol
locationTag PriceDirective{pdsourcepos :: PriceDirective -> SourcePos
pdsourcepos=SourcePos String
fp Pos
l Pos
_}
  | String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
fp   = Maybe CommoditySymbol
forall a. Maybe a
Nothing
  | Bool
otherwise = CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just (CommoditySymbol -> Maybe CommoditySymbol)
-> CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
"location: " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> String -> CommoditySymbol
T.pack String
fp CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
":" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show (Pos -> Int
unPos Pos
l))

-- | Per-commodity stats from the journal's declared price directives.
data PriceStats = PriceStats
  { PriceStats -> CommoditySymbol
psCommodity :: CommoditySymbol
  , PriceStats -> Int
psCount     :: Int
  , PriceStats -> Maybe Day
psEarliest  :: Maybe Day
  , PriceStats -> Maybe Day
psLatest    :: Maybe Day
  , PriceStats -> Set Day
psDays      :: S.Set Day   -- distinct price dates
  }

-- | Stats for one ISO commodity code, gathered from raw P directives.
-- Symbol variants (eg "$" / "USD") are grouped together via 'toCurrencyCode'.
priceStatsFor :: [PriceDirective] -> CurrencyCode -> PriceStats
priceStatsFor :: [PriceDirective] -> CommoditySymbol -> PriceStats
priceStatsFor [PriceDirective]
pds CommoditySymbol
c =
  let xs :: [PriceDirective]
xs  = (PriceDirective -> Bool) -> [PriceDirective] -> [PriceDirective]
forall a. (a -> Bool) -> [a] -> [a]
filter ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c) (CommoditySymbol -> Bool)
-> (PriceDirective -> CommoditySymbol) -> PriceDirective -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> CommoditySymbol
toCurrencyCode (CommoditySymbol -> CommoditySymbol)
-> (PriceDirective -> CommoditySymbol)
-> PriceDirective
-> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> CommoditySymbol
pdcommodity) [PriceDirective]
pds
      dset :: Set Day
dset = [Day] -> Set Day
forall a. Ord a => [a] -> Set a
S.fromList ((PriceDirective -> Day) -> [PriceDirective] -> [Day]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> Day
pddate [PriceDirective]
xs)
  in CommoditySymbol
-> Int -> Maybe Day -> Maybe Day -> Set Day -> PriceStats
PriceStats CommoditySymbol
c ([PriceDirective] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [PriceDirective]
xs)
       ((Day, Set Day) -> Day
forall a b. (a, b) -> a
fst ((Day, Set Day) -> Day) -> Maybe (Day, Set Day) -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Set Day -> Maybe (Day, Set Day)
forall a. Set a -> Maybe (a, Set a)
S.minView Set Day
dset)
       ((Day, Set Day) -> Day
forall a b. (a, b) -> a
fst ((Day, Set Day) -> Day) -> Maybe (Day, Set Day) -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Set Day -> Maybe (Day, Set Day)
forall a. Set a -> Maybe (a, Set a)
S.maxView Set Day
dset)
       Set Day
dset

isWeekday :: Day -> Bool
isWeekday :: Day -> Bool
isWeekday Day
d = case Day -> DayOfWeek
dayOfWeek Day
d of
  DayOfWeek
Saturday -> Bool
False
  DayOfWeek
Sunday   -> Bool
False
  DayOfWeek
_        -> Bool
True

-- | Compact human duration: "45d", "11mo", "1y 3mo".
-- Approximates with 365-day years and 30-day months — display only.
compactDuration :: Int -> T.Text
compactDuration :: Int -> CommoditySymbol
compactDuration Int
n
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
60    = String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show Int
n) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"d"
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
365   = String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show (Int
n Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
30)) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"mo"
  | Bool
otherwise =
      let (Int
y, Int
r) = Int
n Int -> Int -> (Int, Int)
forall a. Integral a => a -> a -> (a, a)
`divMod` Int
365
          mo :: Int
mo     = Int
r Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
30
      in String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show Int
y) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"y" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<>
         (if Int
mo Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then CommoditySymbol
"" else CommoditySymbol
" " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show Int
mo) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"mo")

-- | The text for the period and coverage columns of a stats row.
-- Both are blank when the commodity has fewer than two prices.
-- Coverage is computed on a weekdays-only basis (Mon–Fri), so
-- weekday-only sources (eg FX) approach 100% rather than ~71%.
periodAndCoverage :: PriceStats -> (T.Text, T.Text)
periodAndCoverage :: PriceStats -> (CommoditySymbol, CommoditySymbol)
periodAndCoverage ps :: PriceStats
ps@PriceStats{psEarliest :: PriceStats -> Maybe Day
psEarliest=Just Day
s, psLatest :: PriceStats -> Maybe Day
psLatest=Just Day
e}
  | PriceStats -> Int
psCount PriceStats
ps Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 = (CommoditySymbol
"", CommoditySymbol
"")
  | Bool
otherwise      = (Int -> CommoditySymbol
compactDuration Int
nDays, String -> CommoditySymbol
T.pack (String -> Double -> String
forall r. PrintfType r => String -> r
printf String
"%.f%%" Double
pct))
  where
    days :: [Day]
days      = [Day
s..Day
e]
    nDays :: Int
nDays     = [Day] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Day]
days
    weekdays :: [Day]
weekdays  = (Day -> Bool) -> [Day] -> [Day]
forall a. (a -> Bool) -> [a] -> [a]
filter Day -> Bool
isWeekday [Day]
days
    nWeekdays :: Int
nWeekdays = [Day] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Day]
weekdays
    nCovered :: Int
nCovered  = [Day] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Day -> Bool) -> [Day] -> [Day]
forall a. (a -> Bool) -> [a] -> [a]
filter (Day -> Set Day -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` PriceStats -> Set Day
psDays PriceStats
ps) [Day]
weekdays)
    pct :: Double
pct | Int
nWeekdays Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 = Double
0
        | Bool
otherwise      =
            Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
nCovered Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
nWeekdays Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
100 :: Double
periodAndCoverage PriceStats
_ = (CommoditySymbol
"", CommoditySymbol
"")

-- | Render the per-commodity summary table.
-- Lists every commodity used in the journal except the base currency,
-- normalised to ISO codes and deduplicated. The 'cur:' portion of the
-- query (if any) narrows the listed commodities. The supplied price
-- directives (already query-filtered by the caller) drive the counts.
pricesSummary :: Journal -> Query -> [PriceDirective] -> T.Text
pricesSummary :: Journal -> Query -> [PriceDirective] -> CommoditySymbol
pricesSummary Journal
j Query
q [PriceDirective]
pds =
  let
    base :: CommoditySymbol
base    = Journal -> CommoditySymbol
journalBaseCurrencyCode Journal
j
    -- Just the cur: terms of the query; non-cur terms become Any so
    -- they don't reject every commodity.
    symq :: Query
symq    = (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsCur Query
q
    codes :: [CommoditySymbol]
codes   = [CommoditySymbol] -> [CommoditySymbol]
forall a. Ord a => [a] -> [a]
sort ([CommoditySymbol] -> [CommoditySymbol])
-> ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol]
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [CommoditySymbol] -> [CommoditySymbol]
forall a. Eq a => [a] -> [a]
nub ([CommoditySymbol] -> [CommoditySymbol])
-> ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol]
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol -> Bool) -> [CommoditySymbol] -> [CommoditySymbol]
forall a. (a -> Bool) -> [a] -> [a]
filter (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
base) ([CommoditySymbol] -> [CommoditySymbol])
-> ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol]
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol -> Bool) -> [CommoditySymbol] -> [CommoditySymbol]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> CommoditySymbol -> Bool
matchesCommodity Query
symq)
              ([CommoditySymbol] -> [CommoditySymbol])
-> ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol]
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> CommoditySymbol
toCurrencyCode
              ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ Journal -> [CommoditySymbol]
journalCommoditiesUsed Journal
j
    rows :: [[CommoditySymbol]]
rows    = (CommoditySymbol -> [CommoditySymbol])
-> [CommoditySymbol] -> [[CommoditySymbol]]
forall a b. (a -> b) -> [a] -> [b]
map (PriceStats -> [CommoditySymbol]
statsRow (PriceStats -> [CommoditySymbol])
-> (CommoditySymbol -> PriceStats)
-> CommoditySymbol
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [PriceDirective] -> CommoditySymbol -> PriceStats
priceStatsFor [PriceDirective]
pds) [CommoditySymbol]
codes
    header :: [CommoditySymbol]
header  = [CommoditySymbol
"Commodity", CommoditySymbol
"Prices", CommoditySymbol
"Earliest", CommoditySymbol
"Latest", CommoditySymbol
"Period", CommoditySymbol
"Coverage"]
    aligns :: [ColAlign]
aligns  = [ColAlign
AlignL, ColAlign
AlignR, ColAlign
AlignL, ColAlign
AlignL, ColAlign
AlignR, ColAlign
AlignR]
  in [ColAlign] -> [[CommoditySymbol]] -> CommoditySymbol
renderColumns [ColAlign]
aligns ([CommoditySymbol]
header [CommoditySymbol] -> [[CommoditySymbol]] -> [[CommoditySymbol]]
forall a. a -> [a] -> [a]
: [[CommoditySymbol]]
rows)

statsRow :: PriceStats -> [T.Text]
statsRow :: PriceStats -> [CommoditySymbol]
statsRow PriceStats
ps =
  let (CommoditySymbol
perTxt, CommoditySymbol
covTxt) = PriceStats -> (CommoditySymbol, CommoditySymbol)
periodAndCoverage PriceStats
ps
  in [ PriceStats -> CommoditySymbol
psCommodity PriceStats
ps
     , String -> CommoditySymbol
T.pack (Int -> String
forall a. Show a => a -> String
show (PriceStats -> Int
psCount PriceStats
ps))
     , CommoditySymbol
-> (Day -> CommoditySymbol) -> Maybe Day -> CommoditySymbol
forall b a. b -> (a -> b) -> Maybe a -> b
maybe CommoditySymbol
"-" (String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> (Day -> String) -> Day -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> String
forall a. Show a => a -> String
show) (PriceStats -> Maybe Day
psEarliest PriceStats
ps)
     , CommoditySymbol
-> (Day -> CommoditySymbol) -> Maybe Day -> CommoditySymbol
forall b a. b -> (a -> b) -> Maybe a -> b
maybe CommoditySymbol
"-" (String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> (Day -> String) -> Day -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> String
forall a. Show a => a -> String
show) (PriceStats -> Maybe Day
psLatest PriceStats
ps)
     , CommoditySymbol
perTxt
     , CommoditySymbol
covTxt
     ]

data ColAlign = AlignL | AlignR

-- | Render a list of equal-length rows as a column-aligned plain-text
-- table, two spaces between columns, one row per line.
renderColumns :: [ColAlign] -> [[T.Text]] -> T.Text
renderColumns :: [ColAlign] -> [[CommoditySymbol]] -> CommoditySymbol
renderColumns [ColAlign]
aligns [[CommoditySymbol]]
rs =
  let widths :: [Int]
widths = ([CommoditySymbol] -> Int) -> [[CommoditySymbol]] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ([Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum ([Int] -> Int)
-> ([CommoditySymbol] -> [Int]) -> [CommoditySymbol] -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol -> Int) -> [CommoditySymbol] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> Int
T.length) ([[CommoditySymbol]] -> [[CommoditySymbol]]
forall a. [[a]] -> [[a]]
transpose [[CommoditySymbol]]
rs)
      pad :: ColAlign -> Int -> CommoditySymbol -> CommoditySymbol
pad ColAlign
a Int
w CommoditySymbol
t = case ColAlign
a of ColAlign
AlignL -> Int -> Char -> CommoditySymbol -> CommoditySymbol
T.justifyLeft Int
w Char
' ' CommoditySymbol
t
                            ColAlign
AlignR -> Int -> Char -> CommoditySymbol -> CommoditySymbol
T.justifyRight Int
w Char
' ' CommoditySymbol
t
      renderRow :: [CommoditySymbol] -> CommoditySymbol
renderRow [CommoditySymbol]
r = CommoditySymbol -> CommoditySymbol
T.stripEnd (CommoditySymbol -> [CommoditySymbol] -> CommoditySymbol
T.intercalate CommoditySymbol
"  " ((ColAlign -> Int -> CommoditySymbol -> CommoditySymbol)
-> [ColAlign] -> [Int] -> [CommoditySymbol] -> [CommoditySymbol]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 ColAlign -> Int -> CommoditySymbol -> CommoditySymbol
pad [ColAlign]
aligns [Int]
widths [CommoditySymbol]
r))
  in [CommoditySymbol] -> CommoditySymbol
T.unlines (([CommoditySymbol] -> CommoditySymbol)
-> [[CommoditySymbol]] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map [CommoditySymbol] -> CommoditySymbol
renderRow [[CommoditySymbol]]
rs)

-- XXX performance
-- | Append any new price directives (with different from commodity,
-- to commodity, or date) from the second list to the first.
-- (Does not remove redundant prices from the first; just avoids adding more.)
mergePriceDirectives :: [PriceDirective] -> [PriceDirective] -> [PriceDirective]
mergePriceDirectives :: [PriceDirective] -> [PriceDirective] -> [PriceDirective]
mergePriceDirectives [PriceDirective]
pds1 [PriceDirective]
pds2 =
  [PriceDirective]
pds1 [PriceDirective] -> [PriceDirective] -> [PriceDirective]
forall a. [a] -> [a] -> [a]
++ [ PriceDirective
pd | PriceDirective
pd <- [PriceDirective]
pds2 , PriceDirective -> (Day, CommoditySymbol, CommoditySymbol)
pdid PriceDirective
pd (Day, CommoditySymbol, CommoditySymbol)
-> [(Day, CommoditySymbol, CommoditySymbol)] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [(Day, CommoditySymbol, CommoditySymbol)]
pds1ids ]
  where
    pds1ids :: [(Day, CommoditySymbol, CommoditySymbol)]
pds1ids = (PriceDirective -> (Day, CommoditySymbol, CommoditySymbol))
-> [PriceDirective] -> [(Day, CommoditySymbol, CommoditySymbol)]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> (Day, CommoditySymbol, CommoditySymbol)
pdid [PriceDirective]
pds1
    pdid :: PriceDirective -> (Day, CommoditySymbol, CommoditySymbol)
pdid PriceDirective{Day
pddate :: PriceDirective -> Day
pddate :: Day
pddate,CommoditySymbol
pdcommodity :: PriceDirective -> CommoditySymbol
pdcommodity :: CommoditySymbol
pdcommodity,Amount
pdamount :: PriceDirective -> Amount
pdamount :: Amount
pdamount} = (Day
pddate, CommoditySymbol
pdcommodity, Amount -> CommoditySymbol
acommodity Amount
pdamount)

-- | Convert a market price directive to a corresponding one in the
-- opposite direction, if possible. (A price directive with a zero
-- price can't be reversed.)
--
-- The price's display precision will be set to show all significant
-- decimal digits (or if they appear infinite, a smaller default precision (8).
-- This is visible eg in the prices command's output.
--
reversePriceDirective :: PriceDirective -> Maybe PriceDirective
reversePriceDirective :: PriceDirective -> Maybe PriceDirective
reversePriceDirective pd :: PriceDirective
pd@PriceDirective{pdcommodity :: PriceDirective -> CommoditySymbol
pdcommodity=CommoditySymbol
c, pdamount :: PriceDirective -> Amount
pdamount=Amount
a}
  | Amount -> Bool
amountIsZero Amount
a = Maybe PriceDirective
forall a. Maybe a
Nothing
  | Bool
otherwise      = PriceDirective -> Maybe PriceDirective
forall a. a -> Maybe a
Just PriceDirective
pd{pdcommodity=acommodity a, pdamount=a'}
    where
      lbl :: String -> String -> String
lbl = String -> String -> String -> String
lbl_ String
"reversePriceDirective"
      a' :: Amount
a' =
        Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo (Word8 -> Maybe Word8
forall a. a -> Maybe a
Just Word8
defaultMaxDisplayPrecision) (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$
        Amount -> Amount
invertAmount Amount
a{acommodity=c}
        Amount -> (Amount -> Amount) -> Amount
forall a b. a -> (a -> b) -> b
& (Amount -> String) -> Amount -> Amount
forall a. (a -> String) -> a -> a
dbg9With (String -> String -> String
lbl String
"calculated reverse price"(String -> String) -> (Amount -> String) -> Amount -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Amount -> String
showAmount)
        -- & dbg9With (lbl "precision of reverse price".show.amountDisplayPrecision)