{-# LANGUAGE CPP                 #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Rank2Types          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections       #-}
{-# LANGUAGE RecordWildCards     #-}

{-|

A 'Journal' is a set of transactions, plus optional related data.  This is
hledger's primary data object. It is usually parsed from a journal file or
other data format (see "Hledger.Read").

-}

module Hledger.Data.Journal (
  -- * Parsing helpers
  JournalParser,
  ErroringJournalParser,
  addPriceDirective,
  addTransactionModifier,
  addJournalItem,
  addTransactionItem,
  addPeriodicTransaction,
  addAssertDirective,
  addTransaction,
  journalDbg,
  journalInferMarketPricesFromTransactions,
  journalApplyCommodityAliases,
  CommodityAliases,
  journalCommodityAliases,
  convertAliasAmount,
  commodityAliases,
  commodityRedeclare,
  commodityCombine,
  commoditiesAndAliases,
  journalInferCommodityStyles,
  journalStyleAmounts,
  journalCommodityStyles,
  journalCommodityStylesWith,
  journalToCost,
  journalInferEquityFromCosts,
  journalTagCostsAndEquityAndMaybeInferCosts,
  journalReverse,
  journalSetLastReadTime,
  journalRenumberAccountDeclarations,
  journalPivot,
  journalPostingsAddAccountTags,
  journalPostingsKeepAccountTagsOnly,
  journalPostingsAddCommodityTags,
  journalInferPostingsTransactedCost,
  journalCommodityUsesLots,
  journalAccountUsesNoLots,
  journalAccountLotsTags,
  accountUsesNoLotsWith,
  journalLotfulCommodities,
  journalCommodityLotsMethod,
  postingLotsMethod,
  parseReductionMethod,
  journalCheckLotsTagValues,
-- * Filtering
  filterJournalTransactions,
  filterJournalPostings,
  filterJournalRelatedPostings,
  filterJournalAmounts,
  filterTransactionAmounts,
  filterTransactionPostings,
  filterTransactionPostingsExtra,
  filterTransactionRelatedPostings,
  filterPostingAmount,
  -- * Mapping
  journalMapTransactions,
  journalMapPostings,
  journalMapPostingAmounts,
  -- * Querying
  journalAccountNamesUsed,
  journalAccountNamesImplied,
  journalAccountNamesDeclared,
  journalAccountNamesDeclaredOrUsed,
  journalAccountNamesDeclaredOrImplied,
  journalAccountNames,
  journalLeafAccountNames,
  journalAccountNameTree,
  journalAccountTags,
  journalCommodityTags,
  journalInheritedAccountTags,
  -- journalAmountAndPriceCommodities,
  -- journalAmountStyles,
  -- overJournalAmounts,
  -- traverseJournalAmounts,
  -- journalCanonicalCommodities,
  journalPayeesDeclared,
  journalPayeesUsed,
  journalPayeesDeclaredOrUsed,
  journalTagsDeclared,
  journalTagsUsed,
  journalTagsDeclaredOrUsed,
  journalAmounts,
  journalPostingAmounts,
  journalPostingAndCostAmounts,
  journalCommoditiesDeclared,
  journalCommoditiesUsed,
  journalCommodities,
  journalCommoditiesFromPriceDirectives,
  journalCommoditiesFromTransactions,
  journalBaseCurrency,
  journalBaseCurrencyCode,
  journalDateSpan,
  journalDateSpanBothDates,
  journalStartDate,
  journalEndDate,
  journalLastDay,
  journalDescriptions,
  journalFilePath,
  journalFilePaths,
  journalAllFilePaths,
  journalTransactionAt,
  journalNextTransaction,
  journalPrevTransaction,
  journalPostings,
  showJournalPostingAmountsDebug,
  journalTransactionsSimilarTo,
  -- * Account types
  journalAccountType,
  journalAccountTypes,
  journalAddAccountTypes,
  -- * Conversion accounts
  defaultBaseConversionAccount,
  journalAccountForType,
  journalBaseConversionAccount,
  journalConversionAccounts,
  -- * Gain accounts
  defaultGainAccount,
  journalBaseGainAccount,
  journalGainAccounts,
  -- * Misc
  nulljournal,
  journalConcat,
  journalNumberTransactions,
  journalNumberAndTieTransactions,
  journalTieTransactions,
  journalUntieTransactions,
  journalModifyTransactions,
  journalApplyAliases,
  dbgJournalAcctDeclOrder,
  -- * Tests
  samplejournal,
  samplejournalMaybeExplicit,
  tests_Journal,
  --
)
where

import Control.Applicative ((<|>))
import Control.Monad.Except (ExceptT(..))
import Control.Monad.State.Strict (StateT)
import Data.Char (toUpper, isDigit)
import Data.Containers.ListUtils (nubOrd)
import Data.Decimal (normalizeDecimal)
import Data.Default (Default(..))
import Data.Foldable (toList)
import Data.Function ((&), on)
import Data.List (find, intercalate, minimumBy, sortBy, union, unionBy, (\\))
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.List.Extra (nubSort)
import Data.Array qualified as A
import Data.Map.Strict qualified as M
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybeToList)
import Data.Ord (comparing)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time.Calendar (Day(..), addDays, diffDays, fromGregorian)
import Data.Time.Clock.POSIX (POSIXTime)
import Data.Tree (Tree (..), flatten)
import Safe (headMay, headDef, maximumMay, minimumMay)
import System.FilePath (takeFileName)
import Text.Printf (printf)
import Text.Megaparsec (ParsecT)

import Hledger.Utils
import Hledger.Data.Types
import Hledger.Data.AccountName
import Hledger.Data.AccountType (accountTypeLotDirection, isEquityType, lotDirectionSign)
import Hledger.Data.Amount
import Hledger.Data.Currency (CurrencyCode, toCurrencyCode)
import Hledger.Data.Errors (makeAccountTagErrorExcerpt, makeCommodityTagErrorExcerpt)
import Hledger.Data.Posting
import Hledger.Data.Transaction
import Hledger.Data.TransactionModifier
import Hledger.Data.Valuation
import Hledger.Query


-- | A parser of text that runs in some monad, keeping a Journal as state.
type JournalParser m a = StateT Journal (ParsecT HledgerParseErrorData Text m) a

-- | A parser of text that runs in some monad, keeping a Journal as
-- state, that can throw an exception to end parsing, preventing
-- further parser backtracking.
type ErroringJournalParser m a =
  StateT Journal (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a

-- deriving instance Show Journal
instance Show Journal where
  show :: Journal -> RegexError
show Journal
j
    | Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
3 = RegexError -> RegexError -> Int -> Int -> RegexError
forall r. PrintfType r => RegexError -> r
printf RegexError
"Journal %s with %d transactions, %d accounts"
             (Journal -> RegexError
journalFilePath Journal
j)
             ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Transaction] -> Int) -> [Transaction] -> Int
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j)
             ([TagName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TagName]
accounts)
    | Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
6 = RegexError -> RegexError -> Int -> Int -> ShowS
forall r. PrintfType r => RegexError -> r
printf RegexError
"Journal %s with %d transactions, %d accounts: %s"
             (Journal -> RegexError
journalFilePath Journal
j)
             ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Transaction] -> Int) -> [Transaction] -> Int
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j)
             ([TagName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TagName]
accounts)
             ([TagName] -> RegexError
forall a. Show a => a -> RegexError
show [TagName]
accounts)
    | Bool
otherwise = RegexError -> RegexError -> Int -> Int -> RegexError -> ShowS
forall r. PrintfType r => RegexError -> r
printf RegexError
"Journal %s with %d transactions, %d accounts: %s, commodity styles: %s"
             (Journal -> RegexError
journalFilePath Journal
j)
             ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Transaction] -> Int) -> [Transaction] -> Int
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j)
             ([TagName] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TagName]
accounts)
             ([TagName] -> RegexError
forall a. Show a => a -> RegexError
show [TagName]
accounts)
             (Map TagName AmountStyle -> RegexError
forall a. Show a => a -> RegexError
show (Map TagName AmountStyle -> RegexError)
-> Map TagName AmountStyle -> RegexError
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName AmountStyle
jinferredcommoditystyles Journal
j)
             -- ++ (show $ journalTransactions l)
             where accounts :: [TagName]
accounts = (TagName -> Bool) -> [TagName] -> [TagName]
forall a. (a -> Bool) -> [a] -> [a]
filter (TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
/= TagName
"root") ([TagName] -> [TagName]) -> [TagName] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Tree TagName -> [TagName]
forall a. Tree a -> [a]
flatten (Tree TagName -> [TagName]) -> Tree TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$ Journal -> Tree TagName
journalAccountNameTree Journal
j

journalDbg :: Journal -> RegexError
journalDbg j :: Journal
j@Journal{[Maybe Integer]
[(RegexError, RegexError)]
[(RegexError, [RegexError])]
[(TagName, AccountDeclarationInfo)]
[(TagName, TagDeclarationInfo)]
[(TagName, PayeeDeclarationInfo)]
[TagName]
[JournalFile]
[JournalItem]
[MarketPrice]
[PriceDirective]
[TimeclockEntry]
[AssertDirective]
[PeriodicTransaction]
[TransactionModifier]
[Transaction]
[AccountAlias]
Maybe Char
Maybe Integer
Maybe (TagName, AmountStyle)
Maybe ParsePos
Map TagName [Tag]
Map TagName Commodity
Map TagName AmountStyle
Map TagName AccountType
Map AccountType [TagName]
Set TagName
Set AmountStyle
POSIXTime
FastPathStats
jtxns :: Journal -> [Transaction]
jinferredcommoditystyles :: Journal -> Map TagName AmountStyle
jparsedefaultyear :: Maybe Integer
jparseapplyyears :: [Maybe Integer]
jparsedefaultcommodity :: Maybe (TagName, AmountStyle)
jparsedecimalmark :: Maybe Char
jparseparentaccounts :: [TagName]
jparsealiases :: [AccountAlias]
jparseoptaliases :: [AccountAlias]
jparsetimeclockentries :: [TimeclockEntry]
jparseincludefilestack :: [(RegexError, RegexError)]
jparsepos :: Maybe ParsePos
jparseamountstyles :: Set AmountStyle
jparsetexts :: Set TagName
jparsefastpathstats :: FastPathStats
jdeclaredpayees :: [(TagName, PayeeDeclarationInfo)]
jdeclaredtags :: [(TagName, TagDeclarationInfo)]
jdeclaredaccounts :: [(TagName, AccountDeclarationInfo)]
jdeclaredaccounttags :: Map TagName [Tag]
jdeclaredaccounttypes :: Map AccountType [TagName]
jaccounttypes :: Map TagName AccountType
jdeclaredcommodities :: Map TagName Commodity
jdeclaredcommoditytags :: Map TagName [Tag]
jinferredcommoditystyles :: Map TagName AmountStyle
jglobalcommoditystyles :: Map TagName AmountStyle
jpricedirectives :: [PriceDirective]
jinferredmarketprices :: [MarketPrice]
jtxnmodifiers :: [TransactionModifier]
jperiodictxns :: [PeriodicTransaction]
jasserts :: [AssertDirective]
jtxns :: [Transaction]
jitems :: [JournalItem]
jfiles :: [JournalFile]
jauxfiles :: [(RegexError, [RegexError])]
jlastreadtime :: POSIXTime
jlastreadtime :: Journal -> POSIXTime
jauxfiles :: Journal -> [(RegexError, [RegexError])]
jfiles :: Journal -> [JournalFile]
jitems :: Journal -> [JournalItem]
jasserts :: Journal -> [AssertDirective]
jperiodictxns :: Journal -> [PeriodicTransaction]
jtxnmodifiers :: Journal -> [TransactionModifier]
jinferredmarketprices :: Journal -> [MarketPrice]
jpricedirectives :: Journal -> [PriceDirective]
jglobalcommoditystyles :: Journal -> Map TagName AmountStyle
jdeclaredcommoditytags :: Journal -> Map TagName [Tag]
jdeclaredcommodities :: Journal -> Map TagName Commodity
jaccounttypes :: Journal -> Map TagName AccountType
jdeclaredaccounttypes :: Journal -> Map AccountType [TagName]
jdeclaredaccounttags :: Journal -> Map TagName [Tag]
jdeclaredaccounts :: Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredtags :: Journal -> [(TagName, TagDeclarationInfo)]
jdeclaredpayees :: Journal -> [(TagName, PayeeDeclarationInfo)]
jparsefastpathstats :: Journal -> FastPathStats
jparsetexts :: Journal -> Set TagName
jparseamountstyles :: Journal -> Set AmountStyle
jparsepos :: Journal -> Maybe ParsePos
jparseincludefilestack :: Journal -> [(RegexError, RegexError)]
jparsetimeclockentries :: Journal -> [TimeclockEntry]
jparseoptaliases :: Journal -> [AccountAlias]
jparsealiases :: Journal -> [AccountAlias]
jparseparentaccounts :: Journal -> [TagName]
jparsedecimalmark :: Journal -> Maybe Char
jparsedefaultcommodity :: Journal -> Maybe (TagName, AmountStyle)
jparseapplyyears :: Journal -> [Maybe Integer]
jparsedefaultyear :: Journal -> Maybe Integer
..} = ShowS
chomp ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$ [RegexError] -> RegexError
unlines ([RegexError] -> RegexError) -> [RegexError] -> RegexError
forall a b. (a -> b) -> a -> b
$
  (RegexError
"Journal " RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++ ShowS
takeFileName (Journal -> RegexError
journalFilePath Journal
j)RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++RegexError
":") RegexError -> [RegexError] -> [RegexError]
forall a. a -> [a] -> [a]
:  --  ++ " {"
  ShowS -> [RegexError] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map (RegexError
" "RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>) [
   RegexError
"jparsedefaultyear: "         RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Maybe Integer -> RegexError
forall a. Show a => a -> RegexError
shw Maybe Integer
jparsedefaultyear
  ,RegexError
"jparseapplyyears: "          RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [Maybe Integer] -> RegexError
forall a. Show a => a -> RegexError
shw [Maybe Integer]
jparseapplyyears
  ,RegexError
"jparsedefaultcommodity: "    RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Maybe (TagName, AmountStyle) -> RegexError
forall a. Show a => a -> RegexError
shw Maybe (TagName, AmountStyle)
jparsedefaultcommodity
  ,RegexError
"jparsedecimalmark: "         RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Maybe Char -> RegexError
forall a. Show a => a -> RegexError
shw Maybe Char
jparsedecimalmark
  ,RegexError
"jparseparentaccounts: "      RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [TagName] -> RegexError
forall a. Show a => a -> RegexError
shw [TagName]
jparseparentaccounts
  ,RegexError
"jparsealiases: "             RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [AccountAlias] -> RegexError
forall a. Show a => a -> RegexError
shw [AccountAlias]
jparsealiases
  ,RegexError
"jparseoptaliases: "          RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [AccountAlias] -> RegexError
forall a. Show a => a -> RegexError
shw [AccountAlias]
jparseoptaliases
  -- ,"jparsetimeclockentries: " <> shw jparsetimeclockentries
  ,RegexError
"jparseincludefilestack: "    RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(RegexError, RegexError)] -> RegexError
forall a. Show a => a -> RegexError
shw [(RegexError, RegexError)]
jparseincludefilestack
  ,RegexError
"jdeclaredpayees: "           RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, PayeeDeclarationInfo)] -> RegexError
forall a. Show a => a -> RegexError
shw [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees
  ,RegexError
"jdeclaredtags: "             RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, TagDeclarationInfo)] -> RegexError
forall a. Show a => a -> RegexError
shw [(TagName, TagDeclarationInfo)]
jdeclaredtags
  ,RegexError
"jdeclaredaccounts: "         RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, AccountDeclarationInfo)] -> RegexError
forall a. Show a => a -> RegexError
shw [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts
  ,RegexError
"jdeclaredaccounttags: "      RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map TagName [Tag] -> RegexError
forall a. Show a => a -> RegexError
shw Map TagName [Tag]
jdeclaredaccounttags
  ,RegexError
"jdeclaredaccounttypes: "     RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map AccountType [TagName] -> RegexError
forall a. Show a => a -> RegexError
shw Map AccountType [TagName]
jdeclaredaccounttypes
  ,RegexError
"jaccounttypes: "             RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map TagName AccountType -> RegexError
forall a. Show a => a -> RegexError
shw Map TagName AccountType
jaccounttypes
  ,RegexError
"jdeclaredcommodities: "      RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map TagName Commodity -> RegexError
forall a. Show a => a -> RegexError
shw Map TagName Commodity
jdeclaredcommodities
  ,RegexError
"jinferredcommoditystyles: "  RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle -> RegexError
forall a. Show a => a -> RegexError
shw Map TagName AmountStyle
jinferredcommoditystyles
  ,RegexError
"jglobalcommoditystyles: "    RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle -> RegexError
forall a. Show a => a -> RegexError
shw Map TagName AmountStyle
jglobalcommoditystyles
  ,RegexError
"jpricedirectives: "          RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [PriceDirective] -> RegexError
forall a. Show a => a -> RegexError
shw [PriceDirective]
jpricedirectives
  ,RegexError
"jinferredmarketprices: "     RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [MarketPrice] -> RegexError
forall a. Show a => a -> RegexError
shw [MarketPrice]
jinferredmarketprices
  ,RegexError
"jtxnmodifiers: "             RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [TransactionModifier] -> RegexError
forall a. Show a => a -> RegexError
shw [TransactionModifier]
jtxnmodifiers
  -- ,"jperiodictxns: "          <> shw jperiodictxns
  ,RegexError
"jasserts: "                  RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [AssertDirective] -> RegexError
forall a. Show a => a -> RegexError
shw [AssertDirective]
jasserts
  ,RegexError
"jtxns: "                     RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [Transaction] -> RegexError
forall a. Show a => a -> RegexError
shw [Transaction]
jtxns
  ,RegexError
"jitems: "                    RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Int -> RegexError
forall a. Show a => a -> RegexError
shw ([JournalItem] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [JournalItem]
jitems)
  ,RegexError
"jfiles: "                    RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [JournalFile] -> RegexError
forall a. Show a => a -> RegexError
shw [JournalFile]
jfiles
  ,RegexError
"jauxfiles: "                 RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(RegexError, [RegexError])] -> RegexError
forall a. Show a => a -> RegexError
shw [(RegexError, [RegexError])]
jauxfiles
  ,RegexError
"jlastreadtime: "             RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> POSIXTime -> RegexError
forall a. Show a => a -> RegexError
shw POSIXTime
jlastreadtime
  ]
  -- ++ ["}"]
  where
    shw :: Show a => a -> String
    shw :: forall a. Show a => a -> RegexError
shw = a -> RegexError
forall a. Show a => a -> RegexError
show
    -- shw = pshow

-- The semigroup instance for Journal is useful for two situations.
--
-- 1. concatenating finalised journals, eg with multiple -f options:
-- FIRST <> SECOND.
--
-- 2. merging a child parsed journal, eg with the include directive:
-- CHILD <> PARENT. A parsed journal's data is in reverse order, so
-- this gives what we want.
--
-- Note that (<>) is right-biased, so nulljournal is only a left identity.
-- In particular, this prevents Journal from being a monoid.
instance Semigroup Journal where Journal
j1 <> :: Journal -> Journal -> Journal
<> Journal
j2 = Journal
j1 Journal -> Journal -> Journal
`journalConcat` Journal
j2

-- | Merge two journals into one.
-- Transaction counts are summed, map fields are combined,
-- the second's list fields are appended to the first's,
-- the second's parse state is kept.
journalConcat :: Journal -> Journal -> Journal
journalConcat :: Journal -> Journal -> Journal
journalConcat Journal
j1 Journal
j2 =
  let
    f1 :: RegexError
f1 = ShowS
takeFileName ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$ Journal -> RegexError
journalFilePath Journal
j1
    f2 :: RegexError
f2 = RegexError -> ShowS -> Maybe RegexError -> RegexError
forall b a. b -> (a -> b) -> Maybe a -> b
maybe RegexError
"(unknown)" ShowS
takeFileName (Maybe RegexError -> RegexError) -> Maybe RegexError -> RegexError
forall a b. (a -> b) -> a -> b
$ ((RegexError, RegexError) -> RegexError)
-> Maybe (RegexError, RegexError) -> Maybe RegexError
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (RegexError, RegexError) -> RegexError
forall a b. (a, b) -> a
fst (Maybe (RegexError, RegexError) -> Maybe RegexError)
-> Maybe (RegexError, RegexError) -> Maybe RegexError
forall a b. (a -> b) -> a -> b
$ [(RegexError, RegexError)] -> Maybe (RegexError, RegexError)
forall a. [a] -> Maybe a
headMay ([(RegexError, RegexError)] -> Maybe (RegexError, RegexError))
-> [(RegexError, RegexError)] -> Maybe (RegexError, RegexError)
forall a b. (a -> b) -> a -> b
$ Journal -> [(RegexError, RegexError)]
jparseincludefilestack Journal
j2  -- XXX more accurate than journalFilePath for some reason
  in
    RegexError -> Journal -> Journal
dbgJournalAcctDeclOrder (RegexError
"journalConcat: " RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
f1 RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
" <> " RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
f2 RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
", acct decls renumbered: ") (Journal -> Journal) -> Journal -> Journal
forall a b. (a -> b) -> a -> b
$
    Journal -> Journal
journalRenumberAccountDeclarations (Journal -> Journal) -> Journal -> Journal
forall a b. (a -> b) -> a -> b
$
    RegexError -> Journal -> Journal
