{-|
Functions for ensuring transactions and journals are balanced.
-}

{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE PackageImports      #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell     #-}

module Hledger.Data.Balancing
( -- * BalancingOpts
  BalancingOpts(..)
, HasBalancingOpts(..)
, defbalancingopts
  -- * transaction balancing
, isTransactionBalanced
, balanceSingleTransaction
, balanceTransactionHelper
, transactionBalanceError
, transactionBalancingSum
, roundedPostingTagName
, transactionRoundCalculatedAmounts
, postingRoundCalculatedAmounts
  -- * assertion validation
, transactionCheckAssertions
  -- * journal balancing
, journalBalanceTransactions
, journalBalanceTransactionsAndDeferAssertions
  -- * tests
, tests_Balancing
)
where

import Control.Applicative ((<|>))
import Control.Monad (forM, forM_, when, unless)
import Control.Monad.Except (ExceptT(..), runExceptT, throwError, catchError)
import Control.Monad.Reader as R (ReaderT, reader, runReaderT, ask, asks)
import Control.Monad.ST (ST, runST)
import Control.Monad.Trans.Class (lift)
import Data.Array.ST (STArray, getElems, newListArray, writeArray)
import Data.Bifunctor (second)
import Data.Foldable (asum)
import Data.Function ((&))
import Data.Functor ((<&>), void)
import Data.HashTable.Class qualified as H (toList)
import Data.HashTable.ST.Cuckoo qualified as H
import Data.List (partition, sortOn, intercalate)
import Data.List.Extra (nubSort)
import Data.Either (isRight)
import Data.Maybe (fromJust, fromMaybe, isJust, isNothing, mapMaybe)
import Data.STRef (STRef, newSTRef, readSTRef, modifySTRef')
import Data.Set qualified as S
import Data.Text qualified as T
import Data.Time.Calendar (addDays, fromGregorian)
import Data.Map qualified as M
import Safe (headErr)
import Text.Printf (printf)

import Hledger.Data.Types
import Hledger.Data.AccountName (accountNameType, defaultImbalanceAccount, isAccountNamePrefixOf)
import Hledger.Data.Amount
import Hledger.Data.Journal
import Hledger.Data.Lots (isSetAsideGainPosting, lotBaseAccount, transactionAutoSplitFeeOutflows, transactionHasLotfulAmounts, transactionTagGainPostings)
import Hledger.Data.Posting
import Hledger.Data.Transaction
import Hledger.Data.Errors
import Hledger.Utils


data BalancingOpts = BalancingOpts
  { BalancingOpts -> Bool
ignore_assertions_     :: Bool  -- ^ should failing balance assertions be ignored ?
  , BalancingOpts -> Bool
infer_balancing_costs_ :: Bool  -- ^ Are we permitted to infer missing costs to balance transactions ?
                                    --   Distinct from InputOpts{infer_costs_}.
  , BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_      :: Maybe (M.Map CommoditySymbol AmountStyle)  -- ^ commodity display styles
  , BalancingOpts -> TransactionBalancingPrecision
txn_balancing_         :: TransactionBalancingPrecision
  , BalancingOpts -> Bool
infer_imbalance_       :: Bool  -- ^ should tolerated imbalances be shown, by adding imbalance postings to transactions ?
  , BalancingOpts -> CommoditySymbol
imbalance_account_     :: AccountName  -- ^ the account for imbalance postings (see journalAccountForType)
  , BalancingOpts -> Map CommoditySymbol AccountType
account_types_         :: M.Map AccountName AccountType  -- ^ account type map, passed through for any balancing helpers that need it
  , BalancingOpts -> Set CommoditySymbol
lotful_commodities_    :: S.Set CommoditySymbol  -- ^ commodities declared lotful, used to guide balancing cost inference (when lots are enabled)
  , BalancingOpts -> Map CommoditySymbol CommoditySymbol
account_lots_tags_     :: M.Map AccountName T.Text  -- ^ declared lots: tag values by account, used to detect lots: NONE opt-outs (when lots are enabled)
  , BalancingOpts -> Bool
lenient_lots_          :: Bool  -- ^ with --ignore-lots: relax the lot quantity mismatch veto, inferring a balancing conversion cost anyway
  , BalancingOpts -> Bool
verbose_balancing_tags_        :: Bool  -- ^ should tags added by balancing helpers (eg lot fee splits) also be made visible in comments ?
  } deriving (BalancingOpts -> BalancingOpts -> Bool
(BalancingOpts -> BalancingOpts -> Bool)
-> (BalancingOpts -> BalancingOpts -> Bool) -> Eq BalancingOpts
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BalancingOpts -> BalancingOpts -> Bool
== :: BalancingOpts -> BalancingOpts -> Bool
$c/= :: BalancingOpts -> BalancingOpts -> Bool
/= :: BalancingOpts -> BalancingOpts -> Bool
Eq, Eq BalancingOpts
Eq BalancingOpts =>
(BalancingOpts -> BalancingOpts -> Ordering)
-> (BalancingOpts -> BalancingOpts -> Bool)
-> (BalancingOpts -> BalancingOpts -> Bool)
-> (BalancingOpts -> BalancingOpts -> Bool)
-> (BalancingOpts -> BalancingOpts -> Bool)
-> (BalancingOpts -> BalancingOpts -> BalancingOpts)
-> (BalancingOpts -> BalancingOpts -> BalancingOpts)
-> Ord BalancingOpts
BalancingOpts -> BalancingOpts -> Bool
BalancingOpts -> BalancingOpts -> Ordering
BalancingOpts -> BalancingOpts -> BalancingOpts
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: BalancingOpts -> BalancingOpts -> Ordering
compare :: BalancingOpts -> BalancingOpts -> Ordering
$c< :: BalancingOpts -> BalancingOpts -> Bool
< :: BalancingOpts -> BalancingOpts -> Bool
$c<= :: BalancingOpts -> BalancingOpts -> Bool
<= :: BalancingOpts -> BalancingOpts -> Bool
$c> :: BalancingOpts -> BalancingOpts -> Bool
> :: BalancingOpts -> BalancingOpts -> Bool
$c>= :: BalancingOpts -> BalancingOpts -> Bool
>= :: BalancingOpts -> BalancingOpts -> Bool
$cmax :: BalancingOpts -> BalancingOpts -> BalancingOpts
max :: BalancingOpts -> BalancingOpts -> BalancingOpts
$cmin :: BalancingOpts -> BalancingOpts -> BalancingOpts
min :: BalancingOpts -> BalancingOpts -> BalancingOpts
Ord, Int -> BalancingOpts -> String -> String
[BalancingOpts] -> String -> String
BalancingOpts -> String
(Int -> BalancingOpts -> String -> String)
-> (BalancingOpts -> String)
-> ([BalancingOpts] -> String -> String)
-> Show BalancingOpts
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> BalancingOpts -> String -> String
showsPrec :: Int -> BalancingOpts -> String -> String
$cshow :: BalancingOpts -> String
show :: BalancingOpts -> String
$cshowList :: [BalancingOpts] -> String -> String
showList :: [BalancingOpts] -> String -> String
Show)

defbalancingopts :: BalancingOpts
defbalancingopts :: BalancingOpts
defbalancingopts = BalancingOpts
  { ignore_assertions_ :: Bool
ignore_assertions_     = Bool
False
  , infer_balancing_costs_ :: Bool
infer_balancing_costs_ = Bool
True
  , commodity_styles_ :: Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_      = Maybe (Map CommoditySymbol AmountStyle)
forall a. Maybe a
Nothing
  , txn_balancing_ :: TransactionBalancingPrecision
txn_balancing_         = TransactionBalancingPrecision
TBPEntry
  , infer_imbalance_ :: Bool
infer_imbalance_       = Bool
False
  , imbalance_account_ :: CommoditySymbol
imbalance_account_     = CommoditySymbol
forall {a}. IsString a => a
defaultImbalanceAccount
  , account_types_ :: Map CommoditySymbol AccountType
account_types_         = Map CommoditySymbol AccountType
forall k a. Map k a
M.empty
  , lotful_commodities_ :: Set CommoditySymbol
lotful_commodities_    = Set CommoditySymbol
forall a. Set a
S.empty
  , account_lots_tags_ :: Map CommoditySymbol CommoditySymbol
account_lots_tags_     = Map CommoditySymbol CommoditySymbol
forall k a. Map k a
M.empty
  , lenient_lots_ :: Bool
lenient_lots_          = Bool
False
  , verbose_balancing_tags_ :: Bool
verbose_balancing_tags_        = Bool
False
  }

-- | Check that this transaction would appear balanced to a human when displayed.
-- On success, returns the empty list, otherwise one or more error messages.
--
-- In more detail:
-- For the real postings, and separately for the balanced virtual postings:
--
-- 1. Convert amounts to cost where possible
--
-- 2. When there are two or more non-zero amounts
--    (appearing non-zero when displayed, using the given display styles if provided),
--    are they a mix of positives and negatives ?
--    This is checked separately to give a clearer error message.
--    (Best effort; could be confused by postings with multicommodity amounts.)
--
-- 3. Does the amounts' sum appear non-zero when displayed ?
--    (using the given display styles if provided)
--
transactionCheckBalanced :: BalancingOpts -> Transaction -> [String]
transactionCheckBalanced :: BalancingOpts -> Transaction -> [String]
transactionCheckBalanced BalancingOpts{commodity_styles_ :: BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_=Maybe (Map CommoditySymbol AmountStyle)
_mglobalstyles, TransactionBalancingPrecision
txn_balancing_ :: BalancingOpts -> TransactionBalancingPrecision
txn_balancing_ :: TransactionBalancingPrecision
txn_balancing_, Set CommoditySymbol
lotful_commodities_ :: BalancingOpts -> Set CommoditySymbol
lotful_commodities_ :: Set CommoditySymbol
lotful_commodities_, Bool
lenient_lots_ :: BalancingOpts -> Bool
lenient_lots_ :: Bool
lenient_lots_} Transaction
t = [String]
errs
  where
    -- get real and balanced virtual postings, to be checked separately
    ([Posting]
rps, [Posting]
bvps) = (Posting -> ([Posting], [Posting]) -> ([Posting], [Posting]))
-> ([Posting], [Posting]) -> [Posting] -> ([Posting], [Posting])
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Posting -> ([Posting], [Posting]) -> ([Posting], [Posting])
partitionPosting ([], []) ([Posting] -> ([Posting], [Posting]))
-> [Posting] -> ([Posting], [Posting])
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t
      where
        partitionPosting :: Posting -> ([Posting], [Posting]) -> ([Posting], [Posting])
partitionPosting Posting
p ~([Posting]
l, [Posting]
r) = case Posting -> PostingRealness
preal Posting
p of
            PostingRealness
RealPosting            -> (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
l, [Posting]
r)
            PostingRealness
BalancedVirtualPosting -> ([Posting]
l, Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
r)
            PostingRealness
VirtualPosting         -> ([Posting]
l, [Posting]
r)

    postingBalancingAmount :: Posting -> MixedAmount
postingBalancingAmount = (Posting -> Bool) -> Posting -> MixedAmount
postingBalancingAmountWith Posting -> Bool
setaside

    -- An exactly zero sum (the usual case) looks zero at any precision,
    -- so the display styles are inferred and applied only for inexact sums.
    lookszero :: MixedAmount -> Bool
lookszero MixedAmount
a = MixedAmount -> Bool
mixedAmountIsZero MixedAmount
a Bool -> Bool -> Bool
|| MixedAmount -> Bool
lookszeroatdisplayprecision MixedAmount
a
    lookszeroatdisplayprecision :: MixedAmount -> Bool
lookszeroatdisplayprecision = case TransactionBalancingPrecision
txn_balancing_ of
      TransactionBalancingPrecision
TBPDisplay -> MixedAmount -> Bool
lookszeroatglobaldisplayprecision
      TransactionBalancingPrecision
TBPEntry   -> MixedAmount -> Bool
lookszeroatlocaltransactionprecision

    lookszeroatlocaltransactionprecision :: MixedAmount -> Bool
lookszeroatlocaltransactionprecision = MixedAmount -> Bool
mixedAmountLooksZero (MixedAmount -> Bool)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts (Rounding -> Transaction -> Map CommoditySymbol AmountStyle
transactionCommodityStylesWith Rounding
HardRounding Transaction
t)
    lookszeroatglobaldisplayprecision :: MixedAmount -> Bool
lookszeroatglobaldisplayprecision    = MixedAmount -> Bool
mixedAmountLooksZero (MixedAmount -> Bool)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MixedAmount -> MixedAmount)
-> (Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount)
-> Maybe (Map CommoditySymbol AmountStyle)
-> MixedAmount
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount -> MixedAmount
forall a. a -> a
id Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Maybe (Map CommoditySymbol AmountStyle)
_mglobalstyles

    -- check that the sum looks like zero
    (MixedAmount
rsumcost,  MixedAmount
bvsumcost)  = ((Posting -> MixedAmount) -> [Posting] -> MixedAmount
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Posting -> MixedAmount
postingBalancingAmount [Posting]
rps, (Posting -> MixedAmount) -> [Posting] -> MixedAmount
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Posting -> MixedAmount
postingBalancingAmount [Posting]
bvps)
    ([MixedAmount]
rsumamts,  [MixedAmount]
bvsumamts)  = ((Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
postingBalancingAmount ([Posting] -> [Posting]
nongain [Posting]
rps), (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
postingBalancingAmount ([Posting] -> [Posting]
nongain [Posting]
bvps))
    setaside :: Posting -> Bool
setaside = Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t
    nongain :: [Posting] -> [Posting]
nongain = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Posting -> Bool) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> Bool
setaside)
    gainnote :: t Posting -> a
gainnote t Posting
ps = if (Posting -> Bool) -> t Posting -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
setaside t Posting
ps then a
"  (excluding gain postings)" else a
""
    (Bool
rsumok,    Bool
bvsumok)    = (MixedAmount -> Bool
lookszero MixedAmount
rsumcost, MixedAmount -> Bool
lookszero MixedAmount
bvsumcost)
    (Bool
rsumokold, Bool
bvsumokold) = (MixedAmount -> Bool
lookszeroatglobaldisplayprecision MixedAmount
rsumcost, MixedAmount -> Bool
lookszeroatglobaldisplayprecision MixedAmount
bvsumcost)

    -- when there's multiple non-zeros, check they do not all have the same sign
    (Bool
rsignsok, Bool
bvsignsok)   = ([Posting] -> Bool
signsOk [Posting]
rps, [Posting] -> Bool
signsOk [Posting]
bvps)
      where
        signsOk :: [Posting] -> Bool
signsOk [Posting]
ps = [MixedAmount] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [MixedAmount]
nonzeros Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 Bool -> Bool -> Bool
|| [Bool] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Bool]
nonzerosigns Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
          where
            nonzeros :: [MixedAmount]
nonzeros = (MixedAmount -> Bool) -> [MixedAmount] -> [MixedAmount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not(Bool -> Bool) -> (MixedAmount -> Bool) -> MixedAmount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.MixedAmount -> Bool
lookszero) ([MixedAmount] -> [MixedAmount]) -> [MixedAmount] -> [MixedAmount]
forall a b. (a -> b) -> a -> b
$ (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
postingBalancingAmount [Posting]
ps
            nonzerosigns :: [Bool]
nonzerosigns = [Bool] -> [Bool]
forall a. Ord a => [a] -> [a]
nubSort ([Bool] -> [Bool]) -> [Bool] -> [Bool]
forall a b. (a -> b) -> a -> b
$ (MixedAmount -> Maybe Bool) -> [MixedAmount] -> [Bool]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe MixedAmount -> Maybe Bool
isNegativeMixedAmount [MixedAmount]
nonzeros

    -- Generate error messages if any. Show amounts with their original precisions.
    errs :: [String]
errs = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not(Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null) [String
rmsg, String
bvmsg]
      where
        showamt :: MixedAmount -> String
showamt =
          AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
oneLineNoCostFmt{displayZeroCommodity=True} (MixedAmount -> String)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
          Maybe Word8 -> MixedAmount -> MixedAmount
mixedAmountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing (MixedAmount -> MixedAmount)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
          MixedAmount -> MixedAmount
mixedAmountSetFullPrecision
        rmsg :: String
rmsg
          | Bool
rsumok        = String
""
          | Bool -> Bool
not Bool
rsignsok  = String
"The real postings all have the same sign."
          | Bool
otherwise     = String
"The real postings' sum should be 0 but is "
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showamt MixedAmount
rsumcost
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"  +  " ((MixedAmount -> String) -> [MixedAmount] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map MixedAmount -> String
showamt [MixedAmount]
rsumamts) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  =  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showamt MixedAmount
rsumcost String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
forall {t :: * -> *} {a}.
(Foldable t, IsString a) =>
t Posting -> a
gainnote [Posting]
rps
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
forall {t :: * -> *} {a}.
(Foldable t, IsString a) =>
t Posting -> a
roundedmsg [Posting]
rps
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if Bool
rsumokold then String
oldbalancingmsg else String
"")
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
lotmismatchmsg [Posting]
rps
        bvmsg :: String
bvmsg
          | Bool
bvsumok       = String
""
          | Bool -> Bool
not Bool
bvsignsok = String
"The balanced virtual postings all have the same sign."
          | Bool
otherwise     = String
"The balanced virtual postings' sum should be 0 but is: "
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showamt MixedAmount
bvsumcost
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
" + " ((MixedAmount -> String) -> [MixedAmount] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map MixedAmount -> String
showamt [MixedAmount]
bvsumamts) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" = " String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showamt MixedAmount
bvsumcost String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
forall {t :: * -> *} {a}.
(Foldable t, IsString a) =>
t Posting -> a
gainnote [Posting]
bvps
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
forall {t :: * -> *} {a}.
(Foldable t, IsString a) =>
t Posting -> a
roundedmsg [Posting]
bvps
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if Bool
bvsumokold then String
oldbalancingmsg else String
"")
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ [Posting] -> String
lotmismatchmsg [Posting]
bvps
        -- When a balancing conversion cost was not inferred because of a
        -- lot quantity mismatch (see lotMismatchCommodities), explain that,
        -- since a user unaware of lot processing might expect this entry
        -- to balance by inference.
        lotmismatchmsg :: [Posting] -> String
lotmismatchmsg [Posting]
ps = case (CommoditySymbol -> String) -> [CommoditySymbol] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> String
T.unpack ([CommoditySymbol] -> [String]) -> [CommoditySymbol] -> [String]
forall a b. (a -> b) -> a -> b
$ Set CommoditySymbol -> [Posting] -> [CommoditySymbol]
lotMismatchCommodities Set CommoditySymbol
lotful_commodities_ [Posting]
ps of
          [] -> String