dbgJournalAcctDeclOrder (RegexError
"journalConcat: " RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
f1 RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
" <> " RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
f2 RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
", acct decls           : ") (Journal -> Journal) -> Journal -> Journal
forall a b. (a -> b) -> a -> b
$
    Journal {
     jparsedefaultyear :: Maybe Integer
jparsedefaultyear          = Journal -> Maybe Integer
jparsedefaultyear          Journal
j2
    ,jparseapplyyears :: [Maybe Integer]
jparseapplyyears           = Journal -> [Maybe Integer]
jparseapplyyears           Journal
j2
    ,jparsedefaultcommodity :: Maybe (TagName, AmountStyle)
jparsedefaultcommodity     = Journal -> Maybe (TagName, AmountStyle)
jparsedefaultcommodity     Journal
j2
    ,jparsedecimalmark :: Maybe Char
jparsedecimalmark          = Journal -> Maybe Char
jparsedecimalmark          Journal
j2
    ,jparseparentaccounts :: [TagName]
jparseparentaccounts       = Journal -> [TagName]
jparseparentaccounts       Journal
j2
    ,jparsealiases :: [AccountAlias]
jparsealiases              = Journal -> [AccountAlias]
jparsealiases              Journal
j2
    ,jparseoptaliases :: [AccountAlias]
jparseoptaliases           = Journal -> [AccountAlias]
jparseoptaliases           Journal
j2
    -- ,jparsetransactioncount     = jparsetransactioncount     j1 +  jparsetransactioncount     j2
    ,jparsetimeclockentries :: [TimeclockEntry]
jparsetimeclockentries     = Journal -> [TimeclockEntry]
jparsetimeclockentries     Journal
j1 [TimeclockEntry] -> [TimeclockEntry] -> [TimeclockEntry]
forall a. Semigroup a => a -> a -> a
<> Journal -> [TimeclockEntry]
jparsetimeclockentries     Journal
j2
    ,jparseincludefilestack :: [(RegexError, RegexError)]
jparseincludefilestack     = Journal -> [(RegexError, RegexError)]
jparseincludefilestack Journal
j2
    ,jparsepos :: Maybe ParsePos
jparsepos                  = Journal -> Maybe ParsePos
jparsepos Journal
j2
    ,jparseamountstyles :: Set AmountStyle
jparseamountstyles         = Journal -> Set AmountStyle
jparseamountstyles Journal
j2
    ,jparsetexts :: Set TagName
jparsetexts                = Journal -> Set TagName
jparsetexts Journal
j2
    ,jparsefastpathstats :: FastPathStats
jparsefastpathstats        = Journal -> FastPathStats
jparsefastpathstats Journal
j1 FastPathStats -> FastPathStats -> FastPathStats
forall a. Semigroup a => a -> a -> a
<> Journal -> FastPathStats
jparsefastpathstats Journal
j2
    ,jdeclaredpayees :: [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees            = Journal -> [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees            Journal
j1 [(TagName, PayeeDeclarationInfo)]
-> [(TagName, PayeeDeclarationInfo)]
-> [(TagName, PayeeDeclarationInfo)]
forall a. Semigroup a => a -> a -> a
<> Journal -> [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees            Journal
j2
    ,jdeclaredtags :: [(TagName, TagDeclarationInfo)]
jdeclaredtags              = Journal -> [(TagName, TagDeclarationInfo)]
jdeclaredtags              Journal
j1 [(TagName, TagDeclarationInfo)]
-> [(TagName, TagDeclarationInfo)]
-> [(TagName, TagDeclarationInfo)]
forall a. Semigroup a => a -> a -> a
<> Journal -> [(TagName, TagDeclarationInfo)]
jdeclaredtags              Journal
j2
    ,jdeclaredaccounts :: [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts          = Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts          Journal
j1 [(TagName, AccountDeclarationInfo)]
-> [(TagName, AccountDeclarationInfo)]
-> [(TagName, AccountDeclarationInfo)]
forall a. Semigroup a => a -> a -> a
<> Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts          Journal
j2
    --
    -- The next six fields are Maps, which need to be merged carefully for correct semantics,
    -- especially the first two, which have list values. There may still be room for improvement here.
    --
    -- ,jdeclaredaccounttags   :: M.Map AccountName [Tag]
    -- jdeclaredaccounttags can have multiple duplicated/conflicting values for an account's tag.
    ,jdeclaredaccounttags :: Map TagName [Tag]
jdeclaredaccounttags       = ([Tag] -> [Tag] -> [Tag])
-> Map TagName [Tag] -> Map TagName [Tag] -> Map TagName [Tag]
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith [Tag] -> [Tag] -> [Tag]
forall a. Semigroup a => a -> a -> a
(<>) (Journal -> Map TagName [Tag]
jdeclaredaccounttags Journal
j1) (Journal -> Map TagName [Tag]
jdeclaredaccounttags Journal
j2)
    --
    -- ,jdeclaredaccounttypes  :: M.Map AccountType [AccountName]
    -- jdeclaredaccounttypes can have multiple duplicated/conflicting values for an account's type.
    ,jdeclaredaccounttypes :: Map AccountType [TagName]
jdeclaredaccounttypes      = ([TagName] -> [TagName] -> [TagName])
-> Map AccountType [TagName]
-> Map AccountType [TagName]
-> Map AccountType [TagName]
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith [TagName] -> [TagName] -> [TagName]
forall a. Semigroup a => a -> a -> a
(<>) (Journal -> Map AccountType [TagName]
jdeclaredaccounttypes Journal
j1) (Journal -> Map AccountType [TagName]
jdeclaredaccounttypes Journal
j2)
    --
    -- ,jaccounttypes          :: M.Map AccountName AccountType
    -- jaccounttypes has a single type for any given account. When it had multiple type declarations, the last/rightmost wins.
    ,jaccounttypes :: Map TagName AccountType
jaccounttypes              = (AccountType -> AccountType -> AccountType)
-> Map TagName AccountType
-> Map TagName AccountType
-> Map TagName AccountType
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith ((AccountType -> AccountType)
-> AccountType -> AccountType -> AccountType
forall a b. a -> b -> a
const AccountType -> AccountType
forall a. a -> a
id) (Journal -> Map TagName AccountType
jaccounttypes Journal
j1) (Journal -> Map TagName AccountType
jaccounttypes Journal
j2)
    --
    -- ,jglobalcommoditystyles :: M.Map CommoditySymbol AmountStyle
    ,jglobalcommoditystyles :: Map TagName AmountStyle
jglobalcommoditystyles     = Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
(<>) (Journal -> Map TagName AmountStyle
jglobalcommoditystyles Journal
j1) (Journal -> Map TagName AmountStyle
jglobalcommoditystyles Journal
j2)
    --
    -- ,jdeclaredcommodities           :: M.Map CommoditySymbol Commodity
    -- A commodity declared in both is combined, preferring j1's declaration, see commodityCombine.
    -- (When merging an included file, j1 is the included file, whose declarations are the later ones.
    -- Files read with several -f options are combined differently, see Hledger.Read.combineCommodityDeclarations.)
    ,jdeclaredcommodities :: Map TagName Commodity
jdeclaredcommodities               = (Commodity -> Commodity -> Commodity)
-> Map TagName Commodity
-> Map TagName Commodity
-> Map TagName Commodity
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith Commodity -> Commodity -> Commodity
commodityCombine (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j1) (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j2)
    --
    -- ,jdeclaredcommoditytags     :: M.Map CommoditySymbol [Tag]
    ,jdeclaredcommoditytags :: Map TagName [Tag]
jdeclaredcommoditytags     = ([Tag] -> [Tag] -> [Tag])
-> Map TagName [Tag] -> Map TagName [Tag] -> Map TagName [Tag]
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith [Tag] -> [Tag] -> [Tag]
forall a. Semigroup a => a -> a -> a
(<>) (Journal -> Map TagName [Tag]
jdeclaredcommoditytags Journal
j1) (Journal -> Map TagName [Tag]
jdeclaredcommoditytags Journal
j2)
    --
    -- ,jinferredcommoditystyles   :: M.Map CommoditySymbol AmountStyle
    ,jinferredcommoditystyles :: Map TagName AmountStyle
jinferredcommoditystyles       = Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
(<>) (Journal -> Map TagName AmountStyle
jinferredcommoditystyles Journal
j1) (Journal -> Map TagName AmountStyle
jinferredcommoditystyles Journal
j2)
    --
    --
    ,jpricedirectives :: [PriceDirective]
jpricedirectives           = Journal -> [PriceDirective]
jpricedirectives           Journal
j1 [PriceDirective] -> [PriceDirective] -> [PriceDirective]
forall a. Semigroup a => a -> a -> a
<> Journal -> [PriceDirective]
jpricedirectives           Journal
j2
    ,jinferredmarketprices :: [MarketPrice]
jinferredmarketprices      = Journal -> [MarketPrice]
jinferredmarketprices      Journal
j1 [MarketPrice] -> [MarketPrice] -> [MarketPrice]
forall a. Semigroup a => a -> a -> a
<> Journal -> [MarketPrice]
jinferredmarketprices      Journal
j2
    ,jtxnmodifiers :: [TransactionModifier]
jtxnmodifiers              = Journal -> [TransactionModifier]
jtxnmodifiers              Journal
j1 [TransactionModifier]
-> [TransactionModifier] -> [TransactionModifier]
forall a. Semigroup a => a -> a -> a
<> Journal -> [TransactionModifier]
jtxnmodifiers              Journal
j2
    ,jperiodictxns :: [PeriodicTransaction]
jperiodictxns              = Journal -> [PeriodicTransaction]
jperiodictxns              Journal
j1 [PeriodicTransaction]
-> [PeriodicTransaction] -> [PeriodicTransaction]
forall a. Semigroup a => a -> a -> a
<> Journal -> [PeriodicTransaction]
jperiodictxns              Journal
j2
    ,jasserts :: [AssertDirective]
jasserts                   = Journal -> [AssertDirective]
jasserts                   Journal
j1 [AssertDirective] -> [AssertDirective] -> [AssertDirective]
forall a. Semigroup a => a -> a -> a
<> Journal -> [AssertDirective]
jasserts                   Journal
j2
    ,jtxns :: [Transaction]
jtxns                      = Journal -> [Transaction]
jtxns                      Journal
j1 [Transaction] -> [Transaction] -> [Transaction]
forall a. Semigroup a => a -> a -> a
<> Journal -> [Transaction]
jtxns                      Journal
j2
    ,jitems :: [JournalItem]
jitems                     = Journal -> [JournalItem]
jitems                     Journal
j1 [JournalItem] -> [JournalItem] -> [JournalItem]
forall a. Semigroup a => a -> a -> a
<> Journal -> [JournalItem]
jitems                     Journal
j2
    ,jfiles :: [JournalFile]
jfiles                     = Journal -> [JournalFile]
jfiles                     Journal
j1 [JournalFile] -> [JournalFile] -> [JournalFile]
forall a. Semigroup a => a -> a -> a
<> Journal -> [JournalFile]
jfiles                     Journal
j2
    ,jauxfiles :: [(RegexError, [RegexError])]
jauxfiles                  = Journal -> [(RegexError, [RegexError])]
jauxfiles                  Journal
j1 [(RegexError, [RegexError])]
-> [(RegexError, [RegexError])] -> [(RegexError, [RegexError])]
forall a. Semigroup a => a -> a -> a
<> Journal -> [(RegexError, [RegexError])]
jauxfiles                  Journal
j2
    ,jlastreadtime :: POSIXTime
jlastreadtime              = POSIXTime -> POSIXTime -> POSIXTime
forall a. Ord a => a -> a -> a
max (Journal -> POSIXTime
jlastreadtime Journal
j1) (Journal -> POSIXTime
jlastreadtime Journal
j2)
    }

-- | Renumber all the account declarations. This is useful to call when
-- finalising or concatenating Journals, to give account declarations
-- a total order across files.
journalRenumberAccountDeclarations :: Journal -> Journal
journalRenumberAccountDeclarations :: Journal -> Journal
journalRenumberAccountDeclarations Journal
j = Journal
j{jdeclaredaccounts=jdas'}
  where
    jdas' :: [(TagName, AccountDeclarationInfo)]
jdas' = [(TagName
a, AccountDeclarationInfo
adi{adideclarationorder=n}) | (Int
n, (TagName
a,AccountDeclarationInfo
adi)) <- [Int]
-> [(TagName, AccountDeclarationInfo)]
-> [(Int, (TagName, AccountDeclarationInfo))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
1..] ([(TagName, AccountDeclarationInfo)]
 -> [(Int, (TagName, AccountDeclarationInfo))])
-> [(TagName, AccountDeclarationInfo)]
-> [(Int, (TagName, AccountDeclarationInfo))]
forall a b. (a -> b) -> a -> b
$ Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts Journal
j]
    -- the per-file declaration order saved during parsing is discarded,
    -- it seems unneeded except perhaps for debugging

-- | Debug log the ordering of a journal's account declarations
-- (at debug level 7+).
dbgJournalAcctDeclOrder :: String -> Journal -> Journal
dbgJournalAcctDeclOrder :: RegexError -> Journal -> Journal
dbgJournalAcctDeclOrder RegexError
prefix =
  (Journal -> RegexError) -> Journal -> Journal
forall a. (a -> RegexError) -> a -> a
dbg7With ((RegexError
prefixRegexError -> ShowS
forall a. [a] -> [a] -> [a]
++) ShowS -> (Journal -> RegexError) -> Journal -> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(TagName, AccountDeclarationInfo)] -> RegexError
showAcctDeclsSummary ([(TagName, AccountDeclarationInfo)] -> RegexError)
-> (Journal -> [(TagName, AccountDeclarationInfo)])
-> Journal
-> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts)
  where
    showAcctDeclsSummary :: [(AccountName,AccountDeclarationInfo)] -> String
    showAcctDeclsSummary :: [(TagName, AccountDeclarationInfo)] -> RegexError
showAcctDeclsSummary [(TagName, AccountDeclarationInfo)]
adis
      | [(TagName, AccountDeclarationInfo)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(TagName, AccountDeclarationInfo)]
adis Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< (Int
2Int -> Int -> Int
forall a. Num a => a -> a -> a
*Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
2) = RegexError
"[" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, AccountDeclarationInfo)] -> RegexError
showadis [(TagName, AccountDeclarationInfo)]
adis RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
"]"
      | Bool
otherwise =
          RegexError
"[" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, AccountDeclarationInfo)] -> RegexError
showadis (Int
-> [(TagName, AccountDeclarationInfo)]
-> [(TagName, AccountDeclarationInfo)]
forall a. Int -> [a] -> [a]
take Int
n [(TagName, AccountDeclarationInfo)]
adis) RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
" ... " RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> [(TagName, AccountDeclarationInfo)] -> RegexError
showadis (Int
-> [(TagName, AccountDeclarationInfo)]
-> [(TagName, AccountDeclarationInfo)]
forall a. Int -> [a] -> [a]
takelast Int
n [(TagName, AccountDeclarationInfo)]
adis) RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
"]"
      where
        n :: Int
n = Int
3
        showadis :: [(TagName, AccountDeclarationInfo)] -> RegexError
showadis = RegexError -> [RegexError] -> RegexError
forall a. [a] -> [[a]] -> [a]
intercalate RegexError
", " ([RegexError] -> RegexError)
-> ([(TagName, AccountDeclarationInfo)] -> [RegexError])
-> [(TagName, AccountDeclarationInfo)]
-> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((TagName, AccountDeclarationInfo) -> RegexError)
-> [(TagName, AccountDeclarationInfo)] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, AccountDeclarationInfo) -> RegexError
showadi
        showadi :: (TagName, AccountDeclarationInfo) -> RegexError
showadi (TagName
a,AccountDeclarationInfo
adi) = RegexError
"("RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>Int -> RegexError
forall a. Show a => a -> RegexError
show (AccountDeclarationInfo -> Int
adideclarationorder AccountDeclarationInfo
adi)RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>RegexError
","RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>TagName -> RegexError
T.unpack TagName
aRegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>RegexError
")"
        takelast :: Int -> [a] -> [a]
takelast Int
n' = [a] -> [a]
forall a. [a] -> [a]
reverse ([a] -> [a]) -> ([a] -> [a]) -> [a] -> [a]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Int
n' ([a] -> [a]) -> ([a] -> [a]) -> [a] -> [a]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [a] -> [a]
forall a. [a] -> [a]
reverse

instance Default Journal where
  def :: Journal
def = Journal
nulljournal

nulljournal :: Journal
nulljournal :: Journal
nulljournal = Journal {
   jparsedefaultyear :: Maybe Integer
jparsedefaultyear          = Maybe Integer
forall a. Maybe a
Nothing
  ,jparseapplyyears :: [Maybe Integer]
jparseapplyyears           = []
  ,jparsedefaultcommodity :: Maybe (TagName, AmountStyle)
jparsedefaultcommodity     = Maybe (TagName, AmountStyle)
forall a. Maybe a
Nothing
  ,jparsedecimalmark :: Maybe Char
jparsedecimalmark          = Maybe Char
forall a. Maybe a
Nothing
  ,jparseparentaccounts :: [TagName]
jparseparentaccounts       = []
  ,jparsealiases :: [AccountAlias]
jparsealiases              = []
  ,jparseoptaliases :: [AccountAlias]
jparseoptaliases           = []
  -- ,jparsetransactioncount     = 0
  ,jparsetimeclockentries :: [TimeclockEntry]
jparsetimeclockentries     = []
  ,jparseincludefilestack :: [(RegexError, RegexError)]
jparseincludefilestack     = []
  ,jparsepos :: Maybe ParsePos
jparsepos                  = Maybe ParsePos
forall a. Maybe a
Nothing
  ,jparseamountstyles :: Set AmountStyle
jparseamountstyles         = Set AmountStyle
forall a. Set a
S.empty
  ,jparsetexts :: Set TagName
jparsetexts                = Set TagName
forall a. Set a
S.empty
  ,jparsefastpathstats :: FastPathStats
jparsefastpathstats        = FastPathStats
forall a. Monoid a => a
mempty
  ,jdeclaredpayees :: [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees            = []
  ,jdeclaredtags :: [(TagName, TagDeclarationInfo)]
jdeclaredtags              = []
  ,jdeclaredaccounts :: [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts          = []
  ,jdeclaredaccounttags :: Map TagName [Tag]
jdeclaredaccounttags       = Map TagName [Tag]
forall k a. Map k a
M.empty
  ,jdeclaredaccounttypes :: Map AccountType [TagName]
jdeclaredaccounttypes      = Map AccountType [TagName]
forall k a. Map k a
M.empty
  ,jaccounttypes :: Map TagName AccountType
jaccounttypes              = Map TagName AccountType
forall k a. Map k a
M.empty
  ,jglobalcommoditystyles :: Map TagName AmountStyle
jglobalcommoditystyles     = Map TagName AmountStyle
forall k a. Map k a
M.empty
  ,jdeclaredcommodities :: Map TagName Commodity
jdeclaredcommodities       = Map TagName Commodity
forall k a. Map k a
M.empty
  ,jdeclaredcommoditytags :: Map TagName [Tag]
jdeclaredcommoditytags     = Map TagName [Tag]
forall k a. Map k a
M.empty
  ,jinferredcommoditystyles :: Map TagName AmountStyle
jinferredcommoditystyles   = Map TagName AmountStyle
forall k a. Map k a
M.empty
  ,jpricedirectives :: [PriceDirective]
jpricedirectives           = []
  ,jinferredmarketprices :: [MarketPrice]
jinferredmarketprices      = []
  ,jtxnmodifiers :: [TransactionModifier]
jtxnmodifiers              = []
  ,jperiodictxns :: [PeriodicTransaction]
jperiodictxns              = []
  ,jasserts :: [AssertDirective]
jasserts                   = []
  ,jtxns :: [Transaction]
jtxns                      = []
  ,jitems :: [JournalItem]
jitems                     = []
  ,jfiles :: [JournalFile]
jfiles                     = []
  ,jauxfiles :: [(RegexError, [RegexError])]
jauxfiles                  = []
  ,jlastreadtime :: POSIXTime
jlastreadtime              = POSIXTime
0
  }

journalFilePath :: Journal -> FilePath
journalFilePath :: Journal -> RegexError
journalFilePath = JournalFile -> RegexError
jfpath (JournalFile -> RegexError)
-> (Journal -> JournalFile) -> Journal -> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> JournalFile
mainfile

journalFilePaths :: Journal -> [FilePath]
journalFilePaths :: Journal -> [RegexError]
journalFilePaths = (JournalFile -> RegexError) -> [JournalFile] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map JournalFile -> RegexError
jfpath ([JournalFile] -> [RegexError])
-> (Journal -> [JournalFile]) -> Journal -> [RegexError]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [JournalFile]
jfiles

-- | All the files this journal's data was read from: its data files
-- (journalFilePaths) and any auxiliary files such as CSV rules files (jauxfiles).
-- These are the files to watch for changes when reloading.
-- Each file is listed once, even if it was read more than once
-- (eg a file included twice, or a rules file used by several CSV files).
journalAllFilePaths :: Journal -> [FilePath]
journalAllFilePaths :: Journal -> [RegexError]
journalAllFilePaths Journal
j = [RegexError] -> [RegexError]
forall a. Ord a => [a] -> [a]
nubOrd ([RegexError] -> [RegexError]) -> [RegexError] -> [RegexError]
forall a b. (a -> b) -> a -> b
$ Journal -> [RegexError]
journalFilePaths Journal
j [RegexError] -> [RegexError] -> [RegexError]
forall a. Semigroup a => a -> a -> a
<> ((RegexError, [RegexError]) -> [RegexError])
-> [(RegexError, [RegexError])] -> [RegexError]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (RegexError, [RegexError]) -> [RegexError]
forall a b. (a, b) -> b
snd (Journal -> [(RegexError, [RegexError])]
jauxfiles Journal
j)

mainfile :: Journal -> JournalFile
mainfile :: Journal -> JournalFile
mainfile = JournalFile -> [JournalFile] -> JournalFile
forall a. a -> [a] -> a
headDef (RegexError -> TagName -> Int -> JournalFile
JournalFile RegexError
"(unknown)" TagName
"" Int
0) ([JournalFile] -> JournalFile)
-> (Journal -> [JournalFile]) -> Journal -> JournalFile
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [JournalFile]
jfiles

addTransaction :: Transaction -> Journal -> Journal
addTransaction :: Transaction -> Journal -> Journal
addTransaction Transaction
t j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = let ts' :: [Transaction]
ts' = Transaction
t Transaction -> [Transaction] -> [Transaction]
forall a. a -> [a] -> [a]
: [Transaction]
ts in [Transaction]
ts' [Transaction] -> Journal -> Journal
forall a b. a -> b -> b
`seq` Journal
j { jtxns = ts' }

-- | Add a journal item, evaluated first (its fields are strict) so no parse-time thunks are retained.
-- Consecutive blank line items are collapsed into one.
addJournalItem :: JournalItem -> Journal -> Journal
addJournalItem :: JournalItem -> Journal -> Journal
addJournalItem JournalItem
JIBlank j :: Journal
j@Journal{jitems :: Journal -> [JournalItem]
jitems=JournalItem
JIBlank:[JournalItem]
_} = Journal
j
addJournalItem JournalItem
i j :: Journal
j@Journal{jitems :: Journal -> [JournalItem]
jitems=[JournalItem]
is} = let is' :: [JournalItem]
is' = JournalItem
i JournalItem -> [JournalItem] -> [JournalItem]
forall a. a -> [a] -> [a]
: [JournalItem]
is in JournalItem
i JournalItem -> Journal -> Journal
forall a b. a -> b -> b
`seq` [JournalItem]
is' [JournalItem] -> Journal -> Journal
forall a b. a -> b -> b
`seq` Journal
j { jitems = is' }

-- | Add a transaction parsed from a journal file, and a placeholder item for it.
-- Any comment lines immediately preceding it (the JIComment items on top of jitems)
-- are moved into the transaction's tprecedingcomment.
addTransactionItem :: Transaction -> Journal -> Journal
addTransactionItem :: Transaction -> Journal -> Journal
addTransactionItem Transaction
t j :: Journal
j@Journal{jitems :: Journal -> [JournalItem]
jitems=[JournalItem]
is} =
  -- strict pattern matching here, to avoid leaving thunks in jitems
  case (JournalItem -> Bool)
-> [JournalItem] -> ([JournalItem], [JournalItem])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span JournalItem -> Bool
isCommentItem [JournalItem]
is of
    ([], [JournalItem]
_)    -> Transaction -> Journal -> Journal
addTransactionAndItem Transaction
t Journal
j
    ([JournalItem]
cs, [JournalItem]
rest) -> [JournalItem]
rest [JournalItem] -> Journal -> Journal
forall a b. a -> b -> b
`seq` Transaction -> Journal -> Journal
addTransactionAndItem Transaction
t' Journal
j{jitems=rest}
      where t' :: Transaction
t' = Transaction -> Transaction
txnTieKnot Transaction
t{tprecedingcomment = T.concat $ reverse [c | JIComment c <- cs]}
  where
    addTransactionAndItem :: Transaction -> Journal -> Journal
addTransactionAndItem Transaction
t' = JournalItem -> Journal -> Journal
addJournalItem (SourcePos -> JournalItem
JITransaction (SourcePos -> JournalItem) -> SourcePos -> JournalItem
forall a b. (a -> b) -> a -> b
$ (SourcePos, SourcePos) -> SourcePos
forall a b. (a, b) -> a
fst ((SourcePos, SourcePos) -> SourcePos)
-> (SourcePos, SourcePos) -> SourcePos
forall a b. (a -> b) -> a -> b
$ Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t') (Journal -> Journal) -> (Journal -> Journal) -> Journal -> Journal
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Journal -> Journal
addTransaction Transaction
t'
    isCommentItem :: JournalItem -> Bool
isCommentItem JIComment{} = Bool
True
    isCommentItem JournalItem
_           = Bool
False

addTransactionModifier :: TransactionModifier -> Journal -> Journal
addTransactionModifier :: TransactionModifier -> Journal -> Journal
addTransactionModifier TransactionModifier
mt Journal
j = Journal
j { jtxnmodifiers = mt : jtxnmodifiers j }

addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addPeriodicTransaction PeriodicTransaction
pt Journal
j = Journal
j { jperiodictxns = pt : jperiodictxns j }

deriving instance Show AssertDirective

addAssertDirective :: AssertDirective -> Journal -> Journal
addAssertDirective :: AssertDirective -> Journal -> Journal
addAssertDirective AssertDirective
ad Journal
j = Journal
j { jasserts = ad : jasserts j }

addPriceDirective :: PriceDirective -> Journal -> Journal
addPriceDirective :: PriceDirective -> Journal -> Journal
addPriceDirective PriceDirective
h j :: Journal
j@Journal{jpricedirectives :: Journal -> [PriceDirective]
jpricedirectives=[PriceDirective]
hs} = let hs' :: [PriceDirective]
hs' = PriceDirective
h PriceDirective -> [PriceDirective] -> [PriceDirective]
forall a. a -> [a] -> [a]
: [PriceDirective]
hs in [PriceDirective]
hs' [PriceDirective] -> Journal -> Journal
forall a b. a -> b -> b
`seq` Journal
j { jpricedirectives = hs' }  -- XXX #999 keep sorted

-- | Get the transaction with this index (its 1-based position in the input stream), if any.
journalTransactionAt :: Journal -> Integer -> Maybe Transaction
journalTransactionAt :: Journal -> Integer -> Maybe Transaction
journalTransactionAt Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} Integer
i =
  -- it's probably ts !! (i+1), but we won't assume
  [Transaction] -> Maybe Transaction
forall a. [a] -> Maybe a
headMay [Transaction
t | Transaction
t <- [Transaction]
ts, Transaction -> Integer
tindex Transaction
t Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
i]

-- | Get the transaction that appeared immediately after this one in the input stream, if any.
journalNextTransaction :: Journal -> Transaction -> Maybe Transaction
journalNextTransaction :: Journal -> Transaction -> Maybe Transaction
journalNextTransaction Journal
j Transaction
t = Journal -> Integer -> Maybe Transaction
journalTransactionAt Journal
j (Transaction -> Integer
tindex Transaction
t Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1)

-- | Get the transaction that appeared immediately before this one in the input stream, if any.
journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction
journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction
journalPrevTransaction Journal
j Transaction
t = Journal -> Integer -> Maybe Transaction
journalTransactionAt Journal
j (Transaction -> Integer
tindex Transaction
t Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1)

-- | All postings from this journal's transactions, in order.
journalPostings :: Journal -> [Posting]
journalPostings :: Journal -> [Posting]
journalPostings = (Transaction -> [Posting]) -> [Transaction] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Transaction -> [Posting]
tpostings ([Transaction] -> [Posting])
-> (Journal -> [Transaction]) -> Journal -> [Posting]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Transaction]
jtxns

-- | All posting amounts from this journal, in order.
journalPostingAmounts :: Journal -> [MixedAmount]
journalPostingAmounts :: Journal -> [MixedAmount]
journalPostingAmounts = (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
pamount ([Posting] -> [MixedAmount])
-> (Journal -> [Posting]) -> Journal -> [MixedAmount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Posting]
journalPostings

-- | Show the journal posting amounts rendered, suitable for debug logging.
showJournalPostingAmountsDebug :: Journal -> String
showJournalPostingAmountsDebug :: Journal -> RegexError
showJournalPostingAmountsDebug = [RegexError] -> RegexError
forall a. Show a => a -> RegexError
show ([RegexError] -> RegexError)
-> (Journal -> [RegexError]) -> Journal -> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MixedAmount -> RegexError) -> [MixedAmount] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map MixedAmount -> RegexError
showMixedAmountOneLine ([MixedAmount] -> [RegexError])
-> (Journal -> [MixedAmount]) -> Journal -> [RegexError]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [MixedAmount]
journalPostingAmounts

-- | All raw amounts used in this journal's postings and costs,
-- with MixedAmounts flattened, in parse order.
journalPostingAndCostAmounts :: Journal -> [Amount]
journalPostingAndCostAmounts :: Journal -> [Amount]
journalPostingAndCostAmounts = (Amount -> [Amount]) -> [Amount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Amount -> [Amount]
getAmounts ([Amount] -> [Amount])
-> (Journal -> [Amount]) -> Journal -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> [Amount]) -> [Posting] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount])
-> (Posting -> MixedAmount) -> Posting -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount) ([Posting] -> [Amount])
-> (Journal -> [Posting]) -> Journal -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Posting]
journalPostings

-- | All raw amounts appearing in this journal, with MixedAmounts flattened, in no particular order.
-- (Including from posting amounts, cost amounts, P directives, and the last D directive.)
journalAmounts :: Journal -> S.Set Amount
journalAmounts :: Journal -> Set Amount
journalAmounts = [Amount] -> Set Amount
forall a. Ord a => [a] -> Set a
S.fromList ([Amount] -> Set Amount)
-> (Journal -> [Amount]) -> Journal -> Set Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> Journal -> [Amount]
journalStyleInfluencingAmounts Bool
True

-- | Sorted unique commodity symbols declared by commodity directives in this journal.
journalCommoditiesDeclared :: Journal -> [CommoditySymbol]
journalCommoditiesDeclared :: Journal -> [TagName]
journalCommoditiesDeclared = Map TagName Commodity -> [TagName]
forall k a. Map k a -> [k]
M.keys (Map TagName Commodity -> [TagName])
-> (Journal -> Map TagName Commodity) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Map TagName Commodity
jdeclaredcommodities

-- | Sorted unique commodity symbols used anywhere in this journal, including
-- commodity directives, P directives, the last D directive, posting amounts and cost amounts.
journalCommoditiesUsed :: Journal -> [CommoditySymbol]
journalCommoditiesUsed :: Journal -> [TagName]
journalCommoditiesUsed Journal
j = Set TagName -> [TagName]
forall a. Set a -> [a]
S.elems (Set TagName -> [TagName]) -> Set TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$
  Journal -> Set TagName
journalCommoditiesFromPriceDirectives Journal
j Set TagName -> Set TagName -> Set TagName
forall a. Semigroup a => a -> a -> a
<>
  ([TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList ([TagName] -> Set TagName) -> [TagName] -> Set TagName
forall a b. (a -> b) -> a -> b
$ (Amount -> TagName) -> [Amount] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> TagName
acommodity ([Amount] -> [TagName]) -> [Amount] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Bool -> Journal -> [Amount]
journalStyleInfluencingAmounts Bool
True Journal
j)

-- | Sorted unique commodity symbols mentioned anywhere in this journal.
-- (Including commodity directives, P directives, the last D directive, posting amounts and cost amounts.)
journalCommodities :: Journal -> S.Set CommoditySymbol
journalCommodities :: Journal -> Set TagName
journalCommodities Journal
j =
     Map TagName Commodity -> Set TagName
forall k a. Map k a -> Set k
M.keysSet (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j)
  Set TagName -> Set TagName -> Set TagName
forall a. Semigroup a => a -> a -> a
<> Journal -> Set TagName
journalCommoditiesFromPriceDirectives Journal
j
  Set TagName -> Set TagName -> Set TagName
forall a. Semigroup a => a -> a -> a
<> [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList ((Amount -> TagName) -> [Amount] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> TagName
acommodity ([Amount] -> [TagName]) -> [Amount] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Bool -> Journal -> [Amount]
journalStyleInfluencingAmounts Bool
True Journal
j)

-- | Sorted unique commodity symbols mentioned in this journal's P directives.
journalCommoditiesFromPriceDirectives :: Journal -> S.Set CommoditySymbol
journalCommoditiesFromPriceDirectives :: Journal -> Set TagName
journalCommoditiesFromPriceDirectives = [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList ([TagName] -> Set TagName)
-> (Journal -> [TagName]) -> Journal -> Set TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PriceDirective -> [TagName]) -> [PriceDirective] -> [TagName]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap PriceDirective -> [TagName]
pdcomms ([PriceDirective] -> [TagName])
-> (Journal -> [PriceDirective]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [PriceDirective]
jpricedirectives
  where pdcomms :: PriceDirective -> [TagName]
pdcomms PriceDirective
pd = [PriceDirective -> TagName
pdcommodity PriceDirective
pd, Amount -> TagName
acommodity (Amount -> TagName) -> Amount -> TagName
forall a b. (a -> b) -> a -> b
$ PriceDirective -> Amount
pdamount PriceDirective
pd]

-- | Sorted unique commodity symbols used in transactions, in either posting or cost amounts.
journalCommoditiesFromTransactions :: Journal -> S.Set CommoditySymbol
journalCommoditiesFromTransactions :: Journal -> Set TagName
journalCommoditiesFromTransactions Journal
j = [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList ([TagName] -> Set TagName) -> [TagName] -> Set TagName
forall a b. (a -> b) -> a -> b
$ (Amount -> TagName) -> [Amount] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> TagName
acommodity ([Amount] -> [TagName]) -> [Amount] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Journal -> [Amount]
journalPostingAndCostAmounts Journal
j

-- | Guess a base currency for this journal: Just the commodity symbol
-- as used in the journal, and its ISO 4217 currency code if one is known
-- (otherwise the symbol again), choosing as follows:
-- 1. The "to" commodity that appears most often in P (price) directives, if any.
-- 2. Otherwise, the commodity that appears most often in posting and cost amounts.
-- 3. Otherwise, Nothing.
-- Commodity symbols are normalised to ISO 4217 codes where possible,
-- so that equivalent symbols are tallied together; the symbol returned
-- is the first-occurring one that normalises to the winning code.
-- Ties are broken by first occurrence order.
journalBaseCurrency :: Journal -> Maybe (CommoditySymbol, CurrencyCode)
journalBaseCurrency :: Journal -> Maybe Tag
journalBaseCurrency Journal
j = [TagName] -> Maybe Tag
pick [TagName]
priceTargetComms Maybe Tag -> Maybe Tag -> Maybe Tag
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> [TagName] -> Maybe Tag
pick [TagName]
postingAndCostComms
  where
    pick :: [TagName] -> Maybe Tag
pick [TagName]
syms = do
      code <- [TagName] -> Maybe TagName
forall a. Ord a => [a] -> Maybe a
mostFrequent ([TagName] -> Maybe TagName) -> [TagName] -> Maybe TagName
forall a b. (a -> b) -> a -> b
$ (TagName -> TagName) -> [TagName] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map TagName -> TagName
toCurrencyCode [TagName]
syms
      sym  <- find ((== code) . toCurrencyCode) syms
      Just (sym, code)
    priceTargetComms :: [TagName]
priceTargetComms    = (PriceDirective -> TagName) -> [PriceDirective] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (Amount -> TagName
acommodity (Amount -> TagName)
-> (PriceDirective -> Amount) -> PriceDirective -> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> Amount
pdamount) ([PriceDirective] -> [TagName]) -> [PriceDirective] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Journal -> [PriceDirective]
jpricedirectives Journal
j
    postingAndCostComms :: [TagName]
postingAndCostComms = (Amount -> TagName) -> [Amount] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> TagName
acommodity ([Amount] -> [TagName]) -> [Amount] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Journal -> [Amount]
journalPostingAndCostAmounts Journal
j

    -- Most frequent element, ties broken by first-occurrence order.
    -- A single pass for efficiency: each map entry stores (negate count, first index),
    -- so a minimumBy on those tuples picks most-frequent, earliest-first.
    -- The bang on c forces accumulation strictly to avoid thunk chains.
    mostFrequent :: Ord a => [a] -> Maybe a
    mostFrequent :: forall a. Ord a => [a] -> Maybe a
mostFrequent [] = Maybe a
forall a. Maybe a
Nothing
    mostFrequent [a]
xs = a -> Maybe a
forall a. a -> Maybe a
Just (a -> Maybe a) -> a -> Maybe a
forall a b. (a -> b) -> a -> b
$ (a, (Integer, Int)) -> a
forall a b. (a, b) -> a
fst ((a, (Integer, Int)) -> a) -> (a, (Integer, Int)) -> a
forall a b. (a -> b) -> a -> b
$ ((a, (Integer, Int)) -> (a, (Integer, Int)) -> Ordering)
-> [(a, (Integer, Int))] -> (a, (Integer, Int))
forall (t :: * -> *) a.
Foldable t =>
(a -> a -> Ordering) -> t a -> a
minimumBy (((a, (Integer, Int)) -> (Integer, Int))
-> (a, (Integer, Int)) -> (a, (Integer, Int)) -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (a, (Integer, Int)) -> (Integer, Int)
forall a b. (a, b) -> b
snd) ([(a, (Integer, Int))] -> (a, (Integer, Int)))
-> [(a, (Integer, Int))] -> (a, (Integer, Int))
forall a b. (a -> b) -> a -> b
$ Map a (Integer, Int) -> [(a, (Integer, Int))]
forall k a. Map k a -> [(k, a)]
M.toList Map a (Integer, Int)
stats
      where
        stats :: Map a (Integer, Int)
stats             = (Map a (Integer, Int) -> (Int, a) -> Map a (Integer, Int))
-> Map a (Integer, Int) -> [(Int, a)] -> Map a (Integer, Int)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map a (Integer, Int) -> (Int, a) -> Map a (Integer, Int)
forall {k} {a} {b}.
(Ord k, Num a) =>
Map k (a, b) -> (b, k) -> Map k (a, b)
bump Map a (Integer, Int)
forall k a. Map k a
M.empty ([Int] -> [a] -> [(Int, a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0::Int ..] [a]
xs)
        bump :: Map k (a, b) -> (b, k) -> Map k (a, b)
bump Map k (a, b)
m (b
i, k
x)     = ((a, b) -> (a, b) -> (a, b))
-> k -> (a, b) -> Map k (a, b) -> Map k (a, b)
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith (a, b) -> (a, b) -> (a, b)
forall {a} {p} {b}. Num a => p -> (a, b) -> (a, b)
combine k
x (-a
1, b
i) Map k (a, b)
m
        combine :: p -> (a, b) -> (a, b)
combine p
_ (!a
c, b
i) = (a
c a -> a -> a
forall a. Num a => a -> a -> a
- a
1, b
i)

-- | The ISO 4217 currency code of this journal's guessed base currency
-- ('journalBaseCurrency'), defaulting to "USD".
journalBaseCurrencyCode :: Journal -> CurrencyCode
journalBaseCurrencyCode :: Journal -> TagName
journalBaseCurrencyCode = TagName -> (Tag -> TagName) -> Maybe Tag -> TagName
forall b a. b -> (a -> b) -> Maybe a -> b
maybe TagName
"USD" Tag -> TagName
forall a b. (a, b) -> b
snd (Maybe Tag -> TagName)
-> (Journal -> Maybe Tag) -> Journal -> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Maybe Tag
journalBaseCurrency

-- | Unique transaction descriptions used in this journal.
journalDescriptions :: Journal -> [Text]
journalDescriptions :: Journal -> [TagName]
journalDescriptions = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> TagName) -> [Transaction] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> TagName
tdescription ([Transaction] -> [TagName])
-> (Journal -> [Transaction]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Transaction]
jtxns

-- | Sorted unique payees declared by payee directives in this journal.
journalPayeesDeclared :: Journal -> [Payee]
journalPayeesDeclared :: Journal -> [TagName]
journalPayeesDeclared = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((TagName, PayeeDeclarationInfo) -> TagName)
-> [(TagName, PayeeDeclarationInfo)] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, PayeeDeclarationInfo) -> TagName
forall a b. (a, b) -> a
fst ([(TagName, PayeeDeclarationInfo)] -> [TagName])
-> (Journal -> [(TagName, PayeeDeclarationInfo)])
-> Journal
-> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [(TagName, PayeeDeclarationInfo)]
jdeclaredpayees

-- | Sorted unique payees used by transactions in this journal.
journalPayeesUsed :: Journal -> [Payee]
journalPayeesUsed :: Journal -> [TagName]
journalPayeesUsed = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> TagName) -> [Transaction] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> TagName
transactionPayee ([Transaction] -> [TagName])
-> (Journal -> [Transaction]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Transaction]
jtxns

-- | Sorted unique payees used in transactions or declared by payee directives in this journal.
journalPayeesDeclaredOrUsed :: Journal -> [Payee]
journalPayeesDeclaredOrUsed :: Journal -> [TagName]
journalPayeesDeclaredOrUsed Journal
j = Set TagName -> [TagName]
forall a. Set a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Set TagName -> [TagName]) -> Set TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$ ([TagName] -> Set TagName) -> [[TagName]] -> Set TagName
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList
    [Journal -> [TagName]
journalPayeesDeclared Journal
j, Journal -> [TagName]
journalPayeesUsed Journal
j]

-- | Sorted unique tag names declared by tag directives in this journal.
journalTagsDeclared :: Journal -> [TagName]
journalTagsDeclared :: Journal -> [TagName]
journalTagsDeclared = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((TagName, TagDeclarationInfo) -> TagName)
-> [(TagName, TagDeclarationInfo)] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, TagDeclarationInfo) -> TagName
forall a b. (a, b) -> a
fst ([(TagName, TagDeclarationInfo)] -> [TagName])
-> (Journal -> [(TagName, TagDeclarationInfo)])
-> Journal
-> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [(TagName, TagDeclarationInfo)]
jdeclaredtags

-- | Sorted unique tag names used in this journal (in account directives, transactions, postings..)
journalTagsUsed :: Journal -> [TagName]
journalTagsUsed :: Journal -> [TagName]
journalTagsUsed Journal
j = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName]) -> [TagName] -> [TagName]
forall a b. (a -> b) -> a -> b
$ (Tag -> TagName) -> [Tag] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Tag -> TagName
forall a b. (a, b) -> a
fst ([Tag] -> [TagName]) -> [Tag] -> [TagName]
forall a b. (a -> b) -> a -> b
$ (Transaction -> [Tag]) -> [Transaction] -> [Tag]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Transaction -> [Tag]
transactionAllTags ([Transaction] -> [Tag]) -> [Transaction] -> [Tag]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j
  -- tags used in all transactions and postings and postings' accounts

-- | Sorted unique tag names used in transactions or declared by tag directives in this journal.
journalTagsDeclaredOrUsed :: Journal -> [TagName]
journalTagsDeclaredOrUsed :: Journal -> [TagName]
journalTagsDeclaredOrUsed Journal
j = Set TagName -> [TagName]
forall a. Set a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Set TagName -> [TagName]) -> Set TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$ ([TagName] -> Set TagName) -> [[TagName]] -> Set TagName
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList
    [Journal -> [TagName]
journalTagsDeclared Journal
j, Journal -> [TagName]
journalTagsUsed Journal
j]

-- | Sorted unique account names posted to by this journal's transactions.
journalAccountNamesUsed :: Journal -> [AccountName]
journalAccountNamesUsed :: Journal -> [TagName]
journalAccountNamesUsed = [Posting] -> [TagName]
accountNamesFromPostings ([Posting] -> [TagName])
-> (Journal -> [Posting]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Posting]
journalPostings

-- | Sorted unique account names implied by this journal's transactions -
-- accounts posted to and all their implied parent accounts.
journalAccountNamesImplied :: Journal -> [AccountName]
journalAccountNamesImplied :: Journal -> [TagName]
journalAccountNamesImplied = [TagName] -> [TagName]
expandAccountNames ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [TagName]
journalAccountNamesUsed

-- | Sorted unique account names declared by account directives in this journal.
journalAccountNamesDeclared :: Journal -> [AccountName]
journalAccountNamesDeclared :: Journal -> [TagName]
journalAccountNamesDeclared = [TagName] -> [TagName]
forall a. Ord a => [a] -> [a]
nubSort ([TagName] -> [TagName])
-> (Journal -> [TagName]) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((TagName, AccountDeclarationInfo) -> TagName)
-> [(TagName, AccountDeclarationInfo)] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, AccountDeclarationInfo) -> TagName
forall a b. (a, b) -> a
fst ([(TagName, AccountDeclarationInfo)] -> [TagName])
-> (Journal -> [(TagName, AccountDeclarationInfo)])
-> Journal
-> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts

-- | Sorted unique account names declared by account directives or posted to
-- by transactions in this journal.
journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]
journalAccountNamesDeclaredOrUsed :: Journal -> [TagName]
journalAccountNamesDeclaredOrUsed Journal
j = Set TagName -> [TagName]
forall a. Set a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Set TagName -> [TagName]) -> Set TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$ ([TagName] -> Set TagName) -> [[TagName]] -> Set TagName
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList
    [Journal -> [TagName]
journalAccountNamesDeclared Journal
j, Journal -> [TagName]
journalAccountNamesUsed Journal
j]

-- | Sorted unique account names declared by account directives, or posted to
-- or implied as parents by transactions in this journal.
journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]
journalAccountNamesDeclaredOrImplied :: Journal -> [TagName]
journalAccountNamesDeclaredOrImplied Journal
j = Set TagName -> [TagName]
forall a. Set a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Set TagName -> [TagName]) -> Set TagName -> [TagName]
forall a b. (a -> b) -> a -> b
$ ([TagName] -> Set TagName) -> [[TagName]] -> Set TagName
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList
    [Journal -> [TagName]
journalAccountNamesDeclared Journal
j, [TagName] -> [TagName]
expandAccountNames ([TagName] -> [TagName]) -> [TagName] -> [TagName]
forall a b. (a -> b) -> a -> b
$ Journal -> [TagName]
journalAccountNamesUsed Journal
j]

-- | Convenience/compatibility alias for journalAccountNamesDeclaredOrImplied.
journalAccountNames :: Journal -> [AccountName]
journalAccountNames :: Journal -> [TagName]
journalAccountNames = Journal -> [TagName]
journalAccountNamesDeclaredOrImplied

-- | Sorted unique account names declared or implied in this journal
-- which have no children.
journalLeafAccountNames :: Journal -> [AccountName]
journalLeafAccountNames :: Journal -> [TagName]
journalLeafAccountNames = Tree TagName -> [TagName]
forall a. Tree a -> [a]
treeLeaves (Tree TagName -> [TagName])
-> (Journal -> Tree TagName) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Tree TagName
journalAccountNameTree

journalAccountNameTree :: Journal -> Tree AccountName
journalAccountNameTree :: Journal -> Tree TagName
journalAccountNameTree = [TagName] -> Tree TagName
accountNameTreeFrom ([TagName] -> Tree TagName)
-> (Journal -> [TagName]) -> Journal -> Tree TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [TagName]
journalAccountNamesDeclaredOrImplied

-- | Which tags have been declared explicitly for this account, if any ?
journalAccountTags :: Journal -> AccountName -> [Tag]
journalAccountTags :: Journal -> TagName -> [Tag]
journalAccountTags Journal{Map TagName [Tag]
jdeclaredaccounttags :: Journal -> Map TagName [Tag]
jdeclaredaccounttags :: Map TagName [Tag]
jdeclaredaccounttags} TagName
a = [Tag] -> TagName -> Map TagName [Tag] -> [Tag]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] TagName
a Map TagName [Tag]
jdeclaredaccounttags

-- | Which tags are in effect for this account, including tags inherited from parent accounts ?
journalInheritedAccountTags :: Journal -> AccountName -> [Tag]
journalInheritedAccountTags :: Journal -> TagName -> [Tag]
journalInheritedAccountTags Journal
j TagName
a =
  ([Tag] -> TagName -> [Tag]) -> [Tag] -> [TagName] -> [Tag]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\[Tag]
ts TagName
a' -> [Tag]
ts [Tag] -> [Tag] -> [Tag]
forall a. Eq a => [a] -> [a] -> [a]
`union` Journal -> TagName -> [Tag]
journalAccountTags Journal
j TagName
a') [] [TagName]
as
  where
    as :: [TagName]
as = TagName
a TagName -> [TagName] -> [TagName]
forall a. a -> [a] -> [a]
: TagName -> [TagName]
parentAccountNames TagName
a
-- PERF: cache in journal ?

type DateWeightedSimilarityScore = Double
type SimilarityScore = Double
type TimeDistance = Integer

-- | Find up to N most similar and nearest-dated transactions matching
-- the given transaction description and query and exceeding the given
-- description similarity score (0 to 1, see compareDescriptions).
-- The provided Day (today) is used as the reference date;
-- transactions are penalised by their absolute distance from it in days
-- (both past and future).
-- Returns transactions along with
-- their distance in days from today,
-- their description similarity score,
-- and a heuristically date-weighted variant of this that favours nearby transactions.
journalTransactionsSimilarTo :: Journal -> Day -> Text -> Query -> SimilarityScore -> Int
  -> [(DateWeightedSimilarityScore, TimeDistance, SimilarityScore, Transaction)]
journalTransactionsSimilarTo :: Journal
-> Day
-> TagName
-> Query
-> Double
-> Int
-> [(Double, Integer, Double, Transaction)]
journalTransactionsSimilarTo Journal{[Transaction]
jtxns :: Journal -> [Transaction]
jtxns :: [Transaction]
jtxns} Day
today TagName
desc Query
q Double
similaritythreshold Int
n =
  Int
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a. Int -> [a] -> [a]
take Int
n ([(Double, Integer, Double, Transaction)]
 -> [(Double, Integer, Double, Transaction)])
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a b. (a -> b) -> a -> b
$
  ([(Double, Integer, Double, Transaction)] -> RegexError)
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a. (a -> RegexError) -> a -> a
dbg1With (
    [RegexError] -> RegexError
unlines ([RegexError] -> RegexError)
-> ([(Double, Integer, Double, Transaction)] -> [RegexError])
-> [(Double, Integer, Double, Transaction)]
-> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
    (RegexError
"up to 30 transactions above description similarity threshold "RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>Double -> RegexError
forall a. Show a => a -> RegexError
show Double
similaritythresholdRegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<>RegexError
" ordered by proximity-weighted similarity:"RegexError -> [RegexError] -> [RegexError]
forall a. a -> [a] -> [a]
:) ([RegexError] -> [RegexError])
-> ([(Double, Integer, Double, Transaction)] -> [RegexError])
-> [(Double, Integer, Double, Transaction)]
-> [RegexError]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
    Int -> [RegexError] -> [RegexError]
forall a. Int -> [a] -> [a]
take Int
30 ([RegexError] -> [RegexError])
-> ([(Double, Integer, Double, Transaction)] -> [RegexError])
-> [(Double, Integer, Double, Transaction)]
-> [RegexError]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
    ((Double, Integer, Double, Transaction) -> RegexError)
-> [(Double, Integer, Double, Transaction)] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map ( \(Double
w,Integer
d,Double
s,Transaction{Integer
[Tag]
[Posting]
Maybe Day
(SourcePos, SourcePos)
TagName
Day
Status
tprecedingcomment :: Transaction -> TagName
tsourcepos :: Transaction -> (SourcePos, SourcePos)
tindex :: Transaction -> Integer
tpostings :: Transaction -> [Posting]
tdescription :: Transaction -> TagName
tindex :: Integer
tprecedingcomment :: TagName
tsourcepos :: (SourcePos, SourcePos)
tdate :: Day
tdate2 :: Maybe Day
tstatus :: Status
tcode :: TagName
tdescription :: TagName
tcomment :: TagName
ttags :: [Tag]
tpostings :: [Posting]
ttags :: Transaction -> [Tag]
tcomment :: Transaction -> TagName
tcode :: Transaction -> TagName
tstatus :: Transaction -> Status
tdate2 :: Transaction -> Maybe Day
tdate :: Transaction -> Day
..}) -> RegexError
-> Double
-> Integer
-> Double
-> RegexError
-> TagName
-> RegexError
forall r. PrintfType r => RegexError -> r
printf RegexError
"weighted:%8.3f  distance:%4d similarity:%5.3f  %s %s" Double
w Integer
d Double
s (Day -> RegexError
forall a. Show a => a -> RegexError
show Day
tdate) TagName
tdescription )) ([(Double, Integer, Double, Transaction)]
 -> [(Double, Integer, Double, Transaction)])
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a b. (a -> b) -> a -> b
$
  ((Double, Integer, Double, Transaction)
 -> (Double, Integer, Double, Transaction) -> Ordering)
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (((Double, Integer, Double, Transaction) -> Double)
-> (Double, Integer, Double, Transaction)
-> (Double, Integer, Double, Transaction)
-> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (Double -> Double
forall a. Num a => a -> a
negate(Double -> Double)
-> ((Double, Integer, Double, Transaction) -> Double)
-> (Double, Integer, Double, Transaction)
-> Double
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Double, Integer, Double, Transaction) -> Double
forall {a} {b} {c} {d}. (a, b, c, d) -> a
first4)) ([(Double, Integer, Double, Transaction)]
 -> [(Double, Integer, Double, Transaction)])