""
          [String]
cs -> [String] -> String
unlines ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ [
             String
"\nNote, " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String]
cs String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" is a lot-tracked commodity being transferred between accounts,"
            ,String
"so no balancing conversion cost was inferred; its quantities are expected"
            ,String
"to add up. If the difference is a fee, you can either"
            ,String
"- record the fee expense in the lot-tracked commodity, with posting(s)"
            ,String
"  adding up to the missing quantity"
            ,String
"- or split the sending posting into a transfer part and fee part(s)"
            ,String
"  matching the fee expense(s)."
            ]
            [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String
"(With --ignore-lots, a balancing conversion cost is inferred instead.)" | Bool -> Bool
not Bool
lenient_lots_]
        -- When some amounts were calculated with * or / in amount expressions, and changed
        -- by rounding (see roundedPostingTagName), mention that.
        roundedmsg :: t Posting -> a
roundedmsg t Posting
ps
          | (Posting -> Bool) -> t Posting -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
roundedPostingTagName) t Posting
ps =
              a
"\nNote, amounts calculated with * or / are rounded; to split unevenly, leave one amount blank."
          | Bool
otherwise = a
""
        oldbalancingmsg :: String
oldbalancingmsg = [String] -> String
unlines [
          -- -------------------------------------------------------------------------------
           String
"\nNote, hledger <1.50 accepted this entry because of the global display precision,"
          ,String
"but hledger 1.50+ checks more strictly, using the entry's local precision."
          ,String
"You can use --txn-tolerance=display to keep it working, or fix it (recommended);"
          ,String
"see 'Transaction balancing' in the hledger manual."
          ]

-- | A posting's amount as it counts towards its transaction's balance:
-- converted to cost, unless it has been marked as a redundant cost
-- (equivalent to some nearby equity conversion postings), in which case the cost is ignored;
-- or nothing, if it is a disposal's realised gain posting, which is set aside
-- (according to the given predicate, usually 'isSetAsideGainPosting' partially applied to the transaction).
-- A disposal balances at cost basis, which is equivalent to its non-gain postings balancing
-- at transacted cost (see Hledger.Data.Lots.transactionTagGainPostings;
-- not when the entry has conversion postings, see isSetAsideGainPosting).
postingBalancingAmountWith :: (Posting -> Bool) -> Posting -> MixedAmount
postingBalancingAmountWith :: (Posting -> Bool) -> Posting -> MixedAmount
postingBalancingAmountWith Posting -> Bool
setaside Posting
p
  | CommoditySymbol
costPostingTagName CommoditySymbol -> [CommoditySymbol] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ((CommoditySymbol, CommoditySymbol) -> CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (CommoditySymbol, CommoditySymbol) -> CommoditySymbol
forall a b. (a, b) -> a
fst (Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p) = MixedAmount -> MixedAmount
mixedAmountStripCosts (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
  | Posting -> Bool
setaside Posting
p                                  = MixedAmount
nullmixedamt
  | Bool
otherwise                                   = MixedAmount -> MixedAmount
mixedAmountCost (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p

-- | The sum of all of this transaction's postings, converted to cost as when balancing it,
-- including any unbalanced virtual postings. For a balanced transaction this is zero
-- (or a tolerated imbalance; see transactionCheckBalanced) plus the unbalanced virtual postings' amounts.
-- This is the amount a sum: query tests for a transaction.
transactionBalancingSum :: Transaction -> MixedAmount
transactionBalancingSum :: Transaction -> MixedAmount
transactionBalancingSum Transaction
t = (Posting -> MixedAmount) -> [Posting] -> MixedAmount
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap ((Posting -> Bool) -> Posting -> MixedAmount
postingBalancingAmountWith Posting -> Bool
setaside) ([Posting] -> MixedAmount) -> [Posting] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t
  where setaside :: Posting -> Bool
setaside = Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t

-- | Postings which would show this balanced transaction's remaining imbalance
-- (tolerated because it's smaller than the balancing precision; see transactionCheckBalanced),
-- making the transaction balance exactly. These are postings to the given account,
-- one for each commodity of the real postings' imbalance, and likewise (but balanced virtual)
-- for the balanced virtual postings' imbalance, or none if the transaction balances exactly.
-- They are tagged with imbalancePostingTagName and generatedPostingTagName
-- (and with a true verbosetags argument, visibly too).
-- They behave like amountless postings written by the user, whose amount was inferred:
-- their amounts have the given commodity display styles but keep their full precision,
-- and since their original posting is amountless, these don't influence commodity display precisions
-- (see isExplicitAmount).
-- Imbalances which would display as zero are ignored. These are leftovers from hledger's own division
-- (repeating decimals, rounded at the 255th decimal place), too small to show at the 8 decimal places
-- used to display repeating decimals (see amountSetFullPrecisionUpTo).
-- Imbalances calculated from written amounts and costs are finite decimals, shown in full.
transactionImbalancePostings :: Bool -> AccountName -> M.Map CommoditySymbol AmountStyle -> Transaction -> [Posting]
transactionImbalancePostings :: Bool
-> CommoditySymbol
-> Map CommoditySymbol AmountStyle
-> Transaction
-> [Posting]
transactionImbalancePostings Bool
verbosetags CommoditySymbol
acct Map CommoditySymbol AmountStyle
styles Transaction
t =
  [ PostingRealness -> Amount -> Posting
imbalancePosting PostingRealness
r Amount
a
  | PostingRealness
r <- [PostingRealness
RealPosting, PostingRealness
BalancedVirtualPosting]
  , Amount
a <- MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ (Posting -> MixedAmount) -> [Posting] -> MixedAmount
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap ((Posting -> Bool) -> Posting -> MixedAmount
postingBalancingAmountWith Posting -> Bool
setaside) [Posting
p | Posting
p <- Transaction -> [Posting]
tpostings Transaction
t, Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
r]
  , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Amount -> Bool
amountLooksZero (Amount -> Bool) -> Amount -> Bool
forall a b. (a -> b) -> a -> b
$ Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing Amount
a
  ]
  where
    setaside :: Posting -> Bool
setaside = Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t
    imbalancePosting :: PostingRealness -> Amount -> Posting
imbalancePosting PostingRealness
r Amount
a = Posting
p{poriginal = Just p{pamount = missingmixedamt}}
      where
        p :: Posting
p = Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
generatedPostingTagName, CommoditySymbol
"")
          (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
imbalancePostingTagName, CommoditySymbol
"")
          (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Posting
nullposting{paccount = acct, preal = r,
                        pamount = styleAmounts (styles & amountStylesSetRounding NoRounding) $ mixedAmount $ negate a}

-- | With the infer_imbalance_ option, add postings showing this balanced transaction's
-- tolerated imbalance, if any (see 'transactionImbalancePostings').
-- Returns the (possibly) updated transaction, and the added postings.
transactionMaybeAddImbalancePostings :: BalancingOpts -> Transaction -> (Transaction, [Posting])
transactionMaybeAddImbalancePostings :: BalancingOpts -> Transaction -> (Transaction, [Posting])
transactionMaybeAddImbalancePostings BalancingOpts
bopts Transaction
t
  | Bool -> Bool
not (BalancingOpts -> Bool
infer_imbalance_ BalancingOpts
bopts) Bool -> Bool -> Bool
|| [Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
ips = (Transaction
t, [])
  | Bool
otherwise                                = (Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = tpostings t ++ ips}, [Posting]
ips)
  where
    ips :: [Posting]
ips = Bool
-> CommoditySymbol
-> Map CommoditySymbol AmountStyle
-> Transaction
-> [Posting]
transactionImbalancePostings (BalancingOpts -> Bool
verbose_balancing_tags_ BalancingOpts
bopts) (BalancingOpts -> CommoditySymbol
imbalance_account_ BalancingOpts
bopts) (Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a. a -> Maybe a -> a
fromMaybe Map CommoditySymbol AmountStyle
forall k a. Map k a
M.empty (Maybe (Map CommoditySymbol AmountStyle)
 -> Map CommoditySymbol AmountStyle)
-> Maybe (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_ BalancingOpts
bopts) Transaction
t

-- | Legacy form of transactionCheckBalanced.
isTransactionBalanced :: BalancingOpts -> Transaction -> Bool
isTransactionBalanced :: BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
bopts = [String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([String] -> Bool)
-> (Transaction -> [String]) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalancingOpts -> Transaction -> [String]
transactionCheckBalanced BalancingOpts
bopts

-- | Verify that any assertions in this transaction hold 
-- when included in the larger journal.
transactionCheckAssertions :: BalancingOpts -> Journal -> Transaction -> Either String Transaction
transactionCheckAssertions :: BalancingOpts
-> Journal -> Transaction -> Either String Transaction
transactionCheckAssertions BalancingOpts
bopts Journal
j Transaction
t =
  if (BalancingOpts -> Bool
ignore_assertions_ BalancingOpts
bopts) then Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
t else do
    j' <- Journal -> Either String Journal
journalStyleAmounts Journal
j 
    let newtxns = (Transaction -> Day) -> [Transaction] -> [Transaction]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Transaction -> Day
tdate (Journal -> [Transaction]
jtxns Journal
j' [Transaction] -> [Transaction] -> [Transaction]
forall a. [a] -> [a] -> [a]
++ [ Transaction
t ])
    case journalBalanceTransactions bopts j'{jtxns = newtxns} of
      Right Journal
_ -> Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
t
      Left String
e -> String -> Either String Transaction
forall a b. a -> Either a b
Left String
e

-- | Balance this isolated transaction, ensuring that its postings
-- (and its balanced virtual postings) sum to 0,
-- by inferring a missing amount or conversion price(s) if needed.
-- Or if balancing is not possible, because the amounts don't sum to 0 or
-- because there's more than one missing amount, return an error message.
--
-- Note this is not as accurate as @balanceTransactionInJournal@,
-- which considers the whole journal when calculating balance assignments and balance assertions.
balanceSingleTransaction :: BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction :: BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
bopts = ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String Transaction
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction
forall a b. (a, b) -> a
fst (Either String (Transaction, [(CommoditySymbol, MixedAmount)])
 -> Either String Transaction)
-> (Transaction
    -> Either String (Transaction, [(CommoditySymbol, MixedAmount)]))
-> Transaction
-> Either String Transaction
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts

-- | Like 'balanceTransactionHelper', but in a lots journal, first try
-- balancing the transaction with its lot fee outflows auto-split
-- ('transactionAutoSplitFeeOutflows'): a lot transfer with a priced fee
-- only balances at cost in split form. If no split applies or the split
-- form doesn't balance, balance the unsplit form as usual (preserving its
-- error message if both fail). Lot classification runs after balancing and
-- will classify the split postings (#2686, #2692).
balanceTransactionHelperMaybeSplittingLotFees :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])
balanceTransactionHelperMaybeSplittingLotFees :: BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelperMaybeSplittingLotFees BalancingOpts
bopts Transaction
t0
  | Bool -> Bool
not Bool
haslots = BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t0  -- no lots involved, nothing to tag or split
  | Set CommoditySymbol -> Bool
forall a. Set a -> Bool
S.null Set CommoditySymbol
lotfulcomms = BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t  -- no lotful commodities declared, no fee splitting
  | [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Transaction -> [Posting]
tpostings Transaction
t2) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Transaction -> [Posting]
tpostings Transaction
t) = BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t  -- no split applied
  | Bool
otherwise = case BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t2 of
      r :: Either String (Transaction, [(CommoditySymbol, MixedAmount)])
r@(Right (Transaction, [(CommoditySymbol, MixedAmount)])
_) -> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
r
      Left String
_      -> BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t
  where
    lotfulcomms :: Set CommoditySymbol
lotfulcomms = BalancingOpts -> Set CommoditySymbol
lotful_commodities_ BalancingOpts
bopts
    -- Could this entry involve lots ? Only if some amount has a cost basis or is in a lotful commodity.
    haslots :: Bool
haslots = Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts Set CommoditySymbol
lotfulcomms Transaction
t0
    -- Tag any user-written gain postings in a disposal first, so the balancer
    -- sets them aside. (journalFinalise does this too, but callers balancing a
    -- single entry, like hledger add, rely on it happening here.)
    t :: Transaction
t = Bool
-> Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionTagGainPostings (Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Bool
lenient_lots_ BalancingOpts
bopts) (BalancingOpts -> Bool
verbose_balancing_tags_ BalancingOpts
bopts) (Map CommoditySymbol AccountType
-> CommoditySymbol -> Maybe AccountType
accountNameType (BalancingOpts -> Map CommoditySymbol AccountType
account_types_ BalancingOpts
bopts)) (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms)
          (Map CommoditySymbol CommoditySymbol -> CommoditySymbol -> Bool
accountUsesNoLotsWith (BalancingOpts -> Map CommoditySymbol CommoditySymbol
account_lots_tags_ BalancingOpts
bopts)) Transaction
t0
    t2 :: Transaction
t2 = Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionAutoSplitFeeOutflows (BalancingOpts -> Bool
verbose_balancing_tags_ BalancingOpts
bopts) (Map CommoditySymbol AccountType
-> CommoditySymbol -> Maybe AccountType
accountNameType (BalancingOpts -> Map CommoditySymbol AccountType
account_types_ BalancingOpts
bopts)) (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms)
           (Map CommoditySymbol CommoditySymbol -> CommoditySymbol -> Bool
accountUsesNoLotsWith (BalancingOpts -> Map CommoditySymbol CommoditySymbol
account_lots_tags_ BalancingOpts
bopts)) Transaction
t

-- | An internal tag added by the journal reader to postings whose amount was calculated with
-- * or / in an amount expression, and changed by rounding (see
-- transactionRoundCalculatedAmounts) (#2648).
-- If the transaction doesn't balance, the error mentions the rounding.
-- The tag is removed when the transaction balances, so it is not seen by users or queries.
roundedPostingTagName :: TagName
roundedPostingTagName :: CommoditySymbol
roundedPostingTagName = CommoditySymbol
"_rounded-posting"

-- | Remove the internal 'roundedPostingTagName' tag from a transaction's postings, if any.
transactionRemoveRoundedTags :: Transaction -> Transaction
transactionRemoveRoundedTags :: Transaction -> Transaction
transactionRemoveRoundedTags Transaction
t
  | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
roundedPostingTagName) ([Posting] -> Bool) -> [Posting] -> Bool
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t =
      Transaction
t{tpostings = [p{ptags = filter ((/= roundedPostingTagName) . fst) $ ptags p} | p <- tpostings t]}
  | Bool
otherwise = Transaction
t

-- | Round the amounts in a transaction's postings which were calculated with * or / in an
-- amount expression, and which are exact until now (see amountexprp) (#2648).
-- Each is rounded to the transaction's balancing precision for its commodity, ie the most
-- decimal places of that commodity's posting amounts in the entry, as written, including any
-- amounts written in expressions, not counting costs (see transactionCommodityStyles).
-- As in balancing, amounts to be generated by balance assignments count too; their assigned
-- amounts are used for this.
-- This is done after all postings have been read, so it doesn't depend on their order.
-- Postings whose amount is changed by this get the internal roundedPostingTagName tag,
-- so that if the transaction doesn't balance, the error can mention the rounding.
-- The balancer removes the tag (see balanceTransactionHelper).
transactionRoundCalculatedAmounts :: Transaction -> Transaction
transactionRoundCalculatedAmounts :: Transaction -> Transaction
transactionRoundCalculatedAmounts Transaction
t = Transaction
t{tpostings = map roundposting $ tpostings t}
  where
    styles :: Map CommoditySymbol AmountStyle
styles = Transaction -> Map CommoditySymbol AmountStyle
transactionCommodityStyles Transaction
t{tpostings = map withassignedamount $ tpostings t}
    withassignedamount :: Posting -> Posting
withassignedamount Posting
p = case Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p of
      Just BalanceAssertion
ba | Posting -> Bool
hasBalanceAssignment Posting
p -> Posting
p{pamount = mixedAmount $ baamount ba}
      Maybe BalanceAssertion
_                                -> Posting
p
    roundposting :: Posting -> Posting
roundposting Posting
p = case Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)
postingRoundCalculatedAmounts Map CommoditySymbol AmountStyle
styles Posting
p of
      (Posting
p', Bool
True)  -> Posting -> [(CommoditySymbol, CommoditySymbol)] -> Posting
postingAddTags Posting
p' [(CommoditySymbol
roundedPostingTagName, CommoditySymbol
"")]
      (Posting
p', Bool
False) -> Posting
p'

-- | Round the amounts in this posting which were calculated with * or / in an amount expression
-- (see amountexprp) (#2648). These are the amounts with more decimal places than their precision,
-- which is the most decimal places written in the amounts they were calculated from;
-- other parsed amounts never have more.
-- Each is rounded to the precision of its commodity's style in the given map,
-- or to its own precision if that is larger or the commodity is not in the map.
-- This uses banker's rounding, like other hledger rounding, and the rounded amount gets that precision.
-- Also returns whether this changed any amount's quantity.
postingRoundCalculatedAmounts :: M.Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)
postingRoundCalculatedAmounts :: Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)
postingRoundCalculatedAmounts Map CommoditySymbol AmountStyle
styles Posting
p
  | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
iscalculated [Amount]
amts = (Posting
p, Bool
False)
  | Bool
otherwise = (Posting
p{pamount = mapMixedAmount roundcalculated $ pamount p}, (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
changed [Amount]
amts)
  where
    amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
    iscalculated :: Amount -> Bool
iscalculated Amount
a = case AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
a of
      Precision Word8
n      -> Amount -> Word8
amountInternalPrecision Amount
a Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
> Word8
n
      AmountPrecision
NaturalPrecision -> Bool
False
    precision :: Amount -> Word8
precision Amount
a = case (AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
a, AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision)
-> Maybe AmountStyle -> Maybe AmountPrecision
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CommoditySymbol
-> Map CommoditySymbol AmountStyle -> Maybe AmountStyle
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Amount -> CommoditySymbol
acommodity Amount
a) Map CommoditySymbol AmountStyle
styles) of
      (Precision Word8
n, Just (Precision Word8
m)) -> Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
max Word8
n Word8
m
      (Precision Word8
n, Maybe AmountPrecision
_)                  -> Word8
n
      (AmountPrecision
NaturalPrecision, Maybe AmountPrecision
_)             -> Amount -> Word8
amountInternalPrecision Amount
a
    rounded :: Amount -> Amount
rounded Amount
a = let a' :: Amount
a' = AmountPrecision -> Amount -> Amount
amountSetPrecision (Word8 -> AmountPrecision
Precision (Word8 -> AmountPrecision) -> Word8 -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> Word8
precision Amount
a) Amount
a in Amount
a'{aquantity = amountRoundedQuantity a'}
    roundcalculated :: Amount -> Amount