-> [(Double, Integer, Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a b. (a -> b) -> a -> b
$
  ((Double, Transaction) -> (Double, Integer, Double, Transaction))
-> [(Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a b. (a -> b) -> [a] -> [b]
map (\(Double
s,Transaction
t) -> ((Double, Transaction) -> Double
weightedScore (Double
s,Transaction
t), Transaction -> Integer
timedistance Transaction
t, Double
s, Transaction
t)) ([(Double, Transaction)]
 -> [(Double, Integer, Double, Transaction)])
-> [(Double, Transaction)]
-> [(Double, Integer, Double, Transaction)]
forall a b. (a -> b) -> a -> b
$
  ((Double, Transaction) -> Bool)
-> [(Double, Transaction)] -> [(Double, Transaction)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
similaritythreshold)(Double -> Bool)
-> ((Double, Transaction) -> Double)
-> (Double, Transaction)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Double, Transaction) -> Double
forall a b. (a, b) -> a
fst)
  [(TagName -> TagName -> Double
compareDescriptions TagName
desc (TagName -> Double) -> TagName -> Double
forall a b. (a -> b) -> a -> b
$ Transaction -> TagName
tdescription Transaction
t, Transaction
t) | Transaction
t <- [Transaction]
jtxns, Query
q Query -> Transaction -> Bool
`matchesTransaction` Transaction
t]
  where
    timedistance :: Transaction -> Integer
timedistance Transaction
t = Integer -> Integer
forall a. Num a => a -> a
abs (Integer -> Integer) -> Integer -> Integer
forall a b. (a -> b) -> a -> b
$ Day -> Day -> Integer
diffDays Day
today (Transaction -> Day
tdate Transaction
t)
    -- Combine similarity and time distance heuristically. This gave decent results
    -- in my "find most recent invoice" use case in 2023-03,
    -- but will probably need more attention.
    weightedScore :: (Double, Transaction) -> Double
    weightedScore :: (Double, Transaction) -> Double
weightedScore (Double
s, Transaction
t) = Double
100 Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
s Double -> Double -> Double
forall a. Num a => a -> a -> a
- Integer -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Transaction -> Integer
timedistance Transaction
t) Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Double
4

-- | Return a similarity score from 0 to 1.5 for two transaction descriptions. 
-- This is based on compareStrings, with the following modifications:
--
-- - numbers are stripped out before measuring similarity
--
-- - if the (unstripped) first description appears in its entirety within the second,
--   the score is boosted by 0.5.
--
compareDescriptions :: Text -> Text -> Double
compareDescriptions :: TagName -> TagName -> Double
compareDescriptions TagName
a TagName
b =
  (if TagName
a TagName -> TagName -> Bool
`T.isInfixOf` TagName
b then (Double
0.5Double -> Double -> Double
forall a. Num a => a -> a -> a
+) else Double -> Double
forall a. a -> a
id) (Double -> Double) -> Double -> Double
forall a b. (a -> b) -> a -> b
$
  RegexError -> RegexError -> Double
compareStrings (TagName -> RegexError
simplify TagName
a) (TagName -> RegexError
simplify TagName
b)
  where
    simplify :: TagName -> RegexError
simplify = TagName -> RegexError
T.unpack (TagName -> RegexError)
-> (TagName -> TagName) -> TagName -> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> TagName -> TagName
T.filter (Bool -> Bool
not(Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Char -> Bool
isDigit)

-- | Return a similarity score from 0 to 1 for two strings.  This
-- was based on Simon White's string similarity algorithm
-- (http://www.catalysoft.com/articles/StrikeAMatch.html), later found
-- to be https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient,
-- and modified to handle short strings better.
-- Todo: check out http://nlp.fi.muni.cz/raslan/2008/raslan08.pdf#page=14 .
compareStrings :: String -> String -> Double
compareStrings :: RegexError -> RegexError -> Double
compareStrings RegexError
"" RegexError
"" = Double
1
compareStrings [Char
_] RegexError
"" = Double
0
compareStrings RegexError
"" [Char
_] = Double
0
compareStrings [Char
a] [Char
b] = if Char -> Char
toUpper Char
a Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char -> Char
toUpper Char
b then Double
1 else Double
0
compareStrings RegexError
s1 RegexError
s2 = Double
2 Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
commonpairs Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Double
totalpairs
  where
    pairs1 :: Set RegexError
pairs1      = [RegexError] -> Set RegexError
forall a. Ord a => [a] -> Set a
S.fromList ([RegexError] -> Set RegexError) -> [RegexError] -> Set RegexError
forall a b. (a -> b) -> a -> b
$ RegexError -> [RegexError]
wordLetterPairs (RegexError -> [RegexError]) -> RegexError -> [RegexError]
forall a b. (a -> b) -> a -> b
$ ShowS
uppercase RegexError
s1
    pairs2 :: Set RegexError
pairs2      = [RegexError] -> Set RegexError
forall a. Ord a => [a] -> Set a
S.fromList ([RegexError] -> Set RegexError) -> [RegexError] -> Set RegexError
forall a b. (a -> b) -> a -> b
$ RegexError -> [RegexError]
wordLetterPairs (RegexError -> [RegexError]) -> RegexError -> [RegexError]
forall a b. (a -> b) -> a -> b
$ ShowS
uppercase RegexError
s2
    commonpairs :: Double
commonpairs = Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Double) -> Int -> Double
forall a b. (a -> b) -> a -> b
$ Set RegexError -> Int
forall a. Set a -> Int
S.size (Set RegexError -> Int) -> Set RegexError -> Int
forall a b. (a -> b) -> a -> b
$ Set RegexError -> Set RegexError -> Set RegexError
forall a. Ord a => Set a -> Set a -> Set a
S.intersection Set RegexError
pairs1 Set RegexError
pairs2
    totalpairs :: Double
totalpairs  = Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Double) -> Int -> Double
forall a b. (a -> b) -> a -> b
$ Set RegexError -> Int
forall a. Set a -> Int
S.size Set RegexError
pairs1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Set RegexError -> Int
forall a. Set a -> Int
S.size Set RegexError
pairs2

wordLetterPairs :: String -> [String]
wordLetterPairs :: RegexError -> [RegexError]
wordLetterPairs = (RegexError -> [RegexError]) -> [RegexError] -> [RegexError]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap RegexError -> [RegexError]
letterPairs ([RegexError] -> [RegexError])
-> (RegexError -> [RegexError]) -> RegexError -> [RegexError]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RegexError -> [RegexError]
words

letterPairs :: String -> [String]
letterPairs :: RegexError -> [RegexError]
letterPairs (Char
a:Char
b:RegexError
rest) = [Char
a,Char
b] RegexError -> [RegexError] -> [RegexError]
forall a. a -> [a] -> [a]
: RegexError -> [RegexError]
letterPairs (Char
bChar -> ShowS
forall a. a -> [a] -> [a]
:RegexError
rest)
letterPairs RegexError
_ = []

-- Newer account type code.

journalAccountType :: Journal -> AccountName -> Maybe AccountType
journalAccountType :: Journal -> TagName -> Maybe AccountType
journalAccountType Journal{Map TagName AccountType
jaccounttypes :: Journal -> Map TagName AccountType
jaccounttypes :: Map TagName AccountType
jaccounttypes} = Map TagName AccountType -> TagName -> Maybe AccountType
accountNameType Map TagName AccountType
jaccounttypes

-- | Add a map of all known account types to the journal.
journalAddAccountTypes :: Journal -> Journal
journalAddAccountTypes :: Journal -> Journal
journalAddAccountTypes Journal
j = Journal
j{jaccounttypes = journalAccountTypes j}

-- | An account type inherited from the parent account(s),
-- and whether it was originally declared by an account directive (true) or inferred from an account name (false).
type ParentAccountType = (AccountType, Bool)

-- | Build a map of all known account types, explicitly declared
-- or inferred from the account's parent or name.
journalAccountTypes :: Journal -> M.Map AccountName AccountType
journalAccountTypes :: Journal -> Map TagName AccountType
journalAccountTypes Journal
j = [(TagName, AccountType)] -> Map TagName AccountType
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(TagName
a,AccountType
acctType) | (TagName
a, Just (AccountType
acctType,Bool
_)) <- Tree (TagName, Maybe (AccountType, Bool))
-> [(TagName, Maybe (AccountType, Bool))]
forall a. Tree a -> [a]
flatten Tree (TagName, Maybe (AccountType, Bool))
t']
  where
    t :: Tree TagName
t = [TagName] -> Tree TagName
accountNameTreeFrom ([TagName] -> Tree TagName) -> [TagName] -> Tree TagName
forall a b. (a -> b) -> a -> b
$ Journal -> [TagName]
journalAccountNames Journal
j :: Tree AccountName
    -- Traverse downward through the account tree, applying any explicitly declared account types,
    -- otherwise inferring account types from account names when possible, and propagating account types downward.
    -- Declared account types (possibly inherited from parent) are preferred, inferred types are used as a fallback.
    t' :: Tree (TagName, Maybe (AccountType, Bool))
t' = Maybe (AccountType, Bool)
-> Tree TagName -> Tree (TagName, Maybe (AccountType, Bool))
setTypeHereAndBelow Maybe (AccountType, Bool)
forall a. Maybe a
Nothing Tree TagName
t :: Tree (AccountName, Maybe (AccountType, Bool))
      where
        declaredtypes :: [AccountType]
declaredtypes       = Map AccountType [TagName] -> [AccountType]
forall k a. Map k a -> [k]
M.keys (Map AccountType [TagName] -> [AccountType])
-> Map AccountType [TagName] -> [AccountType]
forall a b. (a -> b) -> a -> b
$ Journal -> Map AccountType [TagName]
jdeclaredaccounttypes Journal
j
        declaredtypesbyname :: Map TagName (AccountType, Bool)
declaredtypesbyname = Journal -> Map TagName AccountType
journalDeclaredAccountTypes Journal
j Map TagName AccountType
-> (Map TagName AccountType -> Map TagName (AccountType, Bool))
-> Map TagName (AccountType, Bool)
forall a b. a -> (a -> b) -> b
& (AccountType -> (AccountType, Bool))
-> Map TagName AccountType -> Map TagName (AccountType, Bool)
forall a b. (a -> b) -> Map TagName a -> Map TagName b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (,Bool
True)
        setTypeHereAndBelow :: Maybe ParentAccountType -> Tree AccountName -> Tree (AccountName, Maybe ParentAccountType)
        setTypeHereAndBelow :: Maybe (AccountType, Bool)
-> Tree TagName -> Tree (TagName, Maybe (AccountType, Bool))
setTypeHereAndBelow Maybe (AccountType, Bool)
mparenttype (Node TagName
a [Tree TagName]
subs) = (TagName, Maybe (AccountType, Bool))
-> [Tree (TagName, Maybe (AccountType, Bool))]
-> Tree (TagName, Maybe (AccountType, Bool))
forall a. a -> [Tree a] -> Tree a
Node (TagName
a, Maybe (AccountType, Bool)
mnewtype) ((Tree TagName -> Tree (TagName, Maybe (AccountType, Bool)))
-> [Tree TagName] -> [Tree (TagName, Maybe (AccountType, Bool))]
forall a b. (a -> b) -> [a] -> [b]
map (Maybe (AccountType, Bool)
-> Tree TagName -> Tree (TagName, Maybe (AccountType, Bool))
setTypeHereAndBelow Maybe (AccountType, Bool)
mnewtype) [Tree TagName]
subs)
          where
            mnewtype :: Maybe (AccountType, Bool)
mnewtype = Maybe (AccountType, Bool)
mthisacctdeclaredtype Maybe (AccountType, Bool)
-> Maybe (AccountType, Bool) -> Maybe (AccountType, Bool)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (AccountType, Bool)
mparentacctdeclaredtype Maybe (AccountType, Bool)
-> Maybe (AccountType, Bool) -> Maybe (AccountType, Bool)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (AccountType, Bool)
mthisacctinferredtype Maybe (AccountType, Bool)
-> Maybe (AccountType, Bool) -> Maybe (AccountType, Bool)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe (AccountType, Bool)
mparentacctinferredtype
              where
                mthisacctdeclaredtype :: Maybe (AccountType, Bool)
mthisacctdeclaredtype   = TagName
-> Map TagName (AccountType, Bool) -> Maybe (AccountType, Bool)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
a Map TagName (AccountType, Bool)
declaredtypesbyname
                mparentacctdeclaredtype :: Maybe (AccountType, Bool)
mparentacctdeclaredtype = if       Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
False (Maybe Bool -> Bool) -> Maybe Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (AccountType, Bool) -> Bool
forall a b. (a, b) -> b
snd ((AccountType, Bool) -> Bool)
-> Maybe (AccountType, Bool) -> Maybe Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (AccountType, Bool)
mparenttype then Maybe (AccountType, Bool)
mparenttype else Maybe (AccountType, Bool)
forall a. Maybe a
Nothing
                mparentacctinferredtype :: Maybe (AccountType, Bool)
mparentacctinferredtype = if Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
True  (Maybe Bool -> Bool) -> Maybe Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (AccountType, Bool) -> Bool
forall a b. (a, b) -> b
snd ((AccountType, Bool) -> Bool)
-> Maybe (AccountType, Bool) -> Maybe Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (AccountType, Bool)
mparenttype then Maybe (AccountType, Bool)
mparenttype else Maybe (AccountType, Bool)
forall a. Maybe a
Nothing
                mthisacctinferredtype :: Maybe (AccountType, Bool)
mthisacctinferredtype   = [AccountType] -> TagName -> Maybe AccountType
accountNameInferTypeExcept [AccountType]
declaredtypes TagName
a Maybe AccountType
-> (Maybe AccountType -> Maybe (AccountType, Bool))
-> Maybe (AccountType, Bool)
forall a b. a -> (a -> b) -> b
& (AccountType -> (AccountType, Bool))
-> Maybe AccountType -> Maybe (AccountType, Bool)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (,Bool
False)  -- XXX not sure about this Except logic.. but for now, tests pass

-- | Build a map from account names to explicitly declared account types.
journalDeclaredAccountTypes :: Journal -> M.Map AccountName AccountType
journalDeclaredAccountTypes :: Journal -> Map TagName AccountType
journalDeclaredAccountTypes Journal{Map AccountType [TagName]
jdeclaredaccounttypes :: Journal -> Map AccountType [TagName]
jdeclaredaccounttypes :: Map AccountType [TagName]
jdeclaredaccounttypes} =
  [(TagName, AccountType)] -> Map TagName AccountType
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([(TagName, AccountType)] -> Map TagName AccountType)
-> [(TagName, AccountType)] -> Map TagName AccountType
forall a b. (a -> b) -> a -> b
$ [[(TagName, AccountType)]] -> [(TagName, AccountType)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [(TagName -> (TagName, AccountType))
-> [TagName] -> [(TagName, AccountType)]
forall a b. (a -> b) -> [a] -> [b]
map (,AccountType
t) [TagName]
as | (AccountType
t,[TagName]
as) <- Map AccountType [TagName] -> [(AccountType, [TagName])]
forall k a. Map k a -> [(k, a)]
M.toList Map AccountType [TagName]
jdeclaredaccounttypes]

-- | To all postings in the journal, add any tags from their account
-- (including those inherited from parent accounts).
-- Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output).
-- If a tag already exists on the posting, it is not changed (the account tag will be ignored).
journalPostingsAddAccountTags :: Journal -> Journal
journalPostingsAddAccountTags :: Journal -> Journal
journalPostingsAddAccountTags Journal
j
  | Map TagName [Tag] -> Bool
forall k a. Map k a -> Bool
M.null (Journal -> Map TagName [Tag]
jdeclaredaccounttags Journal
j) = Journal
j  -- no account tags declared, nothing to add
  | Map TagName [Tag] -> Bool
forall k a. Map k a -> Bool
M.null Map TagName [Tag]
inheritedtagsbyaccount   = Journal
j  -- no posted-to account has any, nothing to add
  | Bool
otherwise = (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
addtags Journal
j
  where
    -- postings whose account has no tags are left as they are (no new posting is built)
    addtags :: Posting -> Posting
addtags Posting
p = Posting -> ([Tag] -> Posting) -> Maybe [Tag] -> Posting
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Posting
p (Posting -> [Tag] -> Posting
postingAddTags Posting
p) (Maybe [Tag] -> Posting) -> Maybe [Tag] -> Posting
forall a b. (a -> b) -> a -> b
$ TagName -> Map TagName [Tag] -> Maybe [Tag]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Posting -> TagName
paccount Posting
p) Map TagName [Tag]
inheritedtagsbyaccount
    -- the inherited tags of each posted-to account which has some, calculated once per account
    inheritedtagsbyaccount :: Map TagName [Tag]
inheritedtagsbyaccount = [(TagName, [Tag])] -> Map TagName [Tag]
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
      [(TagName
a, [Tag]
ts) | TagName
a <- Journal -> [TagName]
journalAccountNamesUsed Journal
j, let ts :: [Tag]
ts = Journal -> TagName -> [Tag]
journalInheritedAccountTags Journal
j TagName
a, Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [Tag] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Tag]
ts]

-- | Remove all tags from the journal's postings except those provided by their account.
-- This is useful for the accounts report.
-- It does not remove tag declarations from the posting comments.
journalPostingsKeepAccountTagsOnly :: Journal -> Journal
journalPostingsKeepAccountTagsOnly :: Journal -> Journal
journalPostingsKeepAccountTagsOnly Journal
j = (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
keepaccounttags Journal
j
  where keepaccounttags :: Posting -> Posting
keepaccounttags Posting
p = Posting
p{ptags=[]} Posting -> [Tag] -> Posting
`postingAddTags` (Journal -> TagName -> [Tag]
journalInheritedAccountTags Journal
j (TagName -> [Tag]) -> TagName -> [Tag]
forall a b. (a -> b) -> a -> b
$ Posting -> TagName
paccount Posting
p)

-- | Get any tags declared for this commodity.
journalCommodityTags :: Journal -> CommoditySymbol -> [Tag]
journalCommodityTags :: Journal -> TagName -> [Tag]
journalCommodityTags Journal{Map TagName [Tag]
jdeclaredcommoditytags :: Journal -> Map TagName [Tag]
jdeclaredcommoditytags :: Map TagName [Tag]
jdeclaredcommoditytags} TagName
c =
  [Tag] -> TagName -> Map TagName [Tag] -> [Tag]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] TagName
c Map TagName [Tag]
jdeclaredcommoditytags

-- | Does this commodity have a 'lots:' tag declared ?
journalCommodityUsesLots :: Journal -> CommoditySymbol -> Bool
journalCommodityUsesLots :: Journal -> TagName -> Bool
journalCommodityUsesLots Journal
j TagName
c = (Tag -> Bool) -> [Tag] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"lots") (TagName -> Bool) -> (Tag -> TagName) -> Tag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TagName -> TagName
T.toLower (TagName -> TagName) -> (Tag -> TagName) -> Tag -> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tag -> TagName
forall a b. (a, b) -> a
fst) (Journal -> TagName -> [Tag]
journalCommodityTags Journal
j TagName
c)

-- | All commodities with a 'lots:' tag declared.
journalLotfulCommodities :: Journal -> S.Set CommoditySymbol
journalLotfulCommodities :: Journal -> Set TagName
journalLotfulCommodities j :: Journal
j@Journal{Map TagName [Tag]
jdeclaredcommoditytags :: Journal -> Map TagName [Tag]
jdeclaredcommoditytags :: Map TagName [Tag]
jdeclaredcommoditytags} =
  (TagName -> Bool) -> Set TagName -> Set TagName
forall a. (a -> Bool) -> Set a -> Set a
S.filter (Journal -> TagName -> Bool
journalCommodityUsesLots Journal
j) (Map TagName [Tag] -> Set TagName
forall k a. Map k a -> Set k
M.keysSet Map TagName [Tag]
jdeclaredcommoditytags)

-- | The declared lots: tag values by account (the first value, if an
-- account somehow has several).
journalAccountLotsTags :: Journal -> M.Map AccountName Text
journalAccountLotsTags :: Journal -> Map TagName TagName
journalAccountLotsTags Journal{Map TagName [Tag]
jdeclaredaccounttags :: Journal -> Map TagName [Tag]
jdeclaredaccounttags :: Map TagName [Tag]
jdeclaredaccounttags} =
  ([Tag] -> Maybe TagName)
-> Map TagName [Tag] -> Map TagName TagName
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
M.mapMaybe (\[Tag]
tags -> [TagName] -> Maybe TagName
forall a. [a] -> Maybe a
listToMaybe [TagName
v | (TagName
k, TagName
v) <- [Tag]
tags, TagName -> TagName
T.toLower TagName
k TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"lots"]) Map TagName [Tag]
jdeclaredaccounttags

-- | Does this account opt out of lot tracking, via a NONE-valued lots: tag
-- on its own or an ancestor's declaration ? The nearest declaration wins,
-- so a subaccount can re-enable tracking with its own lots: method tag.
-- Postings with explicit cost basis annotations are still lot-tracked
-- regardless (the more specific declaration wins).
journalAccountUsesNoLots :: Journal -> AccountName -> Bool
journalAccountUsesNoLots :: Journal -> TagName -> Bool
journalAccountUsesNoLots = Map TagName TagName -> TagName -> Bool
accountUsesNoLotsWith (Map TagName TagName -> TagName -> Bool)
-> (Journal -> Map TagName TagName) -> Journal -> TagName -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Map TagName TagName
journalAccountLotsTags

-- | Like journalAccountUsesNoLots, but taking the 'journalAccountLotsTags'
-- map (useful where no Journal is at hand, eg during balancing).
accountUsesNoLotsWith :: M.Map AccountName Text -> AccountName -> Bool
accountUsesNoLotsWith :: Map TagName TagName -> TagName -> Bool
accountUsesNoLotsWith Map TagName TagName
lotstags TagName
a =
  case [TagName
v | TagName
a' <- TagName
a TagName -> [TagName] -> [TagName]
forall a. a -> [a] -> [a]
: TagName -> [TagName]
parentAccountNames TagName
a, Just TagName
v <- [TagName -> Map TagName TagName -> Maybe TagName
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
a' Map TagName TagName
lotstags]] of
    (TagName
v:[TagName]
_) -> TagName -> Bool
isNoneLotsTagValue TagName
v
    []    -> Bool
False

-- | Is this lots: tag value the special NONE value (case insensitive),
-- valid on account declarations to opt out of lot tracking ?
isNoneLotsTagValue :: Text -> Bool
isNoneLotsTagValue :: TagName -> Bool
isNoneLotsTagValue TagName
v = TagName -> TagName
T.toUpper (TagName -> TagName
T.strip TagName
v) TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"NONE"

-- | Get the reduction method from a commodity's lots: tag value, if any.
journalCommodityLotsMethod :: Journal -> CommoditySymbol -> Maybe ReductionMethod
journalCommodityLotsMethod :: Journal -> TagName -> Maybe ReductionMethod
journalCommodityLotsMethod Journal
j TagName
c =
  case [TagName
v | (TagName
k, TagName
v) <- Journal -> TagName -> [Tag]
journalCommodityTags Journal
j TagName
c, TagName -> TagName
T.toLower TagName
k TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"lots"] of
    (TagName
v:[TagName]
_) -> TagName -> Maybe ReductionMethod
parseReductionMethod TagName
v
    []    -> Maybe ReductionMethod
forall a. Maybe a
Nothing

-- | Get the reduction method from a posting's lots: tag value (typically inherited from its account), if any.
postingLotsMethod :: Posting -> Maybe ReductionMethod
postingLotsMethod :: Posting -> Maybe ReductionMethod
postingLotsMethod Posting
p =
  case [TagName
v | (TagName
k, TagName
v) <- Posting -> [Tag]
ptags Posting
p, TagName -> TagName
T.toLower TagName
k TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"lots"] of
    (TagName
v:[TagName]
_) -> TagName -> Maybe ReductionMethod
parseReductionMethod TagName
v
    []    -> Maybe ReductionMethod
forall a. Maybe a
Nothing

-- | Parse a reduction method name from a lots: tag value.
parseReductionMethod :: Text -> Maybe ReductionMethod
parseReductionMethod :: TagName -> Maybe ReductionMethod
parseReductionMethod TagName
t = case TagName -> TagName
T.toUpper (TagName -> TagName
T.strip TagName
t) of
  TagName
"FIFO"       -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
FIFO
  TagName
"LIFO"       -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
LIFO
  TagName
"HIFO"       -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
HIFO
  TagName
"AVERAGE"    -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
AVERAGE
  TagName
"SPECID"     -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
SPECID
  TagName
"FIFOALL"    -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
FIFOALL
  TagName
"LIFOALL"    -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
LIFOALL
  TagName
"HIFOALL"    -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
HIFOALL
  TagName
"AVERAGEALL" -> ReductionMethod -> Maybe ReductionMethod
forall a. a -> Maybe a
Just ReductionMethod
AVERAGEALL
  TagName
_            -> Maybe ReductionMethod
forall a. Maybe a
Nothing

-- | Check that all lots: tag values on commodity and account declarations are recognised.
-- On a commodity declaration, an empty value (bare @lots:@ tag) is valid,
-- declaring the commodity lotful with the default FIFO reduction method;
-- a non-empty value must be one of the known reduction methods.
-- On an account declaration, the tag only sets the reduction method for
-- lotful commodities in that account, so a method value is required.
journalCheckLotsTagValues :: Journal -> Either String Journal
journalCheckLotsTagValues :: Journal -> Either RegexError Journal
journalCheckLotsTagValues Journal
j = do
  ((TagName, [Tag]) -> Either RegexError ())
-> [(TagName, [Tag])] -> Either RegexError ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (TagName, [Tag]) -> Either RegexError ()
forall {t :: * -> *} {a}.
(Foldable t, PrintfType a) =>
(TagName, t Tag) -> Either a ()
checkCommodity (Map TagName [Tag] -> [(TagName, [Tag])]
forall k a. Map k a -> [(k, a)]
M.toList (Map TagName [Tag] -> [(TagName, [Tag])])
-> Map TagName [Tag] -> [(TagName, [Tag])]
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName [Tag]
jdeclaredcommoditytags Journal
j)
  ((TagName, AccountDeclarationInfo) -> Either RegexError ())
-> [(TagName, AccountDeclarationInfo)] -> Either RegexError ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (TagName, AccountDeclarationInfo) -> Either RegexError ()
forall {a}.
PrintfType a =>
(TagName, AccountDeclarationInfo) -> Either a ()
checkAccount   (Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts Journal
j)
  Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j
  where
    methods :: RegexError
methods = RegexError
"FIFO, LIFO, HIFO, AVERAGE, SPECID, FIFOALL, LIFOALL, HIFOALL, AVERAGEALL"

    unrecognisedmsg :: String
    unrecognisedmsg :: RegexError
unrecognisedmsg = [RegexError] -> RegexError
unlines [
       RegexError
"%s:%d:"
      ,RegexError
"%s"
      ,RegexError
"unrecognised lots: tag value %s."
      ,RegexError
"Use " RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++ RegexError
methods RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++ RegexError
", or nothing (meaning FIFO)"
      ]

    valuelessmsg :: String
    valuelessmsg :: RegexError
valuelessmsg = [RegexError] -> RegexError
unlines [
       RegexError
"%s:%d:"
      ,RegexError
"%s"
      ,RegexError
"An account lots: tag sets the disposal order for lot-tracked commodities there,"
      ,RegexError
"so it needs a value, one of " RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++ RegexError
methods RegexError -> ShowS
forall a. [a] -> [a] -> [a]
++ RegexError
";"
      ,RegexError
"or NONE, to disable lot tracking in this account."
      ,RegexError
"(A commodity lots: tag enables lot tracking, and can also set the disposal order.)"
      ]

    nonecommoditymsg :: String
    nonecommoditymsg :: RegexError
nonecommoditymsg = [RegexError] -> RegexError
unlines [
       RegexError
"%s:%d:"
      ,RegexError
"%s"
      ,RegexError
"lots: NONE is not supported on commodity declarations."
      ,RegexError
"To disable lot tracking of this commodity in particular accounts,"
      ,RegexError
"add a lots: NONE tag to those accounts' declarations instead;"
      ,RegexError
"to disable it everywhere, remove the commodity's lots: tag."
      ]

    checkCommodity :: (TagName, t Tag) -> Either a ()
checkCommodity (TagName
sym, t Tag
tags) =
      case TagName -> Map TagName Commodity -> Maybe Commodity
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
sym (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j) of
        Just Commodity
comm -> (Tag -> Either a ()) -> t Tag -> Either a ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Commodity -> Tag -> Either a ()
forall {a}. PrintfType a => Commodity -> Tag -> Either a ()
checkCommodityTag Commodity
comm) t Tag
tags
        Maybe Commodity
Nothing   -> () -> Either a ()
forall a b. b -> Either a b
Right ()

    checkCommodityTag :: Commodity -> Tag -> Either a ()
checkCommodityTag Commodity
comm (TagName
k, TagName
v)
      | TagName -> TagName
T.toLower TagName
k TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
/= TagName
"lots"       = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | TagName -> Bool
T.null (TagName -> TagName
T.strip TagName
v)          = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | TagName -> Bool
isNoneLotsTagValue TagName
v        = a -> Either a ()
forall a b. a -> Either a b
Left (a -> Either a ()) -> a -> Either a ()
forall a b. (a -> b) -> a -> b
$ RegexError -> RegexError -> Int -> TagName -> a
forall r. PrintfType r => RegexError -> r
printf RegexError
nonecommoditymsg RegexError
f Int
l TagName
ex
      | Just ReductionMethod
_ <- TagName -> Maybe ReductionMethod
parseReductionMethod TagName
v = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | Bool
otherwise = a -> Either a ()
forall a b. a -> Either a b
Left (a -> Either a ()) -> a -> Either a ()
forall a b. (a -> b) -> a -> b
$ RegexError -> RegexError -> Int -> TagName -> RegexError -> a
forall r. PrintfType r => RegexError -> r
printf RegexError
unrecognisedmsg RegexError
f Int
l TagName
ex (TagName -> RegexError
forall a. Show a => a -> RegexError
show TagName
v)
          where (RegexError
f, Int
l, Maybe (Int, Maybe Int)
_mcols, TagName
ex) = Commodity
-> TagName -> (RegexError, Int, Maybe (Int, Maybe Int), TagName)
makeCommodityTagErrorExcerpt Commodity
comm TagName
k

    checkAccount :: (TagName, AccountDeclarationInfo) -> Either a ()
checkAccount (TagName
acctName, AccountDeclarationInfo
adi) =
      (Tag -> Either a ()) -> [Tag] -> Either a ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (TagName -> AccountDeclarationInfo -> Tag -> Either a ()
forall {a}.
PrintfType a =>
TagName -> AccountDeclarationInfo -> Tag -> Either a ()
checkAccountTag TagName
acctName AccountDeclarationInfo
adi) (AccountDeclarationInfo -> [Tag]
aditags AccountDeclarationInfo
adi)

    checkAccountTag :: TagName -> AccountDeclarationInfo -> Tag -> Either a ()
checkAccountTag TagName
acctName AccountDeclarationInfo
adi (TagName
k, TagName
v)
      | TagName -> TagName
T.toLower TagName
k TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
/= TagName
"lots"       = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | TagName -> Bool
T.null (TagName -> TagName
T.strip TagName
v)          = a -> Either a ()
forall a b. a -> Either a b
Left (a -> Either a ()) -> a -> Either a ()
forall a b. (a -> b) -> a -> b
$ RegexError -> RegexError -> Int -> TagName -> a
forall r. PrintfType r => RegexError -> r
printf RegexError
valuelessmsg RegexError
f Int
l TagName
ex
      | TagName -> Bool
isNoneLotsTagValue TagName
v        = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | Just ReductionMethod
_ <- TagName -> Maybe ReductionMethod
parseReductionMethod TagName
v = () -> Either a ()
forall a b. b -> Either a b
Right ()
      | Bool
otherwise = a -> Either a ()
forall a b. a -> Either a b
Left (a -> Either a ()) -> a -> Either a ()
forall a b. (a -> b) -> a -> b
$ RegexError -> RegexError -> Int -> TagName -> RegexError -> a
forall r. PrintfType r => RegexError -> r
printf RegexError
unrecognisedmsg RegexError
f Int
l TagName
ex (TagName -> RegexError
forall a. Show a => a -> RegexError
show TagName
v)
          where (RegexError
f, Int
l, Maybe (Int, Maybe Int)
_mcols, TagName
ex) = (TagName, AccountDeclarationInfo)
-> TagName -> (RegexError, Int, Maybe (Int, Maybe Int), TagName)
makeAccountTagErrorExcerpt (TagName
acctName, AccountDeclarationInfo
adi) TagName
k

-- | To all postings in the journal, add any tags from their amount's commodities.
-- Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output).
-- If a tag already exists on the posting, it is not changed (the commodity tag will be ignored).
journalPostingsAddCommodityTags :: Journal -> Journal
journalPostingsAddCommodityTags :: Journal -> Journal
journalPostingsAddCommodityTags Journal
j
  | Map TagName [Tag] -> Bool
forall k a. Map k a -> Bool
M.null Map TagName [Tag]
taggedcommodities = Journal
j  -- no commodity tags declared, nothing to add
  | Bool
otherwise = (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
addtags Journal
j
  where
    taggedcommodities :: Map TagName [Tag]
taggedcommodities = ([Tag] -> Bool) -> Map TagName [Tag] -> Map TagName [Tag]
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Bool -> Bool
not (Bool -> Bool) -> ([Tag] -> Bool) -> [Tag] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Tag] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null) (Map TagName [Tag] -> Map TagName [Tag])
-> Map TagName [Tag] -> Map TagName [Tag]
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName [Tag]
jdeclaredcommoditytags Journal
j
    -- postings whose commodities have no tags are left as they are (no new posting is built)
    addtags :: Posting -> Posting
addtags Posting
p = case (TagName -> [Tag]) -> [TagName] -> [Tag]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\TagName
c -> [Tag] -> TagName -> Map TagName [Tag] -> [Tag]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] TagName
c Map TagName [Tag]
taggedcommodities) (Posting -> [TagName]
postingCommodities Posting
p) of
      []   -> Posting
p
      [Tag]
tags -> Posting
p Posting -> [Tag] -> Posting
`postingAddTags` [Tag]
tags

-- | For lot-opening postings with a cost basis (positive; or negative in a
-- liability account, which holds short lots), which don't look like lot
-- transfer destinations, infer transacted cost from cost basis. This runs
-- before transaction balancing (the inferred cost lets an acquire entry with
-- an elided cash amount balance at cost), so lot classification hasn't
-- happened yet; transfer destinations - which must not get a transacted
-- cost - are recognised by shape: a positive cost-basis posting is skipped
-- when the transaction has an explicit negative amount of the same commodity
-- and quantity in another account, or unpriced in the same account (a
-- transfer-from counterpart), or the
-- commodity's unpriced negative and positive quantities sum to matching
-- totals (a split or consolidating transfer group, possibly minus a fee),
-- or an equity posting with no cost-basis amounts (an equity transfer, eg
-- close --clopen --lots style opening balances).
journalInferPostingsTransactedCost :: Journal -> Journal
journalInferPostingsTransactedCost :: Journal -> Journal
journalInferPostingsTransactedCost Journal
j = (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
inferTxn Journal
j
  where
    inferTxn :: Transaction -> Transaction
inferTxn Transaction
t = Transaction
t{tpostings = map (postingInferTransactedCost t) (tpostings t)}

    postingInferTransactedCost :: Transaction -> Posting -> Posting
postingInferTransactedCost Transaction
t Posting
p
      | Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
needsInference ([Amount] -> Bool) -> [Amount] -> Bool
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p) = Posting
p  -- nothing to infer
      | Transaction -> Bool
hasEquityCounterpart Transaction
t = Posting
p                          -- equity transfer: not for transfer postings
      | Bool
otherwise = Posting
p'{poriginal = Just $ originalPosting p}
      where
        p' :: Posting
p' = Posting
p{pamount = mapMixedAmount amountInferTransactedCost $ pamount p}
        -- a lot inflow: positive, or negative in a liability account (a short lot)
        -- (the cheap checks first; few amounts have a cost basis, and multiplying Decimals is slow)
        needsInference :: Amount -> Bool
needsInference Amount
a = Amount -> Bool
hasCostBasisCost Amount
a Bool -> Bool -> Bool
&& Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
a) Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* Quantity
lotsign Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0
                        Bool -> Bool -> Bool
&& Bool -> Bool
not (Transaction -> Posting -> Amount -> Bool
hasTransferFromCounterpart Transaction
t Posting
p Amount
a)
                        Bool -> Bool -> Bool
&& Bool -> Bool
not (Transaction -> Posting -> TagName -> Bool
hasTransferGroupShape Transaction
t Posting
p (Amount -> TagName
acommodity Amount
a))
        lotsign :: Quantity
lotsign = Quantity
-> (LotDirection -> Quantity) -> Maybe LotDirection -> Quantity
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Quantity
1 LotDirection -> Quantity
lotDirectionSign (Journal -> TagName -> Maybe AccountType
journalAccountType Journal
j (Posting -> TagName
paccount Posting
p) Maybe AccountType
-> (AccountType -> Maybe LotDirection) -> Maybe LotDirection
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= AccountType -> Maybe LotDirection
accountTypeLotDirection)
        amountInferTransactedCost :: Amount -> Amount
amountInferTransactedCost Amount
a
          | Amount -> Bool
needsInference Amount
a, Just CostBasis{cbCost :: CostBasis -> Maybe Amount
cbCost=Just Amount
c} <- Amount -> Maybe CostBasis
acostbasis Amount
a = Amount
a{acost = Just (UnitCost c)}
          | Bool
otherwise = Amount
a
        hasCostBasisCost :: Amount -> Bool
hasCostBasisCost Amount
a = case Amount -> Maybe CostBasis
acostbasis Amount
a of
          Just CostBasis{cbCost :: CostBasis -> Maybe Amount
cbCost=Just Amount
_} -> Bool
True
          Maybe CostBasis
_ -> Bool
False

    -- Does another posting have an explicit negative amount of this commodity
    -- and quantity, in a different account, or unpriced in the same account ?
    -- Then this looks like a transfer pair (mirroring the lot classifier's
    -- counterpart matching and same-account pairing).
    hasTransferFromCounterpart :: Transaction -> Posting -> Amount -> Bool
hasTransferFromCounterpart Transaction
t Posting
p Amount
a =
      (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Posting
q -> (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
qa -> Amount -> TagName
acommodity Amount
qa TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> TagName
acommodity Amount
a Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
qa Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity -> Quantity
forall a. Num a => a -> a
negate (Amount -> Quantity
aquantity Amount
a)
                           Bool -> Bool -> Bool
&& (Posting -> TagName
paccount Posting
q TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> TagName
paccount Posting
p Bool -> Bool -> Bool
|| Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
qa)))
                     (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)))
          (Transaction -> [Posting]
tpostings Transaction
t)

    -- Do the transaction's unpriced amounts in this commodity look like a
    -- split or consolidating transfer group (#2692) ? True when the total
    -- unpriced negative quantity equals the total unpriced positive quantity,
    -- is nonzero, and at least one negative is in a different account.
    -- Priced amounts are excluded on both sides: a priced posting (eg a fee
    -- disposal -0.02 A {$100} @ $100) is a deliberate trade, not part of the
    -- transfer.
    hasTransferGroupShape :: Transaction -> Posting -> TagName -> Bool
hasTransferGroupShape Transaction
t Posting
p TagName
c =
      Quantity
negTotal Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 Bool -> Bool -> Bool
&& Quantity
negTotal Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
posTotal Bool -> Bool -> Bool
&& (TagName -> Bool) -> [TagName] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> TagName
paccount Posting
p) [TagName]
negAccts
      where
        unpricedAmts :: Posting -> [Amount]
unpricedAmts Posting
q = [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q), Amount -> TagName
acommodity Amount
a TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
c, Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
a)]
        negs :: [(TagName, Quantity)]
negs = [(Posting -> TagName
paccount Posting
q, Quantity -> Quantity
forall a. Num a => a -> a
negate (Amount -> Quantity
aquantity Amount
a)) | Posting
q <- Transaction -> [Posting]
tpostings Transaction
t, Amount
a <- Posting -> [Amount]
unpricedAmts Posting
q, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0]
        posTotal :: Quantity
posTotal = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Amount -> Quantity
aquantity Amount
a | Posting
q <- Transaction -> [Posting]
tpostings Transaction
t, Amount
a <- Posting -> [Amount]
unpricedAmts Posting
q, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0]
        negTotal :: Quantity
negTotal = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum (((TagName, Quantity) -> Quantity)
-> [(TagName, Quantity)] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, Quantity) -> Quantity
forall a b. (a, b) -> b
snd [(TagName, Quantity)]
negs)
        negAccts :: [TagName]
negAccts = ((TagName, Quantity) -> TagName)
-> [(TagName, Quantity)] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (TagName, Quantity) -> TagName
forall a b. (a, b) -> a
fst [(TagName, Quantity)]
negs

    -- Does the transaction have an equity posting with no cost-basis amounts ?
    -- (Mirrors the lot classifier's equity-transfer detection.)
    hasEquityCounterpart :: Transaction -> Bool
hasEquityCounterpart Transaction
t =
      (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Posting
q -> Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isEquityType (Journal -> TagName -> Maybe AccountType
journalAccountType Journal
j (Posting -> TagName
paccount Posting
q))
              Bool -> Bool -> Bool
&& Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q))))
          (Transaction -> [Posting]
tpostings Transaction
t)

-- | The account name to use for postings which hledger generates to an account of the given type:
-- the first account declared with that type (by a type: tag), in declaration order;
-- or if there is none, the alphabetically first account which has that type
-- (inferred from its name, or a parent's);
-- or if there is none, the given default account name.
journalAccountForType :: AccountName -> AccountType -> Journal -> AccountName
journalAccountForType :: TagName -> AccountType -> Journal -> TagName
journalAccountForType TagName
defaultacct AccountType
atype Journal
j = TagName -> [TagName] -> TagName
forall a. a -> [a] -> a
headDef TagName
defaultacct ([TagName] -> TagName) -> [TagName] -> TagName
forall a b. (a -> b) -> a -> b
$ [TagName]
declared [TagName] -> [TagName] -> [TagName]
forall a. [a] -> [a] -> [a]
++ [TagName]
inferred
  where
    declaredtypes :: Map TagName AccountType
declaredtypes = Journal -> Map TagName AccountType
journalDeclaredAccountTypes Journal
j
    declared :: [TagName]
declared = [TagName
a | (TagName
a,AccountDeclarationInfo
_) <- Journal -> [(TagName, AccountDeclarationInfo)]
jdeclaredaccounts Journal
j, TagName -> Map TagName AccountType -> Maybe AccountType
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
a Map TagName AccountType
declaredtypes Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
atype]
    inferred :: [TagName]
inferred = Map TagName AccountType -> [TagName]
forall k a. Map k a -> [k]
M.keys (Map TagName AccountType -> [TagName])
-> Map TagName AccountType -> [TagName]
forall a b. (a -> b) -> a -> b
$ (AccountType -> Bool)
-> Map TagName AccountType -> Map TagName AccountType
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (AccountType -> AccountType -> Bool
forall a. Eq a => a -> a -> Bool
==AccountType
atype) (Map TagName AccountType -> Map TagName AccountType)
-> Map TagName AccountType -> Map TagName AccountType
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName AccountType
jaccounttypes Journal
j

-- | The account name to use for conversion postings generated by --infer-equity
-- (see journalAccountForType; the default is equity:conversion).
journalBaseConversionAccount :: Journal -> AccountName
journalBaseConversionAccount :: Journal -> TagName
journalBaseConversionAccount = TagName -> AccountType -> Journal -> TagName
journalAccountForType TagName
forall {a}. IsString a => a
defaultBaseConversionAccount AccountType
Conversion

-- | All the accounts in this journal which are declared or inferred as V/Conversion type.
-- This does not include new account names which might be generated by --infer-equity, currently.
journalConversionAccounts :: Journal -> [AccountName]
journalConversionAccounts :: Journal -> [TagName]
journalConversionAccounts = Map TagName AccountType -> [TagName]
forall k a. Map k a -> [k]
M.keys (Map TagName AccountType -> [TagName])
-> (Journal -> Map TagName AccountType) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AccountType -> Bool)
-> Map TagName AccountType -> Map TagName AccountType
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (AccountType -> AccountType -> Bool
forall a. Eq a => a -> a -> Bool
==AccountType
Conversion) (Map TagName AccountType -> Map TagName AccountType)
-> (Journal -> Map TagName AccountType)
-> Journal
-> Map TagName AccountType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Map TagName AccountType
jaccounttypes

-- | The account name to use for inferred gain postings
-- (see journalAccountForType; the default is revenues:gain).
journalBaseGainAccount :: Journal -> AccountName
journalBaseGainAccount :: Journal -> TagName
journalBaseGainAccount = TagName -> AccountType -> Journal -> TagName
journalAccountForType TagName
forall {a}. IsString a => a
defaultGainAccount AccountType
Gain

-- | All the accounts in this journal which are declared or inferred as G/Gain type, alphabetically.
journalGainAccounts :: Journal -> [AccountName]
journalGainAccounts :: Journal -> [TagName]
journalGainAccounts = Map TagName AccountType -> [TagName]
forall k a. Map k a -> [k]
M.keys (Map TagName AccountType -> [TagName])
-> (Journal -> Map TagName AccountType) -> Journal -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AccountType -> Bool)
-> Map TagName AccountType -> Map TagName AccountType
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (AccountType -> AccountType -> Bool
forall a. Eq a => a -> a -> Bool
==AccountType
Gain) (Map TagName AccountType -> Map TagName AccountType)
-> (Journal -> Map TagName AccountType)
-> Journal
-> Map TagName AccountType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Map TagName AccountType
jaccounttypes


-- Various kinds of filtering on journals. We do it differently depending
-- on the command.

-------------------------------------------------------------------------------
-- filtering V2

-- | Keep only transactions matching the query expression.
filterJournalTransactions :: Query -> Journal -> Journal
filterJournalTransactions :: Query -> Journal -> Journal
filterJournalTransactions Query
q j :: Journal
j@Journal{[Transaction]
jtxns :: Journal -> [Transaction]
jtxns :: [Transaction]
jtxns}
  | Query -> Bool
queryIsNull Query
q = Journal
j  -- everything matches, nothing to do
  | Bool
otherwise = Journal
j{jtxns=filter (matchesTransactionExtra (journalAccountType j) q) jtxns}

-- | Keep only postings matching the query expression.
-- This can leave unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal
filterJournalPostings :: Query -> Journal -> Journal
filterJournalPostings Query
q j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts}
  | Query -> Bool
queryIsNull Query
q = Journal
j  -- everything matches, nothing to do
  | Bool
otherwise = Journal
j{jtxns=map (filterTransactionPostingsExtra (journalAccountType j) q) ts}

-- | Keep only postings which do not match the query expression, but for which a related posting does.
-- This can leave unbalanced transactions.
filterJournalRelatedPostings :: Query -> Journal -> Journal
filterJournalRelatedPostings :: Query -> Journal -> Journal
filterJournalRelatedPostings Query
q j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=map (filterTransactionRelatedPostings q) ts}

-- | Within each posting's amount, keep only the parts matching the query, and
-- remove any postings with all amounts removed.
-- This can leave unbalanced transactions.
filterJournalAmounts :: Query -> Journal -> Journal
filterJournalAmounts :: Query -> Journal -> Journal
filterJournalAmounts Query
q j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts}
  | Query -> Bool
queryIsNull Query
q = Journal
j  -- everything matches, nothing to do
  | Bool
otherwise = Journal
j{jtxns=map (filterTransactionAmounts q) ts}

-- | Filter out all parts of this transaction's amounts which do not match the
-- query, and remove any postings with all amounts removed.
-- This can leave the transaction unbalanced.
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionAmounts Query
q t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} = Transaction
t{tpostings=mapMaybe (filterPostingAmount q) ps}

-- | Filter out all parts of this posting's amount which do not match the query, and remove the posting
-- if this removes all amounts.
filterPostingAmount :: Query -> Posting -> Maybe Posting
filterPostingAmount :: Query -> Posting -> Maybe Posting
filterPostingAmount Query
q p :: Posting
p@Posting{pamount :: Posting -> MixedAmount
pamount=MixedAmount
as}
  | Map MixedAmountKey Amount -> Bool
forall a. Map MixedAmountKey a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Map MixedAmountKey Amount
newamt = Maybe Posting
forall a. Maybe a
Nothing
  | Bool