roundcalculated Amount
a = if Amount -> Bool
iscalculated Amount
a then Amount -> Amount
rounded Amount
a else Amount
a
    changed :: Amount -> Bool
changed Amount
a = Amount -> Bool
iscalculated Amount
a Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity (Amount -> Amount
rounded Amount
a) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Amount -> Quantity
aquantity Amount
a

-- | Helper used by balanceSingleTransaction and balanceTransactionWithBalanceAssignmentAndCheckAssertionsB;
-- use one of those instead.
-- It also returns a list of accounts and amounts that were inferred.
balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])
balanceTransactionHelper :: BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelper BalancingOpts
bopts Transaction
t = do
  let lbl :: String -> String -> String
lbl = String -> String -> String -> String
lbl_ String
"balanceTransactionHelper"
  (t', inferredamtsandaccts) <- Transaction
t
    Transaction -> (Transaction -> Transaction) -> Transaction
forall a b. a -> (a -> b) -> b
& (if BalancingOpts -> Bool
infer_balancing_costs_ BalancingOpts
bopts then Bool -> Set CommoditySymbol -> Transaction -> Transaction
transactionInferBalancingCosts (BalancingOpts -> Bool
lenient_lots_ BalancingOpts
bopts) (BalancingOpts -> Set CommoditySymbol
lotful_commodities_ BalancingOpts
bopts) else Transaction -> Transaction
forall a. a -> a
id)
    Transaction -> (Transaction -> Transaction) -> Transaction
forall a b. a -> (a -> b) -> b
& (Transaction -> String) -> Transaction -> Transaction
forall a. (a -> String) -> a -> a
dbg9With (String -> String -> String
lbl String
"amounts after balancing-cost-inferring"(String -> String)
-> (Transaction -> String) -> Transaction -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.[String] -> String
forall a. Show a => a -> String
show([String] -> String)
-> (Transaction -> [String]) -> Transaction -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(MixedAmount -> String) -> [MixedAmount] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map MixedAmount -> String
showMixedAmountOneLine([MixedAmount] -> [String])
-> (Transaction -> [MixedAmount]) -> Transaction -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Transaction -> [MixedAmount]
transactionAmounts)
    Transaction
-> (Transaction
    -> Either String (Transaction, [(CommoditySymbol, MixedAmount)]))
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. a -> (a -> b) -> b
& Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AccountType
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
transactionInferBalancingAmount (Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a. a -> Maybe a -> a
fromMaybe Map CommoditySymbol AmountStyle
forall k a. Map k a
M.empty (Maybe (Map CommoditySymbol AmountStyle)
 -> Map CommoditySymbol AmountStyle)
-> Maybe (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_ BalancingOpts
bopts) (BalancingOpts -> Map CommoditySymbol AccountType
account_types_ BalancingOpts
bopts)
    Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> ((Transaction, [(CommoditySymbol, MixedAmount)])
    -> (Transaction, [(CommoditySymbol, MixedAmount)]))
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> ((Transaction, [(CommoditySymbol, MixedAmount)]) -> String)
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> (Transaction, [(CommoditySymbol, MixedAmount)])
forall a. (a -> String) -> a -> a
dbg9With (String -> String -> String
lbl String
"balancing amounts inferred"(String -> String)
-> ((Transaction, [(CommoditySymbol, MixedAmount)]) -> String)
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.[(CommoditySymbol, String)] -> String
forall a. Show a => a -> String
show([(CommoditySymbol, String)] -> String)
-> ((Transaction, [(CommoditySymbol, MixedAmount)])
    -> [(CommoditySymbol, String)])
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.((CommoditySymbol, MixedAmount) -> (CommoditySymbol, String))
-> [(CommoditySymbol, MixedAmount)] -> [(CommoditySymbol, String)]
forall a b. (a -> b) -> [a] -> [b]
map ((MixedAmount -> String)
-> (CommoditySymbol, MixedAmount) -> (CommoditySymbol, String)
forall b c a. (b -> c) -> (a, b) -> (a, c)
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second MixedAmount -> String
showMixedAmountOneLine)([(CommoditySymbol, MixedAmount)] -> [(CommoditySymbol, String)])
-> ((Transaction, [(CommoditySymbol, MixedAmount)])
    -> [(CommoditySymbol, MixedAmount)])
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> [(CommoditySymbol, String)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Transaction, [(CommoditySymbol, MixedAmount)])
-> [(CommoditySymbol, MixedAmount)]
forall a b. (a, b) -> b
snd)
  case transactionCheckBalanced bopts t' of
    []   -> (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. b -> Either a b
Right (Transaction -> Transaction
txnTieKnot (Transaction -> Transaction) -> Transaction -> Transaction
forall a b. (a -> b) -> a -> b
$ Transaction -> Transaction
transactionRemoveRoundedTags Transaction
t', [(CommoditySymbol, MixedAmount)]
inferredamtsandaccts)
    [String]
errs -> String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. a -> Either a b
Left (String
 -> Either String (Transaction, [(CommoditySymbol, MixedAmount)]))
-> String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. (a -> b) -> a -> b
$ Transaction -> [String] -> String
transactionBalanceError Transaction
t' [String]
errs'
      where
        ismulticommodity :: Bool
ismulticommodity = (Set CommoditySymbol -> Int
forall a. Set a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Set CommoditySymbol -> Int) -> Set CommoditySymbol -> Int
forall a b. (a -> b) -> a -> b
$ Transaction -> Set CommoditySymbol
transactionCommodities Transaction
t') Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
        errs' :: [String]
errs' =
          [ String
"Automatic commodity conversion is disabled by strict mode or the balanced check."
          | Bool
ismulticommodity Bool -> Bool -> Bool
&& Bool -> Bool
not (BalancingOpts -> Bool
infer_balancing_costs_ BalancingOpts
bopts)
          ] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
          [String]
errs
          -- silence hints for now
          -- ++
          -- if ismulticommodity
          -- then
          -- [ "Consider adjusting this entry's amounts, adding missing postings,"
          -- , "or recording conversion price(s) with @, @@ or equity postings." 
          -- ]
          -- else []

transactionCommodities :: Transaction -> S.Set CommoditySymbol
transactionCommodities :: Transaction -> Set CommoditySymbol
transactionCommodities Transaction
t = [Set CommoditySymbol] -> Set CommoditySymbol
forall a. Monoid a => [a] -> a
mconcat ([Set CommoditySymbol] -> Set CommoditySymbol)
-> [Set CommoditySymbol] -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (Posting -> Set CommoditySymbol)
-> [Posting] -> [Set CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (MixedAmount -> Set CommoditySymbol
maCommodities (MixedAmount -> Set CommoditySymbol)
-> (Posting -> MixedAmount) -> Posting -> Set CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount) ([Posting] -> [Set CommoditySymbol])
-> [Posting] -> [Set CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t

-- | Generate a transaction balancing error message, given the transaction
-- and one or more suberror messages.
transactionBalanceError :: Transaction -> [String] -> String
transactionBalanceError :: Transaction -> [String] -> String
transactionBalanceError Transaction
t [String]
errs = String -> String -> CommoditySymbol -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:\n%s\n\nThis %stransaction is unbalanced.\n%s"
  ((SourcePos, SourcePos) -> String
sourcePosPairPretty ((SourcePos, SourcePos) -> String)
-> (SourcePos, SourcePos) -> String
forall a b. (a -> b) -> a -> b
$ Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t)
  (CommoditySymbol -> CommoditySymbol
textChomp CommoditySymbol
ex)
  (if Bool
ismulticommodity then String
"multi-commodity " else String
"" :: String)
  (String -> String
chomp (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
unlines [String]
errs)
  where
    ismulticommodity :: Bool
ismulticommodity = (Set CommoditySymbol -> Int
forall a. Set a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Set CommoditySymbol -> Int) -> Set CommoditySymbol -> Int
forall a b. (a -> b) -> a -> b
$ Transaction -> Set CommoditySymbol
transactionCommodities Transaction
t) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
    (String
_f,Int
_l,Maybe (Int, Maybe Int)
_mcols,CommoditySymbol
ex) = Transaction
-> (Transaction -> Maybe (Int, Maybe Int))
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeTransactionErrorExcerpt Transaction
t Transaction -> Maybe (Int, Maybe Int)
forall {p} {a}. p -> Maybe a
finderrcols
      where
        finderrcols :: p -> Maybe a
finderrcols p
_ = Maybe a
forall a. Maybe a
Nothing
        -- finderrcols t = Just (1, Just w)
        --   where
        --     w = maximumDef 1 $ map T.length $ T.lines $ showTransaction t

-- | Infer up to one missing amount for this transactions's real postings, and
-- likewise for its balanced virtual postings, if needed; or return an error
-- message if we can't. Returns the updated transaction and any inferred posting amounts,
-- with the corresponding accounts, in order).
--
-- We can infer a missing amount when there are multiple postings and exactly
-- one of them is amountless. If the amounts had price(s) the inferred amount
-- have the same price(s), and will be converted to the price commodity.
transactionInferBalancingAmount ::
     M.Map CommoditySymbol AmountStyle -- ^ commodity display styles
  -> M.Map AccountName AccountType     -- ^ account type map (passed through; reserved for future use)
  -> Transaction
  -> Either String (Transaction, [(AccountName, MixedAmount)])
transactionInferBalancingAmount :: Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AccountType
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
transactionInferBalancingAmount Map CommoditySymbol AmountStyle
styles Map CommoditySymbol AccountType
_atypes t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps}
  | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Posting -> Bool
hasAmount [Posting]
ps = (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. b -> Either a b
Right (Transaction
t, [])  -- nothing to infer (the usual case), keep the transaction as is
  | [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
amountlessrealps Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
      = String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. a -> Either a b
Left (String
 -> Either String (Transaction, [(CommoditySymbol, MixedAmount)]))
-> String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. (a -> b) -> a -> b
$ Transaction -> [String] -> String
transactionBalanceError Transaction
t
        [String
"There can't be more than one real posting with no amount."
        ,String
"(Remember to put two or more spaces between account and amount.)"]
  | [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
amountlessbvps Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
      = String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. a -> Either a b
Left (String
 -> Either String (Transaction, [(CommoditySymbol, MixedAmount)]))
-> String
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. (a -> b) -> a -> b
$ Transaction -> [String] -> String
transactionBalanceError Transaction
t
        [String
"There can't be more than one balanced virtual posting with no amount."
        ,String
"(Remember to put two or more spaces between account and amount.)"]
  | Bool
otherwise
      = let psandinferredamts :: [(Posting, Maybe MixedAmount)]
psandinferredamts = (Posting -> (Posting, Maybe MixedAmount))
-> [Posting] -> [(Posting, Maybe MixedAmount)]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> (Posting, Maybe MixedAmount)
inferamount [Posting]
ps
            inferredacctsandamts :: [(CommoditySymbol, MixedAmount)]
inferredacctsandamts = [(Posting -> CommoditySymbol
paccount Posting
p, MixedAmount
amt) | (Posting
p, Just MixedAmount
amt) <- [(Posting, Maybe MixedAmount)]
psandinferredamts]
        in (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
forall a b. b -> Either a b
Right (
           Transaction
t{tpostings=map fst psandinferredamts}
          ,[(CommoditySymbol, MixedAmount)]
inferredacctsandamts
           -- & dbg9With (lbl "inferred".show.map (showMixedAmountOneLine.snd))
          )
  where
    lbl :: String -> String -> String
lbl = String -> String -> String -> String
lbl_ String
"transactionInferBalancingAmount"
    -- Gain postings in a disposal are set aside (see transactionCheckBalanced):
    -- they don't contribute to the sum, and an amountless one is not inferred
    -- here (journalAddOrCheckGainPostings fills it in after lot matching).
    setaside :: Posting -> Bool
setaside = Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t
    ([Posting]
amountfulrealps, [Posting]
amountlessrealps) = (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Posting -> Bool
hasAmount ([Posting] -> ([Posting], [Posting]))
-> [Posting] -> ([Posting], [Posting])
forall a b. (a -> b) -> a -> b
$ (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Posting -> Bool) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> Bool
setaside) (Transaction -> [Posting]
realPostings Transaction
t)
    realsum :: MixedAmount
realsum = [MixedAmount] -> MixedAmount
forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum ([MixedAmount] -> MixedAmount) -> [MixedAmount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
balancingamount [Posting]
amountfulrealps
      -- & dbg9With (lbl "real balancing amount".showMixedAmountOneLine)
    ([Posting]
amountfulbvps, [Posting]
amountlessbvps) = (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Posting -> Bool
hasAmount ([Posting] -> ([Posting], [Posting]))
-> [Posting] -> ([Posting], [Posting])
forall a b. (a -> b) -> a -> b
$ (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Posting -> Bool) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> Bool
setaside) (Transaction -> [Posting]
balancedVirtualPostings Transaction
t)
    bvsum :: MixedAmount
bvsum = [MixedAmount] -> MixedAmount
forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum ([MixedAmount] -> MixedAmount) -> [MixedAmount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
balancingamount [Posting]
amountfulbvps
    -- A posting's amount at cost, unless its cost is represented by equity
    -- conversion postings, in which case the cost is ignored (as in transactionCheckBalanced).
    balancingamount :: Posting -> MixedAmount
balancingamount Posting
p
      | CommoditySymbol
costPostingTagName CommoditySymbol -> [CommoditySymbol] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ((CommoditySymbol, CommoditySymbol) -> CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (CommoditySymbol, CommoditySymbol) -> CommoditySymbol
forall a b. (a, b) -> a
fst (Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p) = MixedAmount -> MixedAmount
mixedAmountStripCosts (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
      | Bool
otherwise                                   = MixedAmount -> MixedAmount
mixedAmountCost (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p

    inferamount :: Posting -> (Posting, Maybe MixedAmount)
    inferamount :: Posting -> (Posting, Maybe MixedAmount)
inferamount Posting
p | Posting -> Bool
setaside Posting
p = (Posting
p, Maybe MixedAmount
forall a. Maybe a
Nothing)
    inferamount Posting
p =
      let
        minferredamt :: Maybe MixedAmount
minferredamt = case Posting -> PostingRealness
preal Posting
p of
          PostingRealness
RealPosting            | Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p) -> MixedAmount -> Maybe MixedAmount
forall a. a -> Maybe a
Just MixedAmount
realsum
          PostingRealness
BalancedVirtualPosting | Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p) -> MixedAmount -> Maybe MixedAmount
forall a. a -> Maybe a
Just MixedAmount
bvsum
          PostingRealness
VirtualPosting         | Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p) -> MixedAmount -> Maybe MixedAmount
forall a. a -> Maybe a
Just MixedAmount
0
          PostingRealness
_                                          -> Maybe MixedAmount
forall a. Maybe a
Nothing
      in
        case Maybe MixedAmount
minferredamt of
          Maybe MixedAmount
Nothing -> (Posting
p, Maybe MixedAmount
forall a. Maybe a
Nothing)
          Just MixedAmount
a  -> (Posting
p{pamount=a', poriginal=Just $ originalPosting p}, MixedAmount -> Maybe MixedAmount
forall a. a -> Maybe a
Just MixedAmount
a')
            where
              -- Inferred amounts are converted to cost, and zero amounts
              -- alongside non-zero ones are dropped (a cost posting's quantity
              -- and its conversion posting cancel, leaving a zero which lot
              -- classification would otherwise see as a lotful amount).
              -- Also ensure the new amount has the standard style for its commodity
              -- (since the main amount styling pass happened before this balancing pass);
              a' :: MixedAmount
a' = MixedAmount -> MixedAmount
maNegate MixedAmount
a
                MixedAmount -> (MixedAmount -> MixedAmount) -> MixedAmount
forall a b. a -> (a -> b) -> b
& MixedAmount -> MixedAmount
mixedAmountCost
                MixedAmount -> (MixedAmount -> MixedAmount) -> MixedAmount
forall a b. a -> (a -> b) -> b
& MixedAmount -> MixedAmount
dropZeroResidues
                -- Apply global commodity styles for formatting, but keep the precision unchanged.
                -- This inferred amount's precision won't influence local or global precisions.
                MixedAmount -> (MixedAmount -> MixedAmount) -> MixedAmount
forall a b. a -> (a -> b) -> b
& Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts (Map CommoditySymbol AmountStyle
styles Map CommoditySymbol AmountStyle
-> (Map CommoditySymbol AmountStyle
    -> Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a b. a -> (a -> b) -> b
& Rounding
-> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AmountStyle
amountStylesSetRounding Rounding
NoRounding)
                MixedAmount -> (MixedAmount -> MixedAmount) -> MixedAmount
forall a b. a -> (a -> b) -> b
& (MixedAmount -> String) -> MixedAmount -> MixedAmount
forall a. (a -> String) -> a -> a
dbg9With (String -> String -> String
lbl String
"balancing amount styled"(String -> String)
-> (MixedAmount -> String) -> MixedAmount -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.MixedAmount -> String
showMixedAmountOneLine)
              dropZeroResidues :: MixedAmount -> MixedAmount
dropZeroResidues MixedAmount
ma
                | (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountIsZero) (MixedAmount -> [Amount]
amountsRaw MixedAmount
ma) = (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
amountIsZero) MixedAmount
ma
                | Bool
otherwise                                = MixedAmount
ma

-- | Infer costs for this transaction's posting amounts, if needed to make
-- the postings balance, and if permitted. This is done once for the real
-- postings and again (separately) for the balanced virtual postings. When
-- it's not possible, the transaction is left unchanged.
--
-- The simplest example is a transaction with two postings, each in a
-- different commodity, with no costs specified. In this case we'll add a
-- cost to the first posting such that it can be converted to the commodity
-- of the second posting (with -B), and such that the postings balance.
--
-- In general, we can infer a cost (conversion rate) when the sum of posting amounts
-- contains exactly two different commodities and no explicit costs.  Also
-- all postings are expected to contain an explicit amount (no missing
-- amounts) in a single commodity. Otherwise no cost inferring is attempted.
--
-- The transaction itself could contain more than two commodities, and/or
-- costs, if they cancel out; what matters is that the sum of posting amounts
-- contains exactly two commodities and zero costs.
--
-- There can also be more than two postings in either of the commodities.
--
-- We want to avoid excessive display of digits when the calculated cost is
-- an irrational number, while hopefully also ensuring the displayed numbers
-- make sense if the user does a manual calculation. This is (mostly) achieved
-- in two ways:
--
-- - when there is only one posting in the "from" commodity, a total cost
--   (@@) is used, and all available decimal digits are shown
--
-- - otherwise, a suitable averaged unit cost (@) is applied to the relevant
--   postings, with display precision equal to the summed display precisions
--   of the two commodities being converted between, or 2, whichever is larger.
--
-- (We don't always calculate a good-looking display precision for unit costs
-- when the commodity display precisions are low, eg when a journal doesn't
-- use any decimal places. The minimum of 2 helps make the costs shown by the
-- print command a bit less surprising in this case. Could do better.)
--
transactionInferBalancingCosts :: Bool -> S.Set CommoditySymbol -> Transaction -> Transaction
transactionInferBalancingCosts :: Bool -> Set CommoditySymbol -> Transaction -> Transaction
transactionInferBalancingCosts Bool
lenientlots Set CommoditySymbol
lotfulcomms t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps} =
  case (PostingRealness -> Maybe (Posting -> Posting)
inferrerFor PostingRealness
RealPosting, PostingRealness -> Maybe (Posting -> Posting)
inferrerFor PostingRealness
BalancedVirtualPosting) of
    (Maybe (Posting -> Posting)
Nothing, Maybe (Posting -> Posting)
Nothing) -> Transaction
t  -- no costs can be inferred (the usual case), keep the transaction as is
    (Maybe (Posting -> Posting)
mreal, Maybe (Posting -> Posting)
mbv)       -> Transaction
t{tpostings=map (fromMaybe id mbv . fromMaybe id mreal) ps}
  where
    inferrerFor :: PostingRealness -> Maybe (Posting -> Posting)
inferrerFor = Bool
-> Set CommoditySymbol
-> Transaction
-> PostingRealness
-> Maybe (Posting -> Posting)
costInferrerFor Bool
lenientlots Set CommoditySymbol
lotfulcomms Transaction
t

-- | Does one of these postings make this commodity look lot-related ?
-- True if the commodity appears in a posting amount with a cost basis
-- annotation.
-- (Lot classification runs after balancing, so ptype tags can't be used
-- here; this is a shape check.)
commodityHasLotPosting :: [Posting] -> CommoditySymbol -> Bool
commodityHasLotPosting :: [Posting] -> CommoditySymbol -> Bool
commodityHasLotPosting [Posting]
postings CommoditySymbol
comm = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Posting
p ->
    (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
comm Bool -> Bool -> Bool
&& Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)) (MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p)
  ) [Posting]
postings

-- | Is this commodity lot-related (see commodityHasLotPosting, or declared
-- lotful) and appearing with both signs among these postings (a
-- transfer-like shape) ?
lotRelatedBothSigns :: S.Set CommoditySymbol -> [Posting] -> CommoditySymbol -> Bool
lotRelatedBothSigns :: Set CommoditySymbol -> [Posting] -> CommoditySymbol -> Bool
lotRelatedBothSigns Set CommoditySymbol
lotfulcomms [Posting]
postings CommoditySymbol
c =
  ([Posting] -> CommoditySymbol -> Bool
commodityHasLotPosting [Posting]
postings CommoditySymbol
c Bool -> Bool -> Bool
|| CommoditySymbol
c CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms)
  Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
x -> Amount -> CommoditySymbol
acommodity Amount
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0) [Amount]
pamounts
  Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
x -> Amount -> CommoditySymbol
acommodity Amount
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0) [Amount]
pamounts
  where pamounts :: [Amount]
pamounts = (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]
postings

-- | The lot-related commodities among these postings (of one realness)
-- whose quantities look mismatched: the commodity appears with both signs
-- (a transfer-like shape), yet its residual is nonzero and not exactly one
-- posting's amount. Balancing cost inference is declined for such entries
-- (see costInferrerFor): an inferred cost would attach to both sides, mask
-- the imbalance (eg a fee deducted in kind but recorded in cash), and
-- surface later as a confusing lot error; the balancedness check reports
-- it better, with a note (see transactionCheckBalanced). When the residual
-- equals one posting's amount (a dispose posting alongside a matched
-- transfer pair, eg a same-account reclassify+fee entry), or the commodity
-- appears with one sign only (a bare sale or purchase), a cost is inferred
-- as documented. Returns [] unless the postings' residual is exactly two
-- unpriced opposite-signed commodities (the case where a balancing cost
-- could otherwise be inferred).
lotMismatchCommodities :: S.Set CommoditySymbol -> [Posting] -> [CommoditySymbol]
lotMismatchCommodities :: Set CommoditySymbol -> [Posting] -> [CommoditySymbol]
lotMismatchCommodities Set CommoditySymbol
lotfulcomms [Posting]
postings =
  case [Amount]
sumamounts of
    [Amount
a,Amount
b] | (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
sumamounts
          , Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
a) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
b)
          -> (Amount -> CommoditySymbol) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> CommoditySymbol
acommodity ([Amount] -> [CommoditySymbol]) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter Amount -> Bool
lotrelatedMismatch [Amount
a,Amount
b]
    [Amount]
_ -> []
  where
    sumamounts :: [Amount]
sumamounts = MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Posting] -> MixedAmount
sumPostings [Posting]
postings
    pamounts :: [Amount]
pamounts = (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]
postings
    lotrelatedMismatch :: Amount -> Bool
lotrelatedMismatch Amount
a =
      Set CommoditySymbol -> [Posting] -> CommoditySymbol -> Bool
lotRelatedBothSigns Set CommoditySymbol
lotfulcomms [Posting]
postings CommoditySymbol
c
      Bool -> Bool -> Bool
&& Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
x -> Amount -> CommoditySymbol
acommodity Amount
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
a) [Amount]
pamounts)
      where c :: CommoditySymbol
c = Amount -> CommoditySymbol
acommodity Amount
a

-- | Generate a posting update function which assigns a suitable cost to
-- balance the posting, if and as appropriate for the given transaction and
-- posting realness (real or balanced virtual); or Nothing if we cannot or
-- should not infer costs.
costInferrerFor :: Bool -> S.Set CommoditySymbol -> Transaction -> PostingRealness -> Maybe (Posting -> Posting)
costInferrerFor :: Bool
-> Set CommoditySymbol
-> Transaction
-> PostingRealness
-> Maybe (Posting -> Posting)
costInferrerFor Bool
lenientlots Set CommoditySymbol
lotfulcomms Transaction
t PostingRealness
pt = (Amount, Amount) -> Posting -> Posting
infercost ((Amount, Amount) -> Posting -> Posting)
-> Maybe (Amount, Amount) -> Maybe (Posting -> Posting)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Amount, Amount)
inferFromAndTo
  where
    lbl :: String -> String -> String
lbl = String -> String -> String -> String
lbl_ String
"costInferrerFor"
    setaside :: Posting -> Bool
setaside     = Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t
    postings :: [Posting]
postings     = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Posting
p -> Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
pt Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
setaside Posting
p)) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t  -- gain postings are set aside, as in transactionCheckBalanced
    pcommodities :: [CommoditySymbol]