otherwise   = Posting -> Maybe Posting
forall a. a -> Maybe a
Just Posting
p{pamount=Mixed newamt}
  where
    Mixed Map MixedAmountKey Amount
newamt = (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount (Query
q Query -> Amount -> Bool
`matchesAmount`) MixedAmount
as

filterTransactionPostings :: Query -> Transaction -> Transaction
filterTransactionPostings :: Query -> Transaction -> Transaction
filterTransactionPostings Query
q t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} = Transaction
t{tpostings=filter (q `matchesPosting`) ps}

-- Like filterTransactionPostings, but is given the map of account types so can also filter by account type.
filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction
filterTransactionPostingsExtra :: (TagName -> Maybe AccountType)
-> Query -> Transaction -> Transaction
filterTransactionPostingsExtra TagName -> Maybe AccountType
atypes Query
q t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} =
  Transaction
t{tpostings=filter (matchesPostingExtra atypes q) ps}

filterTransactionRelatedPostings :: Query -> Transaction -> Transaction
filterTransactionRelatedPostings :: Query -> Transaction -> Transaction
filterTransactionRelatedPostings Query
q t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} =
    Transaction
t{tpostings=if null matches then [] else ps \\ matches}
  where matches :: [Posting]
matches = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> Posting -> Bool
matchesPosting Query
q) [Posting]
ps

-- | Apply a transformation to a journal's transactions.
journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
f j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=map f ts}

-- | Apply a transformation to a journal's postings.
journalMapPostings :: (Posting -> Posting) -> Journal -> Journal
journalMapPostings :: (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
f j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=map (transactionMapPostings f) ts}

-- | Apply a transformation to a journal's posting amounts.
journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal
journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal
journalMapPostingAmounts MixedAmount -> MixedAmount
f = (Posting -> Posting) -> Journal -> Journal
journalMapPostings ((MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount MixedAmount -> MixedAmount
f)

{-
-------------------------------------------------------------------------------
-- filtering V1

-- | Keep only transactions we are interested in, as described by the
-- filter specification.
filterJournalTransactions :: FilterSpec -> Journal -> Journal
filterJournalTransactions FilterSpec{datespan=datespan
                                    ,cleared=cleared
                                    -- ,real=real
                                    -- ,empty=empty
                                    ,acctpats=apats
                                    ,descpats=dpats
                                    ,depth=depth
                                    ,fMetadata=md
                                    } =
    filterJournalTransactionsByStatus cleared .
    filterJournalPostingsByDepth depth .
    filterJournalTransactionsByAccount apats .
    filterJournalTransactionsByMetadata md .
    filterJournalTransactionsByDescription dpats .
    filterJournalTransactionsByDate datespan

-- | Keep only postings we are interested in, as described by the filter
-- specification. This can leave unbalanced transactions.
filterJournalPostings :: FilterSpec -> Journal -> Journal
filterJournalPostings FilterSpec{datespan=datespan
                                ,cleared=cleared
                                ,real=real
                                ,empty=empty
                                ,acctpats=apats
                                ,descpats=dpats
                                ,depth=depth
                                ,fMetadata=md
                                } =
    filterJournalPostingsByRealness real .
    filterJournalPostingsByStatus cleared .
    filterJournalPostingsByEmpty empty .
    filterJournalPostingsByDepth depth .
    filterJournalPostingsByAccount apats .
    filterJournalTransactionsByMetadata md .
    filterJournalTransactionsByDescription dpats .
    filterJournalTransactionsByDate datespan

-- | Keep only transactions whose metadata matches all metadata specifications.
filterJournalTransactionsByMetadata :: [(String,String)] -> Journal -> Journal
filterJournalTransactionsByMetadata pats j@Journal{jtxns=ts} = j{jtxns=filter matchmd ts}
    where matchmd t = all (`elem` tmetadata t) pats

-- | Keep only transactions whose description matches the description patterns.
filterJournalTransactionsByDescription :: [String] -> Journal -> Journal
filterJournalTransactionsByDescription pats j@Journal{jtxns=ts} = j{jtxns=filter matchdesc ts}
    where matchdesc = matchpats pats . tdescription

-- | Keep only transactions which fall between begin and end dates.
-- We include transactions on the begin date and exclude transactions on the end
-- date, like ledger.  An empty date string means no restriction.
filterJournalTransactionsByDate :: DateSpan -> Journal -> Journal
filterJournalTransactionsByDate (DateSpan begin end) j@Journal{jtxns=ts} = j{jtxns=filter match ts}
    where match t = maybe True (tdate t>=) begin && maybe True (tdate t<) end

-- | Keep only transactions which have the requested cleared/uncleared
-- status, if there is one.
filterJournalTransactionsByStatus :: Maybe Bool -> Journal -> Journal
filterJournalTransactionsByStatus Nothing j = j
filterJournalTransactionsByStatus (Just val) j@Journal{jtxns=ts} = j{jtxns=filter match ts}
    where match = (==val).tstatus

-- | Keep only postings which have the requested cleared/uncleared status,
-- if there is one.
filterJournalPostingsByStatus :: Maybe Bool -> Journal -> Journal
filterJournalPostingsByStatus Nothing j = j
filterJournalPostingsByStatus (Just c) j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}
    where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter ((==c) . postingCleared) ps}

-- | Strip out any virtual postings, if the flag is true, otherwise do
-- no filtering.
filterJournalPostingsByRealness :: Bool -> Journal -> Journal
filterJournalPostingsByRealness False j = j
filterJournalPostingsByRealness True j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}
    where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter isReal ps}

-- | Strip out any postings with zero amount, unless the flag is true.
filterJournalPostingsByEmpty :: Bool -> Journal -> Journal
filterJournalPostingsByEmpty True j = j
filterJournalPostingsByEmpty False j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}
    where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (not . isEmptyPosting) ps}

-- -- | Keep only transactions which affect accounts deeper than the specified depth.
-- filterJournalTransactionsByDepth :: Maybe Int -> Journal -> Journal
-- filterJournalTransactionsByDepth Nothing j = j
-- filterJournalTransactionsByDepth (Just d) j@Journal{jtxns=ts} =
--     j{jtxns=(filter (any ((<= d+1) . accountNameLevel . paccount) . tpostings) ts)}

-- | Strip out any postings to accounts deeper than the specified depth
-- (and any transactions which have no postings as a result).
filterJournalPostingsByDepth :: Maybe Int -> Journal -> Journal
filterJournalPostingsByDepth Nothing j = j
filterJournalPostingsByDepth (Just d) j@Journal{jtxns=ts} =
    j{jtxns=filter (not . null . tpostings) $ map filtertxns ts}
    where filtertxns t@Transaction{tpostings=ps} =
              t{tpostings=filter ((<= d) . accountNameLevel . paccount) ps}

-- | Keep only postings which affect accounts matched by the account patterns.
-- This can leave transactions unbalanced.
filterJournalPostingsByAccount :: [String] -> Journal -> Journal
filterJournalPostingsByAccount apats j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}
    where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (matchpats apats . paccount) ps}

-- | Keep only transactions which affect accounts matched by the account patterns.
-- More precisely: each positive account pattern excludes transactions
-- which do not contain a posting to a matched account, and each negative
-- account pattern excludes transactions containing a posting to a matched
-- account.
filterJournalTransactionsByAccount :: [String] -> Journal -> Journal
filterJournalTransactionsByAccount apats j@Journal{jtxns=ts} = j{jtxns=filter tmatch ts}
    where
      tmatch t = (null positives || any positivepmatch ps) && (null negatives || not (any negativepmatch ps)) where ps = tpostings t
      positivepmatch p = any (`amatch` a) positives where a = paccount p
      negativepmatch p = any (`amatch` a) negatives where a = paccount p
      amatch pat a = regexMatchesCI (abspat pat) a
      (negatives,positives) = partition isnegativepat apats

-}

-- | Reverse all lists of parsed items, which during parsing were
-- prepended to, so that the items are in parse order. Part of
-- post-parse finalisation.
journalReverse :: Journal -> Journal
journalReverse :: Journal -> Journal
journalReverse Journal
j =
  Journal
j {jfiles            = reverse $ jfiles j
    ,jdeclaredaccounts = reverse $ jdeclaredaccounts j
    ,jtxns             = reverse $ jtxns j
    ,jitems            = reverse $ jitems j
    ,jtxnmodifiers     = reverse $ jtxnmodifiers j
    ,jperiodictxns     = reverse $ jperiodictxns j
    ,jasserts          = reverse $ jasserts j
    ,jpricedirectives  = reverse $ jpricedirectives j
    }

-- | Set this journal's last read time, ie when its files were last read.
journalSetLastReadTime :: POSIXTime -> Journal -> Journal
journalSetLastReadTime :: POSIXTime -> Journal -> Journal
journalSetLastReadTime POSIXTime
t Journal
j = Journal
j{ jlastreadtime = t }


-- | Number this journal's transactions, counting upward from 1, and tie their knots,
-- so that their postings refer to the renumbered transactions.
-- If they are already numbered that way, the journal is returned unchanged
-- (avoiding a new copy of every transaction).
journalNumberAndTieTransactions :: Journal -> Journal
journalNumberAndTieTransactions :: Journal -> Journal
journalNumberAndTieTransactions j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts}
  | [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and ([Bool] -> Bool) -> [Bool] -> Bool
forall a b. (a -> b) -> a -> b
$ (Integer -> Transaction -> Bool)
-> [Integer] -> [Transaction] -> [Bool]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (\Integer
i Transaction
t -> Transaction -> Integer
tindex Transaction
t Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
i) [Integer
1..] [Transaction]
ts = Journal
j
  | Bool
otherwise = Journal -> Journal
journalTieTransactions (Journal -> Journal) -> Journal -> Journal
forall a b. (a -> b) -> a -> b
$ Journal -> Journal
journalNumberTransactions Journal
j

-- | Number (set the tindex field) this journal's transactions, counting upward from 1.
journalNumberTransactions :: Journal -> Journal
journalNumberTransactions :: Journal -> Journal
journalNumberTransactions j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=zipWith (\Integer
i Transaction
t -> Transaction
t{tindex=i}) [1..] ts}

-- | Tie the knot in all of this journal's transactions, ensuring their postings
-- refer to them. This should be done last, after any other transaction-modifying operations.
journalTieTransactions :: Journal -> Journal
journalTieTransactions :: Journal -> Journal
journalTieTransactions j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=map txnTieKnot ts}

-- | Untie all transaction-posting knots in this journal, so that eg
-- recursiveSize and GHCI's :sprint can work on it.
journalUntieTransactions :: Transaction -> Transaction
journalUntieTransactions :: Transaction -> Transaction
journalUntieTransactions t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} = Transaction
t{tpostings=map (\Posting
p -> Posting
p{ptransaction=Nothing}) ps}

-- | Apply any transaction modifier rules in the journal (adding automated
-- postings to transactions, eg). Or if a modifier rule fails to parse,
-- return the error message. A reference date is provided to help interpret
-- relative dates in transaction modifier queries.
-- The first argument selects whether to add visible tags to generated postings & modified transactions.
journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal
journalModifyTransactions :: Bool -> Day -> Journal -> Either RegexError Journal
journalModifyTransactions Bool
verbosetags Day
d Journal
j =
  case (TagName -> Maybe AccountType)
-> (TagName -> [Tag])
-> Map TagName AmountStyle
-> Day
-> Bool
-> [TransactionModifier]
-> [Transaction]
-> Either RegexError [Transaction]
modifyTransactions
         (Journal -> TagName -> Maybe AccountType
journalAccountType Journal
j)
         (Journal -> TagName -> [Tag]
journalInheritedAccountTags Journal
j)
         (Journal -> Map TagName AmountStyle
journalCommodityStyles Journal
j)
         Day
d Bool
verbosetags (Journal -> [TransactionModifier]
jtxnmodifiers Journal
j) (Journal -> [Transaction]
jtxns Journal
j) of
    Right [Transaction]
ts -> Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j{jtxns=ts}
    Left RegexError
err -> RegexError -> Either RegexError Journal
forall a b. a -> Either a b
Left RegexError
err

-- | Apply this journal's commodity display styles to all of its posting amounts.
-- This does no display rounding, keeping decimal digits as they were;
-- it is suitable for an early cleanup pass before calculations.
-- Reports may want to do additional rounding/styling at render time.
-- Price directives' amounts are left as written (though they still influence the inferred styles),
-- so that error messages and `get`'s rewritten price files show them that way;
-- commands which list prices, like prices and print, style them when rendering.
-- This can return an error message eg if inconsistent number formats are found.
journalStyleAmounts :: Journal -> Either String Journal
journalStyleAmounts :: Journal -> Either RegexError Journal
journalStyleAmounts = (Journal -> Journal)
-> Either RegexError Journal -> Either RegexError Journal
forall a b. (a -> b) -> Either RegexError a -> Either RegexError b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Journal -> Journal
applystyles (Either RegexError Journal -> Either RegexError Journal)
-> (Journal -> Either RegexError Journal)
-> Journal
-> Either RegexError Journal
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Either RegexError Journal
journalInferCommodityStyles
  where
    applystyles :: Journal -> Journal
applystyles Journal
j = (Posting -> Posting) -> Journal -> Journal
journalMapPostings (Map TagName AmountStyle -> Posting -> Posting
postingShareStyles Map TagName AmountStyle
styles (Posting -> Posting) -> (Posting -> Posting) -> Posting -> Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map TagName AmountStyle -> Posting -> Posting
forall a. HasAmounts a => Map TagName AmountStyle -> a -> a
styleAmounts Map TagName AmountStyle
styles) Journal
j
      where styles :: Map TagName AmountStyle
styles = Rounding -> Journal -> Map TagName AmountStyle
journalCommodityStylesWith Rounding
NoRounding Journal
j  -- defer rounding, in case of print --round=none

-- | A memory optimisation, used after applying commodity styles to a posting's amounts.
-- An amount whose display precision differs from its commodity's usual precision
-- (eg $5 when the usual is $5.25) ends up with its own copy of the commodity's style,
-- which differs only in precision. This replaces such copies with one shared copy
-- for each commodity and precision, from a table of each commodity's style at every
-- possible precision (whose entries are created only when first needed).
-- On a 100k-transaction journal with mixed precisions this saves about 3% of memory;
-- it doesn't change the run time noticeably.
postingShareStyles :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting
postingShareStyles :: Map TagName AmountStyle -> Posting -> Posting
postingShareStyles Map TagName AmountStyle
styles = (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount ((MixedAmount -> MixedAmount) -> Posting -> Posting)
-> (MixedAmount -> MixedAmount) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ \(Mixed Map MixedAmountKey Amount
m) -> Map MixedAmountKey Amount -> MixedAmount
Mixed (Map MixedAmountKey Amount -> MixedAmount)
-> Map MixedAmountKey Amount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ (Amount -> Amount)
-> Map MixedAmountKey Amount -> Map MixedAmountKey Amount
forall a b k. (a -> b) -> Map k a -> Map k b
M.map Amount -> Amount
shareAmountStyle Map MixedAmountKey Amount
m  -- commodities are unchanged, so the map keys are too
  where
    sharedstyles :: Map TagName (Array Word8 AmountStyle)
sharedstyles = (AmountStyle -> Array Word8 AmountStyle)
-> Map TagName AmountStyle -> Map TagName (Array Word8 AmountStyle)
forall a b k. (a -> b) -> Map k a -> Map k b
M.map (\AmountStyle
s -> (Word8, Word8) -> [AmountStyle] -> Array Word8 AmountStyle
forall i e. Ix i => (i, i) -> [e] -> Array i e
A.listArray (Word8
0, Word8
255) [AmountStyle
s{asprecision=Precision p} | Word8
p <- [Word8
0..Word8
255]]) Map TagName AmountStyle
styles

    shareAmountStyle :: Amount -> Amount
shareAmountStyle Amount
a = Amount
a{astyle = shareStyle (acommodity a) (astyle a), acost = shareCostStyle <$> acost a}

    shareCostStyle :: AmountCost -> AmountCost
shareCostStyle (UnitCost Amount
a)  = Amount -> AmountCost
UnitCost  (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
shareAmountStyle Amount
a
    shareCostStyle (TotalCost Amount
a) = Amount -> AmountCost
TotalCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
shareAmountStyle Amount
a

    -- If this style is the same as a shared one, use the shared one.
    shareStyle :: TagName -> AmountStyle -> AmountStyle
shareStyle TagName
comm AmountStyle
s = case (AmountStyle -> AmountPrecision
asprecision AmountStyle
s, TagName
-> Map TagName (Array Word8 AmountStyle)
-> Maybe (Array Word8 AmountStyle)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
comm Map TagName (Array Word8 AmountStyle)
sharedstyles) of
      (Precision Word8
p, Just Array Word8 AmountStyle
stylesbyprecision) | Array Word8 AmountStyle
stylesbyprecision Array Word8 AmountStyle -> Word8 -> AmountStyle
forall i e. Ix i => Array i e -> i -> e
A.! Word8
p AmountStyle -> AmountStyle -> Bool
forall a. Eq a => a -> a -> Bool
== AmountStyle
s -> Array Word8 AmountStyle
stylesbyprecision Array Word8 AmountStyle -> Word8 -> AmountStyle
forall i e. Ix i => Array i e -> i -> e
A.! Word8
p
      (AmountPrecision, Maybe (Array Word8 AmountStyle))
_ -> AmountStyle
s

-- | Get the canonical amount styles for this journal, whether (in order of precedence):
-- set globally in InputOpts,
-- declared by commodity directives, 
-- declared by a default commodity (D) directive, 
-- or inferred from posting amounts, 
-- as a map from symbol to style. 
-- Styles from directives are assumed to specify the decimal mark.
journalCommodityStyles :: Journal -> M.Map CommoditySymbol AmountStyle
journalCommodityStyles :: Journal -> Map TagName AmountStyle
journalCommodityStyles Journal
j =
  -- XXX could be some redundancy here, cf journalStyleInfluencingAmounts
  Map TagName AmountStyle
explicitstyles Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle
aliasstyles Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle
inferredstyles
  where
    explicitstyles :: Map TagName AmountStyle
explicitstyles        = Map TagName AmountStyle
globalstyles Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle
declaredstyles Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle
defaultcommoditystyle
    globalstyles :: Map TagName AmountStyle
globalstyles          = Journal -> Map TagName AmountStyle
jglobalcommoditystyles Journal
j
    declaredstyles :: Map TagName AmountStyle
declaredstyles        = (Commodity -> Maybe AmountStyle)
-> Map TagName Commodity -> Map TagName AmountStyle
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
M.mapMaybe Commodity -> Maybe AmountStyle
cformat (Map TagName Commodity -> Map TagName AmountStyle)
-> Map TagName Commodity -> Map TagName AmountStyle
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j
    defaultcommoditystyle :: Map TagName AmountStyle
defaultcommoditystyle = [(TagName, AmountStyle)] -> Map TagName AmountStyle
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([(TagName, AmountStyle)] -> Map TagName AmountStyle)
-> [(TagName, AmountStyle)] -> Map TagName AmountStyle
forall a b. (a -> b) -> a -> b
$ [Maybe (TagName, AmountStyle)] -> [(TagName, AmountStyle)]
forall a. [Maybe a] -> [a]
catMaybes [Journal -> Maybe (TagName, AmountStyle)
jparsedefaultcommodity Journal
j]
    inferredstyles :: Map TagName AmountStyle
inferredstyles        = Journal -> Map TagName AmountStyle
jinferredcommoditystyles Journal
j
    -- A commodity alias without a declared style of its own uses its commodity's number format
    -- (precision, decimal mark, digit groups), with the symbol placement of the amounts written
    -- with the alias, if any, otherwise of its commodity.
    aliasstyles :: Map TagName AmountStyle
aliasstyles = [(TagName, AmountStyle)] -> Map TagName AmountStyle
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
      [ (TagName
a, AmountStyle
cst{ascommodityside = ascommodityside pst, ascommodityspaced = ascommodityspaced pst})
      | Commodity
c <- Map TagName Commodity -> [Commodity]
forall k a. Map k a -> [a]
M.elems (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j)
      , Just AmountStyle
cst <- [TagName -> Map TagName AmountStyle -> Maybe AmountStyle
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Commodity -> TagName
csymbol Commodity
c) (Map TagName AmountStyle
explicitstyles Map TagName AmountStyle
-> Map TagName AmountStyle -> Map TagName AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map TagName AmountStyle
inferredstyles)]
      , TagName
a <- Commodity -> [TagName]
commodityAliases Commodity
c
      , let pst :: AmountStyle
pst = AmountStyle -> TagName -> Map TagName AmountStyle -> AmountStyle
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault AmountStyle
cst TagName
a Map TagName AmountStyle
inferredstyles
      ]

-- | Like journalCommodityStyles, but attach a particular rounding strategy to the styles,
-- affecting how they will affect display precisions when applied.
journalCommodityStylesWith :: Rounding -> Journal -> M.Map CommoditySymbol AmountStyle
journalCommodityStylesWith :: Rounding -> Journal -> Map TagName AmountStyle
journalCommodityStylesWith Rounding
r = Rounding -> Map TagName AmountStyle -> Map TagName AmountStyle
amountStylesSetRounding Rounding
r (Map TagName AmountStyle -> Map TagName AmountStyle)
-> (Journal -> Map TagName AmountStyle)
-> Journal
-> Map TagName AmountStyle
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> Map TagName AmountStyle
journalCommodityStyles

-- | Collect and save inferred amount styles for each commodity based on
-- P directive amounts, posting amounts but not cost amounts, and maybe the last D amount, in that commodity.
-- Styles inferred previously for commodities which no longer appear in these are kept
-- (eg for commodity aliases, whose amounts have been converted, so that print can show them as written).
-- Can return an error message eg if inconsistent number formats are found.
journalInferCommodityStyles :: Journal -> Either String Journal
journalInferCommodityStyles :: Journal -> Either RegexError Journal
journalInferCommodityStyles Journal
j =
  Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j{jinferredcommoditystyles = dbg7 "journalInferCommodityStyles" $
            M.mapWithKey withExplicitPrecision allstyles `M.union` jinferredcommoditystyles j}
  where
    -- Styles are inferred from all amounts (for formatting like symbol placement,
    -- decimal mark, digit groups), but precision only from explicitly-written amounts:
    -- inferred balancing amounts must not raise the journal-wide display precision
    -- and surprise the user. Both style maps are accumulated in one traversal of the
    -- postings, with the directive amounts added last so that they take precedence.
    withExplicitPrecision :: TagName -> AmountStyle -> AmountStyle
withExplicitPrecision TagName
sym AmountStyle
s = AmountStyle
-> (AmountStyle -> AmountStyle) -> Maybe AmountStyle -> AmountStyle
forall b a. b -> (a -> b) -> Maybe a -> b
maybe AmountStyle
s (\AmountStyle
s' -> AmountStyle
s{asprecision = asprecision s'}) (Maybe AmountStyle -> AmountStyle)
-> Maybe AmountStyle -> AmountStyle
forall a b. (a -> b) -> a -> b
$ TagName -> Map TagName AmountStyle -> Maybe AmountStyle
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
sym Map TagName AmountStyle
explstyles
    allstyles :: Map TagName AmountStyle
allstyles  = [Amount] -> Map TagName AmountStyle -> Map TagName AmountStyle
forall {t :: * -> *}.
Foldable t =>
t Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyles [Amount]
directiveamts Map TagName AmountStyle
allpostingstyles
    explstyles :: Map TagName AmountStyle
explstyles = [Amount] -> Map TagName AmountStyle -> Map TagName AmountStyle
forall {t :: * -> *}.
Foldable t =>
t Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyles [Amount]
directiveamts Map TagName AmountStyle
explpostingstyles
    (Map TagName AmountStyle
allpostingstyles, Map TagName AmountStyle
explpostingstyles) = (Posting
 -> (Map TagName AmountStyle, Map TagName AmountStyle)
 -> (Map TagName AmountStyle, Map TagName AmountStyle))
-> (Map TagName AmountStyle, Map TagName AmountStyle)
-> [Posting]
-> (Map TagName AmountStyle, Map TagName AmountStyle)
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Posting
-> (Map TagName AmountStyle, Map TagName AmountStyle)
-> (Map TagName AmountStyle, Map TagName AmountStyle)
addPostingStyles (Map TagName AmountStyle
forall a. Monoid a => a
mempty, Map TagName AmountStyle
forall a. Monoid a => a
mempty) ([Posting] -> (Map TagName AmountStyle, Map TagName AmountStyle))
-> [Posting] -> (Map TagName AmountStyle, Map TagName AmountStyle)
forall a b. (a -> b) -> a -> b
$ Journal -> [Posting]
journalPostings Journal
j
    addPostingStyles :: Posting
-> (Map TagName AmountStyle, Map TagName AmountStyle)
-> (Map TagName AmountStyle, Map TagName AmountStyle)
addPostingStyles Posting
p (!Map TagName AmountStyle
allsts, !Map TagName AmountStyle
explsts) =
      ([Amount] -> Map TagName AmountStyle -> Map TagName AmountStyle
forall {t :: * -> *}.
Foldable t =>
t Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyles [Amount]
amts Map TagName AmountStyle
allsts, if Posting -> Bool
isExplicitAmount Posting
p then [Amount] -> Map TagName AmountStyle -> Map TagName AmountStyle
forall {t :: * -> *}.
Foldable t =>
t Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyles [Amount]
amts Map TagName AmountStyle
explsts else Map TagName AmountStyle
explsts)
      where amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
    addAmountStyles :: t Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyles t Amount
amts Map TagName AmountStyle
styles = (Amount -> Map TagName AmountStyle -> Map TagName AmountStyle)
-> Map TagName AmountStyle -> t Amount -> Map TagName AmountStyle
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Amount -> Map TagName AmountStyle -> Map TagName AmountStyle
addAmountStyle Map TagName AmountStyle
styles t Amount
amts
    -- The default commodity (D) amount and price directive amounts. Costs are not included.
    directiveamts :: [Amount]
directiveamts = [Maybe Amount] -> [Amount]
forall a. [Maybe a] -> [a]
catMaybes (Maybe Amount
mdefaultcommodityamt Maybe Amount -> [Maybe Amount] -> [Maybe Amount]
forall a. a -> [a] -> [a]
: (PriceDirective -> Maybe Amount)
-> [PriceDirective] -> [Maybe Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount)
-> (PriceDirective -> Amount) -> PriceDirective -> Maybe Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> Amount
pdamount) (Journal -> [PriceDirective]
jpricedirectives Journal
j))
    mdefaultcommodityamt :: Maybe Amount
mdefaultcommodityamt =
      (\(TagName
sym,AmountStyle
style) -> Amount
nullamt{acommodity=sym, astyle=style}) ((TagName, AmountStyle) -> Amount)
-> Maybe (TagName, AmountStyle) -> Maybe Amount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Journal -> Maybe (TagName, AmountStyle)
jparsedefaultcommodity Journal
j

-- -- | Apply this journal's historical price records to unpriced amounts where possible.
-- journalApplyPriceDirectives :: Journal -> Journal
-- journalApplyPriceDirectives j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}
--     where
--       fixtransaction t@Transaction{tdate=d, tpostings=ps} = t{tpostings=map fixposting ps}
--        where
--         fixposting p@Posting{pamount=a} = p{pamount=fixmixedamount a}
--         fixmixedamount = mapMixedAmount fixamount
--         fixamount = fixprice
--         fixprice a@Amount{price=Just _} = a
--         fixprice a@Amount{commodity=c} = a{price=maybe Nothing (Just . UnitCost) $ journalPriceDirectiveFor j d c}

-- -- | Get the price for a commodity on the specified day from the price database, if known.
-- -- Does only one lookup step, ie will not look up the price of a price.
-- journalPriceDirectiveFor :: Journal -> Day -> CommoditySymbol -> Maybe MixedAmount
-- journalPriceDirectiveFor j d CommoditySymbol{symbol=s} = do
--   let ps = reverse $ filter ((<= d).pddate) $ filter ((s==).hsymbol) $ sortBy (comparing pddate) $ jpricedirectives j
--   case ps of (PriceDirective{pdamount=a}:_) -> Just a
--              _ -> Nothing

-- | Infer transaction-implied market prices from commodity-exchanging
-- transactions, if any. It's best to call this after transactions have
-- been balanced and posting amounts have appropriate prices attached.
journalInferMarketPricesFromTransactions :: Journal -> Journal
journalInferMarketPricesFromTransactions :: Journal -> Journal
journalInferMarketPricesFromTransactions Journal
j =
  Journal
j{jinferredmarketprices =
       dbg4With (("jinferredmarketprices:\n"<>) . showMarketPrices) $
       map priceDirectiveToMarketPrice .
       concatMap postingPriceDirectivesFromCost $
       journalPostings j
   }

-- | Aliases declared on a commodity directive by its @alias:@ tags.
commodityAliases :: Commodity -> [CommoditySymbol]
commodityAliases :: Commodity -> [TagName]
commodityAliases = ((Amount, SourcePos) -> TagName)
-> [(Amount, SourcePos)] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map (Amount -> TagName
acommodity (Amount -> TagName)
-> ((Amount, SourcePos) -> Amount)
-> (Amount, SourcePos)
-> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, SourcePos) -> Amount
forall a b. (a, b) -> a
fst) ([(Amount, SourcePos)] -> [TagName])
-> (Commodity -> [(Amount, SourcePos)]) -> Commodity -> [TagName]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Commodity -> [(Amount, SourcePos)]
caliases

-- | Update a commodity's declaration with a later declaration of it, in the same file tree.
-- The later declaration adds to the earlier one rather than replacing it:
-- aliases are combined, a display style replaces the earlier one only if the later declaration has one,
-- and the later tags come first (so they win, for tags looked up by their first value).
-- The comment and source position are the later declaration's.
commodityRedeclare :: Commodity -> Commodity -> Commodity
commodityRedeclare :: Commodity -> Commodity -> Commodity
commodityRedeclare Commodity
new Commodity
old = Commodity
new{
   cformat  = cformat new <|> cformat old
  ,ctags    = ctags new `union` ctags old
  ,caliases = caliases old `unionAliases` caliases new
  }

-- | Combine two declarations of a commodity from different journals (file trees, or a file and its included file),
-- the first being the later one. Like 'commodityRedeclare', this keeps the later one's comment, source position,
-- and display style if it has one, and the aliases (in reading order) and tags (the later one's first) of both.
commodityCombine :: Commodity -> Commodity -> Commodity
commodityCombine :: Commodity -> Commodity -> Commodity
commodityCombine Commodity
c1 Commodity
c2 = Commodity
c1{
   cformat  = cformat c1 <|> cformat c2
  ,ctags    = ctags c1 `union` ctags c2
  ,caliases = caliases c2 `unionAliases` caliases c1
  }

-- | Combine two lists of commodity aliases, the first being the earlier ones, keeping them in reading order
-- and dropping repeated definitions (same symbol and quantity).
-- An alias redefined with a different quantity is kept, so it can be reported as a conflict.
unionAliases :: [(Amount, SourcePos)] -> [(Amount, SourcePos)] -> [(Amount, SourcePos)]
unionAliases :: [(Amount, SourcePos)]
-> [(Amount, SourcePos)] -> [(Amount, SourcePos)]
unionAliases = ((Amount, SourcePos) -> (Amount, SourcePos) -> Bool)
-> [(Amount, SourcePos)]
-> [(Amount, SourcePos)]
-> [(Amount, SourcePos)]
forall a. (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy ((TagName, Quantity) -> (TagName, Quantity) -> Bool
forall a. Eq a => a -> a -> Bool
(==) ((TagName, Quantity) -> (TagName, Quantity) -> Bool)
-> ((Amount, SourcePos) -> (TagName, Quantity))
-> (Amount, SourcePos)
-> (Amount, SourcePos)
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` \(Amount
a, SourcePos
_) -> (Amount -> TagName
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a))

-- | All commodity symbols that this journal treats as declared:
-- both the canonical 'jdeclaredcommodities' keys and any 'alias:'
-- values declared on those commodity directives.
commoditiesAndAliases :: Journal -> S.Set CommoditySymbol
commoditiesAndAliases :: Journal -> Set TagName
commoditiesAndAliases Journal
j =
  Map TagName Commodity -> Set TagName
forall k a. Map k a -> Set k
M.keysSet (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j)
  Set TagName -> Set TagName -> Set TagName
forall a. Semigroup a => a -> a -> a
<> [TagName] -> Set TagName
forall a. Ord a => [a] -> Set a
S.fromList [ TagName
a
                | Commodity
c <- Map TagName Commodity -> [Commodity]
forall k a. Map k a -> [a]
M.elems (Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j)
                , TagName
a <- Commodity -> [TagName]
commodityAliases Commodity
c
                ]

-- | Commodity aliases: each alias symbol, with its commodity, its quantity
-- (the number of alias units equal to one unit of the commodity),
-- and the commodity's display style if known.
type CommodityAliases = M.Map CommoditySymbol (CommoditySymbol, Quantity, Maybe AmountStyle)

-- | The commodity aliases declared in this journal.
journalCommodityAliases :: Journal -> CommodityAliases
journalCommodityAliases :: Journal -> CommodityAliases
journalCommodityAliases Journal
j =
  [(TagName, (TagName, Quantity, Maybe AmountStyle))]
-> CommodityAliases
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(Amount -> TagName
acommodity Amount
a, (Commodity -> TagName
csymbol Commodity
c, Amount -> Quantity
aquantity Amount
a, TagName -> Map TagName AmountStyle -> Maybe AmountStyle
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Commodity -> TagName
csymbol Commodity
c) Map TagName AmountStyle
styles))
             | Commodity
c <- Map TagName Commodity -> [Commodity]
forall k a. Map k a -> [a]
M.elems (Map TagName Commodity -> [Commodity])
-> Map TagName Commodity -> [Commodity]
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j, (Amount
a, SourcePos
_) <- Commodity -> [(Amount, SourcePos)]
caliases Commodity
c]
  where styles :: Map TagName AmountStyle
styles = Journal -> Map TagName AmountStyle
journalCommodityStyles Journal
j

-- | Convert an amount written in one of these commodity aliases to its commodity,
-- also returning the alias quantity (or 1).
-- The converted amount gets the commodity's display style. For a plain alias, it keeps its display precision;
-- for an alias with a quantity, it gets the commodity's display precision
-- (or more, if needed to show an exactly converted amount fully; or if that's unknown, all its decimal places up to 8).
convertAliasAmount :: CommodityAliases -> Amount -> (Amount, Quantity)
convertAliasAmount :: CommodityAliases -> Amount -> (Amount, Quantity)
convertAliasAmount CommodityAliases
aliases Amount
a = case TagName
-> CommodityAliases -> Maybe (TagName, Quantity, Maybe AmountStyle)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Amount -> TagName
acommodity Amount
a) CommodityAliases
aliases of
  Maybe (TagName, Quantity, Maybe AmountStyle)
Nothing         -> (Amount
a, Quantity
1)
  Just (TagName
c, Quantity
1, Maybe AmountStyle
ms) -> (Amount
a{acommodity = c, astyle = maybe (astyle a) (\AmountStyle
s -> AmountStyle
s{asprecision = asprecision $ astyle a}) ms}, Quantity
1)
  Just (TagName
c, Quantity
q, Maybe AmountStyle
ms) -> (Amount
a'{astyle = style{asprecision = Precision prec}}, Quantity
q)
    where
      a' :: Amount
a'     = Amount
a{acommodity = c, aquantity = aquantity a / q}
      digits :: Word8
digits = Amount -> Word8
amountInternalPrecision Amount
a'
      exact :: Bool
exact  = Quantity -> Quantity -> Quantity
multiplyQuantities (Amount -> Quantity
aquantity Amount
a') Quantity
q Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
a
      (AmountStyle
style, Word8
prec) = case Maybe AmountStyle
ms of
        Just s :: AmountStyle
s@AmountStyle{asprecision :: AmountStyle -> AmountPrecision
asprecision = Precision Word8
n} -> (AmountStyle
s, if Bool
exact then Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
max Word8
n Word8
digits else Word8
n)
        Maybe AmountStyle
_ -> (AmountStyle -> Maybe AmountStyle -> AmountStyle
forall a. a -> Maybe a -> a
fromMaybe (Amount -> AmountStyle
astyle Amount
a) Maybe AmountStyle
ms, Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
min Word8
defaultMaxDisplayPrecision Word8
digits)

-- | Convert all amounts written in a commodity alias to the commodity it is an alias of.
-- For an alias with a quantity (other than 1), amount quantities are divided by it,
-- and unit costs, cost bases and market prices of the alias are multiplied by it
-- (but if an amount or its unit cost converts inexactly, the unit cost is replaced by the exact total cost).
-- This is done for posting amounts, with their costs, cost bases and balance assertions;
-- periodic transaction and auto posting rules (whose multipliers' symbols are just renamed);
-- and price directives. A converted posting keeps its original form in poriginal, for print.
--
-- Returns 'Left' with a verbose error if the same alias is declared on more than one commodity,
-- or if an alias is also declared as a commodity with aliases of its own.
journalApplyCommodityAliases :: Journal -> Either String Journal
journalApplyCommodityAliases :: Journal -> Either RegexError Journal
journalApplyCommodityAliases Journal
j
  | ((TagName
a, [Commodity]
cs):[(TagName, [Commodity])]
_) <- [(TagName, [Commodity])]
conflicts = RegexError -> Either RegexError Journal
forall a b. a -> Either a b
Left (RegexError -> Either RegexError Journal)
-> RegexError -> Either RegexError Journal
forall a b. (a -> b) -> a -> b
$ [RegexError] -> RegexError
unlines ([RegexError] -> RegexError) -> [RegexError] -> RegexError
forall a b. (a -> b) -> a -> b
$
      [ RegexError
"Alias '" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> TagName -> RegexError
T.unpack TagName
a RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
"' is declared on more than one commodity:", RegexError
""] [RegexError] -> [RegexError] -> [RegexError]
forall a. Semigroup a => a -> a -> a
<> (Commodity -> RegexError) -> [Commodity] -> [RegexError]
forall a b. (a -> b) -> [a] -> [b]
map Commodity -> RegexError
commodityExcerpt [Commodity]
cs
  | (Commodity
c:[Commodity]
_) <- [Commodity]
chained = RegexError -> Either RegexError Journal
forall a b. a -> Either a b
Left (RegexError -> Either RegexError Journal)
-> RegexError -> Either RegexError Journal
forall a b. (a -> b) -> a -> b
$ [RegexError] -> RegexError
unlines
      [ RegexError
"Commodity '" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> TagName -> RegexError
T.unpack (Commodity -> TagName
csymbol Commodity
c) RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
"' has aliases, but is also an alias of another commodity:", RegexError
""
      , Commodity -> RegexError
commodityExcerpt Commodity
c ]
  | CommodityAliases -> Bool
forall k a. Map k a -> Bool
M.null CommodityAliases
aliases = Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j
  | Bool
otherwise = Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j
      { jtxns            = map (transactionMapPostings convertPosting) $ jtxns j
      , jperiodictxns    = [pt{ptpostings = map convertPosting $ ptpostings pt} | pt <- jperiodictxns j]
      , jtxnmodifiers    = [tm{tmpostingrules = map convertRule $ tmpostingrules tm} | tm <- jtxnmodifiers j]
      , jpricedirectives = map convertPrice $ jpricedirectives j
      }
  where
    comms :: [Commodity]
comms     = Map TagName Commodity -> [Commodity]
forall k a. Map k a -> [a]
M.elems (Map TagName Commodity -> [Commodity])
-> Map TagName Commodity -> [Commodity]
forall a b. (a -> b) -> a -> b
$ Journal -> Map TagName Commodity
jdeclaredcommodities Journal
j
    conflicts :: [(TagName, [Commodity])]
conflicts = [(TagName
a, [Commodity]
cs) | (TagName
a, [Commodity]
cs) <- Map TagName [Commodity] -> [(TagName, [Commodity])]
forall k a. Map k a -> [(k, a)]
M.toList (Map TagName [Commodity] -> [(TagName, [Commodity])])
-> Map TagName [Commodity] -> [(TagName, [Commodity])]
forall a b. (a -> b) -> a -> b
$ ([Commodity] -> [Commodity] -> [Commodity])
-> [(TagName, [Commodity])] -> Map TagName [Commodity]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [Commodity] -> [Commodity] -> [Commodity]
forall a. [a] -> [a] -> [a]
(++) [(TagName
a, [Commodity
c]) | Commodity
c <- [Commodity]
comms, TagName
a <- Commodity -> [TagName]
commodityAliases Commodity
c], [Commodity] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Commodity]
cs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1]
    chained :: [Commodity]
chained   = [Commodity
c | Commodity
c <- [Commodity]
comms, Bool -> Bool
not ([(Amount, SourcePos)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([(Amount, SourcePos)] -> Bool) -> [(Amount, SourcePos)] -> Bool
forall a b. (a -> b) -> a -> b
$ Commodity -> [(Amount, SourcePos)]
caliases Commodity
c), Commodity -> TagName
csymbol Commodity
c TagName -> CommodityAliases -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` CommodityAliases
aliases]
    commodityExcerpt :: Commodity -> RegexError
commodityExcerpt Commodity
c = let (RegexError
f, Int
l, Maybe (Int, Maybe Int)
_, TagName
ex) = Commodity
-> TagName -> (RegexError, Int, Maybe (Int, Maybe Int), TagName)
makeCommodityTagErrorExcerpt Commodity
c TagName
"alias" in RegexError
f RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
":" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> Int -> RegexError
forall a. Show a => a -> RegexError
show Int
l RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> RegexError
":\n" RegexError -> ShowS
forall a. Semigroup a => a -> a -> a
<> TagName -> RegexError
T.unpack TagName
ex

    aliases :: CommodityAliases
aliases = Journal -> CommodityAliases
journalCommodityAliases Journal
j
    isAlias :: Amount -> Bool
isAlias = (TagName -> CommodityAliases -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` CommodityAliases
aliases) (TagName -> Bool) -> (Amount -> TagName) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> TagName
acommodity
    convertSymbol :: Amount -> (Amount, Quantity)
convertSymbol = CommodityAliases -> Amount -> (Amount, Quantity)
convertAliasAmount CommodityAliases
aliases
    -- Show all of a calculated amount's decimal digits (up to 8), but no trailing zeros.
    withAllDigits :: Amount -> Amount
withAllDigits Amount
a = AmountPrecision -> Amount -> Amount
amountSetPrecision (Word8 -> AmountPrecision
Precision (Word8 -> AmountPrecision) -> Word8 -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
min Word8
defaultMaxDisplayPrecision (Word8 -> Word8) -> Word8 -> Word8
forall a b. (a -> b) -> a -> b
$ Amount -> Word8
amountInternalPrecision Amount
a') Amount
a'
      where a' :: Amount
a' = Amount
a{aquantity = normalizeDecimal $ aquantity a}
    -- Multiply a per-unit price by an alias quantity.
    scaleBy :: Quantity -> Amount -> Amount
scaleBy Quantity
1 Amount
a = Amount
a
    scaleBy Quantity
q Amount
a = Amount -> Amount
withAllDigits Amount
a{aquantity = aquantity a * q}
    -- Convert a cost, price or balance assertion amount, showing all its digits if it was divided.
    convertExactAmount :: Amount -> Amount
convertExactAmount Amount
a = case Amount -> (Amount, Quantity)
convertSymbol Amount
a of
      (Amount
a', Quantity
1) -> Amount
a'
      (Amount
a', Quantity
_) -> Amount -> Amount
withAllDigits Amount
a'
    convertAmount :: Amount -> Amount
convertAmount Amount
a = Amount
a'{ acost      = convertCost <$> acost a
                        , acostbasis = (\CostBasis
cb -> CostBasis
cb{cbCost = scaleBy q . convertExactAmount <$> cbCost cb}) <$> acostbasis a
                        }
      where
        (Amount
a', Quantity
q) = Amount -> (Amount, Quantity)
convertSymbol Amount
a
        -- If the amount or its unit cost converts inexactly (eg 10 min = 0.1666.. h),
        -- use the total cost calculated before converting, so the cost stays exact.
        convertCost :: AmountCost -> AmountCost
convertCost (UnitCost Amount
u)
          | Amount -> Bool
isInexact Amount
a Bool -> Bool -> Bool
|| Amount -> Bool
isInexact Amount
u = Amount -> AmountCost
TotalCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
withAllDigits (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ (Amount, Quantity) -> Amount
forall a b. (a, b) -> a
fst ((Amount, Quantity) -> Amount) -> (Amount, Quantity) -> Amount
forall a b. (a -> b) -> a -> b
$ Amount -> (Amount, Quantity)
convertSymbol Amount
u{aquantity = multiplyQuantities (abs $ aquantity a) (aquantity u)}
          | Bool
otherwise                  = Amount -> AmountCost
UnitCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
scaleBy Quantity
q (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
convertExactAmount Amount
u
        convertCost (TotalCost Amount
t) = Amount -> AmountCost
TotalCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
convertExactAmount Amount
t
    -- Does converting this amount from an alias round its quantity ?
    isInexact :: Amount -> Bool
isInexact Amount
a = case Amount -> (Amount, Quantity)
convertSymbol Amount
a of
      (Amount
_, Quantity
1)  -> Bool
False
      (Amount
a', Quantity
q) -> Quantity -> Quantity -> Quantity
multiplyQuantities (Amount -> Quantity
aquantity Amount
a') Quantity
q Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Amount -> Quantity
aquantity Amount
a
    hasAlias :: Amount -> Bool
hasAlias Amount
a = Amount -> Bool
isAlias Amount
a Bool -> Bool -> Bool
|| (AmountCost -> Bool) -> Maybe AmountCost -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Amount -> Bool
isAlias (Amount -> Bool) -> (AmountCost -> Amount) -> AmountCost -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountCost -> Amount
costAmount) (Amount -> Maybe AmountCost
acost Amount
a) Bool -> Bool -> Bool
|| (Amount -> Bool) -> Maybe Amount -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isAlias (Amount -> Maybe CostBasis
acostbasis Amount
a Maybe CostBasis -> (CostBasis -> 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
>>= CostBasis -> Maybe Amount
cbCost)
      where costAmount :: AmountCost -> Amount
costAmount (UnitCost Amount
u) = Amount
u
            costAmount (TotalCost Amount
t) = Amount
t

    convertPosting :: Posting -> Posting
convertPosting Posting
p
      | (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
hasAlias (MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p) Bool -> Bool -> Bool
|| (BalanceAssertion -> Bool) -> Maybe BalanceAssertion -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Amount -> Bool
isAlias (Amount -> Bool)
-> (BalanceAssertion -> Amount) -> BalanceAssertion -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalanceAssertion -> Amount
baamount) (Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p) =
          Posting
p{ pamount           = mapMixedAmount convertAmount $ pamount p
           , pbalanceassertion = (\BalanceAssertion
ba -> BalanceAssertion
ba{baamount = convertExactAmount $ baamount ba}) <$> pbalanceassertion p
           , poriginal         = Just $ originalPosting p
           }
      | Bool
otherwise = Posting
p
    convertRule :: TMPostingRule -> TMPostingRule
convertRule r :: TMPostingRule
r@TMPostingRule{tmprPosting :: TMPostingRule -> Posting
tmprPosting = Posting
p, tmprIsMultiplier :: TMPostingRule -> Bool
tmprIsMultiplier = Bool
ismult}
      | Bool
ismult    = TMPostingRule
r{tmprPosting = p{pamount = mapMixedAmount (fst . convertSymbol) $ pamount p}}
      | Bool
otherwise = TMPostingRule
r{tmprPosting = convertPosting p}
    convertPrice :: PriceDirective -> PriceDirective
convertPrice pd :: PriceDirective
pd@PriceDirective{pdcommodity :: PriceDirective -> TagName
pdcommodity = TagName
from, pdamount :: PriceDirective -> Amount
pdamount = Amount
a} =
      case TagName
-> CommodityAliases -> Maybe (TagName, Quantity, Maybe AmountStyle)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup TagName
from CommodityAliases
aliases of
        Maybe (TagName, Quantity, Maybe AmountStyle)
Nothing        -> PriceDirective
pd{pdamount = convertExactAmount a}
        Just (TagName
c, Quantity
q, Maybe AmountStyle
_) -> PriceDirective
pd{pdcommodity = c, pdamount = scaleBy q $ convertExactAmount a}

-- | Convert all this journal's amounts to cost using their attached prices, if any.
journalToCost :: ConversionOp -> Journal -> Journal
journalToCost :: ConversionOp -> Journal -> Journal
journalToCost ConversionOp
cost j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal
j{jtxns=map (transactionToCost cost) ts}

-- | Identify and tag (1) equity conversion postings and (2) postings which have (or could have ?) redundant costs.
-- And if the addcosts flag is true, also add any costs which can be inferred from equity conversion postings.
-- This is always called before transaction balancing to tag the redundant-cost postings so they can be ignored.
-- With --infer-costs, it is called again after transaction balancing (when it has more information to work with) to infer costs from equity postings.
-- See transactionTagCostsAndEquityAndMaybeInferCosts for more details, and hledger manual > Cost reporting for more background.
journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either String Journal
journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either RegexError Journal
journalTagCostsAndEquityAndMaybeInferCosts Bool
verbosetags Bool
addcosts Journal
j
  | [TagName] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TagName]
conversionaccts = Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j  -- no conversion accounts, so no conversion postings: nothing to do
  | Bool
otherwise = do
      ts <- (Transaction -> Either RegexError Transaction)
-> [Transaction] -> Either RegexError [Transaction]
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 (Bool
-> Bool
-> [TagName]
-> Transaction
-> Either RegexError Transaction
transactionTagCostsAndEquityAndMaybeInferCosts Bool
verbosetags Bool
addcosts [TagName]
conversionaccts) ([Transaction] -> Either RegexError [Transaction])
-> [Transaction] -> Either RegexError [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j
      return j{jtxns=ts}
  where conversionaccts :: [TagName]
conversionaccts = Journal -> [TagName]
journalConversionAccounts Journal
j

-- | Add equity postings inferred from costs, where needed and possible.
-- See hledger manual > Cost reporting.
journalInferEquityFromCosts :: Bool -> Journal -> Journal
journalInferEquityFromCosts :: Bool -> Journal -> Journal
journalInferEquityFromCosts Bool
verbosetags Journal
j =
  (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions (Bool -> TagName -> Transaction -> Transaction
transactionInferEquityPostings Bool
verbosetags TagName
equityAcct) Journal
j
  where equityAcct :: TagName
equityAcct = Journal -> TagName
journalBaseConversionAccount Journal
j

-- -- | Get this journal's unique, display-preference-canonicalised commodities, by symbol.
-- journalCanonicalCommodities :: Journal -> M.Map String CommoditySymbol
-- journalCanonicalCommodities j = canonicaliseCommodities $ journalAmountCommodities j

-- -- | Get all this journal's amounts' commodities, in the order parsed.
-- journalAmountCommodities :: Journal -> [CommoditySymbol]
-- journalAmountCommodities = map acommodity . concatMap amounts . journalAmounts

-- -- | Get all this journal's amount and price commodities, in the order parsed.
-- journalAmountAndPriceCommodities :: Journal -> [CommoditySymbol]
-- journalAmountAndPriceCommodities = concatMap amountCommodities . concatMap amounts . journalAmounts

-- -- | Get this amount's commodity and any commodities referenced in its price.
-- amountCommodities :: Amount -> [CommoditySymbol]
-- amountCommodities Amount{acommodity=c,acost=p} =
--     case p of Nothing -> [c]
--               Just (UnitCost ma)  -> c:(concatMap amountCommodities $ amounts ma)
--               Just (TotalCost ma) -> c:(concatMap amountCommodities $ amounts ma)

-- | Get an ordered list of amounts in this journal which can influence
-- canonical amount display styles (excluding the ones in commodity directives). 
-- They are, in the following order:
--
-- * amounts in market price (P) directives (in parse order)
-- * posting amounts and optionally cost amounts (in parse order)
-- * the amount in the final default commodity (D) directive
--
journalStyleInfluencingAmounts :: Bool -> Journal -> [Amount]
journalStyleInfluencingAmounts :: Bool -> Journal -> [Amount]
journalStyleInfluencingAmounts Bool
includecost Journal
j =
  RegexError -> [Amount] -> [Amount]
forall a. Show a => RegexError -> a -> a
dbg7 RegexError
"journalStyleInfluencingAmounts" ([Amount] -> [Amount]) -> [Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$
  [Maybe Amount] -> [Amount]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe Amount] -> [Amount]) -> [Maybe Amount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ [[Maybe Amount]] -> [Maybe Amount]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [
   [Maybe Amount
mdefaultcommodityamt]
  ,(PriceDirective -> Maybe Amount)
-> [PriceDirective] -> [Maybe Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount)
-> (PriceDirective -> Amount) -> PriceDirective -> Maybe Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> Amount
pdamount) ([PriceDirective] -> [Maybe Amount])
-> [PriceDirective] -> [Maybe Amount]
forall a b. (a -> b) -> a -> b
$ Journal -> [PriceDirective]
jpricedirectives Journal
j
  ,(Amount -> Maybe Amount) -> [Amount] -> [Maybe Amount]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Maybe Amount
forall a. a -> Maybe a
Just ([Amount] -> [Maybe Amount]) -> [Amount] -> [Maybe Amount]
forall a b. (a -> b) -> a -> b
$ if Bool
includecost
    then Journal -> [Amount]
journalPostingAndCostAmounts Journal
j
    else (MixedAmount -> [Amount]) -> [MixedAmount] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap MixedAmount -> [Amount]
amountsRaw ([MixedAmount] -> [Amount]) -> [MixedAmount] -> [Amount]
forall a b. (a -> b) -> a -> b
$ Journal -> [MixedAmount]
journalPostingAmounts Journal
j
  ]
  where
    -- D's amount style isn't actually stored as an amount, make it into one
    mdefaultcommodityamt :: Maybe Amount
mdefaultcommodityamt =
      case Journal -> Maybe (TagName, AmountStyle)
jparsedefaultcommodity Journal
j of
        Just (TagName
symbol,AmountStyle
style) -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
nullamt{acommodity=symbol,astyle=style}
        Maybe (TagName, AmountStyle)
Nothing -> Maybe Amount
forall a. Maybe a
Nothing

-- overcomplicated/unused amount traversal stuff
--
--  Get an ordered list of 'AmountStyle's from the amounts in this
-- journal which influence canonical amount display styles. See
-- traverseJournalAmounts.
-- journalAmounts :: Journal -> [Amount]
-- journalAmounts = getConst . traverseJournalAmounts (Const . (:[]))
--
--  Apply a transformation to the journal amounts traversed by traverseJournalAmounts.
-- overJournalAmounts :: (Amount -> Amount) -> Journal -> Journal
-- overJournalAmounts f = runIdentity . traverseJournalAmounts (Identity . f)
--
--  A helper that traverses over most amounts in the journal,
-- in particular the ones which influence canonical amount display styles,
-- processing them with the given applicative function.
--
-- These include, in the following order:
--
-- * the amount in the final default commodity (D) directive
-- * amounts in market price (P) directives (in parse order)
-- * posting amounts in transactions (in parse order)
--
-- Transaction price amounts, which may be embedded in posting amounts
-- (the acost field), are left intact but not traversed/processed.
--
-- traverseJournalAmounts :: Applicative f => (Amount -> f Amount) -> Journal -> f Journal
-- traverseJournalAmounts f j =
--   recombine <$> (traverse . dcamt) f (jparsedefaultcommodity j)
--             <*> (traverse . pdamt) f (jpricedirectives j)
--             <*> (traverse . tps . traverse . pamt . amts . traverse) f (jtxns j)
--   where
--     recombine pds txns = j { jpricedirectives = pds, jtxns = txns }
--     -- a bunch of traversals
--     dcamt g pd         = (\mdc -> case mdc of Nothing -> Nothing
--                                               Just ((c,stpd{pdamount =amt}
--                          ) <$> g (pdamount pd)
--     pdamt g pd         = (\amt -> pd{pdamount =amt}) <$> g (pdamount pd)
--     tps   g t          = (\ps  -> t {tpostings=ps }) <$> g (tpostings t)
--     pamt  g p          = (\amt -> p {pamount  =amt}) <$> g (pamount p)
--     amts  g (Mixed as) = Mixed <$> g as

-- | The fully specified exact date span enclosing the dates (primary or secondary)
-- of all this journal's transactions and postings, or DateSpan Nothing Nothing
-- if there are none.
journalDateSpan :: Bool -> Journal -> DateSpan
journalDateSpan :: Bool -> Journal -> DateSpan
journalDateSpan Bool
False = Maybe WhichDate -> Journal -> DateSpan
journalDateSpanHelper (Maybe WhichDate -> Journal -> DateSpan)
-> Maybe WhichDate -> Journal -> DateSpan
forall a b. (a -> b) -> a -> b
$ WhichDate -> Maybe WhichDate
forall a. a -> Maybe a
Just WhichDate
PrimaryDate
journalDateSpan Bool
True  = Maybe WhichDate -> Journal -> DateSpan
journalDateSpanHelper (Maybe WhichDate -> Journal -> DateSpan)
-> Maybe WhichDate -> Journal -> DateSpan
forall a b. (a -> b) -> a -> b
$ WhichDate -> Maybe WhichDate
forall a. a -> Maybe a
Just WhichDate
SecondaryDate

-- | The fully specified date span enclosing the dates (primary and secondary)
-- of all this journal's transactions and postings, or DateSpan Nothing Nothing
-- if there are none.
journalDateSpanBothDates :: Journal -> DateSpan
journalDateSpanBothDates :: Journal -> DateSpan
journalDateSpanBothDates = Maybe WhichDate -> Journal -> DateSpan
journalDateSpanHelper Maybe WhichDate
forall a. Maybe a
Nothing

-- | A helper for journalDateSpan which takes Maybe WhichDate directly. Nothing
-- uses both primary and secondary dates.
journalDateSpanHelper :: Maybe WhichDate -> Journal -> DateSpan
journalDateSpanHelper :: Maybe WhichDate -> Journal -> DateSpan
journalDateSpanHelper Maybe WhichDate
whichdate Journal
j =
    Maybe EFDay -> Maybe EFDay -> DateSpan
DateSpan (Day -> EFDay
Exact (Day -> EFDay) -> Maybe Day -> Maybe EFDay
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Day] -> Maybe Day
forall a. Ord a => [a] -> Maybe a
minimumMay [Day]
dates) (Day -> EFDay
Exact (Day -> EFDay) -> (Day -> Day) -> Day -> EFDay
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Day -> Day
addDays Integer
1 (Day -> EFDay) -> Maybe Day -> Maybe EFDay
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Day] -> Maybe Day
forall a. Ord a => [a] -> Maybe a
maximumMay [Day]
dates)
  where
    dates :: [Day]
dates    = [Day]
pdates [Day] -> [Day] -> [Day]
forall a. [a] -> [a] -> [a]
++ [Day]
tdates
    tdates :: [Day]
tdates   = (Transaction -> [Day]) -> [Transaction] -> [Day]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Transaction -> [Day]
gettdate [Transaction]
ts
    pdates :: [Day]
pdates   = (Posting -> [Day]) -> [Posting] -> [Day]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Posting -> [Day]
getpdate ([Posting] -> [Day]) -> [Posting] -> [Day]
forall a b. (a -> b) -> a -> b
$ (Transaction -> [Posting]) -> [Transaction] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Transaction -> [Posting]
tpostings [Transaction]
ts
    ts :: [Transaction]
ts       = Journal -> [Transaction]
jtxns Journal
j
    gettdate :: Transaction -> [Day]
gettdate Transaction
t = case Maybe WhichDate
whichdate of
        Just WhichDate
PrimaryDate   -> [Transaction -> Day
tdate Transaction
t]
        Just WhichDate
SecondaryDate -> [Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (Transaction -> Day
tdate Transaction
t) (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ Transaction -> Maybe Day
tdate2 Transaction
t]
        Maybe WhichDate
Nothing            -> Transaction -> Day
tdate Transaction
t Day -> [Day] -> [Day]
forall a. a -> [a] -> [a]
: Maybe Day -> [Day]
forall a. Maybe a -> [a]
maybeToList (Transaction -> Maybe Day
tdate2 Transaction
t)
    getpdate :: Posting -> [Day]
getpdate Posting
p = case Maybe WhichDate
whichdate of
        Just WhichDate
PrimaryDate   -> Maybe Day -> [Day]
forall a. Maybe a -> [a]
maybeToList (Maybe Day -> [Day]) -> Maybe Day -> [Day]
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Day
pdate Posting
p
        Just WhichDate
SecondaryDate -> Maybe Day -> [Day]
forall a. Maybe a -> [a]
maybeToList (Maybe Day -> [Day]) -> Maybe Day -> [Day]
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Day
pdate2 Posting
p Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Posting -> Maybe Day
pdate Posting
p
        Maybe WhichDate
Nothing            -> [Maybe Day] -> [Day]
forall a. [Maybe a] -> [a]
catMaybes [Posting -> Maybe Day
pdate Posting
p, Posting -> Maybe Day
pdate2 Posting
p]

-- | The earliest of this journal's transaction and posting dates, or
-- Nothing if there are none.
journalStartDate :: Bool -> Journal -> Maybe Day
journalStartDate :: Bool -> Journal -> Maybe Day
journalStartDate Bool
secondary Journal
j = EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
b where DateSpan Maybe EFDay
b Maybe EFDay
_ = Bool -> Journal -> DateSpan
journalDateSpan Bool
secondary Journal
j

-- | The "exclusive end date" of this journal: the day following its latest transaction 
-- or posting date, or Nothing if there are none.
journalEndDate :: Bool -> Journal -> Maybe Day
journalEndDate :: Bool -> Journal -> Maybe Day
journalEndDate Bool
secondary Journal
j = EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
e where DateSpan Maybe EFDay
_ Maybe EFDay
e = Bool -> Journal -> DateSpan
journalDateSpan Bool
secondary Journal
j

-- | The latest of this journal's transaction and posting dates, or
-- Nothing if there are none.
journalLastDay :: Bool -> Journal -> Maybe Day
journalLastDay :: Bool -> Journal -> Maybe Day
journalLastDay Bool
secondary Journal
j = Integer -> Day -> Day
addDays (-Integer
1) (Day -> Day) -> Maybe Day -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Bool -> Journal -> Maybe Day
journalEndDate Bool
secondary Journal
j

-- | Apply the pivot transformation to all postings in a journal,
-- replacing their account name by their value for the given field or tag.
journalPivot :: Text -> Journal -> Journal
journalPivot :: TagName -> Journal -> Journal
journalPivot TagName
fieldortagname Journal
j = Journal
j{jtxns = map (transactionPivot fieldortagname) . jtxns $ j}

-- | Replace this transaction's postings' account names with the value
-- of the given field or tag, if any.
-- The postings are relinked to the new transaction, so that queries which
-- look at a posting's siblings (any:, all:) see the pivoted account names.
transactionPivot :: Text -> Transaction -> Transaction
transactionPivot :: TagName -> Transaction -> Transaction
transactionPivot TagName
fieldortagname Transaction
t = Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = map (postingPivot fieldortagname) . tpostings $ t}

-- | Replace this posting's account name with the value
-- of the given field or tag, if any, otherwise the empty string.
postingPivot :: Text -> Posting -> Posting
postingPivot :: TagName -> Posting -> Posting
postingPivot TagName
fieldortagname Posting
p =
  Posting
p{paccount = pivotAccount fieldortagname p, poriginal = Just $ originalPosting p}

pivotAccount :: Text -> Posting -> Text
pivotAccount :: TagName -> Posting -> TagName
pivotAccount TagName
fieldortagname Posting
p =
  TagName -> [TagName] -> TagName
T.intercalate TagName
":" [TagName -> Posting -> TagName
pivotComponent TagName
x Posting
p | TagName
x <- HasCallStack => TagName -> TagName -> [TagName]
TagName -> TagName -> [TagName]
T.splitOn TagName
":" TagName
fieldortagname]

-- | Get the value of the given field or tag for this posting.
-- "comm" and "cur" are accepted as synonyms meaning the commodity symbol.
-- Pivoting on an unknown field or tag, or on commodity when there are multiple commodities, returns "".
-- Pivoting on a tag when there are multiple values for that tag, returns the first value.
-- Pivoting on the "type" tag normalises type values to their short spelling.
pivotComponent :: Text -> Posting -> Text
pivotComponent :: TagName -> Posting -> TagName
pivotComponent TagName
fieldortagname Posting
p
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"code",        Just Transaction
t <- Posting -> Maybe Transaction
ptransaction Posting
p = Transaction -> TagName
tcode Transaction
t
  | TagName
fieldortagname TagName -> [TagName] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [TagName]
descnames, Just Transaction
t <- Posting -> Maybe Transaction
ptransaction Posting
p = Transaction -> TagName
tdescription Transaction
t
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"payee",       Just Transaction
t <- Posting -> Maybe Transaction
ptransaction Posting
p = Transaction -> TagName
transactionPayee Transaction
t
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"note",        Just Transaction
t <- Posting -> Maybe Transaction
ptransaction Posting
p = Transaction -> TagName
transactionNote Transaction
t
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"status",      Just Transaction
t <- Posting -> Maybe Transaction
ptransaction Posting
p = RegexError -> TagName
T.pack (RegexError -> TagName)
-> (Transaction -> RegexError) -> Transaction -> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Status -> RegexError
forall a. Show a => a -> RegexError
show (Status -> RegexError)
-> (Transaction -> Status) -> Transaction -> RegexError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Status
tstatus (Transaction -> TagName) -> Transaction -> TagName
forall a b. (a -> b) -> a -> b
$ Transaction
t
  | TagName
fieldortagname TagName -> [TagName] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [TagName]
acctnames = Posting -> TagName
paccount Posting
p
  | TagName
fieldortagname TagName -> [TagName] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [TagName]
commnames = case (Amount -> TagName) -> [Amount] -> [TagName]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> TagName
acommodity ([Amount] -> [TagName]) -> [Amount] -> [TagName]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p of [TagName
s] -> TagName
s; [TagName]
_ -> TagName
unknown
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"amt"         = case MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p of [Amount
a] -> RegexError -> TagName
T.pack (RegexError -> TagName) -> RegexError -> TagName
forall a b. (a -> b) -> a -> b
$ Quantity -> RegexError
forall a. Show a => a -> RegexError
show (Quantity -> RegexError) -> Quantity -> RegexError
forall a b. (a -> b) -> a -> b
$ Amount -> Quantity
aquantity Amount
a; [Amount]
_ -> TagName
unknown
  | TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"cost"        = case MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p of [a :: Amount
a@Amount{acost :: Amount -> Maybe AmountCost
acost=Just AmountCost
_}] -> RegexError -> TagName
T.pack (RegexError -> TagName) -> RegexError -> TagName
forall a b. (a -> b) -> a -> b
$ ShowS
lstrip ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$ Amount -> RegexError
showAmountCost Amount
a; [Amount]
_ -> TagName
unknown
  | Just (TagName
_, TagName
tagvalue) <- TagName -> Posting -> Maybe Tag
postingFindTag TagName
fieldortagname Posting
p =
      if TagName
fieldortagname TagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
== TagName
"type"
      then (RegexError -> TagName)
-> (AccountType -> TagName)
-> Either RegexError AccountType
-> TagName
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (TagName -> RegexError -> TagName
forall a b. a -> b -> a
const TagName
tagvalue) (RegexError -> TagName
T.pack (RegexError -> TagName)
-> (AccountType -> RegexError) -> AccountType -> TagName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AccountType -> RegexError
forall a. Show a => a -> RegexError
show) (Either RegexError AccountType -> TagName)
-> Either RegexError AccountType -> TagName
forall a b. (a -> b) -> a -> b
$ Bool -> TagName -> Either RegexError AccountType
parseAccountType Bool
True TagName
tagvalue
      else TagName
tagvalue
  | Bool
otherwise = TagName
unknown
  where
    descnames :: [TagName]
descnames = [TagName
"desc", TagName
"description"]   -- allow "description" for hledger <=1.30 compat
    acctnames :: [TagName]
acctnames = [TagName
"acct", TagName
"account"]       -- allow either; acct is the query prefix, account is more natural
    commnames :: [TagName]
commnames = [TagName
"cur",TagName
"comm"]            -- allow either; cur is the query prefix, comm is more consistent
    unknown :: TagName
unknown   = TagName
""

postingFindTag :: TagName -> Posting -> Maybe (TagName, TagValue)
postingFindTag :: TagName -> Posting -> Maybe Tag
postingFindTag TagName
tagname Posting
p = (Tag -> Bool) -> [Tag] -> Maybe Tag
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((TagName
tagnameTagName -> TagName -> Bool
forall a. Eq a => a -> a -> Bool
==) (TagName -> Bool) -> (Tag -> TagName) -> Tag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tag -> TagName
forall a b. (a, b) -> a
fst) ([Tag] -> Maybe Tag) -> [Tag] -> Maybe Tag
forall a b. (a -> b) -> a -> b
$ Posting -> [Tag]
postingAllTags Posting
p

-- | Apply some account aliases to all posting account names in the journal, as described by accountNameApplyAliases.
-- This can fail due to a bad replacement pattern in a regular expression alias.
journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal
-- short circuit the common case, just in case there's a performance impact from txnTieKnot etc.
journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal
journalApplyAliases [] Journal
j = Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j
journalApplyAliases [AccountAlias]
aliases Journal
j = 
  case (Transaction -> Either RegexError Transaction)
-> [Transaction] -> Either RegexError [Transaction]
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 ([AccountAlias] -> Transaction -> Either RegexError Transaction
transactionApplyAliases [AccountAlias]
aliases) ([Transaction] -> Either RegexError [Transaction])
-> [Transaction] -> Either RegexError [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j of
    Right [Transaction]
ts -> Journal -> Either RegexError Journal
forall a b. b -> Either a b
Right Journal
j{jtxns = ts}
    Left RegexError
err -> RegexError -> Either RegexError Journal
forall a b. a -> Either a b
Left RegexError
err

-- -- | Build a database of market prices in effect on the given date,
-- -- from the journal's price directives.
-- journalPrices :: Day -> Journal -> Prices
-- journalPrices d = toPrices d . jpricedirectives

-- -- | Render a market price as a P directive.
-- showPriceDirectiveDirective :: PriceDirective -> String
-- showPriceDirectiveDirective pd = unwords
--     [ "P"
--     , showDate (pddate pd)
--     , T.unpack (pdcommodity pd)
--     , (showAmount . amountSetPrecision maxprecision) (pdamount pd
--     )
--     ]

-- debug helpers
-- traceAmountPrecision a = trace (show $ map (precision . acommodity) $ amounts a) a
-- tracePostingsCommodities ps = trace (show $ map ((map (precision . acommodity) . amounts) . pamount) ps) ps

-- tests
--
-- A sample journal for testing, similar to examples/sample.journal.
-- Provide an option to either use explicit amounts or missing amounts, for testing purposes.
--
-- 2008/01/01 income
--     assets:bank:checking  $1
--     income:salary
--
-- 2008/06/01 gift
--     assets:bank:checking  $1
--     income:gifts
--
-- 2008/06/02 save
--     assets:bank:saving  $1
--     assets:bank:checking
--
-- 2008/06/03 * eat & shop
--     expenses:food      $1
--     expenses:supplies  $1
--     assets:cash
--
-- 2008/10/01 take a loan
--     assets:bank:checking $1
--     liabilities:debts    $-1
--
-- 2008/12/31 * pay off
--     liabilities:debts  $1
--     assets:bank:checking

samplejournal :: Journal
samplejournal = Bool -> Journal
samplejournalMaybeExplicit Bool
True

samplejournalMaybeExplicit :: Bool -> Journal
samplejournalMaybeExplicit :: Bool -> Journal
samplejournalMaybeExplicit Bool
explicit = Journal
nulljournal
         {jtxns = [
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 01 01,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="",
             tdescription="income",
             tcomment="",
             ttags=[],
             tpostings=
                 ["assets:bank:checking" `post` usd 1
                 ,"income:salary" `post` if explicit then usd (-1) else missingamt
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 06 01,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="",
             tdescription="gift",
             tcomment="",
             ttags=[],
             tpostings=
                 ["assets:bank:checking" `post` usd 1
                 ,"income:gifts" `post` if explicit then usd (-1) else missingamt
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 06 02,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="",
             tdescription="save",
             tcomment="",
             ttags=[],
             tpostings=
                 ["assets:bank:saving" `post` usd 1
                 ,"assets:bank:checking" `post` if explicit then usd (-1) else missingamt
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 06 03,
             tdate2=Nothing,
             tstatus=Cleared,
             tcode="",
             tdescription="eat & shop",
             tcomment="",
             ttags=[],
             tpostings=["expenses:food" `post` usd 1
                       ,"expenses:supplies" `post` usd 1
                       ,"assets:cash" `post` if explicit then usd (-2) else missingamt
                       ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 10 01,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="",
             tdescription="take a loan",
             tcomment="",
             ttags=[],
             tpostings=["assets:bank:checking" `post` usd 1
                       ,"liabilities:debts" `post` usd (-1)
                       ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot $ Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2008 12 31,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="",
             tdescription="pay off",
             tcomment="",
             ttags=[],
             tpostings=["liabilities:debts" `post` usd 1
                       ,"assets:bank:checking" `post` if explicit then usd (-1) else missingamt
                       ],
             tprecedingcomment=""
           }
          ]
         }

tests_Journal :: TestTree
tests_Journal = RegexError -> [TestTree] -> TestTree
testGroup RegexError
"Journal" [

   RegexError -> Assertion -> TestTree
testCase RegexError
"journalDateSpan" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
    Bool -> Journal -> DateSpan
journalDateSpan Bool
True Journal
nulljournal{
      jtxns = [nulltransaction{tdate = fromGregorian 2014 02 01
                              ,tpostings = [posting{pdate=Just (fromGregorian 2014 01 10)}]
                              }
              ,nulltransaction{tdate = fromGregorian 2014 09 01
                              ,tpostings = [posting{pdate2=Just (fromGregorian 2014 10 10)}]
                              }
              ]
      }
    DateSpan -> DateSpan -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (Maybe EFDay -> Maybe EFDay -> DateSpan
DateSpan (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 -> EFDay) -> Day -> EFDay
forall a b. (a -> b) -> a -> b
$ Integer -> Int -> Int -> Day
fromGregorian Integer
2014 Int
1 Int
10) (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 -> EFDay) -> Day -> EFDay
forall a b. (a -> b) -> a -> b
$ Integer -> Int -> Int -> Day
fromGregorian Integer
2014 Int
10 Int
11))
  ]