pcommodities = (Amount -> CommoditySymbol) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> CommoditySymbol
acommodity ([Amount] -> [CommoditySymbol]) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (Posting -> [Amount]) -> [Posting] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount])
-> (Posting -> MixedAmount) -> Posting -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount) [Posting]
postings
    sumamounts :: [Amount]
sumamounts   = MixedAmount -> [Amount]
amounts (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ [Posting] -> MixedAmount
sumPostings [Posting]
postings  -- amounts normalises to one amount per commodity & price

    -- We can infer prices if there are no prices given, exactly two commodities in the normalised
    -- sum of postings in this transaction, these two have opposite signs, and neither looks like
    -- a lot quantity mismatch (see lotMismatchCommodities; this veto is skipped in lenient
    -- --ignore-lots mode, letting such entries load). The amount we are
    -- converting from is normally the first commodity to appear in the ordered list of postings;
    -- but if exactly one of the two commodities looks lot-related (its posting has a cost basis
    -- annotation or an inherited lots: account tag), or failing that, is a declared lotful
    -- commodity (#2686), prefer that one, so the inferred cost is attached to the posting that
    -- needs it for lot tracking. (Lot classification runs after balancing, so tags can't be
    -- used here; these are shape checks.)
    -- If we cannot infer prices, return Nothing.
    inferFromAndTo :: Maybe (Amount, Amount)
inferFromAndTo = case [Amount]
sumamounts of
      [Amount
a,Amount
b] | Bool
noprices, Bool
oppositesigns, Bool
lenientlots Bool -> Bool -> Bool
|| [CommoditySymbol] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Set CommoditySymbol -> [Posting] -> [CommoditySymbol]
lotMismatchCommodities Set CommoditySymbol
lotfulcomms [Posting]
postings) ->
        (CommoditySymbol -> Bool) -> Maybe (Amount, Amount)
prefer ([Posting] -> CommoditySymbol -> Bool
commodityHasLotPosting [Posting]
postings) Maybe (Amount, Amount)
-> Maybe (Amount, Amount) -> Maybe (Amount, Amount)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (CommoditySymbol -> Bool) -> Maybe (Amount, Amount)
prefer (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms) Maybe (Amount, Amount)
-> Maybe (Amount, Amount) -> Maybe (Amount, Amount)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> [Maybe (Amount, Amount)] -> Maybe (Amount, Amount)
forall (t :: * -> *) (f :: * -> *) a.
(Foldable t, Alternative f) =>
t (f a) -> f a
asum ((CommoditySymbol -> Maybe (Amount, Amount))
-> [CommoditySymbol] -> [Maybe (Amount, Amount)]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> Maybe (Amount, Amount)
orderIfMatches [CommoditySymbol]
pcommodities)
        where
          prefer :: (CommoditySymbol -> Bool) -> Maybe (Amount, Amount)
prefer CommoditySymbol -> Bool
hasquality = case (CommoditySymbol -> Bool
hasquality (Amount -> CommoditySymbol
acommodity Amount
a), CommoditySymbol -> Bool
hasquality (Amount -> CommoditySymbol
acommodity Amount
b)) of
            (Bool
True, Bool
False) -> (Amount, Amount) -> Maybe (Amount, Amount)
forall a. a -> Maybe a
Just (Amount
a, Amount
b)
            (Bool
False, Bool
True) -> (Amount, Amount) -> Maybe (Amount, Amount)
forall a. a -> Maybe a
Just (Amount
b, Amount
a)
            (Bool, Bool)
_             -> Maybe (Amount, Amount)
forall a. Maybe a
Nothing
          noprices :: Bool
noprices      = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
sumamounts
          oppositesigns :: Bool
oppositesigns = Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
a) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
b)
          orderIfMatches :: CommoditySymbol -> Maybe (Amount, Amount)
orderIfMatches CommoditySymbol
x | CommoditySymbol
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
a = (Amount, Amount) -> Maybe (Amount, Amount)
forall a. a -> Maybe a
Just (Amount
a,Amount
b)
                           | CommoditySymbol
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
b = (Amount, Amount) -> Maybe (Amount, Amount)
forall a. a -> Maybe a
Just (Amount
b,Amount
a)
                           | Bool
otherwise         = Maybe (Amount, Amount)
forall a. Maybe a
Nothing
      [Amount]
_ -> Maybe (Amount, Amount)
forall a. Maybe a
Nothing

    -- When the from commodity is lot-related and appears with both signs,
    -- and exactly one single-amount posting equals the residual, attach the
    -- whole cost to that posting only (as a total cost), leaving the others
    -- unpriced: they form matched transfer pairs, which must stay unpriced
    -- for lot classification; only the odd one out (a dispose, eg a fee
    -- disposal alongside a transfer) needs the cost (#2692).
    isTargeted :: Amount -> Bool
isTargeted Amount
fromamount =
      Set CommoditySymbol -> [Posting] -> CommoditySymbol -> Bool
lotRelatedBothSigns Set CommoditySymbol
lotfulcomms [Posting]
postings (Amount -> CommoditySymbol
acommodity Amount
fromamount)
      Bool -> Bool -> Bool
&& [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [()]
residualPostings Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
      where
        residualPostings :: [()]
residualPostings =
          [ () | Posting
q <- [Posting]
postings, [Amount
a] <- [MixedAmount -> [Amount]
amounts (Posting -> MixedAmount
pamount Posting
q)]
               , Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
fromamount, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
fromamount ]

    -- For each posting, if the posting type matches, there is only a single amount in the posting,
    -- and the commodity of the amount matches the amount we're converting from
    -- (and, in the targeted case above, its quantity is the whole residual),
    -- then set its cost based on the ratio between fromamount and toamount.
    infercost :: (Amount, Amount) -> Posting -> Posting
infercost (Amount
fromamount, Amount
toamount) Posting
p
        | [Amount
a] <- MixedAmount -> [Amount]
amounts (Posting -> MixedAmount
pamount Posting
p), Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
pt, Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
fromamount
        , Bool -> Bool
not (Amount -> Bool
isTargeted Amount
fromamount) Bool -> Bool -> Bool
|| Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
fromamount
            = Posting
p{ pamount   = mixedAmount a{acost=Just conversionprice}
                  & dbg9With (lbl "inferred cost".showMixedAmountOneLine)
               , poriginal = Just $ originalPosting p }
        | Bool
otherwise = Posting
p
      where
        -- In the targeted case, or if only one Amount in the posting list matches fromamount,
        -- we can use TotalCost.
        -- Otherwise divide the conversion equally among the Amounts by using a unit price.
        conversionprice :: AmountCost
conversionprice
          | Amount -> Bool
isTargeted Amount
fromamount = Amount -> AmountCost
TotalCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
forall a. Num a => a -> a
negate Amount
toamount
          | Bool
otherwise = case (CommoditySymbol -> Bool) -> [CommoditySymbol] -> [CommoditySymbol]
forall a. (a -> Bool) -> [a] -> [a]
filter (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
fromamount) [CommoditySymbol]
pcommodities of
              [CommoditySymbol
_] -> Amount -> AmountCost
TotalCost (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
forall a. Num a => a -> a
negate Amount
toamount
              [CommoditySymbol]
_   -> Amount -> AmountCost
UnitCost  (Amount -> AmountCost) -> Amount -> AmountCost
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
showFully (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
forall a. Num a => a -> a
negate Amount
unitcost Amount -> AmountPrecision -> Amount
`withPrecision` AmountPrecision
unitprecision

        unitcost :: Amount
unitcost     = Amount -> Quantity
aquantity Amount
fromamount Quantity -> Amount -> Amount
`divideAmount` Amount
toamount
        unitprecision :: AmountPrecision
unitprecision = case (AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
fromamount, AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
toamount) of
            (Precision Word8
a, Precision Word8
b) -> Word8 -> AmountPrecision
Precision (Word8 -> AmountPrecision)
-> (Word8 -> Word8) -> Word8 -> AmountPrecision
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word8 -> Word8 -> Word8
forall a. Ord a => a -> a -> a
max Word8
2 (Word8 -> AmountPrecision) -> Word8 -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Word8 -> Word8 -> Word8
forall {a}. (Ord a, Num a, Bounded a) => a -> a -> a
saturatedAdd Word8
a Word8
b
            (AmountPrecision, AmountPrecision)
_                          -> AmountPrecision
NaturalPrecision
        saturatedAdd :: a -> a -> a
saturatedAdd a
a a
b = if a
forall a. Bounded a => a
maxBound a -> a -> a
forall a. Num a => a -> a -> a
- a
a a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
b then a
forall a. Bounded a => a
maxBound else a
a a -> a -> a
forall a. Num a => a -> a -> a
+ a
b
        -- Show the unit cost exactly, or if it's a repeating decimal, with 8 decimal places,
        -- like other calculated amounts (or with unitprecision, if that's more).
        showFully :: Amount -> Amount
showFully Amount
u = Word8 -> Amount -> Amount
amountSetPrecisionMin (Amount -> Word8
amountDisplayPrecision Amount
u) (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing Amount
u


-- "Transaction balancing", including: inferring missing amounts,
-- applying balance assignments, checking transaction balancedness,
-- checking balance assertions, respecting posting dates. These things
-- are all interdependent.
-- WARN tricky algorithm and code ahead. 
--
-- Code overview as of 20190219, this could/should be simplified/documented more:
--  parseAndFinaliseJournal['] (Cli/Utils.hs), journalAddForecast (Common.hs), journalAddBudgetGoalTransactions (BudgetReport.hs), tests (BalanceReport.hs)
--   journalBalanceTransactions
--    runST
--     runExceptT
--      balanceSingleTransaction (Transaction.hs)
--       balanceTransactionHelper
--      runReaderT
--       balanceTransactionAndCheckAssertionsB
--        addAmountAndCheckAssertionB
--        addOrAssignAmountAndCheckAssertionB
--        balanceTransactionHelper (Transaction.hs)
--  uiCheckBalanceAssertions d ui@UIState{aopts=UIOpts{cliopts_=copts}, ajournal=j} (ErrorScreen.hs)
--   journalCheckBalanceAssertions
--    journalBalanceTransactions
--  transactionWizard, postingsBalanced (Add.hs), tests (Transaction.hs)
--   balanceSingleTransaction (Transaction.hs)  XXX hledger add won't allow balance assignments + missing amount ?

-- | Monad used for statefully balancing/amount-inferring/assertion-checking
-- a sequence of transactions.
-- Perhaps can be simplified, or would a different ordering of layers make sense ?
-- If you see a way, let us know.
type Balancing s = ReaderT (BalancingState s) (ExceptT String (ST s))

-- | Whether and how to check balance assertions while balancing:
-- not at all; erroring at the first failure; or checking but deferring
-- a failure - recording the first one in the given mutable slot and
-- continuing, so it can be reported later
-- (see journalBalanceTransactionsAndDeferAssertions).
data AssertionsMode s
  = DontCheckAssertions
  | CheckAssertions
  | DeferAssertions (STRef s (Maybe String))

-- | The state used while balancing a sequence of transactions.
data BalancingState s = BalancingState {
   -- read only
   forall s. BalancingState s -> BalancingOpts
bsBalancingOpts :: BalancingOpts                              -- ^ the balancing options (with the journal's commodity display styles), for balancing the transactions with balance assignments
  ,forall s. BalancingState s -> Set CommoditySymbol
bsUnassignable :: S.Set AccountName                          -- ^ accounts where balance assignments may not be used (because of auto posting rules)
  ,forall s. BalancingState s -> AssertionsMode s
bsAssrt        :: AssertionsMode s                           -- ^ whether/how to check balance assertions
  ,forall s. BalancingState s -> CommodityAliases
bsAliases      :: CommodityAliases  -- ^ commodity aliases with a quantity other than 1, whose amounts running balances keep unconverted (see postingRunningBalanceAmount)
   -- mutable
  ,forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances     :: H.HashTable s AccountName MixedAmount      -- ^ running account balances, initially empty
  ,forall s. BalancingState s -> STArray s Integer Transaction
bsTransactions :: STArray s Integer Transaction              -- ^ a mutable array of the transactions being balanced
    -- (for efficiency ? journalBalanceTransactions says: not strictly necessary but avoids a sort at the end I think)
  }

-- | Access the current balancing state, and possibly modify the mutable bits,
-- lifting through the Except and Reader layers into the Balancing monad.
withRunningBalance :: (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance :: forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance BalancingState s -> ST s a
f = ReaderT
  (BalancingState s) (ExceptT String (ST s)) (BalancingState s)
forall r (m :: * -> *). MonadReader r m => m r
ask ReaderT
  (BalancingState s) (ExceptT String (ST s)) (BalancingState s)
-> (BalancingState s
    -> ReaderT (BalancingState s) (ExceptT String (ST s)) a)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall a b.
ReaderT (BalancingState s) (ExceptT String (ST s)) a
-> (a -> ReaderT (BalancingState s) (ExceptT String (ST s)) b)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ExceptT String (ST s) a
-> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a.
Monad m =>
m a -> ReaderT (BalancingState s) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ExceptT String (ST s) a
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) a)
-> (BalancingState s -> ExceptT String (ST s) a)
-> BalancingState s
-> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ST s a -> ExceptT String (ST s) a
forall (m :: * -> *) a. Monad m => m a -> ExceptT String m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ST s a -> ExceptT String (ST s) a)
-> (BalancingState s -> ST s a)
-> BalancingState s
-> ExceptT String (ST s) a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalancingState s -> ST s a
f

-- | Get this account's current exclusive running balance.
getRunningBalanceB :: AccountName -> Balancing s MixedAmount
getRunningBalanceB :: forall s. CommoditySymbol -> Balancing s MixedAmount
getRunningBalanceB CommoditySymbol
acc = (BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount)
-> (BalancingState s -> ST s MixedAmount)
-> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState{HashTable s CommoditySymbol MixedAmount
bsBalances :: forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances :: HashTable s CommoditySymbol MixedAmount
bsBalances, CommodityAliases
bsAliases :: forall s. BalancingState s -> CommodityAliases
bsAliases :: CommodityAliases
bsAliases} -> do
  CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
bsAliases (MixedAmount -> MixedAmount)
-> (Maybe MixedAmount -> MixedAmount)
-> Maybe MixedAmount
-> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> Maybe MixedAmount -> MixedAmount
forall a. a -> Maybe a -> a
fromMaybe MixedAmount
nullmixedamt (Maybe MixedAmount -> MixedAmount)
-> ST s (Maybe MixedAmount) -> ST s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HashTable s CommoditySymbol MixedAmount
-> CommoditySymbol -> ST s (Maybe MixedAmount)
forall k s v.
(Eq k, Hashable k) =>
HashTable s k v -> k -> ST s (Maybe v)
H.lookup HashTable s CommoditySymbol MixedAmount
bsBalances CommoditySymbol
acc

-- | Get this account's current inclusive running balance
-- (the sum of the running balances of this account and any subaccounts seen so far).
getInclusiveRunningBalanceB :: AccountName -> Balancing s MixedAmount
getInclusiveRunningBalanceB :: forall s. CommoditySymbol -> Balancing s MixedAmount
getInclusiveRunningBalanceB CommoditySymbol
acc = (BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount)
-> (BalancingState s -> ST s MixedAmount)
-> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState{HashTable s CommoditySymbol MixedAmount
bsBalances :: forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances :: HashTable s CommoditySymbol MixedAmount
bsBalances, CommodityAliases
bsAliases :: forall s. BalancingState s -> CommodityAliases
bsAliases :: CommodityAliases
bsAliases} ->
  CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
bsAliases (MixedAmount -> MixedAmount)
-> ST s MixedAmount -> ST s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (MixedAmount -> (CommoditySymbol, MixedAmount) -> ST s MixedAmount)
-> MixedAmount
-> HashTable s CommoditySymbol MixedAmount
-> ST s MixedAmount
forall a k v s.
(a -> (k, v) -> ST s a) -> a -> HashTable s k v -> ST s a
H.foldM
    (\MixedAmount
ibal (CommoditySymbol
a, MixedAmount
amt) -> MixedAmount -> ST s MixedAmount
forall a. a -> ST s a
forall (m :: * -> *) a. Monad m => a -> m a
return (MixedAmount -> ST s MixedAmount)
-> MixedAmount -> ST s MixedAmount
forall a b. (a -> b) -> a -> b
$
      if CommoditySymbol
accCommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
==CommoditySymbol
a Bool -> Bool -> Bool
|| CommoditySymbol
acc CommoditySymbol -> CommoditySymbol -> Bool
`isAccountNamePrefixOf` CommoditySymbol
a then MixedAmount -> MixedAmount -> MixedAmount
maPlus MixedAmount
ibal MixedAmount
amt else MixedAmount
ibal)
    MixedAmount
nullmixedamt
    HashTable s CommoditySymbol MixedAmount
bsBalances

-- | Add this amount to this account's exclusive running balance.
-- Returns the new running balance.
addToRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount
addToRunningBalanceB :: forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
addToRunningBalanceB CommoditySymbol
acc MixedAmount
amt = (BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount)
-> (BalancingState s -> ST s MixedAmount)
-> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState{HashTable s CommoditySymbol MixedAmount
bsBalances :: forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances :: HashTable s CommoditySymbol MixedAmount
bsBalances} -> do
  old <- MixedAmount -> Maybe MixedAmount -> MixedAmount
forall a. a -> Maybe a -> a
fromMaybe MixedAmount
nullmixedamt (Maybe MixedAmount -> MixedAmount)
-> ST s (Maybe MixedAmount) -> ST s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HashTable s CommoditySymbol MixedAmount
-> CommoditySymbol -> ST s (Maybe MixedAmount)
forall k s v.
(Eq k, Hashable k) =>
HashTable s k v -> k -> ST s (Maybe v)
H.lookup HashTable s CommoditySymbol MixedAmount
bsBalances CommoditySymbol
acc
  let new = MixedAmount -> MixedAmount -> MixedAmount
maPlus MixedAmount
old MixedAmount
amt
  H.insert bsBalances acc new
  return new

-- | Set this account's exclusive running balance to this amount.
-- Returns the change in exclusive running balance.
setRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount
setRunningBalanceB :: forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
setRunningBalanceB CommoditySymbol
acc MixedAmount
amt = (BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount)
-> (BalancingState s -> ST s MixedAmount)
-> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState{HashTable s CommoditySymbol MixedAmount
bsBalances :: forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances :: HashTable s CommoditySymbol MixedAmount
bsBalances, CommodityAliases
bsAliases :: forall s. BalancingState s -> CommodityAliases
bsAliases :: CommodityAliases
bsAliases} -> do
  old <- MixedAmount -> Maybe MixedAmount -> MixedAmount
forall a. a -> Maybe a -> a
fromMaybe MixedAmount
nullmixedamt (Maybe MixedAmount -> MixedAmount)
-> ST s (Maybe MixedAmount) -> ST s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HashTable s CommoditySymbol MixedAmount
-> CommoditySymbol -> ST s (Maybe MixedAmount)
forall k s v.
(Eq k, Hashable k) =>
HashTable s k v -> k -> ST s (Maybe v)
H.lookup HashTable s CommoditySymbol MixedAmount
bsBalances CommoditySymbol
acc
  H.insert bsBalances acc amt
  return $ maMinus amt $ maConvertAliases bsAliases old

-- | Set this account's exclusive running balance to whatever amount
-- makes its *inclusive* running balance (the sum of exclusive running
-- balances of this account and any subaccounts) be the given amount.
-- Returns the change in exclusive running balance.
setInclusiveRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount
setInclusiveRunningBalanceB :: forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
setInclusiveRunningBalanceB CommoditySymbol
acc MixedAmount
newibal = (BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s MixedAmount) -> Balancing s MixedAmount)
-> (BalancingState s -> ST s MixedAmount)
-> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState{HashTable s CommoditySymbol MixedAmount
bsBalances :: forall s.
BalancingState s -> HashTable s CommoditySymbol MixedAmount
bsBalances :: HashTable s CommoditySymbol MixedAmount
bsBalances, CommodityAliases
bsAliases :: forall s. BalancingState s -> CommodityAliases
bsAliases :: CommodityAliases
bsAliases} -> do
  oldebal  <- CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
bsAliases (MixedAmount -> MixedAmount)
-> (Maybe MixedAmount -> MixedAmount)
-> Maybe MixedAmount
-> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> Maybe MixedAmount -> MixedAmount
forall a. a -> Maybe a -> a
fromMaybe MixedAmount
nullmixedamt (Maybe MixedAmount -> MixedAmount)
-> ST s (Maybe MixedAmount) -> ST s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HashTable s CommoditySymbol MixedAmount
-> CommoditySymbol -> ST s (Maybe MixedAmount)
forall k s v.
(Eq k, Hashable k) =>
HashTable s k v -> k -> ST s (Maybe v)
H.lookup HashTable s CommoditySymbol MixedAmount
bsBalances CommoditySymbol
acc
  allebals <- H.toList bsBalances
  let subsibal =  -- sum of any subaccounts' running balances
        CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
bsAliases (MixedAmount -> MixedAmount)
-> ([(CommoditySymbol, MixedAmount)] -> MixedAmount)
-> [(CommoditySymbol, MixedAmount)]
-> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [MixedAmount] -> MixedAmount
forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum ([MixedAmount] -> MixedAmount)
-> ([(CommoditySymbol, MixedAmount)] -> [MixedAmount])
-> [(CommoditySymbol, MixedAmount)]
-> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((CommoditySymbol, MixedAmount) -> MixedAmount)
-> [(CommoditySymbol, MixedAmount)] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map (CommoditySymbol, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd ([(CommoditySymbol, MixedAmount)] -> MixedAmount)
-> [(CommoditySymbol, MixedAmount)] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ ((CommoditySymbol, MixedAmount) -> Bool)
-> [(CommoditySymbol, MixedAmount)]
-> [(CommoditySymbol, MixedAmount)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((CommoditySymbol
acc CommoditySymbol -> CommoditySymbol -> Bool
`isAccountNamePrefixOf`)(CommoditySymbol -> Bool)
-> ((CommoditySymbol, MixedAmount) -> CommoditySymbol)
-> (CommoditySymbol, MixedAmount)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(CommoditySymbol, MixedAmount) -> CommoditySymbol
forall a b. (a, b) -> a
fst) [(CommoditySymbol, MixedAmount)]
allebals
  let newebal = MixedAmount -> MixedAmount -> MixedAmount
maMinus MixedAmount
newibal MixedAmount
subsibal
  H.insert bsBalances acc newebal
  return $ maMinus newebal oldebal

-- | The amount a posting adds to its account's running balance.
-- An amount converted from a commodity alias with a quantity is kept in the alias, as written
-- (without costs), and running balances are converted only when they're used (see maConvertAliases).
-- This way, eg three amounts of 10 min add up to exactly 0.5 h,
-- though each of them converts to 0.1666.. h, rounded at the 255th decimal place.
postingRunningBalanceAmount :: CommodityAliases -> Posting -> MixedAmount
postingRunningBalanceAmount :: CommodityAliases -> Posting -> MixedAmount
postingRunningBalanceAmount CommodityAliases
aliases Posting
p
  | CommodityAliases -> Bool
forall k a. Map k a -> Bool
M.null CommodityAliases
aliases = Posting -> MixedAmount
pamount Posting
p
  | (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((CommoditySymbol -> CommodityAliases -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` CommodityAliases
aliases) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) (MixedAmount -> [Amount]
amountsRaw MixedAmount
written)
    Bool -> Bool -> Bool
&& MixedAmount -> Bool
mixedAmountIsZero (CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
aliases MixedAmount
written MixedAmount -> MixedAmount -> MixedAmount
`maMinus` MixedAmount -> MixedAmount
mixedAmountStripCosts (Posting -> MixedAmount
pamount Posting
p)) = MixedAmount
written
  | Bool
otherwise = Posting -> MixedAmount
pamount Posting
p
  where written :: MixedAmount
written = MixedAmount -> MixedAmount
mixedAmountStripCosts (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount (Posting -> MixedAmount) -> Posting -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> Posting
originalPosting Posting
p

-- | Convert any amounts in these commodity aliases to their commodity.
-- Each alias's total is divided only once, so the result is exact when possible
-- (eg 30 min is exactly 0.5 h).
maConvertAliases :: CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases :: CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases CommodityAliases
aliases MixedAmount
ma
  | CommodityAliases -> Bool
forall k a. Map k a -> Bool
M.null CommodityAliases
aliases = MixedAmount
ma
  | Bool
otherwise      = (Amount -> MixedAmount) -> [Amount] -> MixedAmount
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount)
-> (Amount -> Amount) -> Amount -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, Quantity) -> Amount
forall a b. (a, b) -> a
fst ((Amount, Quantity) -> Amount)
-> (Amount -> (Amount, Quantity)) -> Amount -> Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommodityAliases -> Amount -> (Amount, Quantity)
convertAliasAmount CommodityAliases
aliases) ([Amount] -> MixedAmount) -> [Amount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> MixedAmount
mixedAmountStripCosts MixedAmount
ma

-- | Update (overwrite) this transaction in the balancing state.
updateTransactionB :: Transaction -> Balancing s ()
updateTransactionB :: forall s. Transaction -> Balancing s ()
updateTransactionB Transaction
t = (BalancingState s -> ST s ()) -> Balancing s ()
forall s a. (BalancingState s -> ST s a) -> Balancing s a
withRunningBalance ((BalancingState s -> ST s ()) -> Balancing s ())
-> (BalancingState s -> ST s ()) -> Balancing s ()
forall a b. (a -> b) -> a -> b
$ \BalancingState{STArray s Integer Transaction
bsTransactions :: forall s. BalancingState s -> STArray s Integer Transaction
bsTransactions :: STArray s Integer Transaction
bsTransactions}  ->
  ST s () -> ST s ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ST s () -> ST s ()) -> ST s () -> ST s ()
forall a b. (a -> b) -> a -> b
$ STArray s Integer Transaction -> Integer -> Transaction -> ST s ()
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> i -> e -> m ()
writeArray STArray s Integer Transaction
bsTransactions (Transaction -> Integer
tindex Transaction
t) Transaction
t

-- | Infer any missing amounts and/or conversion costs
-- (as needed to balance transactions and satisfy balance assignments);
-- and check that all transactions are balanced;
-- and (optional) check that all balance assertions pass.
-- Or, return an error message (just the first error encountered).
--
-- Assumes journalStyleAmounts has been called, since amount styles
-- affect transaction balancing.
--
-- This does multiple things at once because amount inferring, balance
-- assignments, balance assertions and posting dates are interdependent.
--
journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
bopts Journal
j = (Journal, Maybe String) -> Journal
forall a b. (a, b) -> a
fst ((Journal, Maybe String) -> Journal)
-> Either String (Journal, Maybe String) -> Either String Journal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Bool
-> BalancingOpts
-> Journal
-> Either String (Journal, Maybe String)
journalBalanceTransactionsHelper Bool
False BalancingOpts
bopts Journal
j

-- | Like journalBalanceTransactions, but instead of erroring at the first
-- failed balance assertion, keep going and also return the first assertion
-- failure's error message, if any. This lets callers (journalFinalise) run
-- further checks, eg the lot stages, and report their errors first.
journalBalanceTransactionsAndDeferAssertions :: BalancingOpts -> Journal -> Either String (Journal, Maybe String)
journalBalanceTransactionsAndDeferAssertions :: BalancingOpts -> Journal -> Either String (Journal, Maybe String)
journalBalanceTransactionsAndDeferAssertions = Bool
-> BalancingOpts
-> Journal
-> Either String (Journal, Maybe String)
journalBalanceTransactionsHelper Bool
True

journalBalanceTransactionsHelper :: Bool -> BalancingOpts -> Journal -> Either String (Journal, Maybe String)
journalBalanceTransactionsHelper :: Bool
-> BalancingOpts
-> Journal
-> Either String (Journal, Maybe String)
journalBalanceTransactionsHelper Bool
deferassertions BalancingOpts
bopts' Journal
j' =
  let
    -- ensure transactions are numbered, so we can store them by number
    j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = Journal -> Journal
journalNumberTransactions Journal
j'
    -- display precisions used in balanced checking
    styles :: Maybe (Map CommoditySymbol AmountStyle)
styles = Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
forall a. a -> Maybe a
Just (Map CommoditySymbol AmountStyle
 -> Maybe (Map CommoditySymbol AmountStyle))
-> Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
forall a b. (a -> b) -> a -> b
$
      -- Use all the specified commodity display precisions, with hard rounding, when checking txn balancedness.
      -- XXX Problem, those precisions will also be used when inferring balancing amounts;
      -- it would be better to give those the precision of the amount they are balancing.
      Rounding -> Journal -> Map CommoditySymbol AmountStyle
journalCommodityStylesWith Rounding
HardRounding
      Journal
j
    bopts :: BalancingOpts
bopts = BalancingOpts
bopts'{commodity_styles_=styles}
      -- XXX ^ The commodity directive styles and default style and inferred styles
      -- are merged into the command line styles in commodity_styles_ - why ?
      -- Mainly for the precisions, used during amount and cost inference and balanced checking ?
    -- balance assignments are not allowed on accounts affected by auto postings
    autopostingaccts :: Set CommoditySymbol
autopostingaccts = [CommoditySymbol] -> Set CommoditySymbol
forall a. Ord a => [a] -> Set a
S.fromList ([CommoditySymbol] -> Set CommoditySymbol)
-> ([TransactionModifier] -> [CommoditySymbol])
-> [TransactionModifier]
-> Set CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TMPostingRule -> CommoditySymbol)
-> [TMPostingRule] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (Posting -> CommoditySymbol
paccount (Posting -> CommoditySymbol)
-> (TMPostingRule -> Posting) -> TMPostingRule -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TMPostingRule -> Posting
tmprPosting) ([TMPostingRule] -> [CommoditySymbol])
-> ([TransactionModifier] -> [TMPostingRule])
-> [TransactionModifier]
-> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TransactionModifier -> [TMPostingRule])
-> [TransactionModifier] -> [TMPostingRule]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap TransactionModifier -> [TMPostingRule]
tmpostingrules ([TransactionModifier] -> Set CommoditySymbol)
-> [TransactionModifier] -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Journal -> [TransactionModifier]
jtxnmodifiers Journal
j
  in
    -- Store the transactions in a mutable array, which we'll update as we balance them.
    -- Not strictly necessary but avoids a sort at the end I think.
    (forall s. ST s (Either String (Journal, Maybe String)))
-> Either String (Journal, Maybe String)
forall a. (forall s. ST s a) -> a
runST ((forall s. ST s (Either String (Journal, Maybe String)))
 -> Either String (Journal, Maybe String))
-> (forall s. ST s (Either String (Journal, Maybe String)))
-> Either String (Journal, Maybe String)
forall a b. (a -> b) -> a -> b
$ do
      balancedtxns <- (Integer, Integer)
-> [Transaction] -> ST s (STArray s Integer Transaction)
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
(i, i) -> [e] -> m (a i e)
newListArray (Integer
1, Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Integer) -> Int -> Integer
forall a b. (a -> b) -> a -> b
$ [Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
ts) [Transaction]
ts
      -- Holds the first deferred balance assertion failure, if any.
      massertionerr <- newSTRef Nothing
      let assertionsmode
            | BalancingOpts -> Bool
ignore_assertions_ BalancingOpts
bopts = AssertionsMode s
forall s. AssertionsMode s
DontCheckAssertions
            | Bool
deferassertions          = STRef s (Maybe String) -> AssertionsMode s
forall s. STRef s (Maybe String) -> AssertionsMode s
DeferAssertions STRef s (Maybe String)
massertionerr
            | Bool
otherwise                = AssertionsMode s
forall s. AssertionsMode s
CheckAssertions

      -- Process all transactions, or short-circuit with an error.
      runExceptT $ do

        -- Two passes are required:
        -- 1. Step through the transactions, balancing the ones which don't have balance assignments,
        -- postponing those which do until later. The balanced ones are split into their postings,
        -- keeping these and the not-yet-balanced transactions in the same relative order.
        -- (With --infer-imbalance, balanced transactions also get postings showing any tolerated imbalance.)
        psandts :: [Either Posting Transaction] <- fmap concat $ forM ts $ \case
          Transaction
t | [Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([Posting] -> Bool) -> [Posting] -> Bool
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
assignmentPostings Transaction
t -> case (Transaction, [Posting]) -> Transaction
forall a b. (a, b) -> a
fst ((Transaction, [Posting]) -> Transaction)
-> ((Transaction, [(CommoditySymbol, MixedAmount)])
    -> (Transaction, [Posting]))
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> Transaction
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalancingOpts -> Transaction -> (Transaction, [Posting])
transactionMaybeAddImbalancePostings BalancingOpts
bopts (Transaction -> (Transaction, [Posting]))
-> ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> (Transaction, [(CommoditySymbol, MixedAmount)])
-> (Transaction, [Posting])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction
forall a b. (a, b) -> a
fst ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String Transaction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelperMaybeSplittingLotFees BalancingOpts
bopts Transaction
t of
              Left  String
e  -> String -> ExceptT String (ST s) [Either Posting Transaction]
forall a. String -> ExceptT String (ST s) a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError String
e
              Right Transaction
t' -> do
                ST s () -> ExceptT String (ST s) ()
forall (m :: * -> *) a. Monad m => m a -> ExceptT String m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ST s () -> ExceptT String (ST s) ())
-> ST s () -> ExceptT String (ST s) ()
forall a b. (a -> b) -> a -> b
$ STArray s Integer Transaction -> Integer -> Transaction -> ST s ()
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> i -> e -> m ()
writeArray STArray s Integer Transaction
balancedtxns (Transaction -> Integer
tindex Transaction
t') Transaction
t'
                [Either Posting Transaction]
-> ExceptT String (ST s) [Either Posting Transaction]
forall a. a -> ExceptT String (ST s) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Either Posting Transaction]
 -> ExceptT String (ST s) [Either Posting Transaction])
-> [Either Posting Transaction]
-> ExceptT String (ST s) [Either Posting Transaction]
forall a b. (a -> b) -> a -> b
$ (Posting -> Either Posting Transaction)
-> [Posting] -> [Either Posting Transaction]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Either Posting Transaction
forall a b. a -> Either a b
Left ([Posting] -> [Either Posting Transaction])
-> [Posting] -> [Either Posting Transaction]
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t'
          Transaction
t -> [Either Posting Transaction]
-> ExceptT String (ST s) [Either Posting Transaction]
forall a. a -> ExceptT String (ST s) a
forall (m :: * -> *) a. Monad m => a -> m a
return [Transaction -> Either Posting Transaction
forall a b. b -> Either a b
Right Transaction
t]

        -- 2. Step through these items in date order (and preserved same-day order),
        -- keeping running balances for all accounts.
        -- This pass serves only balance assignments and assertions, so it is
        -- skipped when there are none to process (a big saving on large journals).
        let
          checkingassertions = case AssertionsMode s
assertionsmode of AssertionsMode s
DontCheckAssertions -> Bool
False; AssertionsMode s
_ -> Bool
True
          hasassertions = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe BalanceAssertion -> Bool
forall a. Maybe a -> Bool
isJust (Maybe BalanceAssertion -> Bool)
-> (Posting -> Maybe BalanceAssertion) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> Maybe BalanceAssertion
pbalanceassertion) [Posting
p | Left Posting
p <- [Either Posting Transaction]
psandts]
          hasassignments = (Either Posting Transaction -> Bool)
-> [Either Posting Transaction] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Either Posting Transaction -> Bool
forall a b. Either a b -> Bool
isRight [Either Posting Transaction]
psandts
        when (hasassignments || (checkingassertions && hasassertions)) $ do
          runningbals <- lift $ H.newSized (length $ journalAccountNamesUsed j)
          let aliases = ((CommoditySymbol, Quantity, Maybe AmountStyle) -> Bool)
-> CommodityAliases -> CommodityAliases
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (\(CommoditySymbol
_, Quantity
q, Maybe AmountStyle
_) -> Quantity
q Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
1) (CommodityAliases -> CommodityAliases)
-> CommodityAliases -> CommodityAliases
forall a b. (a -> b) -> a -> b
$ Journal -> CommodityAliases
journalCommodityAliases Journal
j
          flip runReaderT (BalancingState bopts autopostingaccts assertionsmode aliases runningbals balancedtxns) $ do
            -- On encountering any not-yet-balanced transaction with a balance assignment,
            -- enact the balance assignment then finish balancing the transaction.
            -- And, check any balance assertions encountered along the way.
            void $ mapM' balanceTransactionAndCheckAssertionsB $ sortOn (either postingDate tdate) psandts

        -- Return the now fully-balanced and checked transactions,
        -- and any deferred balance assertion failure.
        ts' <- lift $ getElems balancedtxns
        merr <- lift $ readSTRef massertionerr
        return (j{jtxns=ts'}, merr)

-- Before #2039: "Costs are removed, which helps eg assertions.test: 15. Mix different commodities and assignments."

-- | This function is called statefully on each of a date-ordered sequence of
-- 1. fully explicit postings from already-balanced transactions and
-- 2. not-yet-balanced transactions containing balance assignments.
-- It executes balance assignments and finishes balancing the transactions,
-- and checks balance assertions on each posting as it goes.
-- An error will be thrown if a transaction can't be balanced
-- or if an illegal balance assignment is found (cf checkIllegalBalanceAssignment).
-- This stores the balanced transactions in case 2 but not in case 1.
balanceTransactionAndCheckAssertionsB :: Either Posting Transaction -> Balancing s ()
balanceTransactionAndCheckAssertionsB :: forall s. Either Posting Transaction -> Balancing s ()
balanceTransactionAndCheckAssertionsB (Left p :: Posting
p@Posting{}) =
  -- Update the account's running balance and check the balance assertion if any.
  -- Cost is ignored when checking balance assertions currently.
  ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$ Posting
-> ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
forall s. Posting -> Balancing s Posting
addAmountAndCheckAssertionB (Posting
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) Posting)
-> Posting
-> ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
forall a b. (a -> b) -> a -> b
$ Posting -> Posting
postingStripCosts Posting
p
balanceTransactionAndCheckAssertionsB (Right t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps}) = do
  -- make sure we can handle the balance assignments
  (Posting -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> [Posting]
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Posting -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall s. Posting -> Balancing s ()
checkIllegalBalanceAssignmentB [Posting]
ps
  -- for each posting, in date order (though without disturbing their display order),
  -- 1. infer its amount from the balance assignment if applicable,
  -- 2. update the account's running balance, and
  -- 3. check the balance assertion if any.
  ps' <- [Posting]
ps
    [Posting]
-> ([Posting] -> [(Integer, Posting)]) -> [(Integer, Posting)]
forall a b. a -> (a -> b) -> b
& [Integer] -> [Posting] -> [(Integer, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Integer
1..]                 -- attach original positions
    [(Integer, Posting)]
-> ([(Integer, Posting)] -> [(Integer, Posting)])
-> [(Integer, Posting)]
forall a b. a -> (a -> b) -> b
& ((Integer, Posting) -> Day)
-> [(Integer, Posting)] -> [(Integer, Posting)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Posting -> Day
postingDate(Posting -> Day)
-> ((Integer, Posting) -> Posting) -> (Integer, Posting) -> Day
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Integer, Posting) -> Posting
forall a b. (a, b) -> b
snd)  -- sort by date
    [(Integer, Posting)]
-> ([(Integer, Posting)]
    -> ReaderT
         (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)])
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)]
forall a b. a -> (a -> b) -> b
& ((Integer, Posting)
 -> ReaderT
      (BalancingState s) (ExceptT String (ST s)) (Integer, Posting))
-> [(Integer, Posting)]
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (f :: * -> *) a b. Monad f => (a -> f b) -> [a] -> f [b]
mapM (Integer, Posting)
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) (Integer, Posting)
forall s. (Integer, Posting) -> Balancing s (Integer, Posting)
addOrAssignAmountAndCheckAssertionB  -- infer amount, check assertion on each one
    ReaderT
  (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)]
-> ([(Integer, Posting)] -> [(Integer, Posting)])
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)]
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> ((Integer, Posting) -> Integer)
-> [(Integer, Posting)] -> [(Integer, Posting)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Integer, Posting) -> Integer
forall a b. (a, b) -> a
fst              -- restore original order
    ReaderT
  (BalancingState s) (ExceptT String (ST s)) [(Integer, Posting)]
-> ([(Integer, Posting)] -> [Posting])
-> ReaderT (BalancingState s) (ExceptT String (ST s)) [Posting]
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> ((Integer, Posting) -> Posting)
-> [(Integer, Posting)] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Integer, Posting) -> Posting
forall a b. (a, b) -> b
snd                 -- discard positions

  -- infer any remaining missing amounts, and make sure the transaction is now fully balanced
  -- (using all the balancing options, as for the other transactions)
  bopts1 <- R.asks bsBalancingOpts
  let t1 = Transaction
t{tpostings=ps'}
      -- The transaction may be a lot transfer with a fee (whose outflow amount
      -- possibly was only just inferred from a balance assignment): a priced
      -- fee's entry only balances in split form, and any elided posting must
      -- infer the post-split residual (rather than wrongly absorbing the fee's
      -- cost value). (#2686)
      balanceres = BalancingOpts
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
balanceTransactionHelperMaybeSplittingLotFees BalancingOpts
bopts1 Transaction
t1
  case balanceres of
    Left String
err -> String -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a.
String -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError String
err
    Right (Transaction
t', [(CommoditySymbol, MixedAmount)]
inferredacctsandamts) -> do
      -- with --infer-imbalance, show any tolerated imbalance
      let (Transaction
t'', [Posting]
imbalanceps) = BalancingOpts -> Transaction -> (Transaction, [Posting])
transactionMaybeAddImbalancePostings BalancingOpts
bopts1 Transaction
t'
      -- for each amount just inferred or added, update the running balance
      ((CommoditySymbol, MixedAmount)
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount)
-> [(CommoditySymbol, MixedAmount)]
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ((CommoditySymbol
 -> MixedAmount
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount)
-> (CommoditySymbol, MixedAmount)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry CommoditySymbol
-> MixedAmount
-> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount
forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
addToRunningBalanceB) ([(CommoditySymbol, MixedAmount)]
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> [(CommoditySymbol, MixedAmount)]
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$ [(CommoditySymbol, MixedAmount)]
inferredacctsandamts [(CommoditySymbol, MixedAmount)]
-> [(CommoditySymbol, MixedAmount)]
-> [(CommoditySymbol, MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [(Posting -> CommoditySymbol
paccount Posting
p, Posting -> MixedAmount
pamount Posting
p) | Posting
p <- [Posting]
imbalanceps]
      -- and save the balanced transaction.
      Transaction
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall s. Transaction -> Balancing s ()
updateTransactionB Transaction
t''

type NumberedPosting = (Integer, Posting)

-- | If this posting has an explicit amount, add it to the account's running balance.
-- If it has a missing amount and a balance assignment, infer the amount from, and
-- reset the running balance to, the assigned balance.
-- If it has a missing amount and no balance assignment, leave it for later.
-- Then test the balance assertion if any.
addOrAssignAmountAndCheckAssertionB :: NumberedPosting -> Balancing s NumberedPosting
addOrAssignAmountAndCheckAssertionB :: forall s. (Integer, Posting) -> Balancing s (Integer, Posting)
addOrAssignAmountAndCheckAssertionB (Integer
i,p :: Posting
p@Posting{paccount :: Posting -> CommoditySymbol
paccount=CommoditySymbol
acc, pbalanceassertion :: Posting -> Maybe BalanceAssertion
pbalanceassertion=Maybe BalanceAssertion
mba})
  -- an explicit posting amount
  | Posting -> Bool
hasAmount Posting
p = do
      aliases <- (BalancingState s -> CommodityAliases)
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) CommodityAliases
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
R.asks BalancingState s -> CommodityAliases
forall s. BalancingState s -> CommodityAliases
bsAliases
      newbal <- addToRunningBalanceB acc $ postingRunningBalanceAmount aliases p
      checkOrDeferBalanceAssertionB p newbal
      return (i,p)

  -- no explicit posting amount, but there is a balance assignment
  | Just BalanceAssertion{Amount
baamount :: BalanceAssertion -> Amount
baamount :: Amount
baamount,Bool
batotal :: Bool
batotal :: BalanceAssertion -> Bool
batotal,Bool
bainclusive :: Bool
bainclusive :: BalanceAssertion -> Bool
bainclusive} <- Maybe BalanceAssertion
mba = do
      let (CommoditySymbol -> Balancing s MixedAmount
getbal, CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
setbal) | Bool
bainclusive = (CommoditySymbol -> Balancing s MixedAmount
forall s. CommoditySymbol -> Balancing s MixedAmount
getInclusiveRunningBalanceB, CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
setInclusiveRunningBalanceB)
                           | Bool
otherwise   = (CommoditySymbol -> Balancing s MixedAmount
forall s. CommoditySymbol -> Balancing s MixedAmount
getRunningBalanceB, CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
forall s. CommoditySymbol -> MixedAmount -> Balancing s MixedAmount
setRunningBalanceB)
      newbal <- if Bool
batotal
                   -- a total balance assignment (==, all commodities)
                   then MixedAmount -> Balancing s MixedAmount
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return (MixedAmount -> Balancing s MixedAmount)
-> MixedAmount -> Balancing s MixedAmount
forall a b. (a -> b) -> a -> b
$ Amount -> MixedAmount
mixedAmount Amount
baamount
                   -- a partial balance assignment (=, one commodity), keeping the other commodities
                   else do
                     oldbalothercommodities <- (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount ((Amount -> CommoditySymbol
acommodity Amount
baamount CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/=) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) (MixedAmount -> MixedAmount)
-> Balancing s MixedAmount -> Balancing s MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CommoditySymbol -> Balancing s MixedAmount
forall s. CommoditySymbol -> Balancing s MixedAmount
getbal CommoditySymbol
acc
                     return $ maAddAmount oldbalothercommodities baamount
      diff <- setbal acc newbal
      let p' = Posting
p{pamount=filterMixedAmount (not . amountIsZero) diff, poriginal=Just $ originalPosting p}
      checkOrDeferBalanceAssertionB p' newbal
      return (i,p')

  -- no explicit posting amount, no balance assignment
  | Bool
otherwise = (Integer, Posting)
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) (Integer, Posting)
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Integer
i,Posting
p)

-- | Add the posting's amount to its account's running balance, and
-- optionally check the posting's balance assertion if any.
-- The posting is expected to have an explicit amount (otherwise this does nothing).
-- Adding and checking balance assertions are tightly paired because we
-- need to see the balance as it stands after each individual posting.
addAmountAndCheckAssertionB :: Posting -> Balancing s Posting
addAmountAndCheckAssertionB :: forall s. Posting -> Balancing s Posting
addAmountAndCheckAssertionB Posting
p | Posting -> Bool
hasAmount Posting
p = do
  aliases <- (BalancingState s -> CommodityAliases)
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) CommodityAliases
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
R.asks BalancingState s -> CommodityAliases
forall s. BalancingState s -> CommodityAliases
bsAliases
  newbal <- addToRunningBalanceB (paccount p) $ postingRunningBalanceAmount aliases p
  checkOrDeferBalanceAssertionB p newbal
  return p
addAmountAndCheckAssertionB Posting
p = Posting
-> ReaderT (BalancingState s) (ExceptT String (ST s)) Posting
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return Posting
p

-- | Check the posting's balance assertion (if any) against the given balance,
-- per the current assertions mode: not at all; erroring immediately on a
-- failure; or recording the first failure and continuing.
checkOrDeferBalanceAssertionB :: Posting -> MixedAmount -> Balancing s ()
checkOrDeferBalanceAssertionB :: forall s. Posting -> MixedAmount -> Balancing s ()
checkOrDeferBalanceAssertionB Posting
p MixedAmount
newbal0 = do
  newbal <- (BalancingState s -> MixedAmount)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
R.asks ((BalancingState s -> MixedAmount)
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount)
-> (BalancingState s -> MixedAmount)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) MixedAmount
forall a b. (a -> b) -> a -> b
$ \BalancingState s
s -> CommodityAliases -> MixedAmount -> MixedAmount
maConvertAliases (BalancingState s -> CommodityAliases
forall s. BalancingState s -> CommodityAliases
bsAliases BalancingState s
s) MixedAmount
newbal0
  R.reader bsAssrt >>= \case
    AssertionsMode s
DontCheckAssertions -> () -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    AssertionsMode s
CheckAssertions     -> Posting
-> MixedAmount
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall s. Posting -> MixedAmount -> Balancing s ()
checkBalanceAssertionB Posting
p MixedAmount
newbal
    DeferAssertions STRef s (Maybe String)
ref -> Posting
-> MixedAmount
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall s. Posting -> MixedAmount -> Balancing s ()
checkBalanceAssertionB Posting
p MixedAmount
newbal ReaderT (BalancingState s) (ExceptT String (ST s)) ()
-> (String
    -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a.
ReaderT (BalancingState s) (ExceptT String (ST s)) a
-> (String -> ReaderT (BalancingState s) (ExceptT String (ST s)) a)
-> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
`catchError` \String
e ->
      ExceptT String (ST s) ()
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (m :: * -> *) a.
Monad m =>
m a -> ReaderT (BalancingState s) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ExceptT String (ST s) ()
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> (ST s () -> ExceptT String (ST s) ())
-> ST s ()
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ST s () -> ExceptT String (ST s) ()
forall (m :: * -> *) a. Monad m => m a -> ExceptT String m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ST s () -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ST s () -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$ STRef s (Maybe String) -> (Maybe String -> Maybe String) -> ST s ()
forall s a. STRef s a -> (a -> a) -> ST s ()
modifySTRef' STRef s (Maybe String)
ref (Maybe String -> Maybe String -> Maybe String
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> String -> Maybe String
forall a. a -> Maybe a
Just String
e)

-- | Check a posting's balance assertion against the given actual balance, and
-- return an error if the assertion is not satisfied.
-- If the assertion is partial, unasserted commodities in the actual balance
-- are ignored; if it is total, they will cause the assertion to fail.
checkBalanceAssertionB :: Posting -> MixedAmount -> Balancing s ()
checkBalanceAssertionB :: forall s. Posting -> MixedAmount -> Balancing s ()
checkBalanceAssertionB p :: Posting
p@Posting{pbalanceassertion :: Posting -> Maybe BalanceAssertion
pbalanceassertion=Just (BalanceAssertion{Amount
baamount :: BalanceAssertion -> Amount
baamount :: Amount
baamount,Bool
batotal :: BalanceAssertion -> Bool
batotal :: Bool
batotal})} MixedAmount
actualbal =
  [Amount]
-> (Amount
    -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (Amount
baamount Amount -> [Amount] -> [Amount]
forall a. a -> [a] -> [a]
: [Amount]
otheramts) ((Amount -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> (Amount
    -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$ \Amount
amt -> Posting
-> Amount
-> MixedAmount
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall s. Posting -> Amount -> MixedAmount -> Balancing s ()
checkBalanceAssertionOneCommodityB Posting
p Amount
amt MixedAmount
actualbal
  where
    assertedcomm :: CommoditySymbol
assertedcomm = Amount -> CommoditySymbol
acommodity Amount
baamount
    otheramts :: [Amount]
otheramts | Bool
batotal   = (Amount -> Amount) -> [Amount] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (\Amount
a -> Amount
a{aquantity=0}) ([Amount] -> [Amount])
-> (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> [Amount]
amountsRaw
                          (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/=CommoditySymbol
assertedcomm)(CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Amount -> CommoditySymbol
acommodity) MixedAmount
actualbal
              | Bool
otherwise = []
checkBalanceAssertionB Posting
_ MixedAmount
_ = () -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Does this (single commodity) expected balance match the amount of that
-- commodity in the given (multicommodity) actual balance, ignoring costs ?
-- If not, returns a balance assertion failure message based on the provided posting.
-- To match, the amounts must be exactly equal (display precision is ignored here).
-- If the assertion is inclusive, the expected amount is compared with the account's
-- subaccount-inclusive balance; otherwise, with the subaccount-exclusive balance.
checkBalanceAssertionOneCommodityB :: Posting -> Amount -> MixedAmount -> Balancing s ()
checkBalanceAssertionOneCommodityB :: forall s. Posting -> Amount -> MixedAmount -> Balancing s ()
checkBalanceAssertionOneCommodityB p :: Posting
p@Posting{paccount :: Posting -> CommoditySymbol
paccount=CommoditySymbol
assertedacct} Amount
assertedcommbal MixedAmount
actualbal = do
  let isinclusive :: Bool
isinclusive = Bool
-> (BalanceAssertion -> Bool) -> Maybe BalanceAssertion -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False BalanceAssertion -> Bool
bainclusive (Maybe BalanceAssertion -> Bool) -> Maybe BalanceAssertion -> Bool
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p
  let istotal :: Bool
istotal     = Bool
-> (BalanceAssertion -> Bool) -> Maybe BalanceAssertion -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False BalanceAssertion -> Bool
batotal     (Maybe BalanceAssertion -> Bool) -> Maybe BalanceAssertion -> Bool
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p
  -- mstyles <- R.asks (commodity_styles_ . bsBalancingOpts)
  -- let styled = maybe id styleAmounts mstyles
  actualbal' <- if Bool
isinclusive then CommoditySymbol -> Balancing s MixedAmount
forall s. CommoditySymbol -> Balancing s MixedAmount
getInclusiveRunningBalanceB CommoditySymbol
assertedacct else MixedAmount -> Balancing s MixedAmount
forall a. a -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall (m :: * -> *) a. Monad m => a -> m a
return MixedAmount
actualbal
  let
    assertedcomm = Amount -> CommoditySymbol
acommodity Amount
assertedcommbal

    -- The asserted single-commodity balance, without cost
    assertedcommbalcostless = Amount -> Amount
amountStripCost Amount
assertedcommbal

    -- The balance in this commodity, from the current multi-commodity running balance at this point.
    -- This is unnormalised, and could include one or more different costs.
    actualcommbal           = CommoditySymbol -> MixedAmount -> MixedAmount
filterMixedAmountByCommodity CommoditySymbol
assertedcomm (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount
actualbal'

    -- The above balance without costs, as a single Amount (Amount's + discards costs).
    actualcommbalcostless   = [Amount] -> Amount
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Amount] -> Amount) -> [Amount] -> Amount
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw MixedAmount
actualcommbal

    -- test the assertion
    pass =
      Amount -> Quantity
aquantity Amount
assertedcommbalcostless
      Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
==
      Amount -> Quantity
aquantity Amount
actualcommbalcostless

    errmsg = String -> String
chomp (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String
-> String
-> CommoditySymbol
-> String
-> CommoditySymbol
-> String
-> CommoditySymbol
-> CommoditySymbol
-> String
-> String
-> String
-> String
-> String
-> String
forall r. PrintfType r => String -> r
printf ([String] -> String
unlines
      [ String
"%s:",
        String
"%s\n",
        String
"Balance assertion failed in %s",
        String
"%s at this point, %s, ignoring costs,",
        String
"the asserted balance is:        %s",
        String
"but the calculated balance is:  %s",
        String
"(difference: %s)",
        String
"To troubleshoot, check this account's running balance with assertions disabled, eg:",
        String
"hledger reg -E --ignore-assertions '%s'%s -e %s%s"
      ])

      (SourcePos -> String
sourcePosPretty SourcePos
pos)  -- position
      (CommoditySymbol -> CommoditySymbol
textChomp CommoditySymbol
ex)  -- journal excerpt
      String
acct  -- asserted account
      (if Bool
istotal then CommoditySymbol
"Across all commodities" else CommoditySymbol
"In commodity " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
assertedcommstr)  -- asserted commodity or all commodities ?
      (if Bool
isinclusive then String
"including subaccounts" else String
"excluding subaccounts" :: String)  -- inclusive or exclusive balance asserted ?
      (String -> CommoditySymbol
pad String
assertedstr  -- asserted amount, without cost
        CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> if Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
2 then CommoditySymbol
" (with cost:  " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> String -> CommoditySymbol
T.pack (AmountFormat -> Amount -> String
showAmountWith AmountFormat
fmt Amount
assertedcommbal) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
")" else CommoditySymbol
""
      )
      (String -> CommoditySymbol
pad String
actualstr    -- actual amount, without cost
        CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> if Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
2 then CommoditySymbol
" (with costs: " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> String -> CommoditySymbol
T.pack (AmountFormat -> MixedAmount -> String
showMixedAmountWith AmountFormat
fmt MixedAmount
actualcommbal) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
")" else CommoditySymbol
""
      )
      String
diffstr  -- their difference
      (CommoditySymbol -> String
T.unpack (CommoditySymbol -> CommoditySymbol
regexEscape (Posting -> CommoditySymbol
paccount Posting
p)) String -> String -> String
forall a. [a] -> [a] -> [a]
++ if Bool
isinclusive then String
"" else String
"$")  -- query matching the account(s) postings
      (if Bool
istotal then String
"" else (String
" cur:" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
quoteForCommandLine (CommoditySymbol -> String
T.unpack (CommoditySymbol -> CommoditySymbol
regexEscape (CommoditySymbol
assertedcomm)))))  -- query matching the commodity(ies)
      (Day -> String
forall a. Show a => a -> String
show (Day -> String) -> Day -> String
forall a b. (a -> b) -> a -> b
$ Integer -> Day -> Day
addDays Integer
1 (Day -> Day) -> Day -> Day
forall a b. (a -> b) -> a -> b
$ Posting -> Day
postingDate Posting
p)  -- exclusive end date just after the assertion's date
      String
lotSubHint  -- lot subaccount hint (empty for non-lot accounts)

      where
        acct :: String
acct = CommoditySymbol -> String
T.unpack (CommoditySymbol -> String) -> CommoditySymbol -> String
forall a b. (a -> b) -> a -> b
$ Posting -> CommoditySymbol
paccount Posting
p
        ass :: BalanceAssertion
ass = Maybe BalanceAssertion -> BalanceAssertion
forall a. HasCallStack => Maybe a -> a
fromJust (Maybe BalanceAssertion -> BalanceAssertion)
-> Maybe BalanceAssertion -> BalanceAssertion
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p  -- PARTIAL: fromJust won't fail, there is a balance assertion
        pos :: SourcePos
pos = BalanceAssertion -> SourcePos
baposition BalanceAssertion
ass
        (String
_,Int
_,Maybe (Int, Maybe Int)
_,CommoditySymbol
ex) = Posting -> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeBalanceAssertionErrorExcerpt Posting
p
        assertedcommstr :: CommoditySymbol
assertedcommstr = if CommoditySymbol -> Bool
T.null CommoditySymbol
assertedcomm then CommoditySymbol
"\"\"" else CommoditySymbol
assertedcomm
        fmt :: AmountFormat
fmt = AmountFormat
oneLineFmt{displayZeroCommodity=True}
        (String
assertedstr, String
actualstr) =
          AmountFormat -> Amount -> Amount -> (String, String)
showAmountsDistinctly AmountFormat
fmt Amount
assertedcommbalcostless Amount
actualcommbalcostless
        diffstr :: String
diffstr     = AmountFormat -> Amount -> String
showAmountWith AmountFormat
fmt (Amount -> String) -> Amount -> String
forall a b. (a -> b) -> a -> b
$ Amount
assertedcommbalcostless Amount -> Amount -> Amount
forall a. Num a => a -> a -> a
- Amount
actualcommbalcostless
        pad :: String -> CommoditySymbol
pad = Maybe Int
-> Maybe Int -> Bool -> Bool -> CommoditySymbol -> CommoditySymbol
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
w) Maybe Int
forall a. Maybe a
Nothing Bool
False Bool
False (CommoditySymbol -> CommoditySymbol)
-> (String -> CommoditySymbol) -> String -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> CommoditySymbol
T.pack where w :: Int
w = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
assertedstr) (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
actualstr)
        -- If this is a lot subaccount assertion, remind that balance assertions generally
        -- don't work on lot subaccounts. (#2659)
        lotSubHint :: String
lotSubHint
          | Bool
isLotSub =
              String
"\n\nNote '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
assertedacct String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"' is a lot subaccount.\n"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Balance assertions aren't supported here unless all postings\n"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"to this lot mention the lot subaccount name explicitly.\n"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"So it's probably best to avoid using balance assertions on this account.\n"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"If needed, you could assert the parent account's balance instead."
          | Bool
otherwise = String
""
          where
            isLotSub :: Bool
isLotSub = CommoditySymbol
assertedacct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
assertedacct

  unless pass $ throwError errmsg
{- XXX
When the posting amount has a cost, the highlight region expands to the full line:

*** Exception: Error: /Users/simon/src/hledger/2024-01-21.j:12:69:
   | 2023-12-31 closing balances
12 |     assets:cash:petty:saved:rent       -4.00 EUR @ 2 UAH == 0.00 EUR
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |     equity:opening/closing balances                8 UAH

Maybe it's better than the normal region ?

*** Exception: Error: /Users/simon/src/hledger/2024-01-21.j:12:61:
   | 2023-12-31 closing balances
12 |     assets:cash:petty:saved:rent          -4.00 EUR == 0.00 EUR @ 3 UAH
   |                                                     ^^^^^^^^^^^^^^^^^^^
   |     equity:opening/closing balances        4.00 EUR

If changed also check flycheck-hledger, which currently highlights the equals:

    assets:cash:petty:saved:rent                  -4.00 EUR @ 2 UAH == 0.00 EUR @ 3 UAH 
                                                                    --
-}

-- | Throw an error if this posting is trying to do an illegal balance assignment.
checkIllegalBalanceAssignmentB :: Posting -> Balancing s ()
checkIllegalBalanceAssignmentB :: forall s. Posting -> Balancing s ()
checkIllegalBalanceAssignmentB Posting
p = do
  Posting -> Balancing s ()
forall s. Posting -> Balancing s ()
checkBalanceAssignmentPostingDateB Posting
p
  Posting -> Balancing s ()
forall s. Posting -> Balancing s ()
checkBalanceAssignmentUnassignableAccountB Posting
p

-- XXX these should show position. annotateErrorWithTransaction t ?

-- | Throw an error if this posting is trying to do a balance assignment and
-- has a custom posting date (which makes amount inference too hard/impossible).
checkBalanceAssignmentPostingDateB :: Posting -> Balancing s ()
checkBalanceAssignmentPostingDateB :: forall s. Posting -> Balancing s ()
checkBalanceAssignmentPostingDateB Posting
p =
  Bool
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Posting -> Bool
hasBalanceAssignment Posting
p Bool -> Bool -> Bool
&& Maybe Day -> Bool
forall a. Maybe a -> Bool
isJust (Posting -> Maybe Day
pdate Posting
p)) (ReaderT (BalancingState s) (ExceptT String (ST s)) ()
 -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
-> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$
    String -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a.
String -> ReaderT (BalancingState s) (ExceptT String (ST s)) a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (String -> ReaderT (BalancingState s) (ExceptT String (ST s)) ())
-> String -> ReaderT (BalancingState s) (ExceptT String (ST s)) ()
forall a b. (a -> b) -> a -> b
$ String -> String
chomp (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
unlines [
       String
"Balance assignments and custom posting dates may not be combined."
      ,String
""
      ,String -> String
chomp1 (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> String
T.unpack (CommoditySymbol -> String) -> CommoditySymbol -> String
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
-> (Transaction -> CommoditySymbol)
-> Maybe Transaction
-> CommoditySymbol
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([CommoditySymbol] -> CommoditySymbol
T.unlines ([CommoditySymbol] -> CommoditySymbol)
-> [CommoditySymbol] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> [CommoditySymbol]
showPostingLines Posting
p) Transaction -> CommoditySymbol
showTransaction (Maybe Transaction -> CommoditySymbol)
-> Maybe Transaction -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Transaction
ptransaction Posting
p
      ,String
"Balance assignments may not be used on postings with a custom posting date"
      ,String
"(it makes balancing the journal impossible)."
      ,String
"Please write the posting amount explicitly (or remove the posting date)."
      ]

-- | Throw an error if this posting is trying to do a balance assignment and
-- the account does not allow balance assignments (eg because it is referenced
-- by an auto posting rule, which might generate additional postings to it).
checkBalanceAssignmentUnassignableAccountB :: Posting -> Balancing s ()
checkBalanceAssignmentUnassignableAccountB :: forall s. Posting -> Balancing s ()
checkBalanceAssignmentUnassignableAccountB Posting
p = do
  unassignable <- (BalancingState s -> Set CommoditySymbol)
-> ReaderT
     (BalancingState s) (ExceptT String (ST s)) (Set CommoditySymbol)
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
R.asks BalancingState s -> Set CommoditySymbol
forall s. BalancingState s -> Set CommoditySymbol
bsUnassignable
  when (hasBalanceAssignment p && paccount p `S.member` unassignable) $
    throwError $ chomp $ unlines [
       "Balance assignments and auto postings may not be combined."
      ,""
      ,chomp1 $ T.unpack $ maybe (T.unlines $ showPostingLines p) (showTransaction) $ ptransaction p
      ,"Balance assignments may not be used on accounts affected by auto posting rules"
      ,"(it makes balancing the journal impossible)."
      ,"Please write the posting amount explicitly (or remove the auto posting rule(s))."
      ]

-- lenses

makeHledgerClassyLenses ''BalancingOpts

-- tests

tests_Balancing :: TestTree
tests_Balancing :: TestTree
tests_Balancing =
  String -> [TestTree] -> TestTree
testGroup String
"Balancing" [

      String -> Assertion -> TestTree
testCase String
"transactionInferBalancingAmount" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
         ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction
forall a b. (a, b) -> a
fst ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String Transaction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AccountType
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
transactionInferBalancingAmount Map CommoditySymbol AmountStyle
forall k a. Map k a
M.empty Map CommoditySymbol AccountType
forall k a. Map k a
M.empty Transaction
nulltransaction) Either String Transaction -> Either String Transaction -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
nulltransaction
         ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction
forall a b. (a, b) -> a
fst ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String Transaction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AccountType
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
transactionInferBalancingAmount Map CommoditySymbol AmountStyle
forall k a. Map k a
M.empty Map CommoditySymbol AccountType
forall k a. Map k a
M.empty Transaction
nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` missingamt]}) Either String Transaction -> Either String Transaction -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
           Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` usd 5]}
         ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction
forall a b. (a, b) -> a
fst ((Transaction, [(CommoditySymbol, MixedAmount)]) -> Transaction)
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
-> Either String Transaction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AccountType
-> Transaction
-> Either String (Transaction, [(CommoditySymbol, MixedAmount)])
transactionInferBalancingAmount Map CommoditySymbol AmountStyle
forall k a. Map k a
M.empty Map CommoditySymbol AccountType
forall k a. Map k a
M.empty Transaction
nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` (eur 3 @@ usd 4), "c" `post` missingamt]}) Either String Transaction -> Either String Transaction -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
           Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` (eur 3 @@ usd 4), "c" `post` usd 1]}

    , String -> [TestTree] -> TestTree
testGroup String
"balanceSingleTransaction" [
         String -> Assertion -> TestTree
testCase String
"detect unbalanced entry, sign error" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          Either String Transaction -> Assertion
forall b a. (HasCallStack, Eq b, Show b) => Either a b -> Assertion
assertLeft
            (BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
               (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
                  Integer
0
                  CommoditySymbol
""
                  (SourcePos, SourcePos)
nullsourcepospair
                  (Integer -> Int -> Int -> Day
fromGregorian Integer
2007 Int
01 Int
28)
                  Maybe Day
forall a. Maybe a
Nothing
                  Status
Unmarked
                  CommoditySymbol
""
                  CommoditySymbol
"test"
                  CommoditySymbol
""
                  []
                  [Posting
posting {paccount = "a", pamount = mixedAmount (usd 1)}, Posting
posting {paccount = "b", pamount = mixedAmount (usd 1)}]))
        ,String -> Assertion -> TestTree
testCase String
"detect unbalanced entry, multiple missing amounts" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          Either String Transaction -> Assertion
forall b a. (HasCallStack, Eq b, Show b) => Either a b -> Assertion
assertLeft (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$
             BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
               (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
                  Integer
0
                  CommoditySymbol
""
                  (SourcePos, SourcePos)
nullsourcepospair
                  (Integer -> Int -> Int -> Day
fromGregorian Integer
2007 Int
01 Int
28)
                  Maybe Day
forall a. Maybe a
Nothing
                  Status
Unmarked
                  CommoditySymbol
""
                  CommoditySymbol
"test"
                  CommoditySymbol
""
                  []
                  [ Posting
posting {paccount = "a", pamount = missingmixedamt}
                  , Posting
posting {paccount = "b", pamount = missingmixedamt}
                  ])
        ,String -> Assertion -> TestTree
testCase String
"one missing amount is inferred" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          (Posting -> MixedAmount
pamount (Posting -> MixedAmount)
-> (Transaction -> Posting) -> Transaction -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Posting] -> Posting
forall a. HasCallStack => [a] -> a
last ([Posting] -> Posting)
-> (Transaction -> [Posting]) -> Transaction -> Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings (Transaction -> MixedAmount)
-> Either String Transaction -> Either String MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
           BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
             (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
                Integer
0
                CommoditySymbol
""
                (SourcePos, SourcePos)
nullsourcepospair
                (Integer -> Int -> Int -> Day
fromGregorian Integer
2007 Int
01 Int
28)
                Maybe Day
forall a. Maybe a
Nothing
                Status
Unmarked
                CommoditySymbol
""
                CommoditySymbol
""
                CommoditySymbol
""
                []
                [Posting
posting {paccount = "a", pamount = mixedAmount (usd 1)}, Posting
posting {paccount = "b", pamount = missingmixedamt}])) Either String MixedAmount -> Either String MixedAmount -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
          MixedAmount -> Either String MixedAmount
forall a b. b -> Either a b
Right (Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount) -> Amount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount
usd (-Quantity
1))
        ,String -> Assertion -> TestTree
testCase String
"conversion price is inferred" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          (Posting -> MixedAmount
pamount (Posting -> MixedAmount)
-> (Transaction -> Posting) -> Transaction -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Posting] -> Posting
forall a. HasCallStack => [a] -> a
headErr ([Posting] -> Posting)
-> (Transaction -> [Posting]) -> Transaction -> Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings (Transaction -> MixedAmount)
-> Either String Transaction -> Either String MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>  -- PARTIAL headErr succeeds because non-null postings list
           BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
             (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
                Integer
0
                CommoditySymbol
""
                (SourcePos, SourcePos)
nullsourcepospair
                (Integer -> Int -> Int -> Day
fromGregorian Integer
2007 Int
01 Int
28)
                Maybe Day
forall a. Maybe a
Nothing
                Status
Unmarked
                CommoditySymbol
""
                CommoditySymbol
""
                CommoditySymbol
""
                []
                [ Posting
posting {paccount = "a", pamount = mixedAmount (usd 1.35)}
                , Posting
posting {paccount = "b", pamount = mixedAmount (eur (-1))}
                ])) Either String MixedAmount -> Either String MixedAmount -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
          MixedAmount -> Either String MixedAmount
forall a b. b -> Either a b
Right (Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount) -> Amount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount
usd Quantity
1.35 Amount -> Amount -> Amount
@@ Quantity -> Amount
eur Quantity
1)
        ,String -> Assertion -> TestTree
testCase String
"balanceSingleTransaction balances based on cost if there are unit prices" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          Either String Transaction -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
            (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
               Integer
0
               CommoditySymbol
""
               (SourcePos, SourcePos)
nullsourcepospair
               (Integer -> Int -> Int -> Day
fromGregorian Integer
2011 Int
01 Int
01)
               Maybe Day
forall a. Maybe a
Nothing
               Status
Unmarked
               CommoditySymbol
""
               CommoditySymbol
""
               CommoditySymbol
""
               []
               [ Posting
posting {paccount = "a", pamount = mixedAmount $ usd 1 `at` eur 2}
               , Posting
posting {paccount = "a", pamount = mixedAmount $ usd (-2) `at` eur 1}
               ])
        ,String -> Assertion -> TestTree
testCase String
"balanceSingleTransaction balances based on cost if there are total prices" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          Either String Transaction -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Either String Transaction
balanceSingleTransaction BalancingOpts
defbalancingopts
            (Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
               Integer
0
               CommoditySymbol
""
               (SourcePos, SourcePos)
nullsourcepospair
               (Integer -> Int -> Int -> Day
fromGregorian Integer
2011 Int
01 Int
01)
               Maybe Day
forall a. Maybe a
Nothing
               Status
Unmarked
               CommoditySymbol
""
               CommoditySymbol
""
               CommoditySymbol
""
               []
               [ Posting
posting {paccount = "a", pamount = mixedAmount $ usd 1 @@ eur 1}
               , Posting
posting {paccount = "a", pamount = mixedAmount $ usd (-2) @@ eur (-1)}
               ])
        ]
    , String -> [TestTree] -> TestTree
testGroup String
"isTransactionBalanced" [
         String -> Assertion -> TestTree
testCase String
"detect balanced" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [ Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}
            , Posting
posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}
            ]
        ,String -> Assertion -> TestTree
testCase String
"detect unbalanced" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [ Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}
            , Posting
posting {paccount = "c", pamount = mixedAmount (usd (-1.01))}
            ]
        ,String -> Assertion -> TestTree
testCase String
"detect unbalanced, one posting" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}]
        ,String -> Assertion -> TestTree
testCase String
"one zero posting is considered balanced for now" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [Posting
posting {paccount = "b", pamount = mixedAmount (usd 0)}]
        ,String -> Assertion -> TestTree
testCase String
"virtual postings don't need to balance" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [ Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}
            , Posting
posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}
            , Posting
posting {paccount = "d", pamount = mixedAmount (usd 100), preal = VirtualPosting}
            ]
        ,String -> Assertion -> TestTree
testCase String
"balanced virtual postings need to balance among themselves" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [ Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}
            , Posting
posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}
            , Posting
posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}
            ]
        ,String -> Assertion -> TestTree
testCase String
"balanced virtual postings need to balance among themselves (2)" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
          HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$
          BalancingOpts -> Transaction -> Bool
isTransactionBalanced BalancingOpts
defbalancingopts (Transaction -> Bool) -> Transaction -> Bool
forall a b. (a -> b) -> a -> b
$
          Integer
-> CommoditySymbol
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> CommoditySymbol
-> CommoditySymbol
-> CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)]
-> [Posting]
-> Transaction
Transaction
            Integer
0
            CommoditySymbol
""
            (SourcePos, SourcePos)
nullsourcepospair
            (Integer -> Int -> Int -> Day
fromGregorian Integer
2009 Int
01 Int
01)
            Maybe Day
forall a. Maybe a
Nothing
            Status
Unmarked
            CommoditySymbol
""
            CommoditySymbol
"a"
            CommoditySymbol
""
            []
            [ Posting
posting {paccount = "b", pamount = mixedAmount (usd 1.00)}
            , Posting
posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}
            , Posting
posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}
            , Posting
posting {paccount = "3", pamount = mixedAmount (usd (-100)), preal = BalancedVirtualPosting}
            ]
        ]

  ,String -> [TestTree] -> TestTree
testGroup String
"journalBalanceTransactions" [

     String -> Assertion -> TestTree
testCase String
"missing-amounts" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      let ej :: Either String Journal
ej = BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
defbalancingopts (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$ Bool -> Journal
samplejournalMaybeExplicit Bool
False
      Either String Journal -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight Either String Journal
ej
      Journal -> [Posting]
journalPostings (Journal -> [Posting])
-> Either String Journal -> Either String [Posting]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either String Journal
ej Either String [Posting] -> Either String [Posting] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Posting] -> Either String [Posting]
forall a b. b -> Either a b
Right (Journal -> [Posting]
journalPostings Journal
samplejournal)

    ,String -> Assertion -> TestTree
testCase String
"balance-assignment" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      let ej :: Either String Journal
ej = BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
defbalancingopts (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$
            --2019/01/01
            --  (a)            = 1
            Journal
nulljournal{ jtxns = [
              transaction (fromGregorian 2019 01 01) [ vpost' "a" missingamt (balassert (num 1)) ]
            ]}
      Either String Journal -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight Either String Journal
ej
      case Either String Journal
ej of Right Journal
j -> (Journal -> [Transaction]
jtxns Journal
j [Transaction] -> ([Transaction] -> Transaction) -> Transaction
forall a b. a -> (a -> b) -> b
& [Transaction] -> Transaction
forall a. HasCallStack => [a] -> a
headErr Transaction -> (Transaction -> [Posting]) -> [Posting]
forall a b. a -> (a -> b) -> b
& Transaction -> [Posting]
tpostings [Posting] -> ([Posting] -> Posting) -> Posting
forall a b. a -> (a -> b) -> b
& [Posting] -> Posting
forall a. HasCallStack => [a] -> a
headErr Posting -> (Posting -> MixedAmount) -> MixedAmount
forall a b. a -> (a -> b) -> b
& Posting -> MixedAmount
pamount MixedAmount -> (MixedAmount -> [Amount]) -> [Amount]
forall a b. a -> (a -> b) -> b
& MixedAmount -> [Amount]
amountsRaw) [Amount] -> [Amount] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Quantity -> Amount
num Quantity
1]  -- PARTIAL headErrs succeed because non-null txns & postings lists given
                 Left String
_  -> String -> Assertion
forall a. String -> a
error' String
"balance-assignment test: shouldn't happen"

    ,String -> Assertion -> TestTree
testCase String
"same-day-1" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      Either String Journal -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Journal -> Assertion)
-> Either String Journal -> Assertion
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
defbalancingopts (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$
            --2019/01/01
            --  (a)            = 1
            --2019/01/01
            --  (a)          1 = 2
            Journal
nulljournal{ jtxns = [
               transaction (fromGregorian 2019 01 01) [ vpost' "a" missingamt (balassert (num 1)) ]
              ,transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 1)    (balassert (num 2)) ]
            ]}

    ,String -> Assertion -> TestTree
testCase String
"same-day-2" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      Either String Journal -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Journal -> Assertion)
-> Either String Journal -> Assertion
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
defbalancingopts (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$
            --2019/01/01
            --    (a)                  2 = 2
            --2019/01/01
            --    b                    1
            --    a
            --2019/01/01
            --    a                    0 = 1
            Journal
nulljournal{ jtxns = [
               transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 2)    (balassert (num 2)) ]
              ,transaction (fromGregorian 2019 01 01) [
                 post' "b" (num 1)     Nothing
                ,post' "a"  missingamt Nothing
              ]
              ,transaction (fromGregorian 2019 01 01) [ post' "a" (num 0)     (balassert (num 1)) ]
            ]}

    ,String -> Assertion -> TestTree
testCase String
"out-of-order" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      Either String Journal -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Journal -> Assertion)
-> Either String Journal -> Assertion
forall a b. (a -> b) -> a -> b
$ BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
defbalancingopts (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$
            --2019/1/2
            --  (a)    1 = 2
            --2019/1/1
            --  (a)    1 = 1
            Journal
nulljournal{ jtxns = [
               transaction (fromGregorian 2019 01 02) [ vpost' "a" (num 1)    (balassert (num 2)) ]
              ,transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 1)    (balassert (num 1)) ]
            ]}

    ]

    ,String -> [TestTree] -> TestTree
testGroup String
"transactionCheckAssertions" ([TestTree] -> TestTree) -> [TestTree] -> TestTree
forall a b. (a -> b) -> a -> b
$ [
      String -> Assertion -> TestTree
testCase String
"simple assertion on same day" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do 
        Either String Transaction -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$ 
          BalancingOpts
-> Journal -> Transaction -> Either String Transaction
transactionCheckAssertions BalancingOpts
defbalancingopts Journal
nulljournal{ jtxns = [
            transaction (fromGregorian 2025 01 01) [ vpost' "a" (usd 1) Nothing ]
            ] } (Day -> [Posting] -> Transaction
transaction (Integer -> Int -> Int -> Day
fromGregorian Integer
2025 Int
01 Int
01) [ CommoditySymbol -> Amount -> Maybe BalanceAssertion -> Posting
vpost' CommoditySymbol
"a" (Quantity -> Amount
usd Quantity
1) (Amount -> Maybe BalanceAssertion
balassert (Quantity -> Amount
usd Quantity
2)) ])

      ,String -> Assertion -> TestTree
testCase String
"inclusive assertions" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do 
        Either String Transaction -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$ 
          BalancingOpts
-> Journal -> Transaction -> Either String Transaction
transactionCheckAssertions BalancingOpts
defbalancingopts Journal
nulljournal{ jtxns = [
            transaction (fromGregorian 2025 01 01) [ vpost' "a:a" (usd 1) Nothing ] 
            ,transaction (fromGregorian 2025 01 02) [ vpost' "a:b" (usd 2) Nothing]
            ,transaction (fromGregorian 2025 01 02) [ vpost' "a:c" (usd 5) Nothing]
            ,transaction (fromGregorian 2025 01 03) [ vpost' "a:d" (eur 10) Nothing]
            ] } (Day -> [Posting] -> Transaction
transaction (Integer -> Int -> Int -> Day
fromGregorian Integer
2025 Int
01 Int
04) [ CommoditySymbol -> Amount -> Maybe BalanceAssertion -> Posting
vpost' CommoditySymbol
"a" (Quantity -> Amount
usd Quantity
2) (Amount -> Maybe BalanceAssertion
balassertParInc (Quantity -> Amount
usd Quantity
10))])

      ,String -> Assertion -> TestTree
testCase String
"multicommodity assertion" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do 
        Either String Transaction -> Assertion
forall a b. (HasCallStack, Eq a, Show a) => Either a b -> Assertion
assertRight (Either String Transaction -> Assertion)
-> Either String Transaction -> Assertion
forall a b. (a -> b) -> a -> b
$ 
          BalancingOpts
-> Journal -> Transaction -> Either String Transaction
transactionCheckAssertions BalancingOpts
defbalancingopts Journal
nulljournal{ jtxns = [
            transaction (fromGregorian 2025 01 01) [ vpost' "a" (usd 1) Nothing ] 
            ,transaction (fromGregorian 2025 01 02) [ vpost' "a:b" (eur 2) Nothing ]
            ,transaction (fromGregorian 2025 01 02) [ vpost' "a:c" (usd 5) Nothing ]
            ,transaction (fromGregorian 2025 01 03) [ vpost' "a:b" (eur (-2)) Nothing ]
            ] } (Day -> [Posting] -> Transaction
transaction (Integer -> Int -> Int -> Day
fromGregorian Integer
2025 Int
01 Int
03) [ CommoditySymbol -> Amount -> Maybe BalanceAssertion -> Posting
vpost' CommoditySymbol
"a" (Quantity -> Amount
usd Quantity
2) (Amount -> Maybe BalanceAssertion
balassertTotInc (Quantity -> Amount
usd Quantity
8)) ])
    ]

    ,String -> [TestTree] -> TestTree
testGroup String
"commodityStylesFromAmounts" ([TestTree] -> TestTree) -> [TestTree] -> TestTree
forall a b. (a -> b) -> a -> b
$ [

      -- Journal similar to the one on #1091:
      -- 2019/09/24
      --     (a)            1,000.00
      -- 
      -- 2019/09/26
      --     (a)             1000,000
      --
      String -> Assertion -> TestTree
testCase String
"1091a" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
        [Amount] -> Either String (Map CommoditySymbol AmountStyle)
commodityStylesFromAmounts [
           Amount
nullamt{aquantity=1000, astyle=AmountStyle L False Nothing (Just ',') (Precision 3) NoRounding}
          ,Amount
nullamt{aquantity=1000, astyle=AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 2) NoRounding}
          ]
         Either String (Map CommoditySymbol AmountStyle)
-> Either String (Map CommoditySymbol AmountStyle) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
          -- The commodity style should have period as decimal mark
          -- and comma as digit group mark.
          Map CommoditySymbol AmountStyle
-> Either String (Map CommoditySymbol AmountStyle)
forall a b. b -> Either a b
Right ([(CommoditySymbol, AmountStyle)] -> Map CommoditySymbol AmountStyle
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [
            (CommoditySymbol
"", Side
-> Bool
-> Maybe DigitGroupStyle
-> Maybe Char
-> AmountPrecision
-> Rounding
-> AmountStyle
AmountStyle Side
L Bool
False (DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3])) (Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.') (Word8 -> AmountPrecision
Precision Word8
3) Rounding
NoRounding)
          ])
        -- same journal, entries in reverse order
      ,String -> Assertion -> TestTree
testCase String
"1091b" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
        [Amount] -> Either String (Map CommoditySymbol AmountStyle)
commodityStylesFromAmounts [
           Amount
nullamt{aquantity=1000, astyle=AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 2) NoRounding}
          ,Amount
nullamt{aquantity=1000, astyle=AmountStyle L False Nothing (Just ',') (Precision 3) NoRounding}
          ]
         Either String (Map CommoditySymbol AmountStyle)
-> Either String (Map CommoditySymbol AmountStyle) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?=
          -- The commodity style should have period as decimal mark
          -- and comma as digit group mark.
          Map CommoditySymbol AmountStyle
-> Either String (Map CommoditySymbol AmountStyle)
forall a b. b -> Either a b
Right ([(CommoditySymbol, AmountStyle)] -> Map CommoditySymbol AmountStyle
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [
            (CommoditySymbol
"", Side
-> Bool
-> Maybe DigitGroupStyle
-> Maybe Char
-> AmountPrecision
-> Rounding
-> AmountStyle
AmountStyle Side
L Bool
False (DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3])) (Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.') (Word8 -> AmountPrecision
Precision Word8
3) Rounding
NoRounding)
          ])

     ]

  ]