{-|
Lot tracking for investment accounting.

This module implements two pipeline stages (see doc\/SPEC-finalising.md):

1. Classification ('journalClassifyLotPostings'): identifies lot postings
   and tags them as acquire, dispose, transfer-from, or transfer-to.

2. Calculation ('journalCalculateLots'): walks transactions in date order,
   accumulating a map from commodities to their lots, and:

   - For acquire postings: generates lot names from cost basis and appends
     them to the account name as subaccounts.

   - For dispose postings: selects an existing lot subaccount matched by
     the posting's lot selector, using the configured reduction method
     (FIFO by default, configurable per account\/commodity via @lots:@ tag).
     If needed and if the lot selector permits it, selects multiple lots,
     splitting the posting into one per lot.
     Dispose postings with a transacted price (selling price) generate gain postings.
     Bare disposes without a price (e.g. fee deductions) get lot subaccounts but no gain.

   - For transfer postings: selects lots from the source account (like
     dispose) and recreates them under the destination account. The lot's
     cost basis is preserved through the transfer.
     Multi-lot transfers are supported (eg via @{}@ to transfer all lots).

For background, see doc\/SPEC-lots.md and doc\/PLAN-lots.md.

== Errors

User-visible errors from this module. See also Hledger.Data.Errors and doc/ERRORS.md.

journalCalculateLots:

* validateUserLabels:
  "lot id is not unique: commodity X, date D, label L"

* processAcquirePosting:
  "acquire posting has no cost basis",
  "...has multiple cost basis amounts",
  "X is lotful but this acquire posting has no cost basis or price",
  "...has no lot cost",
  "duplicate lot id: {...} for commodity X"

* processDisposePosting:
  "dispose posting has no cost basis",
  "...has no transacted price (selling price)" / "(buying price, to cover the short)",
  "...has non-negative quantity" / "non-positive quantity (a short position is covered by a positive posting)",
  "SPECID requires a lot selector",
  "lot ... has no cost basis (internal error)",
  "lot subaccount ... does not match resolved lot"

* groupIndexedTransferPostings:
  "transfer-to/from posting ... has no matching ... posting",
  "Mismatched transfer quantities for lot-tracked commodity X",
  "... posting has no lotful commodity"

* processTransferGroup:
  "transfer-from posting has no cost basis",
  "...has multiple cost basis amounts",
  "lot transfers should have no transacted price",
  "transfer-from posting has non-negative quantity",
  "transfer-to posting has no single positive X amount",
  "could not distribute transferred lots exactly (internal error)",
  "lot ... has no cost basis (internal error)",
  "lot cost basis ... does not match transfer-to cost basis"

* selectLots:
  "SPECID requires an explicit lot selector",
  "no X lots available for transfer/disposal from account Y on DATE"
  (with a hint to use a liability account for a short position),
  and on any lot error, a hint naming a later same-date entry which adds
  the commodity to an empty source account (see laterSupplyHint),
  "no lots matching {...} for commodity X in account Y on DATE",
  "lot selector is ambiguous, matches N lots in account Y",
  "Insufficient lots for commodity X in account Y"

* validateGlobalCompliance:
  "METHOD: lot(s) on other account(s) have higher priority than the lots in ACCT"

* poolWeightedAvgCost:
  "no lots with cost basis available for averaging",
  "cannot average lots with different cost commodities",
  "cannot average lots with zero total quantity"

* foldMPostings (via isUnclassifiedLotfulPosting):
  "X is declared lotful ... but this posting was not classified"
  (exempt: zero-amount lotful postings; in a liability account, notes that
  short lots can't be transferred yet)

-}

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

module Hledger.Data.Lots (
  journalHasLotFeatures,
  transactionHasLotfulAmounts,
  journalClassifyLotPostings,
  journalStripBalancerCopiedBases,
  transactionAutoSplitFeeOutflows,
  journalCalculateLots,
  journalCheckAcquireBasis,
  journalCheckLotsMethodCoherence,
  journalAveragePoolTotals,
  journalAveragePoolCosts,
  journalCollapseLotDetail,
  journalTagGainPostings,
  transactionTagGainPostings,
  journalAddOrCheckGainPostings,
  isDisposePosting,
  isGainPosting,
  isSetAsideGainPosting,
  lotBaseAccount,
  lotDirectionOf,
  journalLotDirection,
  lotSubaccountName,
  mergeCostBasis,
  parseLotName,
  resolveReductionMethodForAccount,
  showLotName,
) where

import Control.Applicative ((<|>))
import Data.Bifunctor (first)
import Control.Monad (foldM, guard, unless, when)
import Data.List (dropWhileEnd, intercalate, partition, sort, sortOn)
import Data.Ord (Down(..))
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.Map.Strict qualified as M
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Char (isDigit)
import Data.Decimal (decimalPlaces, roundTo)
import Data.Time.Calendar (Day, fromGregorianValid)
import Text.Printf (printf)

import Hledger.Data.AccountName (accountNameType, parentAccountNames)
import Hledger.Data.AccountType (LotDirection(..), accountTypeLotDirection, isAssetType, isEquityType, isLiabilityType, lotDirectionSign)
import Hledger.Data.Amount (AmountFormat(..), mixed, maPlus, mixedAmountStripCosts, amountRoundedQuantity, amountSetPrecisionMin, amountSetQuantity, amountsRaw, divideAmountAndUpdatePrecision, isNegativeAmount, maNegate, maSum, mapMixedAmount, mixedAmount, mixedAmountCost, mixedAmountIsZero, mixedAmountLooksZero, multiplyQuantities, nullmixedamt, noCostFmt, oneLineNoCostFmt, showAmountWith, showAmountsDistinctly, showMixedAmountOneLine, showMixedAmountsDistinctly)
import Hledger.Data.Errors (makeAccountTagErrorExcerpt, makeCommodityTagErrorExcerpt, makePostingErrorExcerptByIndex, makeTransactionErrorExcerpt, transactionFindPostingIndex)
import Hledger.Data.Journal (journalAccountLotsTags, journalAccountType, journalAccountUsesNoLots, journalBaseGainAccount, journalCommodityLotsMethod, journalCommodityStylesWith, journalCommodityUsesLots, journalInheritedAccountTags, journalLotfulCommodities, journalMapPostings, journalMapTransactions, journalPostings, journalTieTransactions, parseReductionMethod)
import Hledger.Data.Posting (costPostingTagName, generatedPostingTagName, hasAmount, isReal, isVirtual, lotParentAssertionTagName, lotsplitPostingTagName, nullposting, originalPosting, postingAddHiddenAndMaybeVisibleTag, postingRemoveHiddenAndVisibleTag, postingDate, postingHasTag, postingStripCosts, feesplitPostingTagName)
import Hledger.Data.Transaction (transactionCommodityStyles, txnTieKnot)
import Hledger.Data.Types
import Hledger.Utils (dbg5, dbg5With)

-- Types

-- | Map from commodity to (map from lot id to (map from account name to lot balance)).
-- Keyed by commodity at the top level so lots of different commodities don't clash.
-- The inner Map LotId is ordered by date then label, supporting FIFO/LIFO naturally.
-- The innermost Map AccountName allows the same lot to exist at multiple accounts
-- (eg after a partial lot transfer).
type LotState = M.Map CommoditySymbol (M.Map LotId (M.Map AccountName Amount))

-- | Resolve which reduction method to use for a posting, and where it came from.
-- Checks account-inherited tags first, then commodity tags, defaulting to FIFO.
-- Since commodity tags are propagated to ptags, we distinguish by checking the
-- commodity's own declared tags separately.
resolveReductionMethodWithSource :: Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodWithSource :: Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodWithSource Journal
j Posting
p = Journal
-> CommoditySymbol -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodForAccount Journal
j (Posting -> CommoditySymbol
paccount Posting
p)

-- | Resolve which reduction method is in effect for an account and commodity,
-- and where it came from: the account's (inherited) lots: tag if any,
-- else the commodity's lots: tag value if any, else FIFO.
resolveReductionMethodForAccount :: Journal -> AccountName -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodForAccount :: Journal
-> CommoditySymbol -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodForAccount Journal
j CommoditySymbol
acct CommoditySymbol
commodity =
  case Maybe ReductionMethod
accountLotsMethod of
    Just ReductionMethod
m  -> (ReductionMethod
m, String
"from account tag on " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
acct)
    Maybe ReductionMethod
Nothing -> case Journal -> CommoditySymbol -> Maybe ReductionMethod
journalCommodityLotsMethod Journal
j CommoditySymbol
commodity of
      Just ReductionMethod
m  -> (ReductionMethod
m, String
"from commodity tag on " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity)
      Maybe ReductionMethod
Nothing -> (ReductionMethod
FIFO, String
"default")
  where
    -- Check account-inherited tags only (excluding commodity-propagated tags).
    accountLotsMethod :: Maybe ReductionMethod
accountLotsMethod =
      let acctTags :: [(CommoditySymbol, CommoditySymbol)]
acctTags = Journal -> CommoditySymbol -> [(CommoditySymbol, CommoditySymbol)]
journalInheritedAccountTags Journal
j CommoditySymbol
acct
      in case [CommoditySymbol
v | (CommoditySymbol
k, CommoditySymbol
v) <- [(CommoditySymbol, CommoditySymbol)]
acctTags, CommoditySymbol -> CommoditySymbol
T.toLower CommoditySymbol
k CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
"lots"] of
           (CommoditySymbol
v:[CommoditySymbol]
_) -> CommoditySymbol -> Maybe ReductionMethod
parseReductionMethod CommoditySymbol
v
           []    -> Maybe ReductionMethod
forall a. Maybe a
Nothing

-- | Check that global (*ALL) reduction methods are used coherently:
-- when any account holding a lot-tracked commodity resolves to a global
-- method, every account holding that commodity must resolve to the same
-- method. Mixing a global method with any other is rejected, because the
-- global validation (and, for AVERAGEALL, the global pool updates) only
-- make sense when every account participates. Local methods (FIFO, LIFO,
-- HIFO, SPECID, AVERAGE) may be mixed per account freely.
journalCheckLotsMethodCoherence :: Journal -> Either String Journal
journalCheckLotsMethodCoherence :: Journal -> Either String Journal
journalCheckLotsMethodCoherence Journal
j = do
    (((CommoditySymbol, LotDirection), Set CommoditySymbol)
 -> Either String ())
-> [((CommoditySymbol, LotDirection), Set CommoditySymbol)]
-> Either String ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ((CommoditySymbol, LotDirection), Set CommoditySymbol)
-> Either String ()
forall {b}.
((CommoditySymbol, b), Set CommoditySymbol) -> Either String ()
checkCommodity (Map (CommoditySymbol, LotDirection) (Set CommoditySymbol)
-> [((CommoditySymbol, LotDirection), Set CommoditySymbol)]
forall k a. Map k a -> [(k, a)]
M.toList Map (CommoditySymbol, LotDirection) (Set CommoditySymbol)
holdings)
    Journal -> Either String Journal
forall a b. b -> Either a b
Right Journal
j
  where
    -- The base accounts holding each lot-tracked commodity (postings with
    -- a cost basis annotation, or a lotful commodity in an account that
    -- hasn't opted out of lot tracking with lots: NONE), grouped by lot
    -- direction: long lots (asset accounts) and short lots (liability
    -- accounts) are separate pools, which may use different methods.
    holdings :: M.Map (CommoditySymbol, LotDirection) (S.Set AccountName)
    holdings :: Map (CommoditySymbol, LotDirection) (Set CommoditySymbol)
holdings = (Set CommoditySymbol -> Set CommoditySymbol -> Set CommoditySymbol)
-> [((CommoditySymbol, LotDirection), Set CommoditySymbol)]
-> Map (CommoditySymbol, LotDirection) (Set CommoditySymbol)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Set CommoditySymbol -> Set CommoditySymbol -> Set CommoditySymbol
forall a. Ord a => Set a -> Set a -> Set a
S.union
      [ ((Amount -> CommoditySymbol
acommodity Amount
a, Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j CommoditySymbol
acct), CommoditySymbol -> Set CommoditySymbol
forall a. a -> Set a
S.singleton CommoditySymbol
acct)
      | Posting
p <- Journal -> [Posting]
journalPostings Journal
j
      , let acct :: CommoditySymbol
acct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
      , Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      , Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)
        Bool -> Bool -> Bool
|| (Journal -> CommoditySymbol -> Bool
journalCommodityUsesLots Journal
j (Amount -> CommoditySymbol
acommodity Amount
a) Bool -> Bool -> Bool
&& Bool -> Bool
not (Journal -> CommoditySymbol -> Bool
journalAccountUsesNoLots Journal
j CommoditySymbol
acct)) ]

    resolutions :: CommoditySymbol
-> Set CommoditySymbol
-> [(CommoditySymbol, ReductionMethod, String)]
resolutions CommoditySymbol
c Set CommoditySymbol
accts = [ (CommoditySymbol
acct, ReductionMethod
m, String
src)
                          | CommoditySymbol
acct <- Set CommoditySymbol -> [CommoditySymbol]
forall a. Set a -> [a]
S.toList Set CommoditySymbol
accts
                          , let (ReductionMethod
m, String
src) = Journal
-> CommoditySymbol -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodForAccount Journal
j CommoditySymbol
acct CommoditySymbol
c ]

    checkCommodity :: ((CommoditySymbol, b), Set CommoditySymbol) -> Either String ()
checkCommodity ((CommoditySymbol
c, b
_), Set CommoditySymbol
accts) =
      case [(CommoditySymbol, ReductionMethod, String)
r | r :: (CommoditySymbol, ReductionMethod, String)
r@(CommoditySymbol
_, ReductionMethod
m, String
_) <- [(CommoditySymbol, ReductionMethod, String)]
rs, ReductionMethod -> Bool
methodIsGlobal ReductionMethod
m] of
        [] -> () -> Either String ()
forall a b. b -> Either a b
Right ()
        (CommoditySymbol
gacct, ReductionMethod
gmethod, String
gsrc):[(CommoditySymbol, ReductionMethod, String)]
_ ->
          case [(CommoditySymbol, ReductionMethod, String)
r | r :: (CommoditySymbol, ReductionMethod, String)
r@(CommoditySymbol
_, ReductionMethod
m, String
_) <- [(CommoditySymbol, ReductionMethod, String)]
rs, ReductionMethod
m ReductionMethod -> ReductionMethod -> Bool
forall a. Eq a => a -> a -> Bool
/= ReductionMethod
gmethod] of
            []        -> () -> Either String ()
forall a b. b -> Either a b
Right ()
            [(CommoditySymbol, ReductionMethod, String)]
conflicts -> String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
-> CommoditySymbol
-> ReductionMethod
-> String
-> [(CommoditySymbol, ReductionMethod, String)]
-> String
forall {a} {a}.
(Show a, Show a) =>
CommoditySymbol
-> CommoditySymbol
-> a
-> String
-> [(CommoditySymbol, a, String)]
-> String
errmsg CommoditySymbol
c CommoditySymbol
gacct ReductionMethod
gmethod String
gsrc [(CommoditySymbol, ReductionMethod, String)]
conflicts
      where rs :: [(CommoditySymbol, ReductionMethod, String)]
rs = CommoditySymbol
-> Set CommoditySymbol
-> [(CommoditySymbol, ReductionMethod, String)]
resolutions CommoditySymbol
c Set CommoditySymbol
accts

    errmsg :: CommoditySymbol
-> CommoditySymbol
-> a
-> String
-> [(CommoditySymbol, a, String)]
-> String
errmsg CommoditySymbol
c CommoditySymbol
gacct a
gmethod String
gsrc [(CommoditySymbol, a, String)]
conflicts =
         String
-> ((String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
    -> String)
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
-> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe String
"" (\(String
f, Int
l, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) -> String -> String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" String
f Int
l CommoditySymbol
ex) (CommoditySymbol
-> CommoditySymbol
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
methodDecl CommoditySymbol
gacct CommoditySymbol
c)
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
c String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" uses the global method " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
gmethod String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
gsrc String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
gacct String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
",\nbut a different method elsewhere:\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ [String] -> String
unlines [String
"  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
acct String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" uses " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
m String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
src String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")" | (CommoditySymbol
acct, a
m, String
src) <- [(CommoditySymbol, a, String)]
conflicts]
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"A global (*ALL) method must be used by every account holding the commodity.\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Declare it once on the commodity declaration, and remove conflicting account lots: tags."

    -- The declaration providing an account's method for a commodity,
    -- rendered as an error excerpt: the nearest self-or-ancestor account
    -- declaration with a method-valued lots: tag, else the commodity's
    -- declaration. Mirrors resolveReductionMethodForAccount's precedence.
    methodDecl :: AccountName -> CommoditySymbol -> Maybe (FilePath, Int, Maybe (Int, Maybe Int), Text)
    methodDecl :: CommoditySymbol
-> CommoditySymbol
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
methodDecl CommoditySymbol
acct CommoditySymbol
c =
      case [ (CommoditySymbol
a', AccountDeclarationInfo
adi) | CommoditySymbol
a' <- CommoditySymbol
acct CommoditySymbol -> [CommoditySymbol] -> [CommoditySymbol]
forall a. a -> [a] -> [a]
: CommoditySymbol -> [CommoditySymbol]
parentAccountNames CommoditySymbol
acct
                       , Just AccountDeclarationInfo
adi <- [CommoditySymbol
-> [(CommoditySymbol, AccountDeclarationInfo)]
-> Maybe AccountDeclarationInfo
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup CommoditySymbol
a' (Journal -> [(CommoditySymbol, AccountDeclarationInfo)]
jdeclaredaccounts Journal
j)]
                       , ((CommoditySymbol, CommoditySymbol) -> Bool)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol, CommoditySymbol) -> Bool
isMethodTag (AccountDeclarationInfo -> [(CommoditySymbol, CommoditySymbol)]
aditags AccountDeclarationInfo
adi) ] of
        ((CommoditySymbol
a', AccountDeclarationInfo
adi):[(CommoditySymbol, AccountDeclarationInfo)]
_) -> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
forall a. a -> Maybe a
Just ((String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
 -> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol))
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol, AccountDeclarationInfo)
-> CommoditySymbol
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeAccountTagErrorExcerpt (CommoditySymbol
a', AccountDeclarationInfo
adi) CommoditySymbol
"lots"
        []            -> (Commodity
-> CommoditySymbol
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
`makeCommodityTagErrorExcerpt` CommoditySymbol
"lots") (Commodity
 -> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol))
-> Maybe Commodity
-> Maybe (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CommoditySymbol -> Map CommoditySymbol Commodity -> Maybe Commodity
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
c (Journal -> Map CommoditySymbol Commodity
jdeclaredcommodities Journal
j)
      where isMethodTag :: (CommoditySymbol, CommoditySymbol) -> Bool
isMethodTag (CommoditySymbol
k, CommoditySymbol
v) = CommoditySymbol -> CommoditySymbol
T.toLower CommoditySymbol
k CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
"lots" Bool -> Bool -> Bool
&& Maybe ReductionMethod -> Bool
forall a. Maybe a -> Bool
isJust (CommoditySymbol -> Maybe ReductionMethod
parseReductionMethod CommoditySymbol
v)

-- | The units and total cost basis of each AVERAGE or AVERAGEALL lot pool,
-- from the journal's lot postings dated before the given date (if any),
-- keyed by base account and commodity. Dividing gives the pool's running
-- average cost: acquisitions carry their acquisition cost and disposals
-- and transfers the then-current average, so the quantity-weighted sum
-- works out to the pool's average. An AVERAGE pool is one account's lots;
-- an AVERAGEALL pool is the lots in all accounts with the same lot
-- direction (long lots in asset accounts, or short lots in liability
-- accounts). Pools with no units, or with cost bases in several
-- commodities, are omitted.
-- The lot subaccount names of AVERAGE lots leave out the cost (it changes
-- as the pool is re-averaged), so this is how reports and generated
-- entries (holdings, close) find it.
journalAveragePoolTotals :: Journal -> Maybe Day -> M.Map (AccountName, CommoditySymbol) (Quantity, Amount)
journalAveragePoolTotals :: Journal
-> Maybe Day
-> Map (CommoditySymbol, CommoditySymbol) (Quantity, Amount)
journalAveragePoolTotals Journal
j Maybe Day
mend = [((CommoditySymbol, CommoditySymbol), (Quantity, Amount))]
-> Map (CommoditySymbol, CommoditySymbol) (Quantity, Amount)
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
  [ ((CommoditySymbol
base, CommoditySymbol
c), (Quantity
units, Amount
ub1{aquantity = sum [aquantity a * aquantity ub | (a, ub) <- entries]}))
  | (CommoditySymbol
base, CommoditySymbol
c) <- Set (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)]
forall a. Set a -> [a]
S.toList (Set (CommoditySymbol, CommoditySymbol)
 -> [(CommoditySymbol, CommoditySymbol)])
-> Set (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)]
forall a b. (a -> b) -> a -> b
$ [(CommoditySymbol, CommoditySymbol)]
-> Set (CommoditySymbol, CommoditySymbol)
forall a. Ord a => [a] -> Set a
S.fromList [ (CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
sub, Amount -> CommoditySymbol
acommodity Amount
a) | (CommoditySymbol
sub, Amount
a) <- [(CommoditySymbol, Amount)]
lotamts ]
  , let method :: ReductionMethod
method = (ReductionMethod, String) -> ReductionMethod
forall a b. (a, b) -> a
fst ((ReductionMethod, String) -> ReductionMethod)
-> (ReductionMethod, String) -> ReductionMethod
forall a b. (a -> b) -> a -> b
$ Journal
-> CommoditySymbol -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodForAccount Journal
j CommoditySymbol
base CommoditySymbol
c
  , ReductionMethod -> Bool
methodIsAverage ReductionMethod
method
  , let inPool :: CommoditySymbol -> Bool
inPool CommoditySymbol
sub
          | ReductionMethod -> Bool
methodIsGlobal ReductionMethod
method = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j (CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
sub) LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j CommoditySymbol
base
          | Bool
otherwise             = CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
sub CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
base
        entries :: [(Amount, Amount)]
entries = [ (Amount
a, Amount
ub) | (CommoditySymbol
sub, Amount
a) <- [(CommoditySymbol, Amount)]
lotamts, Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c, CommoditySymbol -> Bool
inPool CommoditySymbol
sub
                            , Just Amount
ub <- [CostBasis -> Maybe Amount
cbCost (CostBasis -> Maybe Amount) -> Maybe CostBasis -> Maybe Amount
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Amount -> Maybe CostBasis
acostbasis Amount
a] ]
  , (Amount
ub1:[Amount]
_) <- [((Amount, Amount) -> Amount) -> [(Amount, Amount)] -> [Amount]
forall a b. (a -> b) -> [a] -> [b]
map (Amount, Amount) -> Amount
forall a b. (a, b) -> b
snd [(Amount, Amount)]
entries]
  , ((Amount, Amount) -> Bool) -> [(Amount, Amount)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
ub1) (CommoditySymbol -> Bool)
-> ((Amount, Amount) -> CommoditySymbol)
-> (Amount, Amount)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity (Amount -> CommoditySymbol)
-> ((Amount, Amount) -> Amount)
-> (Amount, Amount)
-> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount, Amount) -> Amount
forall a b. (a, b) -> b
snd) [(Amount, Amount)]
entries
  , let units :: Quantity
units = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Amount -> Quantity
aquantity Amount
a | (Amount
a, Amount
_) <- [(Amount, Amount)]
entries]
  , Quantity
units Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0
  ]
  where
    -- the amounts posted to lot subaccounts before the end date
    lotamts :: [(CommoditySymbol, Amount)]
lotamts = [ (Posting -> CommoditySymbol
paccount Posting
p, Amount
a)
              | Posting
p <- Journal -> [Posting]
journalPostings Journal
j
              , Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CommoditySymbol -> Bool) -> Maybe CommoditySymbol -> Bool
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> Maybe CommoditySymbol
lotSubaccountName (CommoditySymbol -> Maybe CommoditySymbol)
-> CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> CommoditySymbol
paccount Posting
p
              , Bool -> (Day -> Bool) -> Maybe Day -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Posting -> Day
postingDate Posting
p Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
<) Maybe Day
mend
              , Amount
a <- MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p ]

-- | The average cost of each AVERAGE or AVERAGEALL lot pool, as of (just
-- before) the given date, keyed by base account and commodity. Exact,
-- displayed with at most 8 decimal places. See 'journalAveragePoolTotals'.
journalAveragePoolCosts :: Journal -> Maybe Day -> M.Map (AccountName, CommoditySymbol) Amount
journalAveragePoolCosts :: Journal
-> Maybe Day -> Map (CommoditySymbol, CommoditySymbol) Amount
journalAveragePoolCosts Journal
j Maybe Day
mend =
  ((Quantity, Amount) -> Amount)
-> Map (CommoditySymbol, CommoditySymbol) (Quantity, Amount)
-> Map (CommoditySymbol, CommoditySymbol) Amount
forall a b k. (a -> b) -> Map k a -> Map k b
M.map (\(Quantity
units, Amount
cost) -> Quantity -> Amount -> Amount
divideAmountAndUpdatePrecision Quantity
units Amount
cost) (Journal
-> Maybe Day
-> Map (CommoditySymbol, CommoditySymbol) (Quantity, Amount)
journalAveragePoolTotals Journal
j Maybe Day
mend)

-- | If the account name's final colon-separated component is enclosed in @{@
-- and @}@, treat it as a lot subaccount and return @Just (base, "{...}")@.
-- Otherwise return @Nothing@.
-- Full validation of the lot name (parts, dates, costs) is left to 'parseLotName';
-- this function only identifies candidates so they can be validated uniformly.
splitLotSubaccount :: AccountName -> Maybe (AccountName, Text)
splitLotSubaccount :: CommoditySymbol -> Maybe (CommoditySymbol, CommoditySymbol)
splitLotSubaccount CommoditySymbol
a = do
  -- check this first: it's cheap, and rules out almost all account names. (breakOnEnd reverses the text.)
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
"}" CommoditySymbol -> CommoditySymbol -> Bool
`T.isSuffixOf` CommoditySymbol
a
  let (CommoditySymbol
prefix, CommoditySymbol
leaf) = HasCallStack =>
CommoditySymbol
-> CommoditySymbol -> (CommoditySymbol, CommoditySymbol)
CommoditySymbol
-> CommoditySymbol -> (CommoditySymbol, CommoditySymbol)
T.breakOnEnd CommoditySymbol
":" CommoditySymbol
a
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (CommoditySymbol -> Bool
T.null CommoditySymbol
prefix)
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
"{" CommoditySymbol -> CommoditySymbol -> Bool
`T.isPrefixOf` CommoditySymbol
leaf
  (CommoditySymbol, CommoditySymbol)
-> Maybe (CommoditySymbol, CommoditySymbol)
forall a. a -> Maybe a
Just (Int -> CommoditySymbol -> CommoditySymbol
T.dropEnd Int
1 CommoditySymbol
prefix, CommoditySymbol
leaf)

-- | Strip any trailing lot subaccount (a final @:{...}@ component) from an
-- account name. E.g., @\"assets:broker:{2026-01-15, $50}\"@ becomes
-- @\"assets:broker\"@.
lotBaseAccount :: AccountName -> AccountName
lotBaseAccount :: CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
a = CommoditySymbol
-> ((CommoditySymbol, CommoditySymbol) -> CommoditySymbol)
-> Maybe (CommoditySymbol, CommoditySymbol)
-> CommoditySymbol
forall b a. b -> (a -> b) -> Maybe a -> b
maybe CommoditySymbol
a (CommoditySymbol, CommoditySymbol) -> CommoditySymbol
forall a b. (a, b) -> a
fst (CommoditySymbol -> Maybe (CommoditySymbol, CommoditySymbol)
splitLotSubaccount CommoditySymbol
a)

-- | The lot direction of an account (or of a lot subaccount's base account):
-- Long for asset accounts, Short for liability accounts (which hold short
-- positions), none for other account types. See 'LotDirection'.
lotDirectionOf :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe LotDirection
lotDirectionOf :: (CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
acct =
  CommoditySymbol -> Maybe AccountType
lookupAccountType (CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
acct) Maybe AccountType
-> (AccountType -> Maybe LotDirection) -> Maybe LotDirection
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= AccountType -> Maybe LotDirection
accountTypeLotDirection

-- | The lot direction of an account in this journal. See 'lotDirectionOf'.
journalLotDirection :: Journal -> AccountName -> Maybe LotDirection
journalLotDirection :: Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j = (CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf (Journal -> CommoditySymbol -> Maybe AccountType
journalAccountType Journal
j)

-- | The lot direction of an account in this journal, treating accounts
-- of other types (which can hold lots only when written with explicit
-- cost basis annotations, eg equity:opening) as Long.
journalLotDirectionOrLong :: Journal -> AccountName -> LotDirection
journalLotDirectionOrLong :: Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j = LotDirection -> Maybe LotDirection -> LotDirection
forall a. a -> Maybe a -> a
fromMaybe LotDirection
Long (Maybe LotDirection -> LotDirection)
-> (CommoditySymbol -> Maybe LotDirection)
-> CommoditySymbol
-> LotDirection
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j

-- | Does this amount open or receive a lot (an inflow) in an account with
-- this direction ? Positive in a Long account, negative in a Short one.
isLotInflow :: LotDirection -> Amount -> Bool
isLotInflow :: LotDirection -> Amount -> Bool
isLotInflow LotDirection
dir Amount
a = Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* LotDirection -> Quantity
lotDirectionSign LotDirection
dir Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0

-- | Does this amount close or send a lot (an outflow) in an account with
-- this direction ? Negative in a Long account, positive in a Short one.
isLotOutflow :: LotDirection -> Amount -> Bool
isLotOutflow :: LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
a = Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* LotDirection -> Quantity
lotDirectionSign LotDirection
dir Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0

-- | Render a lot name in the consolidated hledger format for use as a subaccount name.
-- Format: @{YYYY-MM-DD, COST}@ or @{YYYY-MM-DD, \"LABEL\", COST}@.
-- The cost amount is rendered using its own intrinsic style. Callers that want
-- the journal's canonical commodity styles applied (eg when building a lot
-- subaccount name) should pre-style the 'CostBasis' with 'styleLotCbCost'.
showLotName :: CostBasis -> T.Text
showLotName :: CostBasis -> CommoditySymbol
showLotName CostBasis{Maybe Day
cbDate :: Maybe Day
cbDate :: CostBasis -> Maybe Day
cbDate, Maybe CommoditySymbol
cbLabel :: Maybe CommoditySymbol
cbLabel :: CostBasis -> Maybe CommoditySymbol
cbLabel, Maybe Amount
cbCost :: CostBasis -> Maybe Amount
cbCost :: Maybe Amount
cbCost} =
  CommoditySymbol
"{" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol -> [CommoditySymbol] -> CommoditySymbol
T.intercalate CommoditySymbol
", " [CommoditySymbol]
parts CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"}"
  where
    parts :: [CommoditySymbol]
parts = [Maybe CommoditySymbol] -> [CommoditySymbol]
forall a. [Maybe a] -> [a]
catMaybes
      [ (Day -> CommoditySymbol) -> Maybe Day -> Maybe CommoditySymbol
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> (Day -> String) -> Day -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> String
forall a. Show a => a -> String
show) Maybe Day
cbDate
      , (CommoditySymbol -> CommoditySymbol)
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\CommoditySymbol
l -> CommoditySymbol
"\"" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
l CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"\"") Maybe CommoditySymbol
cbLabel
      -- Show a zero cost with its commodity symbol (eg $0), not as a bare 0:
      -- the name is the lot's basis of record, and must round-trip faithfully.
      , (Amount -> CommoditySymbol)
-> Maybe Amount -> Maybe CommoditySymbol
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> (Amount -> String) -> Amount -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat -> Amount -> String
showAmountWith AmountFormat
noCostFmt{displayZeroCommodity=True}) Maybe Amount
cbCost
      ]

-- | Apply the journal's canonical commodity styles to a 'CostBasis's cost
-- amount, for consistent rendering of the amount inside a lot subaccount name.
-- Styles should have been computed with 'NoRounding' (preserving the original
-- decimal digits); all other style fields — decimal mark, digit group separators,
-- commodity position and spacing — come from the canonical style.
styleLotCbCost :: M.Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost :: Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
cb = CostBasis
cb{cbCost = styleAmounts styles <$> cbCost cb}

-- | Widen a 'CostBasis's cost amount's display precision to at least the
-- commodity style's declared precision (if any), so eg with @commodity €1.00@
-- an inferred per-unit cost of 2.5 renders as @2.50@. For user-written
-- explicit costs, prefer 'styleLotCbCost' alone (no widening).
widenLotCbCost :: M.Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
widenLotCbCost :: Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
widenLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
cb = CostBasis
cb{cbCost = widen <$> cbCost cb}
  where
    widen :: Amount -> Amount
widen Amount
a = case 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
      Just AmountStyle{asprecision :: AmountStyle -> AmountPrecision
asprecision = Precision Word8
p} -> Word8 -> Amount -> Amount
amountSetPrecisionMin Word8
p Amount
a
      Maybe AmountStyle
_                                           -> Amount
a

-- | Render a lot subaccount name, dropping the cost component under AVERAGE/AVERAGEALL.
-- AVERAGE pools share a single running per-unit cost that changes on every
-- acquisition; embedding it in the subaccount name would make the subaccount
-- unstable across acquisitions. The running cost remains on each lot's
-- @acostbasis@ for use by reports and @print --lots@.
showLotNameForMethod :: ReductionMethod -> CostBasis -> T.Text
showLotNameForMethod :: ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
method CostBasis
cb
  | ReductionMethod -> Bool
methodIsAverage ReductionMethod
method = CostBasis -> CommoditySymbol
showLotName CostBasis
cb{cbCost = Nothing}
  | Bool
otherwise              = CostBasis -> CommoditySymbol
showLotName CostBasis
cb

-- | Like 'mergeCostBasis', but under AVERAGE/AVERAGEALL the cost field is
-- ignored: the pool's running cost legitimately differs from what the user
-- wrote on any specific acquire posting.
mergeCostBasisForMethod :: ReductionMethod -> CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasisForMethod :: ReductionMethod
-> CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasisForMethod ReductionMethod
method CostBasis
a CostBasis
b
  | ReductionMethod -> Bool
methodIsAverage ReductionMethod
method = CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasis CostBasis
a{cbCost = Nothing} CostBasis
b{cbCost = Nothing}
  | Bool
otherwise              = CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasis CostBasis
a CostBasis
b

-- | Extract the lot subaccount name (the @{...}@ component) from an account name,
-- or @Nothing@ if there is none.
-- E.g., @\"assets:broker:{2026-01-15, $50}\"@ returns @Just \"{2026-01-15, $50}\"@.
lotSubaccountName :: AccountName -> Maybe Text
lotSubaccountName :: CommoditySymbol -> Maybe CommoditySymbol
lotSubaccountName = ((CommoditySymbol, CommoditySymbol) -> CommoditySymbol)
-> Maybe (CommoditySymbol, CommoditySymbol)
-> Maybe CommoditySymbol
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (CommoditySymbol, CommoditySymbol) -> CommoditySymbol
forall a b. (a, b) -> b
snd (Maybe (CommoditySymbol, CommoditySymbol) -> Maybe CommoditySymbol)
-> (CommoditySymbol -> Maybe (CommoditySymbol, CommoditySymbol))
-> CommoditySymbol
-> Maybe CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> Maybe (CommoditySymbol, CommoditySymbol)
splitLotSubaccount

-- | Parse a lot name (as produced by 'showLotName') back into a 'CostBasis'.
-- The input should be the full @{...}@ string including braces.
-- Parts are comma-separated and all optional: date (@YYYY-MM-DD@),
-- label (@\"LABEL\"@), and cost (parsed by the supplied callback).
-- The callback avoids an import cycle (Lots.hs cannot import Read-layer parsers).
parseLotName :: (String -> Maybe Amount) -> Text -> Either String CostBasis
parseLotName :: (String -> Maybe Amount)
-> CommoditySymbol -> Either String CostBasis
parseLotName String -> Maybe Amount
parseAmt CommoditySymbol
t = do
  inner <- case CommoditySymbol -> CommoditySymbol -> Maybe CommoditySymbol
T.stripPrefix CommoditySymbol
"{" CommoditySymbol
t Maybe CommoditySymbol
-> (CommoditySymbol -> Maybe CommoditySymbol)
-> Maybe CommoditySymbol
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CommoditySymbol -> CommoditySymbol -> Maybe CommoditySymbol
T.stripSuffix CommoditySymbol
"}" of
    Just CommoditySymbol
s  -> CommoditySymbol -> Either String CommoditySymbol
forall a b. b -> Either a b
Right (CommoditySymbol -> CommoditySymbol
T.strip CommoditySymbol
s)
    Maybe CommoditySymbol
Nothing -> String -> Either String CommoditySymbol
forall a b. a -> Either a b
Left (String -> Either String CommoditySymbol)
-> String -> Either String CommoditySymbol
forall a b. (a -> b) -> a -> b
$ String
"lot name must be enclosed in braces: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
t
  if T.null inner
    then Right $ CostBasis Nothing Nothing Nothing
    else do
      let parts = (CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> CommoditySymbol
T.strip ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> [CommoditySymbol]
splitParts CommoditySymbol
inner
      parseParts parts
  where
    parseParts :: [CommoditySymbol] -> Either String CostBasis
parseParts [CommoditySymbol]
parts = [CommoditySymbol]
-> Maybe Day
-> Maybe CommoditySymbol
-> Maybe Amount
-> Either String CostBasis
go [CommoditySymbol]
parts Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing Maybe Amount
forall a. Maybe a
Nothing
      where
        go :: [CommoditySymbol]
-> Maybe Day
-> Maybe CommoditySymbol
-> Maybe Amount
-> Either String CostBasis
go [] Maybe Day
d Maybe CommoditySymbol
l Maybe Amount
c = CostBasis -> Either String CostBasis
forall a b. b -> Either a b
Right (CostBasis -> Either String CostBasis)
-> CostBasis -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
d Maybe CommoditySymbol
l Maybe Amount
c
        go (CommoditySymbol
p:[CommoditySymbol]
ps) Maybe Day
d Maybe CommoditySymbol
l Maybe Amount
c
          | CommoditySymbol -> Bool
isDatePart CommoditySymbol
p = case CommoditySymbol -> Maybe Day
parseDate CommoditySymbol
p of
              Just Day
day -> [CommoditySymbol]
-> Maybe Day
-> Maybe CommoditySymbol
-> Maybe Amount
-> Either String CostBasis
go [CommoditySymbol]
ps (Day -> Maybe Day
forall a. a -> Maybe a
Just Day
day) Maybe CommoditySymbol
l Maybe Amount
c
              Maybe Day
Nothing  -> String -> Either String CostBasis
forall a b. a -> Either a b
Left (String -> Either String CostBasis)
-> String -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ String
"invalid date in lot name: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
p
          | CommoditySymbol -> Bool
isLabelPart CommoditySymbol
p = [CommoditySymbol]
-> Maybe Day
-> Maybe CommoditySymbol
-> Maybe Amount
-> Either String CostBasis
go [CommoditySymbol]
ps Maybe Day
d (CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just (Int -> CommoditySymbol -> CommoditySymbol
T.drop Int
1 (Int -> CommoditySymbol -> CommoditySymbol
T.dropEnd Int
1 CommoditySymbol
p))) Maybe Amount
c
          | Bool
otherwise = case String -> Maybe Amount
parseAmt (CommoditySymbol -> String
T.unpack CommoditySymbol
p) of
              Just Amount
amt -> [CommoditySymbol]
-> Maybe Day
-> Maybe CommoditySymbol
-> Maybe Amount
-> Either String CostBasis
go [CommoditySymbol]
ps Maybe Day
d Maybe CommoditySymbol
l (Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
amt)
              Maybe Amount
Nothing  -> String -> Either String CostBasis
forall a b. a -> Either a b
Left (String -> Either String CostBasis)
-> String -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe (String
"invalid lot name: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
p)
                                           (CommoditySymbol -> Maybe String
missingDateCommaHint CommoditySymbol
p 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
<|> CommoditySymbol -> Maybe String
wrongOrderHint CommoditySymbol
p)

        -- If the cost part starts with a date, or is followed by a comma and
        -- something date- or label-like, the parts are out of order
        -- (eg @{$10, "note"}@ or @{"note", 2026-01-15, $10}@).
        wrongOrderHint :: Text -> Maybe String
        wrongOrderHint :: CommoditySymbol -> Maybe String
wrongOrderHint CommoditySymbol
p
          | CommoditySymbol -> Bool
isDatePart (Int -> CommoditySymbol -> CommoditySymbol
T.take Int
10 CommoditySymbol
p)
            Bool -> Bool -> Bool
|| (CommoditySymbol -> Bool) -> [CommoditySymbol] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any CommoditySymbol -> Bool
startsAnotherPart ((CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (CommoditySymbol -> CommoditySymbol
T.stripStart (CommoditySymbol -> CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> CommoditySymbol
-> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> CommoditySymbol -> CommoditySymbol
T.drop Int
1) ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol -> Bool) -> [CommoditySymbol] -> [CommoditySymbol]
forall a. (a -> Bool) -> [a] -> [a]
filter (CommoditySymbol
"," CommoditySymbol -> CommoditySymbol -> Bool
`T.isPrefixOf`) ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> [CommoditySymbol]
T.tails CommoditySymbol
p)
          = String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"lot name parts must be in this order (if present): {DATE, \"LABEL\", COST}: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
t
          | Bool
otherwise = Maybe String
forall a. Maybe a
Nothing
          where startsAnotherPart :: CommoditySymbol -> Bool
startsAnotherPart CommoditySymbol
s = CommoditySymbol
"\"" CommoditySymbol -> CommoditySymbol -> Bool
`T.isPrefixOf` CommoditySymbol
s Bool -> Bool -> Bool
|| CommoditySymbol -> Bool
isDatePart (Int -> CommoditySymbol -> CommoditySymbol
T.take Int
10 CommoditySymbol
s)

        -- If a part starts with what looks like a date but no comma followed,
        -- the user probably forgot the comma (eg @{2026-01-15 $10}@). Show a
        -- corrected form to make the fix obvious.
        missingDateCommaHint :: Text -> Maybe String
        missingDateCommaHint :: CommoditySymbol -> Maybe String
missingDateCommaHint CommoditySymbol
p
          | CommoditySymbol -> Int
T.length CommoditySymbol
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
10
          , let (CommoditySymbol
candidate, CommoditySymbol
rest) = Int -> CommoditySymbol -> (CommoditySymbol, CommoditySymbol)
T.splitAt Int
10 CommoditySymbol
p
          , CommoditySymbol -> Bool
isDatePart CommoditySymbol
candidate
          , let rest' :: CommoditySymbol
rest' = CommoditySymbol -> CommoditySymbol
T.stripStart CommoditySymbol
rest
          , Bool -> Bool
not (CommoditySymbol -> Bool
T.null CommoditySymbol
rest')
          , HasCallStack => CommoditySymbol -> Char
CommoditySymbol -> Char
T.head CommoditySymbol
rest' Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
','
          = String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"Missing comma in lot name: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
p
                String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nDid you mean:              " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
candidate String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
", " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
rest' String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" ?"
          | Bool
otherwise = Maybe String
forall a. Maybe a
Nothing

    isDatePart :: CommoditySymbol -> Bool
isDatePart CommoditySymbol
p = CommoditySymbol -> Int
T.length CommoditySymbol
p Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
10 Bool -> Bool -> Bool
&& (Char -> Bool) -> CommoditySymbol -> Bool
T.all (\Char
c -> Char -> Bool
isDigit Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-') CommoditySymbol
p
    isLabelPart :: CommoditySymbol -> Bool
isLabelPart CommoditySymbol
p = CommoditySymbol
"\"" CommoditySymbol -> CommoditySymbol -> Bool
`T.isPrefixOf` CommoditySymbol
p Bool -> Bool -> Bool
&& CommoditySymbol
"\"" CommoditySymbol -> CommoditySymbol -> Bool
`T.isSuffixOf` CommoditySymbol
p Bool -> Bool -> Bool
&& CommoditySymbol -> Int
T.length CommoditySymbol
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
2

    parseDate :: CommoditySymbol -> Maybe Day
parseDate CommoditySymbol
p = do
      let s :: String
s = CommoditySymbol -> String
T.unpack CommoditySymbol
p
      case String
s of
        [Char
y1,Char
y2,Char
y3,Char
y4,Char
'-',Char
m1,Char
m2,Char
'-',Char
d1,Char
d2] ->
          Integer -> Int -> Int -> Maybe Day
fromGregorianValid
            (String -> Integer
forall a. Read a => String -> a
read [Char
y1,Char
y2,Char
y3,Char
y4])
            (String -> Int
forall a. Read a => String -> a
read [Char
m1,Char
m2])
            (String -> Int
forall a. Read a => String -> a
read [Char
d1,Char
d2])
        String
_ -> Maybe Day
forall a. Maybe a
Nothing

    -- Split the inner text of a lot name into up to 3 parts (date, label, cost)
    -- by peeling known-format prefixes in DLC order, exploiting the fact that
    -- dates and labels have unambiguous syntax.  This avoids splitting on commas,
    -- which would break when the cost amount contains a decimal comma (e.g. @1,5@)
    -- or when the commodity symbol contains commas (e.g. @"an, odd, commodity"@).
    -- After each part, @,@ followed by optional whitespace is consumed.
    --
    -- Examples:
    -- @"2026-01-15, \"my, label\", €1,50"@               -> @["2026-01-15", "\"my, label\"", "€1,50"]@
    -- @"2026-01-15, \"an, odd, commodity\" 1,5"@          -> @["2026-01-15", "\"an, odd, commodity\" 1,5"]@
    -- @"2026-01-15, \"a, b\", \"an, odd, commodity\" 1,5" -> @["2026-01-15", "\"a, b\"", "\"an, odd, commodity\" 1,5"]@
    -- @"$100"@                                            -> @["$100"]@
    splitParts :: Text -> [Text]
    splitParts :: CommoditySymbol -> [CommoditySymbol]
splitParts CommoditySymbol
s =
      let (Maybe CommoditySymbol
mdate, CommoditySymbol
s1) = CommoditySymbol -> (Maybe CommoditySymbol, CommoditySymbol)
peelDate CommoditySymbol
s
          (Maybe CommoditySymbol
mlabel, CommoditySymbol
s2) = CommoditySymbol -> (Maybe CommoditySymbol, CommoditySymbol)
peelLabel CommoditySymbol
s1
          mcost :: Maybe CommoditySymbol
mcost = let c :: CommoditySymbol
c = CommoditySymbol -> CommoditySymbol
T.strip CommoditySymbol
s2 in if CommoditySymbol -> Bool
T.null CommoditySymbol
c then Maybe CommoditySymbol
forall a. Maybe a
Nothing else CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
c
      in [Maybe CommoditySymbol] -> [CommoditySymbol]
forall a. [Maybe a] -> [a]
catMaybes [Maybe CommoditySymbol
mdate, Maybe CommoditySymbol
mlabel, Maybe CommoditySymbol
mcost]

    -- Try to peel a date (YYYY-MM-DD) from the front. Returns the date text
    -- and the remainder after stripping a comma separator, or Nothing and the
    -- unchanged input. Requires that the date candidate is followed by end of
    -- string or a comma with optional surrounding whitespace (to keep the 
    -- syntax regular; gives a helpful error if the comma is missing).
    peelDate :: Text -> (Maybe Text, Text)
    peelDate :: CommoditySymbol -> (Maybe CommoditySymbol, CommoditySymbol)
peelDate CommoditySymbol
s
      | CommoditySymbol -> Int
T.length CommoditySymbol
s Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
10
      , let (CommoditySymbol
candidate, CommoditySymbol
rest) = Int -> CommoditySymbol -> (CommoditySymbol, CommoditySymbol)
T.splitAt Int
10 CommoditySymbol
s
      , CommoditySymbol -> Bool
isDatePart CommoditySymbol
candidate
      , CommoditySymbol -> Bool
properBoundary CommoditySymbol
rest
      = (CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
candidate, CommoditySymbol -> CommoditySymbol
stripSep CommoditySymbol
rest)
      | Bool
otherwise = (Maybe CommoditySymbol
forall a. Maybe a
Nothing, CommoditySymbol
s)
      where
        properBoundary :: CommoditySymbol -> Bool
properBoundary CommoditySymbol
txt = case CommoditySymbol -> Maybe (Char, CommoditySymbol)
T.uncons (CommoditySymbol -> CommoditySymbol
T.stripStart CommoditySymbol
txt) of
          Maybe (Char, CommoditySymbol)
Nothing       -> Bool
True
          Just (Char
',', CommoditySymbol
_) -> Bool
True
          Maybe (Char, CommoditySymbol)
_             -> Bool
False

    -- Try to peel a double-quoted label from the front. Scans from the opening
    -- quote to the next closing quote. A quoted string is only treated as a
    -- label if it is followed by a comma separator or end of input. If it is
    -- followed by digits or other amount-starting characters (after optional
    -- whitespace), it is a quoted commodity symbol that belongs to the cost
    -- amount, so we leave it alone.
    peelLabel :: Text -> (Maybe Text, Text)
    peelLabel :: CommoditySymbol -> (Maybe CommoditySymbol, CommoditySymbol)
peelLabel CommoditySymbol
s
      | Just CommoditySymbol
s' <- CommoditySymbol -> CommoditySymbol -> Maybe CommoditySymbol
T.stripPrefix CommoditySymbol
"\"" CommoditySymbol
s
      = let (CommoditySymbol
inner, CommoditySymbol
rest) = (Char -> Bool)
-> CommoditySymbol -> (CommoditySymbol, CommoditySymbol)
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"') CommoditySymbol
s'
        in case CommoditySymbol -> Maybe (Char, CommoditySymbol)
T.uncons CommoditySymbol
rest of
             Just (Char
'"', CommoditySymbol
rest')
               | CommoditySymbol -> Bool
looksLikeCostRemainder CommoditySymbol
rest' -> (Maybe CommoditySymbol
forall a. Maybe a
Nothing, CommoditySymbol
s)  -- quoted commodity symbol, not a label
               | Bool
otherwise -> (CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just (CommoditySymbol
"\"" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
inner CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
"\""), CommoditySymbol -> CommoditySymbol
stripSep CommoditySymbol
rest')
             Maybe (Char, CommoditySymbol)
_ -> (Maybe CommoditySymbol
forall a. Maybe a
Nothing, CommoditySymbol
s)  -- malformed, leave for parseAmt
      | Bool
otherwise = (Maybe CommoditySymbol
forall a. Maybe a
Nothing, CommoditySymbol
s)

    -- After a closing quote, does the remainder look like it continues as a
    -- cost amount (i.e. the quoted string was a commodity symbol, not a label)?
    -- True when the next non-space character is a digit, sign, or decimal mark.
    looksLikeCostRemainder :: Text -> Bool
    looksLikeCostRemainder :: CommoditySymbol -> Bool
looksLikeCostRemainder CommoditySymbol
t' =
      case CommoditySymbol -> Maybe (Char, CommoditySymbol)
T.uncons (CommoditySymbol -> CommoditySymbol
T.stripStart CommoditySymbol
t') of
        Just (Char
c, CommoditySymbol
_) -> Char -> Bool
isDigit Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'+' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.'
        Maybe (Char, CommoditySymbol)
Nothing     -> Bool
False

    -- Strip an optional comma and any surrounding whitespace.
    stripSep :: Text -> Text
    stripSep :: CommoditySymbol -> CommoditySymbol
stripSep CommoditySymbol
s0 =
      let s1 :: CommoditySymbol
s1 = CommoditySymbol -> CommoditySymbol
T.stripStart CommoditySymbol
s0
      in case CommoditySymbol -> Maybe (Char, CommoditySymbol)
T.uncons CommoditySymbol
s1 of
           Just (Char
',', CommoditySymbol
s2) -> CommoditySymbol -> CommoditySymbol
T.stripStart CommoditySymbol
s2
           Maybe (Char, CommoditySymbol)
_              -> CommoditySymbol
s1

-- | Do two lot cost amounts refer to the same cost, for lot identification ?
-- True if their commodities match and their quantities are equal exactly,
-- or one equals the other's display-rounded value, or one equals the other
-- rounded to its own number of decimal places. The latter two let a
-- displayed lot name (eg an inferred $10/3 cost rendered as $3.33333333),
-- or a coarser written cost (eg $3.33), be written back in a journal and
-- still identify the lot, while stored lot costs keep full precision for
-- exact gain arithmetic (#2689). This is the same agreement rule as
-- 'journalCheckAcquireBasis' applies between a written basis and the
-- transacted cost.
lotCostsMatch :: Amount -> Amount -> Bool
lotCostsMatch :: Amount -> Amount -> Bool
lotCostsMatch Amount
x Amount
y =
  Amount -> CommoditySymbol
acommodity Amount
x CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
y Bool -> Bool -> Bool
&&
  (Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
y
   Bool -> Bool -> Bool
|| Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
amountRoundedQuantity Amount
y
   Bool -> Bool -> Bool
|| Amount -> Quantity
amountRoundedQuantity Amount
x Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
y
   Bool -> Bool -> Bool
|| Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo (Amount -> Word8
places Amount
x) (Amount -> Quantity
aquantity Amount
y)
   Bool -> Bool -> Bool
|| Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo (Amount -> Word8
places Amount
y) (Amount -> Quantity
aquantity Amount
x) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
y)
  where places :: Amount -> Word8
places = Quantity -> Word8
forall i. DecimalRaw i -> Word8
decimalPlaces (Quantity -> Word8) -> (Amount -> Quantity) -> Amount -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity  -- as written, trailing zeros included

-- | Merge two 'CostBasis' values. For each field, if both are @Just@, they
-- must agree (returns error if not); otherwise takes whichever is @Just@.
-- The first argument is typically the account-name basis (more complete),
-- the second is the amount's existing basis.
mergeCostBasis :: CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasis :: CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasis CostBasis
a CostBasis
b = do
  d <- String
-> (Day -> String)
-> Maybe Day
-> Maybe Day
-> Either String (Maybe Day)
forall a.
Eq a =>
String
-> (a -> String) -> Maybe a -> Maybe a -> Either String (Maybe a)
mergeField String
"date"  Day -> String
forall a. Show a => a -> String
show     (CostBasis -> Maybe Day
cbDate CostBasis
a) (CostBasis -> Maybe Day
cbDate CostBasis
b)
  l <- mergeField "label" T.unpack (cbLabel a) (cbLabel b)
  c <- mergeCostField (cbCost a) (cbCost b)
  Right $ CostBasis d l c
  where
    mergeField :: Eq a => String -> (a -> String) -> Maybe a -> Maybe a -> Either String (Maybe a)
    mergeField :: forall a.
Eq a =>
String
-> (a -> String) -> Maybe a -> Maybe a -> Either String (Maybe a)
mergeField String
_ a -> String
_ Maybe a
Nothing  Maybe a
y       = Maybe a -> Either String (Maybe a)
forall a b. b -> Either a b
Right Maybe a
y
    mergeField String
_ a -> String
_ Maybe a
x       Maybe a
Nothing  = Maybe a -> Either String (Maybe a)
forall a b. b -> Either a b
Right Maybe a
x
    mergeField String
name a -> String
showVal (Just a
x) (Just a
y)
      | a
x a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
y    = Maybe a -> Either String (Maybe a)
forall a b. b -> Either a b
Right (a -> Maybe a
forall a. a -> Maybe a
Just a
x)
      | Bool
otherwise = String -> Either String (Maybe a)
forall a b. a -> Either a b
Left (String -> Either String (Maybe a))
-> String -> Either String (Maybe a)
forall a b. (a -> b) -> a -> b
$ String
"conflicting cost basis " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": account name has " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
showVal a
x
                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" but amount has " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
showVal a
y

    mergeCostField :: Maybe Amount -> Maybe Amount -> Either String (Maybe Amount)
    mergeCostField :: Maybe Amount -> Maybe Amount -> Either String (Maybe Amount)
mergeCostField Maybe Amount
Nothing  Maybe Amount
y       = Maybe Amount -> Either String (Maybe Amount)
forall a b. b -> Either a b
Right Maybe Amount
y
    mergeCostField Maybe Amount
x       Maybe Amount
Nothing  = Maybe Amount -> Either String (Maybe Amount)
forall a b. b -> Either a b
Right Maybe Amount
x
    mergeCostField (Just Amount
x) (Just Amount
y)
      | Amount -> Amount -> Bool
lotCostsMatch Amount
x Amount
y = Maybe Amount -> Either String (Maybe Amount)
forall a b. b -> Either a b
Right (Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
x)
      | Bool
otherwise = String -> Either String (Maybe Amount)
forall a b. a -> Either a b
Left (String -> Either String (Maybe Amount))
-> String -> Either String (Maybe Amount)
forall a b. (a -> b) -> a -> b
$ String
"conflicting cost basis cost"
                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": account name has " String -> String -> String
forall a. [a] -> [a] -> [a]
++ AmountFormat -> Amount -> String
showAmountWith AmountFormat
noCostFmt Amount
x
                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" but amount has " String -> String -> String
forall a. [a] -> [a] -> [a]
++ AmountFormat -> Amount -> String
showAmountWith AmountFormat
noCostFmt Amount
y

-- | Does this journal use lots at all ? True if any commodity is declared
-- lotful, any account declaration has a lots: tag, or any posting (in
-- transactions, periodic transaction rules or auto posting rules) has a cost
-- basis annotation or a lot subaccount name. When false, the lot-related
-- finalisation stages would all be no-ops, so journalFinalise skips them.
journalHasLotFeatures :: Journal -> Bool
journalHasLotFeatures :: Journal -> Bool
journalHasLotFeatures Journal
j =
     Bool -> Bool
not (Set CommoditySymbol -> Bool
forall a. Set a -> Bool
S.null (Set CommoditySymbol -> Bool) -> Set CommoditySymbol -> Bool
forall a b. (a -> b) -> a -> b
$ Journal -> Set CommoditySymbol
journalLotfulCommodities Journal
j)
  Bool -> Bool -> Bool
|| Bool -> Bool
not (Map CommoditySymbol CommoditySymbol -> Bool
forall k a. Map k a -> Bool
M.null (Map CommoditySymbol CommoditySymbol -> Bool)
-> Map CommoditySymbol CommoditySymbol -> Bool
forall a b. (a -> b) -> a -> b
$ Journal -> Map CommoditySymbol CommoditySymbol
journalAccountLotsTags Journal
j)
  Bool -> Bool -> Bool
|| (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
postingHasLotFeature [Posting]
allpostings
  where
    allpostings :: [Posting]
allpostings =
         Journal -> [Posting]
journalPostings Journal
j
      [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ (PeriodicTransaction -> [Posting])
-> [PeriodicTransaction] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap PeriodicTransaction -> [Posting]
ptpostings (Journal -> [PeriodicTransaction]
jperiodictxns Journal
j)
      [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ [TMPostingRule -> Posting
tmprPosting TMPostingRule
r | TransactionModifier
tm <- Journal -> [TransactionModifier]
jtxnmodifiers Journal
j, TMPostingRule
r <- TransactionModifier -> [TMPostingRule]
tmpostingrules TransactionModifier
tm]
    postingHasLotFeature :: Posting -> Bool
postingHasLotFeature Posting
p =
         (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) (MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p)
      Bool -> Bool -> Bool
|| Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isJust (CommoditySymbol -> Maybe CommoditySymbol
lotSubaccountName (CommoditySymbol -> Maybe CommoditySymbol)
-> CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> CommoditySymbol
paccount Posting
p)

-- Classification (pipeline stage 1)

-- | Classify lot-related postings by adding ptype tags.
-- Must be called after journalAddAccountTypes so account types are available,
-- and after transaction balancing, so that all posting amounts (including
-- ones inferred from elided amounts or balance assignments) are known:
-- classification then gives the same result for every entry shape as if all
-- amounts had been written explicitly (#2686, #2690, #2692).
-- The verbosetags parameter controls whether the ptype tags will be made visible in comments.
-- Before classification, try to auto-split lot transfers with fees
-- into a transfer portion and a dispose portion, so both get classified correctly.
journalClassifyLotPostings :: Bool -> Journal -> Journal
journalClassifyLotPostings :: Bool -> Journal -> Journal
journalClassifyLotPostings Bool
verbosetags Journal
j = (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
classify Journal
j
  where
    classify :: Transaction -> Transaction
classify Transaction
t
      | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts Set CommoditySymbol
lotfulcomms Transaction
t = Transaction
t  -- nothing lot-related here: leave it, and its knot, alone
      | Bool
otherwise =
          Transaction -> Transaction
txnTieKnot  -- retie the postings' transaction pointers (nothing else does after this)
        (Transaction -> Transaction)
-> (Transaction -> Transaction) -> Transaction -> Transaction
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionClassifyLotPostings Bool
verbosetags CommoditySymbol -> Maybe AccountType
lookupType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots
        (Transaction -> Transaction)
-> (Transaction -> Transaction) -> Transaction -> Transaction
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionAutoSplitFeeOutflows Bool
verbosetags CommoditySymbol -> Maybe AccountType
lookupType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots
        (Transaction -> Transaction) -> Transaction -> Transaction
forall a b. (a -> b) -> a -> b
$ Transaction
t
    lookupType :: CommoditySymbol -> Maybe AccountType
lookupType = Journal -> CommoditySymbol -> Maybe AccountType
journalAccountType Journal
j
    lotfulcomms :: Set CommoditySymbol
lotfulcomms = Journal -> Set CommoditySymbol
journalLotfulCommodities Journal
j
    commodityIsLotful :: CommoditySymbol -> Bool
commodityIsLotful = (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms)
    accountUsesNoLots :: CommoditySymbol -> Bool
accountUsesNoLots = Journal -> CommoditySymbol -> Bool
journalAccountUsesNoLots Journal
j

-- | Could this transaction involve lots ? True if any of its amounts has a
-- cost basis annotation or is in one of the given lotful commodities.
-- A cheap test, broader than any of the lot stages' own triggers, so they
-- can skip the (usually many) transactions for which it is false.
transactionHasLotfulAmounts :: S.Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts :: Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts Set CommoditySymbol
lotfulcomms = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
lotful ([Amount] -> Bool) -> (Posting -> [Amount]) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount])
-> (Posting -> MixedAmount) -> Posting -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount) ([Posting] -> Bool)
-> (Transaction -> [Posting]) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings
  where lotful :: Amount -> Bool
lotful Amount
a = Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a) Bool -> Bool -> Bool
|| Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms

-- | Detect a lot transfer with a fee - an unpriced negative lotful asset
-- posting (bare in a lotful commodity, or carrying a cost basis annotation)
-- whose absolute quantity exceeds the positive quantities received by
-- asset accounts, where the excess matches a non-asset posting (typically a
-- fee paid in the lotful commodity) - and split it into a transfer portion
-- (matching the positive sum) and a dispose portion, so classification can
-- correctly tag the two roles. When the fee counterpart has a transacted
-- price, the dispose portion carries it (and a gain will be calculated);
-- otherwise the dispose portion is priceless (lots are still reduced, but
-- no gain is calculated).
--
-- If no such pattern is found, the transaction is returned unchanged.
-- The transfer portion inherits the original's identity (poriginal preserves
-- the unsplit quantity, so plain print shows the user's original entry).
-- The dispose portion is tagged `_feesplit-posting` so plain print hides it,
-- and `_generated-posting` to mark its provenance; -x or --verbose-tags
-- reveals it.
-- The dispose portion(s) come first, then the transfer portion, which keeps
-- the original posting's balance assertion, so it is still checked after
-- the full original quantity has been posted.
transactionAutoSplitFeeOutflows ::
     Bool
  -> (AccountName -> Maybe AccountType)
  -> (CommoditySymbol -> Bool)
  -> (AccountName -> Bool)
  -> Transaction -> Transaction
transactionAutoSplitFeeOutflows :: Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionAutoSplitFeeOutflows Bool
verbosetags CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots Transaction
t =
    Transaction
t{tpostings = concatMap (\Posting
p -> [Posting] -> Maybe [Posting] -> [Posting]
forall a. a -> Maybe a -> a
fromMaybe [Posting
p] (Posting -> Maybe [Posting]
trySplit Posting
p)) (tpostings t)}
  where
    ps :: [Posting]
ps = Transaction -> [Posting]
tpostings Transaction
t
    isAsset :: CommoditySymbol -> Bool
isAsset    CommoditySymbol
acct = Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType (CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
acct))
    -- A fee counterpart is in an account holding no lots (not a liability
    -- account either: those hold short lots).
    isNonAsset :: CommoditySymbol -> Bool
isNonAsset CommoditySymbol
acct = Maybe LotDirection -> Bool
forall a. Maybe a -> Bool
isNothing ((CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
acct)
    -- An account with a lots: NONE tag doesn't participate in lot tracking,
    -- unless the posting carries explicit cost basis annotations.
    optedOut :: Posting -> Bool
optedOut Posting
p = CommoditySymbol -> Bool
accountUsesNoLots (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p))
                 Bool -> Bool -> Bool
&& Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)))

    -- Try to split posting p into a transfer portion and dispose portion(s).
    -- Requires: a single unpriced negative asset amount, either bare in a
    -- lotful commodity or carrying a cost basis annotation, with matching
    -- non-asset counterpart(s). Positive postings naturally exclude p itself.
    -- Fee fragments from an earlier split (during balancing) are left alone.
    trySplit :: Posting -> Maybe [Posting]
trySplit Posting
p = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
feesplitPostingTagName Posting
p)
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> Bool
isAsset (Posting -> CommoditySymbol
paccount Posting
p)
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Posting -> Bool
optedOut Posting
p)
      [a] <- [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just ([Amount] -> Maybe [Amount]) -> [Amount] -> Maybe [Amount]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      guard $ aquantity a < 0
           && (commodityIsLotful (acommodity a) || isJust (acostbasis a))
           && isNothing (acost a)
      let comm    = Amount -> CommoditySymbol
acommodity Amount
a
          fromQty = Quantity -> Quantity
forall a. Num a => a -> a
negate (Amount -> Quantity
aquantity Amount
a)
          toQty   = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ Amount -> Quantity
aquantity Amount
pa
                        | Posting
q  <- [Posting]
ps
                        , CommoditySymbol -> Bool
isAsset (Posting -> CommoditySymbol
paccount Posting
q)
                        , Bool -> Bool
not (Posting -> Bool
optedOut Posting
q)
                        , Amount
pa <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
                        , Amount -> CommoditySymbol
acommodity Amount
pa CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
comm
                        , Amount -> Quantity
aquantity Amount
pa Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0
                        , Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
pa)
                        ]
          feeQty  = Quantity
fromQty Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
toQty
      guard $ toQty > 0 && feeQty > 0
      feeAmts <- findFeeCounterparts comm feeQty
      let origP = Posting -> Posting
originalPosting Posting
p
          -- The fee portions come first, then the transfer portion, which
          -- keeps any balance assertion (checked after the full original
          -- quantity has been posted). This order also shows, and re-reads,
          -- the lot processing order (fee disposals before the transfer).
          p1    = Posting
p{ pamount = mixedAmount (amountSetQuantity (negate toQty)  a)
                   , poriginal = Just origP }
          mkFeePart Amount
fa
                = CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
feesplitPostingTagName
                (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
generatedPostingTagName
                (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Posting
p{ pamount = mixedAmount (amountSetQuantity (negate (aquantity fa)) a){ acost = acost fa }
                   , poriginal = Just origP
                   , pbalanceassertion = Nothing }
      Just (map mkFeePart feeAmts ++ [p1])

    addTag :: CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
name = Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
name, CommoditySymbol
"")

    -- Find non-lot-account counterpart posting amounts accounting for the given
    -- fee quantity in the given commodity: the first single amount equal to
    -- it, or otherwise all of the positive amounts, if they sum to it exactly.
    findFeeCounterparts :: CommoditySymbol -> Quantity -> Maybe [Amount]
findFeeCounterparts CommoditySymbol
comm Quantity
qty
      | (Amount
fa:[Amount]
_) <- [Amount
fa | Amount
fa <- [Amount]
candidates, Amount -> Quantity
aquantity Amount
fa Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
qty] = [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [Amount
fa]
      | Bool -> Bool
not ([Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Amount]
candidates) Bool -> Bool -> Bool
&& [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((Amount -> Quantity) -> [Amount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Quantity
aquantity [Amount]
candidates) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
qty = [Amount] -> Maybe [Amount]
forall a. a -> Maybe a
Just [Amount]
candidates
      | Bool
otherwise = Maybe [Amount]
forall a. Maybe a
Nothing
      where
        candidates :: [Amount]
candidates =
          [ Amount
pa
          | Posting
q  <- [Posting]
ps, CommoditySymbol -> Bool
isNonAsset (Posting -> CommoditySymbol
paccount Posting
q)
          , Amount
pa <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
          , Amount -> CommoditySymbol
acommodity Amount
pa CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
comm, Amount -> Quantity
aquantity Amount
pa Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0
          ]

-- | Classify lot-related postings by adding a ptype tag.
-- For each posting with a cost basis (any account type):
-- - determine if it's of type "acquire" or "dispose" (based on amount sign)
-- - or "transfer-from" or "transfer-to" (if counterposting with same commodity exists in a different account).
-- For asset postings without cost basis:
-- - a lotful posting can be classified as "transfer-to" (see shouldClassifyLotful)
-- - a bare positive posting can be classified as "transfer-to" if there's a
--   matching transfer-from counterpart (see shouldClassifyBareTransferTo).
-- The lookupAccountType function should typically be `journalAccountType journal`.
-- The commodityIsLotful function should typically be `journalCommodityUsesLots journal`.
-- The verbosetags parameter controls whether the tags are made visible in comments.
--
-- For more detail on classification rules, please see doc/SPEC-lots.md > Lot postings.
--
transactionClassifyLotPostings :: Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction
transactionClassifyLotPostings :: Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionClassifyLotPostings Bool
verbosetags CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots t :: Transaction
t@Transaction{tpostings :: Transaction -> [Posting]
tpostings=[Posting]
ps}
  | Bool -> Bool
not ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
hasLotRelevantAmount [Posting]
ps)
    = Transaction -> String -> Transaction -> Transaction
forall a. Transaction -> String -> a -> a
lotDbg Transaction
t String
"no lot-relevant amounts, skipping" Transaction
t
  | Bool
otherwise = Transaction -> String -> Transaction -> Transaction
forall a. Transaction -> String -> a -> a
lotDbg Transaction
t String
"classifying" (Transaction -> Transaction) -> Transaction -> Transaction
forall a b. (a -> b) -> a -> b
$ Transaction
t{tpostings=zipWith classifyAt [0..] ps}
  where
    hasCostBasis :: Posting -> Bool
    hasCostBasis :: Posting -> Bool
hasCostBasis Posting
p = let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
                         result :: Bool
result = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts
                     in String -> Bool -> Bool
forall a. Show a => String -> a -> a
dbg5 (String
"classifyLotPostings: hasCostBasis " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
forall a. Show a => a -> String
show (Posting -> CommoditySymbol
paccount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" amts=" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show ([Amount] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Amount]
amts)) Bool
result

    -- An account with a lots: NONE tag doesn't participate in lot tracking:
    -- its postings are not classified and are invisible to counterpart
    -- detection - unless they carry explicit cost basis annotations
    -- (the more specific declaration wins).
    optedOut :: Posting -> Bool
    optedOut :: Posting -> Bool
optedOut Posting
p = CommoditySymbol -> Bool
accountUsesNoLots (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)) Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasCostBasis Posting
p)

    -- Is this posting in a Short (liability) account, holding short lots ?
    -- Short lots take no part in transfer detection (transferring them is
    -- not supported yet): such postings are never transfer counterparts,
    -- and are classified only as acquire or dispose (see shouldClassifyShort).
    isShortPosting :: Posting -> Bool
    isShortPosting :: Posting -> Bool
isShortPosting Posting
p = (CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf CommoditySymbol -> Maybe AccountType
lookupAccountType (Posting -> CommoditySymbol
paccount Posting
p) Maybe LotDirection -> Maybe LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection -> Maybe LotDirection
forall a. a -> Maybe a
Just LotDirection
Short

    hasLotRelevantAmount :: Posting -> Bool
    hasLotRelevantAmount :: Posting -> Bool
hasLotRelevantAmount Posting
p = Posting -> Bool
isReal Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasBalancerCopiedBasis Posting
p) Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
optedOut Posting
p)
      Bool -> Bool -> Bool
&& (Posting -> Bool
hasCostBasis Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
hasNegativeLotfulAmount Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
hasPositiveLotfulAmount Posting
p)

    hasNegativeLotfulAmount :: Posting -> Bool
    hasNegativeLotfulAmount :: Posting -> Bool
hasNegativeLotfulAmount Posting
p =
      let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      in Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts)
         Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
         Bool -> Bool -> Bool
&& [Amount] -> Bool
amountsAreLotful [Amount]
amts

    hasPositiveLotfulAmount :: Posting -> Bool
    hasPositiveLotfulAmount :: Posting -> Bool
hasPositiveLotfulAmount Posting
p =
      let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      in Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts)
         Bool -> Bool -> Bool
&& Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts)
         Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0) [Amount]
amts  -- has a strictly positive amount (not zero or amountless)
         Bool -> Bool -> Bool
&& [Amount] -> Bool
amountsAreLotful [Amount]
amts

    -- Same-account transfer pairs: within each account, match positive and negative
    -- unpriced postings with the same commodity and absolute quantity as transfer pairs.
    -- When there are more of one sign than the other, the excess are left unmatched
    -- (and will be classified normally as acquire/dispose).
    -- Priced postings are excluded (a priced posting is a deliberate trade,
    -- eg a stock split's dispose/re-acquire postings; and lot transfers may
    -- not have a transacted price, so pairing one would only force an error).
    sameAcctTransferSet :: S.Set Int
    sameAcctTransferSet :: Set Int
sameAcctTransferSet = [Int] -> Set Int
forall a. Ord a => [a] -> Set a
S.fromList ([Int] -> Set Int) -> [Int] -> Set Int
forall a b. (a -> b) -> a -> b
$ (([Int], [Int]) -> [Int]) -> [([Int], [Int])] -> [Int]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Int], [Int]) -> [Int]
forall {a}. ([a], [a]) -> [a]
matchPairs ([([Int], [Int])] -> [Int]) -> [([Int], [Int])] -> [Int]
forall a b. (a -> b) -> a -> b
$ Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
-> [([Int], [Int])]
forall k a. Map k a -> [a]
M.elems Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
grouped
      where
        grouped :: M.Map (AccountName, CommoditySymbol, Quantity) ([Int], [Int])
        grouped :: Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
grouped = (Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
 -> (Int, Posting)
 -> Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int]))
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
-> [(Int, Posting)]
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
-> (Int, Posting)
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
forall {a}.
Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
-> (a, Posting)
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
addPosting Map (CommoditySymbol, CommoditySymbol, Quantity) ([Int], [Int])
forall k a. Map k a
M.empty ([Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] [Posting]
ps)
        addPosting :: Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
-> (a, Posting)
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
addPosting Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
m (a
i, Posting
p)
          | Bool -> Bool
not (Posting -> Bool
isReal Posting
p) = Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
m
          | Bool -> Bool
not (Posting -> Bool
hasLotRelevantAmount Posting
p) = Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
m
          | Posting -> Bool
isShortPosting Posting
p = Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
m
          | Bool
otherwise = (Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
 -> Amount
 -> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a]))
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
-> [Amount]
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (a
-> CommoditySymbol
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
-> Amount
-> Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
forall {a} {a}.
Ord a =>
a
-> a
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
-> Amount
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
addAmt a
i (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p))) Map (CommoditySymbol, CommoditySymbol, Quantity) ([a], [a])
m (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
        addAmt :: a
-> a
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
-> Amount
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
addAmt a
i a
acct Map (a, CommoditySymbol, Quantity) ([a], [a])
m Amount
a
          | Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe AmountCost
acost Amount
a) = Map (a, CommoditySymbol, Quantity) ([a], [a])
m
          | Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0     = (([a], [a]) -> ([a], [a]) -> ([a], [a]))
-> (a, CommoditySymbol, Quantity)
-> ([a], [a])
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith ([a], [a]) -> ([a], [a]) -> ([a], [a])
forall {a} {a}. ([a], [a]) -> ([a], [a]) -> ([a], [a])
mergePair (a
acct, Amount -> CommoditySymbol
acommodity Amount
a, Quantity -> Quantity
forall a. Num a => a -> a
negate Quantity
q) ([a
i], []) Map (a, CommoditySymbol, Quantity) ([a], [a])
m
          | Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0     = (([a], [a]) -> ([a], [a]) -> ([a], [a]))
-> (a, CommoditySymbol, Quantity)
-> ([a], [a])
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
-> Map (a, CommoditySymbol, Quantity) ([a], [a])
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith ([a], [a]) -> ([a], [a]) -> ([a], [a])
forall {a} {a}. ([a], [a]) -> ([a], [a]) -> ([a], [a])
mergePair (a
acct, Amount -> CommoditySymbol
acommodity Amount
a, Quantity
q)        ([], [a
i]) Map (a, CommoditySymbol, Quantity) ([a], [a])
m
          | Bool
otherwise = Map (a, CommoditySymbol, Quantity) ([a], [a])
m
          where q :: Quantity
q = Amount -> Quantity
aquantity Amount
a
        mergePair :: ([a], [a]) -> ([a], [a]) -> ([a], [a])
mergePair ([a]
n1, [a]
p1) ([a]
n2, [a]
p2) = ([a]
n1[a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++[a]
n2, [a]
p1[a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++[a]
p2)
        matchPairs :: ([a], [a]) -> [a]
matchPairs ([a]
negs, [a]
poss) =
          let n :: Int
n = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
negs) ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
poss)
          in Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Int
n [a]
negs [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Int
n [a]
poss

    -- Could this balancer-copied-basis posting (see 'hasBalancerCopiedBasis')
    -- serve as the elided destination or source of a lot transfer? True for
    -- a nonzero, unpriced amount in a lot-tracking asset account. Such
    -- postings are otherwise invisible to classification, since they may be
    -- the artifact of a disposal missing its selling price (positive mirror)
    -- or an acquisition missing its cost (negative mirror); but those
    -- readings would fail anyway (no price / no lot cost), so preferring the
    -- transfer reading only makes otherwise-erroring entries work.
    -- (A forgotten-price disposal is thus read as a lot transfer to the
    -- elided account, quietly; print -a shows the result for checking.)
    isMirroredTransferCandidate :: Posting -> Bool
    isMirroredTransferCandidate :: Posting -> Bool
isMirroredTransferCandidate Posting
p =
      let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
          baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
      in Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
baseAcct)
         Bool -> Bool -> Bool
&& Bool -> Bool
not (CommoditySymbol -> Bool
accountUsesNoLots CommoditySymbol
baseAcct)
         Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Quantity -> Bool) -> (Amount -> Quantity) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity) [Amount]
amts
         Bool -> Bool -> Bool
&& Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts)

    -- Precompute per-commodity, per-quantity transfer counterpart info (O(n)).
    -- Keyed by (commodity, |quantity|) for exact quantity matching, the primary
    -- transfer detection; see negSums/posSums below for the sum-based fallback.
    -- For each key, which accounts have:
    --   negative postings with cost basis  (transfer-from candidates; any account type)
    --   positive postings with cost basis  (transfer-to candidates, standard path; any account type)
    --   positive asset postings without cost basis  (transfer-to candidates, bare path; asset only)
    -- Account lists are deduplicated (typically 1-2 accounts per commodity).
    negCBAccts, posCBAccts, posNoCBAccts :: M.Map (CommoditySymbol, Quantity) [AccountName]
    (Map (CommoditySymbol, Quantity) [CommoditySymbol]
negCBAccts, Map (CommoditySymbol, Quantity) [CommoditySymbol]
posCBAccts, Map (CommoditySymbol, Quantity) [CommoditySymbol]
posNoCBAccts) = ((Map (CommoditySymbol, Quantity) [CommoditySymbol],
  Map (CommoditySymbol, Quantity) [CommoditySymbol],
  Map (CommoditySymbol, Quantity) [CommoditySymbol])
 -> (Int, Posting)
 -> (Map (CommoditySymbol, Quantity) [CommoditySymbol],
     Map (CommoditySymbol, Quantity) [CommoditySymbol],
     Map (CommoditySymbol, Quantity) [CommoditySymbol]))
-> (Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> [(Int, Posting)]
-> (Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol])
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (Map (CommoditySymbol, Quantity) [CommoditySymbol],
 Map (CommoditySymbol, Quantity) [CommoditySymbol],
 Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> (Int, Posting)
-> (Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol])
collect (Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall k a. Map k a
M.empty, Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall k a. Map k a
M.empty, Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall k a. Map k a
M.empty) ([Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] [Posting]
ps)
      where
        collect :: (Map (CommoditySymbol, Quantity) [CommoditySymbol],
 Map (CommoditySymbol, Quantity) [CommoditySymbol],
 Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> (Int, Posting)
-> (Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol],
    Map (CommoditySymbol, Quantity) [CommoditySymbol])
collect (!Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, !Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, !Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB) (Int
i, Posting
p)
              | Bool -> Bool
not (Posting -> Bool
isReal Posting
p) = (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB)  -- skip virtual postings
              -- skip balancer-copied basis annotations, except elided
              -- transfer source/destination candidates (isMirroredTransferCandidate)
              | Posting -> Bool
hasBalancerCopiedBasis Posting
p, Bool -> Bool
not (Posting -> Bool
isMirroredTransferCandidate Posting
p) = (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB)
              | Int
i Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Int
sameAcctTransferSet = (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB)  -- skip same-account transfer pairs
              | Posting -> Bool
optedOut Posting
p = (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB)  -- skip lots: NONE accounts' postings
              | Posting -> Bool
isShortPosting Posting
p = (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg, Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos, Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB)  -- short lots don't transfer
              | Bool
otherwise =
              let baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
                  isAsset :: Bool
isAsset  = Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
baseAcct)
                  amts :: [Amount]
amts     = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
                  acct :: CommoditySymbol
acct     = CommoditySymbol
baseAcct
                  isNeg :: Bool
isNeg    = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
                  hasCB :: Bool
hasCB    = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts
                  isLotful :: Bool
isLotful = [Amount] -> Bool
amountsAreLotful [Amount]
amts
                  cbKeys :: [(CommoditySymbol, Quantity)]
cbKeys   = [(Amount -> CommoditySymbol
acommodity Amount
a, Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
a)) | Amount
a <- [Amount]
amts, Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)]
                  allKeys :: [(CommoditySymbol, Quantity)]
allKeys  = [(Amount -> CommoditySymbol
acommodity Amount
a, Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
a)) | Amount
a <- [Amount]
amts]
                  -- Include cost-basis negatives (any account type) and bare lotful
                  -- negatives on asset accounts. Non-asset bare lotful negatives
                  -- (e.g. revenue) are excluded — they shouldn't be transfer counterparts.
                  -- Equity transfers are handled separately via hasEquityCounterpart.
                  neg' :: Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg'     = if Bool
isNeg Bool -> Bool -> Bool
&& (Bool
hasCB Bool -> Bool -> Bool
|| (Bool
isLotful Bool -> Bool -> Bool
&& Bool
isAsset))
                             then (Map (CommoditySymbol, Quantity) [CommoditySymbol]
 -> (CommoditySymbol, Quantity)
 -> Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [(CommoditySymbol, Quantity)]
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (CommoditySymbol
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> (CommoditySymbol, Quantity)
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall {k} {a}. (Ord k, Eq a) => a -> Map k [a] -> k -> Map k [a]
addAcct CommoditySymbol
acct) Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg (if Bool
hasCB then [(CommoditySymbol, Quantity)]
cbKeys else [(CommoditySymbol, Quantity)]
allKeys) else Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg
                  pos' :: Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos'     = if Bool -> Bool
not Bool
isNeg Bool -> Bool -> Bool
&& Bool
hasCB
                             then (Map (CommoditySymbol, Quantity) [CommoditySymbol]
 -> (CommoditySymbol, Quantity)
 -> Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [(CommoditySymbol, Quantity)]
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (CommoditySymbol
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> (CommoditySymbol, Quantity)
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall {k} {a}. (Ord k, Eq a) => a -> Map k [a] -> k -> Map k [a]
addAcct CommoditySymbol
acct) Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos [(CommoditySymbol, Quantity)]
cbKeys else Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos
                  noCB' :: Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB'    = if Bool -> Bool
not Bool
isNeg Bool -> Bool -> Bool
&& Bool
isAsset Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
hasCB
                             then (Map (CommoditySymbol, Quantity) [CommoditySymbol]
 -> (CommoditySymbol, Quantity)
 -> Map (CommoditySymbol, Quantity) [CommoditySymbol])
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [(CommoditySymbol, Quantity)]
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (CommoditySymbol
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> (CommoditySymbol, Quantity)
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
forall {k} {a}. (Ord k, Eq a) => a -> Map k [a] -> k -> Map k [a]
addAcct CommoditySymbol
acct) Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB [(CommoditySymbol, Quantity)]
allKeys else Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB
              in (Map (CommoditySymbol, Quantity) [CommoditySymbol]
neg', Map (CommoditySymbol, Quantity) [CommoditySymbol]
pos', Map (CommoditySymbol, Quantity) [CommoditySymbol]
noCB')
        -- Add an account to a (commodity, quantity) key's account list, deduplicating.
        addAcct :: a -> Map k [a] -> k -> Map k [a]
addAcct a
acct Map k [a]
m k
k = ([a] -> [a] -> [a]) -> k -> [a] -> Map k [a] -> Map k [a]
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith (\[a]
_ [a]
old -> if a
acct a -> [a] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [a]
old then [a]
old else a
acct a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
old) k
k [a
acct] Map k [a]
m

    -- Is there a transfer counterpart for a posting in this account, with this sign,
    -- in this commodity and quantity?
    hasCounterpart :: AccountName -> Bool -> CommoditySymbol -> Quantity -> Bool
    hasCounterpart :: CommoditySymbol -> Bool -> CommoditySymbol -> Quantity -> Bool
hasCounterpart CommoditySymbol
acct Bool
isNeg CommoditySymbol
c Quantity
q
      | Bool
isNeg     = Map (CommoditySymbol, Quantity) [CommoditySymbol] -> Bool
anyOtherAcct Map (CommoditySymbol, Quantity) [CommoditySymbol]
posCBAccts Bool -> Bool -> Bool
|| Map (CommoditySymbol, Quantity) [CommoditySymbol] -> Bool
anyOtherAcct Map (CommoditySymbol, Quantity) [CommoditySymbol]
posNoCBAccts
      | Bool
otherwise = Map (CommoditySymbol, Quantity) [CommoditySymbol] -> Bool
anyOtherAcct Map (CommoditySymbol, Quantity) [CommoditySymbol]
negCBAccts
      where anyOtherAcct :: Map (CommoditySymbol, Quantity) [CommoditySymbol] -> Bool
anyOtherAcct Map (CommoditySymbol, Quantity) [CommoditySymbol]
m = (CommoditySymbol -> Bool) -> [CommoditySymbol] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
acct) ([CommoditySymbol]
-> (CommoditySymbol, Quantity)
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [CommoditySymbol]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] (CommoditySymbol
c, Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
q) Map (CommoditySymbol, Quantity) [CommoditySymbol]
m)

    -- Is there a transfer-from counterpart (negative with cost basis or lotful)
    -- for this commodity and quantity?
    hasTransferFromCounterpart :: AccountName -> CommoditySymbol -> Quantity -> Bool
    hasTransferFromCounterpart :: CommoditySymbol -> CommoditySymbol -> Quantity -> Bool
hasTransferFromCounterpart CommoditySymbol
acct CommoditySymbol
c Quantity
q = (CommoditySymbol -> Bool) -> [CommoditySymbol] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
acct) ([CommoditySymbol]
-> (CommoditySymbol, Quantity)
-> Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [CommoditySymbol]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] (CommoditySymbol
c, Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
q) Map (CommoditySymbol, Quantity) [CommoditySymbol]
negCBAccts)

    -- Commodity-only transfer-from check (ignores quantity).
    -- Fallback for transfer+fee patterns where quantities don't match exactly.
    hasTransferFromCommodityMatch :: AccountName -> CommoditySymbol -> Bool
    hasTransferFromCommodityMatch :: CommoditySymbol -> CommoditySymbol -> Bool
hasTransferFromCommodityMatch CommoditySymbol
acct CommoditySymbol
c =
      (((CommoditySymbol, Quantity), [CommoditySymbol]) -> Bool)
-> [((CommoditySymbol, Quantity), [CommoditySymbol])] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\((CommoditySymbol
c', Quantity
_), [CommoditySymbol]
accts) -> CommoditySymbol
c' CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c Bool -> Bool -> Bool
&& (CommoditySymbol -> Bool) -> [CommoditySymbol] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
acct) [CommoditySymbol]
accts)
          (Map (CommoditySymbol, Quantity) [CommoditySymbol]
-> [((CommoditySymbol, Quantity), [CommoditySymbol])]
forall k a. Map k a -> [(k, a)]
M.toList Map (CommoditySymbol, Quantity) [CommoditySymbol]
negCBAccts)

    -- Per-commodity totals of unpriced transfer-candidate amounts, with their
    -- accounts. Used for sum-based transfer detection when quantities don't
    -- pair one to one (a split or consolidating transfer, #2692).
    -- Priced amounts are excluded (a priced posting is a deliberate trade,
    -- eg a fee disposal), as are auto-split fee dispose fragments (feesplit
    -- tag), which would otherwise inflate the outflow total.
    -- Side criteria mirror the counterpart maps above: negatives need cost
    -- basis (any account type) or bare lotful in an asset account; positives
    -- need cost basis (any account type) or an asset account.
    negSums, posSums :: M.Map CommoditySymbol (Quantity, [AccountName])
    (Map CommoditySymbol (Quantity, [CommoditySymbol])
negSums, Map CommoditySymbol (Quantity, [CommoditySymbol])
posSums) = ((Map CommoditySymbol (Quantity, [CommoditySymbol]),
  Map CommoditySymbol (Quantity, [CommoditySymbol]))
 -> (Int, Posting)
 -> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
     Map CommoditySymbol (Quantity, [CommoditySymbol])))
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> [(Int, Posting)]
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (Map CommoditySymbol (Quantity, [CommoditySymbol]),
 Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> (Int, Posting)
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
collectSums (Map CommoditySymbol (Quantity, [CommoditySymbol])
forall k a. Map k a
M.empty, Map CommoditySymbol (Quantity, [CommoditySymbol])
forall k a. Map k a
M.empty) ([Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] [Posting]
ps)
      where
        collectSums :: (Map CommoditySymbol (Quantity, [CommoditySymbol]),
 Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> (Int, Posting)
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
collectSums (!Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, !Map CommoditySymbol (Quantity, [CommoditySymbol])
pos) (Int
i, Posting
p)
          | Bool -> Bool
not (Posting -> Bool
isReal Posting
p) = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | Posting -> Bool
hasBalancerCopiedBasis Posting
p = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | Int
i Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Int
sameAcctTransferSet = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
feesplitPostingTagName Posting
p = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | Posting -> Bool
optedOut Posting
p = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | Posting -> Bool
isShortPosting Posting
p = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos)
          | Bool
otherwise = ((Map CommoditySymbol (Quantity, [CommoditySymbol]),
  Map CommoditySymbol (Quantity, [CommoditySymbol]))
 -> Amount
 -> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
     Map CommoditySymbol (Quantity, [CommoditySymbol])))
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> [Amount]
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (Map CommoditySymbol (Quantity, [CommoditySymbol]),
 Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> Amount
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
addAmt (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg, Map CommoditySymbol (Quantity, [CommoditySymbol])
pos) [Amount]
amts
          where
            acct :: CommoditySymbol
acct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
            isAsset :: Bool
isAsset = Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
acct)
            isLotful :: Bool
isLotful = [Amount] -> Bool
amountsAreLotful [Amount]
amts
            amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
            addAmt :: (Map CommoditySymbol (Quantity, [CommoditySymbol]),
 Map CommoditySymbol (Quantity, [CommoditySymbol]))
-> Amount
-> (Map CommoditySymbol (Quantity, [CommoditySymbol]),
    Map CommoditySymbol (Quantity, [CommoditySymbol]))
addAmt (!Map CommoditySymbol (Quantity, [CommoditySymbol])
neg', !Map CommoditySymbol (Quantity, [CommoditySymbol])
pos') Amount
a
              | Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe AmountCost
acost Amount
a) = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg', Map CommoditySymbol (Quantity, [CommoditySymbol])
pos')
              | Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0, Bool
hasCB Bool -> Bool -> Bool
|| (Bool
isLotful Bool -> Bool -> Bool
&& Bool
isAsset) = (Map CommoditySymbol (Quantity, [CommoditySymbol])
-> Quantity -> Map CommoditySymbol (Quantity, [CommoditySymbol])
forall {a}.
Num a =>
Map CommoditySymbol (a, [CommoditySymbol])
-> a -> Map CommoditySymbol (a, [CommoditySymbol])
addTo Map CommoditySymbol (Quantity, [CommoditySymbol])
neg' (Quantity -> Quantity
forall a. Num a => a -> a
negate Quantity
q), Map CommoditySymbol (Quantity, [CommoditySymbol])
pos')
              | Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0, Bool
hasCB Bool -> Bool -> Bool
|| Bool
isAsset               = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg', Map CommoditySymbol (Quantity, [CommoditySymbol])
-> Quantity -> Map CommoditySymbol (Quantity, [CommoditySymbol])
forall {a}.
Num a =>
Map CommoditySymbol (a, [CommoditySymbol])
-> a -> Map CommoditySymbol (a, [CommoditySymbol])
addTo Map CommoditySymbol (Quantity, [CommoditySymbol])
pos' Quantity
q)
              | Bool
otherwise = (Map CommoditySymbol (Quantity, [CommoditySymbol])
neg', Map CommoditySymbol (Quantity, [CommoditySymbol])
pos')
              where
                q :: Quantity
q = Amount -> Quantity
aquantity Amount
a
                hasCB :: Bool
hasCB = Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)
                addTo :: Map CommoditySymbol (a, [CommoditySymbol])
-> a -> Map CommoditySymbol (a, [CommoditySymbol])
addTo Map CommoditySymbol (a, [CommoditySymbol])
m a
qty = ((a, [CommoditySymbol])
 -> (a, [CommoditySymbol]) -> (a, [CommoditySymbol]))
-> CommoditySymbol
-> (a, [CommoditySymbol])
-> Map CommoditySymbol (a, [CommoditySymbol])
-> Map CommoditySymbol (a, [CommoditySymbol])
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith (a, [CommoditySymbol])
-> (a, [CommoditySymbol]) -> (a, [CommoditySymbol])
forall {a} {t :: * -> *} {a}.
(Num a, Foldable t, Eq a) =>
(a, t a) -> (a, [a]) -> (a, [a])
merge (Amount -> CommoditySymbol
acommodity Amount
a) (a
qty, [CommoditySymbol
acct]) Map CommoditySymbol (a, [CommoditySymbol])
m
                merge :: (a, t a) -> (a, [a]) -> (a, [a])
merge (a
newq, t a
newaccts) (a
oldq, [a]
oldaccts) =
                  (a
newq a -> a -> a
forall a. Num a => a -> a -> a
+ a
oldq, (a -> [a] -> [a]) -> [a] -> t a -> [a]
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr a -> [a] -> [a]
forall {a}. Eq a => a -> [a] -> [a]
insertAcct [a]
oldaccts t a
newaccts)
                insertAcct :: a -> [a] -> [a]
insertAcct a
x [a]
xs = if a
x a -> [a] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [a]
xs then [a]
xs else a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
xs

    -- Is there a sum-matched transfer counterpart for this commodity ?
    -- True when the commodity's total unpriced outflow equals its total
    -- unpriced inflow (per the sum maps above), and the opposite side
    -- includes an account other than this posting's. Detects transfers
    -- whose postings don't pair one to one (#2692).
    hasSumCounterpart :: AccountName -> Bool -> CommoditySymbol -> Bool
    hasSumCounterpart :: CommoditySymbol -> Bool -> CommoditySymbol -> Bool
hasSumCounterpart CommoditySymbol
acct Bool
isNeg CommoditySymbol
c =
      case (CommoditySymbol
-> Map CommoditySymbol (Quantity, [CommoditySymbol])
-> Maybe (Quantity, [CommoditySymbol])
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
c Map CommoditySymbol (Quantity, [CommoditySymbol])
negSums, CommoditySymbol
-> Map CommoditySymbol (Quantity, [CommoditySymbol])
-> Maybe (Quantity, [CommoditySymbol])
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
c Map CommoditySymbol (Quantity, [CommoditySymbol])
posSums) of
        (Just (Quantity
nq, [CommoditySymbol]
naccts), Just (Quantity
pq, [CommoditySymbol]
paccts)) ->
          Quantity
nq Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
pq Bool -> Bool -> Bool
&& (CommoditySymbol -> Bool) -> [CommoditySymbol] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
acct) (if Bool
isNeg then [CommoditySymbol]
paccts else [CommoditySymbol]
naccts)
        (Maybe (Quantity, [CommoditySymbol]),
 Maybe (Quantity, [CommoditySymbol]))
_ -> Bool
False

    classifyAt :: Int -> Posting -> Posting
    classifyAt :: Int -> Posting -> Posting
classifyAt Int
i Posting
p
      | Bool -> Bool
not (Posting -> Bool
isReal Posting
p) = Posting
p  -- skip virtual (parenthesised) postings
      | Posting -> Bool
isClassifiedPosting Posting
p = Posting
p  -- skip postings already carrying a ptype tag (eg gain postings tagged by transactionTagGainPostings)
      -- A balancer-copied basis posting is normally left unclassified,
      -- except when it can be read as the elided destination or source of
      -- a lot transfer (see isMirroredTransferCandidate).
      | Posting -> Bool
hasBalancerCopiedBasis Posting
p =
          let baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
              cbPairs :: [(CommoditySymbol, Quantity)]
cbPairs = [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)]
              isNeg :: Bool
isNeg = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
              hasMatch :: Bool
hasMatch
                | Bool
isNeg     = ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> Bool -> CommoditySymbol -> Quantity -> Bool
hasCounterpart CommoditySymbol
baseAcct Bool
True CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
cbPairs
                | Bool
otherwise = ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> CommoditySymbol -> Quantity -> Bool
hasTransferFromCounterpart CommoditySymbol
baseAcct CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
cbPairs
          in if Posting -> Bool
isMirroredTransferCandidate Posting
p Bool -> Bool -> Bool
&& Bool
hasMatch
             then CommoditySymbol -> Posting -> Posting
addTag (if Bool
isNeg then CommoditySymbol
"transfer-from" else CommoditySymbol
"transfer-to") Posting
p
             else Posting
p
      | Int
i Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Int
sameAcctTransferSet =
          let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
              cls :: CommoditySymbol
cls = if (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts then CommoditySymbol
"transfer-from" else CommoditySymbol
"transfer-to"
          in CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
cls Posting
p
      | Bool
otherwise =
      case String -> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a. Show a => String -> a -> a
dbg5 (String
"classifyLotPostings: classifyPosting " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
forall a. Show a => a -> String
show (Posting -> CommoditySymbol
paccount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" result") (Maybe CommoditySymbol -> Maybe CommoditySymbol)
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe CommoditySymbol
shouldClassify Posting
p of
        Just CommoditySymbol
classification -> CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
classification Posting
p
        Maybe CommoditySymbol
Nothing -> Posting
p
      where addTag :: CommoditySymbol -> Posting -> Posting
addTag CommoditySymbol
cls = Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
True Bool
verbosetags ((CommoditySymbol, CommoditySymbol)
-> (CommoditySymbol, CommoditySymbol)
toHiddenTag (CommoditySymbol
"ptype", CommoditySymbol
cls))

    -- Check if posting should be classified and return the classification:
    -- one of acquire, dispose, transfer-from, transfer-to.
    shouldClassify :: Posting -> Maybe Text
    shouldClassify :: Posting -> Maybe CommoditySymbol
shouldClassify Posting
p = do
      let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
          baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
      -- Zero-amount postings (eg balance assertion carriers) move no lots and
      -- are left unclassified, consistent with isUnclassifiedLotfulPosting's
      -- zero exemption. (Eg a zero posting beside a transfer must not become
      -- a transfer-to via commodity matching.)
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Quantity -> Bool) -> (Amount -> Quantity) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity) [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Posting -> Bool
optedOut Posting
p)
      if Posting -> Bool
isShortPosting Posting
p
        then String -> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a. Show a => String -> a -> a
dbg5 (String
"classifyLotPostings: shouldClassify " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
forall a. Show a => a -> String
show (Posting -> CommoditySymbol
paccount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" short") (Maybe CommoditySymbol -> Maybe CommoditySymbol)
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$
             Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyShort Posting
p [Amount]
amts
      else if (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts
        -- Cost basis present: classify regardless of account type (fix A)
        then String -> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a. Show a => String -> a -> a
dbg5 (String
"classifyLotPostings: shouldClassify " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
forall a. Show a => a -> String
show (Posting -> CommoditySymbol
paccount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" withCostBasis") (Maybe CommoditySymbol -> Maybe CommoditySymbol)
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$
             Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyWithCostBasis Posting
p [Amount]
amts
        else do
          -- No cost basis: require asset account type
          acctType <- String -> Maybe AccountType -> Maybe AccountType
forall a. Show a => String -> a -> a
dbg5 (String
"classifyLotPostings: shouldClassify " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
forall a. Show a => a -> String
show (Posting -> CommoditySymbol
paccount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" acctType") (Maybe AccountType -> Maybe AccountType)
-> Maybe AccountType -> Maybe AccountType
forall a b. (a -> b) -> a -> b
$
                      CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
baseAcct
          guard $ isAssetType acctType
          dbg5 ("classifyLotPostings: shouldClassify " ++ show (paccount p) ++ " lotful/bare") $
            shouldClassifyNegativeLotful p amts <|> shouldClassifyLotful p amts <|> shouldClassifyBareTransferTo p amts <|> shouldClassifyPositiveLotful p amts

    -- True when the transaction has an equity posting with no explicit cost-basis amounts.
    -- This indicates an equity transfer: lots move to/from equity in two parts
    -- (e.g. close --clopen --lots generates a closing txn transferring lots into equity,
    -- and an opening txn transferring them back out), allowing the negative lot postings
    -- to be classified as transfer-from rather than dispose.
    hasEquityCounterpart :: Bool
    hasEquityCounterpart :: Bool
hasEquityCounterpart = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isEquityNonLotPosting [Posting]
ps
      where
        isEquityNonLotPosting :: Posting -> Bool
isEquityNonLotPosting Posting
q =
          Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isEquityType (CommoditySymbol -> Maybe AccountType
lookupAccountType (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
q)))
          -- A balancer-copied basis annotation is not user-written
          -- (an elided equity posting still counts as an equity counterpart).
          Bool -> Bool -> Bool
&& (Posting -> Bool
hasBalancerCopiedBasis Posting
q Bool -> Bool -> Bool
|| Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q))))

    -- Classify a posting that has cost basis: acquire, dispose, transfer-from, or transfer-to.
    shouldClassifyWithCostBasis :: Posting -> [Amount] -> Maybe Text
    shouldClassifyWithCostBasis :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyWithCostBasis Posting
p [Amount]
amts = do
      let
        baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
        isNeg :: Bool
isNeg = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
        primaryType :: CommoditySymbol
primaryType = if Bool
isNeg then CommoditySymbol
"dispose" else CommoditySymbol
"acquire"
        cbAmts :: [(CommoditySymbol, Quantity)]
cbAmts = [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- [Amount]
amts, Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)]
        -- A transfer counterpart can match by exact quantity, or by commodity
        -- sums when postings don't pair one to one (#2692). The sum fallback
        -- is only for unpriced postings (a priced posting is a deliberate
        -- trade) and not for auto-split fee fragments (which must remain
        -- disposals even though the remaining transfer sums match).
        isTransfer :: Bool
isTransfer = ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> Bool -> CommoditySymbol -> Quantity -> Bool
hasCounterpart CommoditySymbol
baseAcct Bool
isNeg CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
cbAmts
          Bool -> Bool -> Bool
|| (Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts)
              Bool -> Bool -> Bool
&& Bool -> Bool
not (CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
feesplitPostingTagName Posting
p)
              Bool -> Bool -> Bool
&& ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Bool -> CommoditySymbol -> Bool
hasSumCounterpart CommoditySymbol
baseAcct Bool
isNeg (CommoditySymbol -> Bool)
-> ((CommoditySymbol, Quantity) -> CommoditySymbol)
-> (CommoditySymbol, Quantity)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol, Quantity) -> CommoditySymbol
forall a b. (a, b) -> a
fst) [(CommoditySymbol, Quantity)]
cbAmts)
        -- Also treat as equity transfer when: no transacted price written,
        -- and an equity counterpart posting is present. This handles lots moving
        -- to/from equity (e.g. close --clopen --lots generates a closing txn with
        -- negative lot postings and an opening txn with positive lot postings).
        isEquityTransfer :: Bool
isEquityTransfer = Bool -> Bool
not ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts) Bool -> Bool -> Bool
&& Bool
hasEquityCounterpart
      if Bool
isTransfer Bool -> Bool -> Bool
|| Bool
isEquityTransfer
        then CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return (CommoditySymbol -> Maybe CommoditySymbol)
-> CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ if Bool
isNeg then CommoditySymbol
"transfer-from" else CommoditySymbol
"transfer-to"
        else do
          -- Don't classify income statement accounts (Revenue, Expense, Gain) as acquire/dispose.
          -- These are flow accounts that should not track lots or get lot subaccounts.
          -- E.g. expenses:fees 0.1 ETSY {$80} @ $90 in a stock-fee disposal.
          Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isIncomeStatementAccountType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
baseAcct)
          CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
primaryType

    -- Classify a negative lotful posting without cost basis as dispose or transfer-from.
    -- If the posting has no transacted price and another asset account in the same
    -- transaction receives a positive lotful amount of the same commodity (even at
    -- different quantity), skip classification — it's a transfer+fee pattern and
    -- global FIFO will handle the lot reduction when the destination account trades.
    shouldClassifyNegativeLotful :: Posting -> [Amount] -> Maybe Text
    shouldClassifyNegativeLotful :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyNegativeLotful Posting
p [Amount]
amts = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ [Amount] -> Bool
amountsAreLotful [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
      let baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
          hasPrice :: Bool
hasPrice = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts
          negAmts :: [Amount]
negAmts = [Amount
a | Amount
a <- [Amount]
amts, Amount -> Bool
isNegativeAmount Amount
a]
          negCommodities :: Set CommoditySymbol
negCommodities = [CommoditySymbol] -> Set CommoditySymbol
forall a. Ord a => [a] -> Set a
S.fromList [Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- [Amount]
negAmts]
          amtPairs :: [(CommoditySymbol, Quantity)]
amtPairs = [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- [Amount]
amts]
          isTransfer :: Bool
isTransfer = ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> Bool -> CommoditySymbol -> Quantity -> Bool
hasCounterpart CommoditySymbol
baseAcct Bool
True CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
amtPairs
          -- Check for positive lotful amounts in other asset accounts (same commodity).
          otherAssetReceives :: Bool
otherAssetReceives = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isOtherAssetWithLotful ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Posting -> Posting -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting
p) [Posting]
ps)
          isOtherAssetWithLotful :: Posting -> Bool
isOtherAssetWithLotful Posting
q =
            let qAmts :: [Amount]
qAmts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
                qBase :: CommoditySymbol
qBase = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
q)
            in CommoditySymbol
qBase CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
baseAcct
               Bool -> Bool -> Bool
&& Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
qBase)
               Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
optedOut Posting
q)
               Bool -> Bool -> Bool
&& [Amount] -> Bool
amountsAreLotful [Amount]
qAmts
               Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 Bool -> Bool -> Bool
&& Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
negCommodities) [Amount]
qAmts
          -- Does a non-asset posting receive exactly this commodity+quantity?
          -- If so, this posting is likely a fee/dispose (e.g. paired with expenses:fees),
          -- not part of a transfer to another asset account.
          hasFeeCounterpart :: Bool
hasFeeCounterpart = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isFeeCounterpart ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Posting -> Posting -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting
p) [Posting]
ps)
          isFeeCounterpart :: Posting -> Bool
isFeeCounterpart Posting
q =
            let qAmts :: [Amount]
qAmts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
                qBase :: CommoditySymbol
qBase = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
q)
            in Bool -> Bool
not (Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isAssetType (CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol
qBase))
               Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0
                          Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
na -> Amount -> CommoditySymbol
acommodity Amount
na CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> CommoditySymbol
acommodity Amount
a
                                      Bool -> Bool -> Bool
&& Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
na) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
a) [Amount]
negAmts) [Amount]
qAmts
      -- The other-asset-receives heuristic (transfer+fee pattern) applies only
      -- to unpriced postings: a transacted price signals dispose intent, eg an
      -- explicit priced fee disposal written alongside a matched transfer pair.
      if Bool
isTransfer Bool -> Bool -> Bool
|| (Bool
otherAssetReceives Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
hasFeeCounterpart Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
hasPrice)
        then CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"transfer-from"
        else do
          Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool
hasPrice Bool -> Bool -> Bool
|| Bool
hasFeeCounterpart Bool -> Bool -> Bool
|| Bool -> Bool
not Bool
otherAssetReceives
          CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"dispose"

    -- Classify a lotful posting without cost basis.
    -- A positive posting in a lotful commodity/account, with no transacted price,
    -- and with a matching transfer-from counterpart, is classified as transfer-to.
    shouldClassifyLotful :: Posting -> [Amount] -> Maybe Text
    shouldClassifyLotful :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyLotful Posting
p [Amount]
amts = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ [Amount] -> Bool
amountsAreLotful [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts
      let baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
          amtPairs :: [(CommoditySymbol, Quantity)]
amtPairs = [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- [Amount]
amts]
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> CommoditySymbol -> Quantity -> Bool
hasTransferFromCounterpart CommoditySymbol
baseAcct CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
amtPairs
           Bool -> Bool -> Bool
|| ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
_) -> CommoditySymbol -> CommoditySymbol -> Bool
hasTransferFromCommodityMatch CommoditySymbol
baseAcct CommoditySymbol
c) [(CommoditySymbol, Quantity)]
amtPairs
      CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"transfer-to"

    -- Classify a bare positive asset posting (no cost basis, not necessarily lotful)
    -- as transfer-to if there's a matching transfer-from counterpart (fix C).
    shouldClassifyBareTransferTo :: Posting -> [Amount] -> Maybe Text
    shouldClassifyBareTransferTo :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyBareTransferTo Posting
p [Amount]
amts = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Amount -> Bool
isNegativeAmount [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts
      let baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
          amtPairs :: [(CommoditySymbol, Quantity)]
amtPairs = [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- [Amount]
amts]
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> CommoditySymbol -> Quantity -> Bool
hasTransferFromCounterpart CommoditySymbol
baseAcct CommoditySymbol
c Quantity
q) [(CommoditySymbol, Quantity)]
amtPairs
           Bool -> Bool -> Bool
|| ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
_) -> CommoditySymbol -> CommoditySymbol -> Bool
hasTransferFromCommodityMatch CommoditySymbol
baseAcct CommoditySymbol
c) [(CommoditySymbol, Quantity)]
amtPairs
      CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"transfer-to"

    -- Classify a positive lotful posting without cost basis as acquire.
    -- This is the fallback for positive lotful postings that aren't transfer-to.
    -- Requires a plausible cost source: transacted price, different-commodity posting
    -- (for balancer inference), or a transfer-from counterpart (whose lot cost is inherited).
    -- Without any of these, no lot can be created so we skip classification.
    shouldClassifyPositiveLotful :: Posting -> [Amount] -> Maybe Text
    shouldClassifyPositiveLotful :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyPositiveLotful Posting
p [Amount]
amts = do
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ [Amount] -> Bool
amountsAreLotful [Amount]
amts
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0) [Amount]
amts
      let hasPrice :: Bool
hasPrice = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts
          baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
          hasTransferFrom :: Bool
hasTransferFrom = ((CommoditySymbol, Quantity) -> Bool)
-> [(CommoditySymbol, Quantity)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(CommoditySymbol
c, Quantity
q) -> CommoditySymbol -> CommoditySymbol -> Quantity -> Bool
hasTransferFromCounterpart CommoditySymbol
baseAcct CommoditySymbol
c Quantity
q)
                              [(Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a) | Amount
a <- [Amount]
amts]
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool
hasPrice Bool -> Bool -> Bool
|| Posting -> [Amount] -> Bool
hasOtherCommodityPosting Posting
p [Amount]
amts Bool -> Bool -> Bool
|| Bool
hasTransferFrom
      CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"acquire"

    -- Classify a posting in a Short (liability) account, which holds short
    -- positions: a negative amount opens a short lot (acquire), a positive
    -- one covers it (dispose). Short lots can't be transferred between
    -- accounts yet (see isShortPosting), but can be moved to or from
    -- equity (close --clopen --lots): with no transacted price and an
    -- equity counterpart, it is an equity transfer, like a long posting.
    -- Like a long posting, a bare open needs a cost source (a transacted
    -- price, or another commodity to infer it from); a bare cover without
    -- a price is a priceless disposal.
    shouldClassifyShort :: Posting -> [Amount] -> Maybe Text
    shouldClassifyShort :: Posting -> [Amount] -> Maybe CommoditySymbol
shouldClassifyShort Posting
p [Amount]
amts = do
      let hasCB :: Bool
hasCB    = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) [Amount]
amts
          hasPrice :: Bool
hasPrice = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) [Amount]
amts
          isInflow :: Bool
isInflow = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (LotDirection -> Amount -> Bool
isLotInflow LotDirection
Short) [Amount]
amts
          isEquityTransfer :: Bool
isEquityTransfer = Bool -> Bool
not Bool
hasPrice Bool -> Bool -> Bool
&& Bool
hasEquityCounterpart
      Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool
hasCB Bool -> Bool -> Bool
|| [Amount] -> Bool
amountsAreLotful [Amount]
amts
      if Bool
isEquityTransfer
        then CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return (CommoditySymbol -> Maybe CommoditySymbol)
-> CommoditySymbol -> Maybe CommoditySymbol
forall a b. (a -> b) -> a -> b
$ if Bool
isInflow then CommoditySymbol
"transfer-to" else CommoditySymbol
"transfer-from"
      else if Bool
isInflow
        then do
          Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> Bool -> Maybe ()
forall a b. (a -> b) -> a -> b
$ Bool
hasCB Bool -> Bool -> Bool
|| Bool
hasPrice Bool -> Bool -> Bool
|| Posting -> [Amount] -> Bool
hasOtherCommodityPosting Posting
p [Amount]
amts
          CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"acquire"
        else CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
"dispose"

    -- Does another amountful posting in the transaction have a commodity
    -- other than this posting's ? (Then the balancer can infer a cost.)
    hasOtherCommodityPosting :: Posting -> [Amount] -> Bool
    hasOtherCommodityPosting :: Posting -> [Amount] -> Bool
hasOtherCommodityPosting Posting
p [Amount]
amts =
      (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Posting
q -> (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.notMember` Set CommoditySymbol
commodities) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)))
          ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Posting
q -> Posting
q Posting -> Posting -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting
p Bool -> Bool -> Bool
&& Posting -> Bool
hasAmount Posting
q) [Posting]
ps)
      where commodities :: Set CommoditySymbol
commodities = [CommoditySymbol] -> Set CommoditySymbol
forall a. Ord a => [a] -> Set a
S.fromList [Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- [Amount]
amts]

    -- Check if a posting's amounts are lotful: one of their commodities has a lots: tag.
    amountsAreLotful :: [Amount] -> Bool
    amountsAreLotful :: [Amount] -> Bool
amountsAreLotful = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Bool
commodityIsLotful (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity)

-- Lot calculation (pipeline stage 2)

-- | Calculate detailed lot movements by walking transactions in date order.
-- Handles acquire postings (generating lot names as subaccounts),
-- dispose postings (matching to existing lots using FIFO, splitting if needed),
-- and transfer postings (moving lots between accounts, preserving cost basis).
-- The verbosetags parameter controls whether generated-posting tags are made visible in comments.
-- All lot selection/classification failures are hard errors.
-- Same-date transactions are processed in parse order, never reordered.
journalCalculateLots :: Bool -> Journal -> Either String Journal
journalCalculateLots :: Bool -> Journal -> Either String Journal
journalCalculateLots Bool
verbosetags Journal
j
  | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Transaction -> Bool) -> [Transaction] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isLotPosting ([Posting] -> Bool)
-> (Transaction -> [Posting]) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings) [Transaction]
txns = do
      ((Transaction, Int, Posting) -> Either String ())
-> [(Transaction, Int, Posting)] -> Either String ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Transaction, Int, Posting) -> Either String ()
checkUnclassified [(Transaction
t, Int
i, Posting
p) | Transaction
t <- [Transaction]
txns, (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t)]
      Journal -> Either String Journal
forall a b. b -> Either a b
Right Journal
j
  | Bool
otherwise = do
      [Transaction] -> Either String ()
validateUserLabels [Transaction]
txns
      let needsLabels :: Set (CommoditySymbol, Day)
needsLabels = [Transaction] -> Set (CommoditySymbol, Day)
findDatesNeedingLabels [Transaction]
txns
          -- Transactions with no lotful amounts can't affect lots; pass them through untouched.
          -- An error gets a hint if a later transaction might have been meant to come first.
          process :: (LotState, [Transaction])
-> Transaction
-> [Transaction]
-> Either String (LotState, [Transaction])
process acc :: (LotState, [Transaction])
acc@(LotState
ls, [Transaction]
done) Transaction
t [Transaction]
later
            | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts Set CommoditySymbol
lotfulcomms Transaction
t = (LotState, [Transaction])
-> Either String (LotState, [Transaction])
forall a b. b -> Either a b
Right (LotState
ls, Transaction
t Transaction -> [Transaction] -> [Transaction]
forall a. a -> [a] -> [a]
: [Transaction]
done)
            | Bool
otherwise = (String -> String)
-> Either String (LotState, [Transaction])
-> Either String (LotState, [Transaction])
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Transaction -> String -> String
appendPostingsReadAs Transaction
t (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> String -> String
forall a. [a] -> [a] -> [a]
++ LotState -> Transaction -> [Transaction] -> String
laterSupplyHint LotState
ls Transaction
t [Transaction]
later) (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n'))
                        (Either String (LotState, [Transaction])
 -> Either String (LotState, [Transaction]))
-> Either String (LotState, [Transaction])
-> Either String (LotState, [Transaction])
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Set (CommoditySymbol, Day)
-> (LotState, [Transaction])
-> Transaction
-> Either String (LotState, [Transaction])
processTransaction Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Set (CommoditySymbol, Day)
needsLabels (LotState, [Transaction])
acc Transaction
t
          walk :: (LotState, [Transaction])
-> [Transaction] -> Either String (LotState, [Transaction])
walk (LotState, [Transaction])
acc []         = (LotState, [Transaction])
-> Either String (LotState, [Transaction])
forall a b. b -> Either a b
Right (LotState, [Transaction])
acc
          walk (LotState, [Transaction])
acc (Transaction
t:[Transaction]
later) = (LotState, [Transaction])
-> Transaction
-> [Transaction]
-> Either String (LotState, [Transaction])
process (LotState, [Transaction])
acc Transaction
t [Transaction]
later Either String (LotState, [Transaction])
-> ((LotState, [Transaction])
    -> Either String (LotState, [Transaction]))
-> Either String (LotState, [Transaction])
forall a b.
Either String a -> (a -> Either String b) -> Either String b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \(LotState, [Transaction])
acc' -> (LotState, [Transaction])
-> [Transaction] -> Either String (LotState, [Transaction])
walk (LotState, [Transaction])
acc' [Transaction]
later
      (_, txns') <- (LotState, [Transaction])
-> [Transaction] -> Either String (LotState, [Transaction])
walk (LotState
forall k a. Map k a
M.empty, []) ((Transaction -> Day) -> [Transaction] -> [Transaction]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Transaction -> Day
tdate [Transaction]
txns)
      Right (journalTieTransactions $ j{jtxns = reverse txns'})
  where
    txns :: [Transaction]
txns = Journal -> [Transaction]
jtxns Journal
j
    lotfulcomms :: Set CommoditySymbol
lotfulcomms = Journal -> Set CommoditySymbol
journalLotfulCommodities Journal
j
    -- Journal's canonical commodity styles, used for rendering the cost amount
    -- in lot subaccount names. NoRounding preserves the original decimal digits
    -- while still applying the canonical decimal mark, digit group separators,
    -- and commodity position/spacing.
    styles :: Map CommoditySymbol AmountStyle
styles = Rounding -> Journal -> Map CommoditySymbol AmountStyle
journalCommodityStylesWith Rounding
NoRounding Journal
j
    checkUnclassified :: (Transaction, Int, Posting) -> Either String ()
checkUnclassified (Transaction
t, Int
i, Posting
p)
      | Journal -> Posting -> Bool
isUnclassifiedLotfulPosting Journal
j Posting
p = String -> Either String ()
forall a b. a -> Either a b
Left (Transaction -> String -> String
appendPostingsReadAs Transaction
t (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ Journal -> Transaction -> Int -> Posting -> String
unclassifiedLotWarning Journal
j Transaction
t Int
i Posting
p)
      | Bool
otherwise                       = () -> Either String ()
forall a b. b -> Either a b
Right ()

-- | A hint for a lot error in this transaction, explaining that a later entry
-- on the same date adds the commodity to an account which the transaction takes
-- it from, but which holds none of it yet. Same-date entries are processed in
-- parse order, so the later entry may have been meant to come first (eg the
-- other side of a transfer recorded through a clearing account, or a same-day
-- purchase). Starts with a newline; empty when there is no such entry.
laterSupplyHint :: LotState -> Transaction -> [Transaction] -> String
laterSupplyHint :: LotState -> Transaction -> [Transaction] -> String
laterSupplyHint LotState
ls Transaction
t [Transaction]
later = case [(CommoditySymbol, CommoditySymbol, Transaction)]
supplies of
  []           -> String
""
  (CommoditySymbol
a, CommoditySymbol
c, Transaction
f) : [(CommoditySymbol, CommoditySymbol, Transaction)]
_ -> String -> String -> String -> String -> String
forall r. PrintfType r => String -> r
printf
    (String
"\n\nA later entry on the same date adds %s to %s:\n  %s\n"
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Same-date entries are processed in the order they are read; perhaps that entry should come first.")
    (CommoditySymbol -> String
T.unpack CommoditySymbol
c) (CommoditySymbol -> String
T.unpack CommoditySymbol
a) (Transaction -> String
txnDbgPrefix Transaction
f)
  where
    sameDate :: [Transaction]
sameDate = (Transaction -> Bool) -> [Transaction] -> [Transaction]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile ((Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
== Transaction -> Day
tdate Transaction
t) (Day -> Bool) -> (Transaction -> Day) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Day
tdate) [Transaction]
later
    unheld :: [(CommoditySymbol, CommoditySymbol)]
unheld = [ (CommoditySymbol
a, Amount -> CommoditySymbol
acommodity Amount
x)
             | Posting
p <- Transaction -> [Posting]
tpostings Transaction
t, Posting -> Bool
isTransferFromPosting Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
isDisposePosting Posting
p
             , let a :: CommoditySymbol
a = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
             , Amount
x <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Amount -> Quantity
aquantity Amount
x Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0
             , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ (Map CommoditySymbol Amount -> Bool)
-> Map LotId (Map CommoditySymbol Amount) -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Map CommoditySymbol Amount -> Bool
forall k a. Ord k => k -> Map k a -> Bool
M.member CommoditySymbol
a) (Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty (Amount -> CommoditySymbol
acommodity Amount
x) LotState
ls) ]
    supplies :: [(CommoditySymbol, CommoditySymbol, Transaction)]
supplies = [ (CommoditySymbol
a, CommoditySymbol
c, Transaction
f) | (CommoditySymbol
a, CommoditySymbol
c) <- [(CommoditySymbol, CommoditySymbol)]
unheld, Transaction
f <- [Transaction]
sameDate, (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> CommoditySymbol -> Posting -> Bool
addsTo CommoditySymbol
a CommoditySymbol
c) (Transaction -> [Posting]
tpostings Transaction
f) ]
    addsTo :: CommoditySymbol -> CommoditySymbol -> Posting -> Bool
addsTo CommoditySymbol
a CommoditySymbol
c Posting
q = (Posting -> Bool
isAcquirePosting Posting
q Bool -> Bool -> Bool
|| Posting -> Bool
isTransferToPosting Posting
q)
                Bool -> Bool -> Bool
&& CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
q) CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
a
                Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
c) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q))

-- Disposal gain postings

-- | Make a generated realised-gain posting with the given account and amount,
-- tagged @_ptype:gain@ and @_generated-posting@ (the latter visible as
-- @generated-posting:@ in @print --verbose-tags@).
mkGeneratedGainPosting :: Bool -> AccountName -> MixedAmount -> Posting
mkGeneratedGainPosting :: Bool -> CommoditySymbol -> MixedAmount -> Posting
mkGeneratedGainPosting Bool
verbosetags CommoditySymbol
acc MixedAmount
amt =
    Bool -> Posting -> Posting
tagGain Bool
verbosetags
  (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ 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
$ Posting
nullposting{paccount = acc, pamount = amt}

-- | Tag a posting as a gain posting (@_ptype:gain@).
tagGain :: Bool -> Posting -> Posting
tagGain :: Bool -> Posting -> Posting
tagGain Bool
verbosetags = Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
True Bool
verbosetags ((CommoditySymbol, CommoditySymbol)
-> (CommoditySymbol, CommoditySymbol)
toHiddenTag (CommoditySymbol
"ptype", CommoditySymbol
"gain"))

-- | Does this posting look like a lot disposal (or transfer source) ?
-- True if it has a lot outflow amount (negative, or positive in a liability
-- account, which holds short lots) with a cost basis annotation, or in a
-- lotful commodity (unless the account opts out with lots: NONE).
-- A shape check, usable before lot classification has run.
postingHasDisposeShape :: (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Posting -> Bool
postingHasDisposeShape :: (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Posting
-> Bool
postingHasDisposeShape CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots Posting
p =
  (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
a
          Bool -> Bool -> Bool
&& (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)
              Bool -> Bool -> Bool
|| (CommoditySymbol -> Bool
commodityIsLotful (Amount -> CommoditySymbol
acommodity Amount
a)
                  Bool -> Bool -> Bool
&& Bool -> Bool
not (CommoditySymbol -> Bool
accountUsesNoLots (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p))))))
      (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
  where dir :: LotDirection
dir = LotDirection -> Maybe LotDirection -> LotDirection
forall a. a -> Maybe a -> a
fromMaybe LotDirection
Long ((CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf CommoditySymbol -> Maybe AccountType
lookupAccountType (Posting -> CommoditySymbol
paccount Posting
p))

-- | In a disposal transaction, tag the user-written realised gain
-- postings with @_ptype:gain@, so that the transaction balancer sets them
-- aside (see 'Hledger.Data.Balancing.transactionCheckBalanced').
--
-- A disposal balances at cost basis: the dispose posting counts as its
-- quantity times its basis, and the gain posting accounts for the
-- difference from the transacted proceeds. The basis is not known until
-- lot matching, which runs after balancing; but since
-- @q*B + q*(T-B) == q*T@, balancing the non-gain postings at transacted
-- cost is equivalent, and that is what the balancer does. Whether the gain
-- amount is right is checked afterwards by 'journalAddOrCheckGainPostings'.
--
-- Disposal transactions are recognised by shape, since classification has
-- not run yet: a real posting with a negative lotful or cost-basis amount
-- ('postingHasDisposeShape'; this also matches transfer sources, where a
-- gain posting is later rejected by journalAddOrCheckGainPostings, the
-- gain being zero). Gain postings are recognised in one of two ways:
--
-- 1. By account type: real postings on a Gain-typed account. These may be
--    amountless (unless the first argument is false, in lenient --ignore-lots
--    mode, where there'll be no lot matching to fill the amount in): the
--    balancer leaves such a posting alone and 'journalAddOrCheckGainPostings'
--    sets its amount to the calculated gain.
--
-- 2. Heuristically, when there is no Gain-typed posting: real, amountful
--    postings whose account type is not Asset, Liability or Equity (or a
--    subtype), and which don't carry a lotful or cost-basis amount; accepted
--    only if all postings have amounts and the remaining postings sum to
--    zero at transacted cost (a well-formed disposal), or to an unpriced
--    sale: a lot commodity net sold plus one other commodity net received
--    (which balancing cost inference will resolve). A net purchase with a
--    cash fee posting is not mistaken for a disposal with a gain.
--    This lets a gain posting be written on any account without declaring
--    it type:G, for simple entries.
--
-- Virtual (parenthesised) postings are ignored throughout, as the balancer
-- and the lot machinery ignore them. A transaction which already has a
-- tagged gain posting is returned unchanged, so this is safe to run
-- repeatedly: it runs as a journalFinalise step, and again inside the
-- balancer for callers which balance single entries (hledger add, hledger-web).
transactionTagGainPostings
  :: Bool                                -- ^ also tag amountless Gain-typed postings (not in lenient mode)
  -> Bool                                -- ^ also add visible tags
  -> (AccountName -> Maybe AccountType)  -- ^ account type lookup
  -> (CommoditySymbol -> Bool)           -- ^ is this a lotful commodity ?
  -> (AccountName -> Bool)               -- ^ does this account use lots: NONE ?
  -> Transaction -> Transaction
transactionTagGainPostings :: Bool
-> Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionTagGainPostings Bool
tagamountless Bool
verbosetags CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots Transaction
t
  | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isGainPosting [Posting]
realps  = Transaction
t
  | Bool -> Bool
not ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
hasDisposeShape [Posting]
realps) = Transaction
t
  | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isGainTyped [Posting]
realps     = (Posting -> Bool) -> Transaction
tagPostings Posting -> Bool
isGainTyped
  | Bool
heuristicOk                = (Posting -> Bool) -> Transaction
tagPostings Posting -> Bool
isCandidate
  | Bool
otherwise                  = Transaction
t
  where
    realps :: [Posting]
realps = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter Posting -> Bool
isReal (Transaction -> [Posting]
tpostings Transaction
t)
    hasDisposeShape :: Posting -> Bool
hasDisposeShape = (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Posting
-> Bool
postingHasDisposeShape CommoditySymbol -> Maybe AccountType
lookupAccountType CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol -> Bool
accountUsesNoLots
    isGainTyped :: Posting -> Bool
isGainTyped Posting
p = (Bool
tagamountless Bool -> Bool -> Bool
|| Posting -> Bool
hasAmount Posting
p) Bool -> Bool -> Bool
&& CommoditySymbol -> Maybe AccountType
lookupAccountType (Posting -> CommoditySymbol
paccount Posting
p) Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Gain
    hasLotfulOrBasisAmount :: Posting -> Bool
hasLotfulOrBasisAmount Posting
p =
      (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Amount
a -> Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a) Bool -> Bool -> Bool
|| CommoditySymbol -> Bool
commodityIsLotful (Amount -> CommoditySymbol
acommodity Amount
a)) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
    tagPostings :: (Posting -> Bool) -> Transaction
tagPostings Posting -> Bool
isgain = Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = map tag (tpostings t)}
      where tag :: Posting -> Posting
tag Posting
p = if Posting -> Bool
isReal Posting
p Bool -> Bool -> Bool
&& Posting -> Bool
isgain Posting
p then Bool -> Posting -> Posting
tagGain Bool
verbosetags Posting
p else Posting
p

    -- Heuristic gain candidates, and whether the other postings balance without them.
    isCandidate :: Posting -> Bool
isCandidate Posting
p = Posting -> Bool
hasAmount Posting
p Bool -> Bool -> Bool
&& Posting -> Bool
notALE Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasLotfulOrBasisAmount Posting
p)
      where
        notALE :: Posting -> Bool
notALE Posting
q = case CommoditySymbol -> Maybe AccountType
lookupAccountType (Posting -> CommoditySymbol
paccount Posting
q) of
          Just AccountType
ty -> Bool -> Bool
not (AccountType -> Bool
isAssetType AccountType
ty Bool -> Bool -> Bool
|| AccountType -> Bool
isLiabilityType AccountType
ty Bool -> Bool -> Bool
|| AccountType -> Bool
isEquityType AccountType
ty)
          Maybe AccountType
Nothing -> Bool
True
    heuristicOk :: Bool
heuristicOk =
         (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Posting -> Bool
hasAmount [Posting]
realps          -- with an elided amount, leave it to the balancer
      Bool -> Bool -> Bool
&& Bool -> Bool
not ([Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
candidates)
      Bool -> Bool -> Bool
&& (if Transaction -> Bool
transactionHasCostPostings Transaction
t
            -- with equity conversion postings, the gain counts (see isSetAsideGainPosting):
            -- the whole entry, candidates included, nets to zero
            then MixedAmount -> Bool
mixedAmountIsZero (MixedAmount
residual MixedAmount -> MixedAmount -> MixedAmount
`maPlus` (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
balancingAmount [Posting]
candidates)
            else MixedAmount -> Bool
mixedAmountIsZero MixedAmount
residual   -- well-formed disposal: net zero
              Bool -> Bool -> Bool
|| [Amount] -> Bool
isPricelessClose [Amount]
nonzeroresidual)  -- unpriced sale: cost inference will resolve
      where
        ([Posting]
candidates, [Posting]
noncandidates) = (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Posting -> Bool
isCandidate [Posting]
realps
        residual :: MixedAmount
residual = (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
balancingAmount [Posting]
noncandidates
        -- as the balancer counts it: at cost, unless the cost is represented by conversion postings
        balancingAmount :: Posting -> MixedAmount
balancingAmount Posting
p
          | CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
costPostingTagName Posting
p = MixedAmount -> MixedAmount
mixedAmountStripCosts (Posting -> MixedAmount
pamount Posting
p)
          | Bool
otherwise                          = MixedAmount -> MixedAmount
mixedAmountCost (Posting -> MixedAmount
pamount Posting
p)
        nonzeroresidual :: [Amount]
nonzeroresidual = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Quantity -> Bool) -> (Amount -> Quantity) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity) (MixedAmount -> [Amount]
amountsRaw MixedAmount
residual)
        -- The residual is a lot commodity net closed (sold; or bought, to
        -- cover a short) and one other commodity net received (or paid).
        -- (A net purchase with a cash fee has the opposite signs; there the
        -- fee is not a gain.)
        isPricelessClose :: [Amount] -> Bool
isPricelessClose [Amount]
as = case (Amount -> Bool) -> [Amount] -> ([Amount], [Amount])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (CommoditySymbol -> Bool
isLotCommodity (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) [Amount]
as of
          ([Amount
closed], [Amount
other]) -> (LotDirection -> Bool) -> [LotDirection] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (LotDirection -> Amount -> Bool
`isLotOutflow` Amount
closed) [LotDirection]
disposedirs
                                 Bool -> Bool -> Bool
&& Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
other) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity -> Quantity
forall a. Num a => a -> a
negate (Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
closed))
          ([Amount], [Amount])
_                   -> Bool
False
        isLotCommodity :: CommoditySymbol -> Bool
isLotCommodity CommoditySymbol
c = CommoditySymbol -> Bool
commodityIsLotful CommoditySymbol
c Bool -> Bool -> Bool
|| CommoditySymbol
c CommoditySymbol -> [CommoditySymbol] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (Amount -> CommoditySymbol) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> CommoditySymbol
acommodity [Amount]
disposeamounts
        disposeshaped :: [Posting]
disposeshaped = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter Posting -> Bool
hasDisposeShape [Posting]
realps
        disposeamounts :: [Amount]
disposeamounts = (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]
disposeshaped
        disposedirs :: [LotDirection]
disposedirs = [LotDirection -> Maybe LotDirection -> LotDirection
forall a. a -> Maybe a -> a
fromMaybe LotDirection
Long ((CommoditySymbol -> Maybe AccountType)
-> CommoditySymbol -> Maybe LotDirection
lotDirectionOf CommoditySymbol -> Maybe AccountType
lookupAccountType (Posting -> CommoditySymbol
paccount Posting
p)) | Posting
p <- [Posting]
disposeshaped]

-- | Apply 'transactionTagGainPostings' to each transaction. In lenient
-- (--ignore-lots) mode, amountless gain postings are left untagged, for the
-- balancer to infer like any other posting.
journalTagGainPostings :: Bool -> Bool -> Journal -> Either String Journal
journalTagGainPostings :: Bool -> Bool -> Journal -> Either String Journal
journalTagGainPostings Bool
lenient Bool
verbosetags Journal
j = Journal -> Either String Journal
forall a b. b -> Either a b
Right (Journal -> Either String Journal)
-> Journal -> Either String Journal
forall a b. (a -> b) -> a -> b
$ (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
tag Journal
j
  where
    tag :: Transaction -> Transaction
tag Transaction
t
      | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set CommoditySymbol -> Transaction -> Bool
transactionHasLotfulAmounts Set CommoditySymbol
lotfulcomms Transaction
t = Transaction
t  -- can't be a disposal
      | Bool
otherwise = Bool
-> Bool
-> (CommoditySymbol -> Maybe AccountType)
-> (CommoditySymbol -> Bool)
-> (CommoditySymbol -> Bool)
-> Transaction
-> Transaction
transactionTagGainPostings (Bool -> Bool
not Bool
lenient) Bool
verbosetags (Journal -> CommoditySymbol -> Maybe AccountType
journalAccountType Journal
j) (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
lotfulcomms) (Journal -> CommoditySymbol -> Bool
journalAccountUsesNoLots Journal
j) Transaction
t
    lotfulcomms :: Set CommoditySymbol
lotfulcomms = Journal -> Set CommoditySymbol
journalLotfulCommodities Journal
j

-- | Error for a disposal with a gain posting whose amount was inferred by
-- the balancer because the disposal could only be recognised afterwards
-- (eg its amounts came from a balance assignment).
amountlessErr :: Transaction -> String
amountlessErr :: Transaction -> String
amountlessErr Transaction
t =
  Transaction -> String
txnErrPrefix Transaction
t
  String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This disposal has an amountless gain posting, which can't be inferred here.\n"
  String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Write the amount explicitly, or omit the posting entirely\n"
  String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"(hledger will then infer the realised gain from the cost basis)."

-- | Error for a disposal with more than one amountless gain posting.
multipleAmountlessErr :: Transaction -> String
multipleAmountlessErr :: Transaction -> String
multipleAmountlessErr Transaction
t =
  Transaction -> String
txnErrPrefix Transaction
t
  String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This disposal has more than one amountless gain posting.\n"
  String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"At most one gain posting can have its amount inferred."

-- | Check that no acquire-shaped posting (a real posting with a positive
-- amount, in an asset account) writes both a per-unit cost basis and a
-- transacted cost which disagree. In an acquisition these are the same
-- thing, what the units cost; a typo in either would silently miscalculate
-- gains. (Real-world cases of a basis differing from what was paid, like a
-- gift with carryover basis, are written with the difference funded by a
-- separate posting.)
--
-- They may agree only at the precision of the written basis: typically a
-- non-terminating unit cost rendered to 8 decimal places by print (as a
-- basis annotation or in a lot subaccount name), re-read alongside its
-- exact @@ total cost. Then the exact transacted unit cost replaces the
-- written basis, so nothing is lost in the round trip.
--
-- This runs before transaction balancing, so that such an entry gets this
-- error rather than an unbalanced-transaction error; it needs only the
-- amounts as written (after 'journalInferPostingsTransactedCost').
journalCheckAcquireBasis :: Journal -> Either String Journal
journalCheckAcquireBasis :: Journal -> Either String Journal
journalCheckAcquireBasis Journal
j = do
  ts <- (Transaction -> Either String Transaction)
-> [Transaction] -> Either String [Transaction]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Transaction -> Either String Transaction
checkTxn (Journal -> [Transaction]
jtxns Journal
j)
  Right j{jtxns = ts}
  where
    checkTxn :: Transaction -> Either String Transaction
checkTxn Transaction
t = do
      ps <- ((Int, Posting) -> Either String Posting)
-> [(Int, Posting)] -> Either String [Posting]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Int, Posting) -> Either String Posting
checkPosting ([Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t))
      Right $ txnTieKnot t{tpostings = ps}
      where
        checkPosting :: (Int, Posting) -> Either String Posting
checkPosting (Int
idx, Posting
p)
          | Posting -> Bool
isReal Posting
p, Just LotDirection
dir <- Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j (Posting -> CommoditySymbol
paccount Posting
p) = do
              as <- (Amount -> Either String Amount)
-> [Amount] -> Either String [Amount]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (LotDirection -> Int -> Posting -> Amount -> Either String Amount
checkAmount LotDirection
dir Int
idx Posting
p) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
              Right p{pamount = mixed as}
          | Bool
otherwise = Posting -> Either String Posting
forall a b. b -> Either a b
Right Posting
p
        checkAmount :: LotDirection -> Int -> Posting -> Amount -> Either String Amount
checkAmount LotDirection
dir Int
idx Posting
p Amount
a = case (Amount -> Maybe CostBasis
acostbasis Amount
a, Amount -> Maybe AmountCost
acost Amount
a) of
          (Just cb :: CostBasis
cb@CostBasis{cbCost :: CostBasis -> Maybe Amount
cbCost = Just Amount
basis}, Just AmountCost
tc)
            | LotDirection -> Amount -> Bool
isLotInflow LotDirection
dir Amount
a  -- acquire-shaped (a disposal's basis and sale price are expected to differ)
            , let transacted :: Amount
transacted = Quantity -> AmountCost -> Amount
amountCostToUnitCost (Amount -> Quantity
aquantity Amount
a) AmountCost
tc
            -> CostBasis -> Amount -> Amount -> Either String Amount
checkBasis CostBasis
cb Amount
basis Amount
transacted
          (Maybe CostBasis, Maybe AmountCost)
_ -> Amount -> Either String Amount
forall a b. b -> Either a b
Right Amount
a
          where
            checkBasis :: CostBasis -> Amount -> Amount -> Either String Amount
checkBasis CostBasis
cb Amount
basis Amount
transacted
              | Amount -> Quantity
aquantity Amount
basis Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
transacted = Amount -> Either String Amount
forall a b. b -> Either a b
Right Amount
a
              | Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo (Amount -> Word8
writtenPlaces Amount
basis) (Amount -> Quantity
aquantity Amount
transacted) Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Quantity
aquantity Amount
basis
                  = Amount -> Either String Amount
forall a b. b -> Either a b
Right Amount
a{acostbasis = Just cb{cbCost = Just transacted}}
              | Bool
otherwise = String -> Either String Amount
forall a b. a -> Either a b
Left (Transaction -> Int -> Posting -> Amount -> Amount -> String
acquireBasisErr Transaction
t Int
idx Posting
p Amount
basis Amount
transacted)
        writtenPlaces :: Amount -> Word8
writtenPlaces = Quantity -> Word8
forall i. DecimalRaw i -> Word8
decimalPlaces (Quantity -> Word8) -> (Amount -> Quantity) -> Amount -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity  -- trailing zeros included: {$46.00} is not $45.56

    acquireBasisErr :: Transaction -> Int -> Posting -> Amount -> Amount -> String
acquireBasisErr Transaction
t Int
idx Posting
p Amount
basis Amount
transacted =
      String -> String -> Int -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" String
f Int
l (CommoditySymbol -> String
T.unpack CommoditySymbol
ex)
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This acquire posting's cost basis (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
basisStr
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
") differs from its transacted cost (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
transactedStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
").\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Options:\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  - drop {} or {{}} so basis is inferred from the transacted cost\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  - drop @ or @@ so transacted cost is inferred from the basis\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  - use {{TotalCost}} or write the per-unit basis at higher precision\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  - if the difference is real (gift, NSO, RSU, etc.), fund it via a separate posting"
      where
        col1 :: Int
col1 = Int
5 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ if Posting -> Bool
isVirtual Posting
p then Int
1 else Int
0
        col2 :: Int
col2 = Int
col1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ CommoditySymbol -> Int
T.length (Posting -> CommoditySymbol
paccount (Posting -> CommoditySymbol) -> Posting -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> Posting
originalPosting Posting
p) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1
        (String
f, Int
l, Maybe (Int, Maybe Int)
_mcols, CommoditySymbol
ex) = Transaction
-> Int
-> Maybe (Int, Maybe Int)
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makePostingErrorExcerptByIndex (Transaction -> Transaction
transactionAsWritten Transaction
t) (Transaction -> Int -> Int
asWrittenPostingIndex Transaction
t Int
idx) ((Int, Maybe Int) -> Maybe (Int, Maybe Int)
forall a. a -> Maybe a
Just (Int
col1, Int -> Maybe Int
forall a. a -> Maybe a
Just Int
col2))
        (String
basisStr, String
transactedStr) =
          AmountFormat -> Amount -> Amount -> (String, String)
showAmountsDistinctly AmountFormat
oneLineNoCostFmt{displayZeroCommodity=True} Amount
basis Amount
transacted

-- | For each disposal transaction with a transacted price, add a realised-gain
-- posting to a 'Gain'-type account (default @revenues:gain@) with
-- the negated gain amount; or if the transaction already has gain posting(s)
-- (user-written; see 'transactionTagGainPostings'), check that their sum
-- matches the calculated gain.
--
-- With the gain posting present, the disposal balances at cost basis, and
-- no counter posting is needed: hledger records gains by the historical cost
-- convention, in which unrealised gains are not posted (though they can be
-- reported from market prices).
--
-- The gain amount is the disposal gain: for each dispose posting amount with
-- both a cost basis and a transacted cost, contribute @aquantity * (B - T)@
-- (equivalently: cost-basis value minus transacted-cost value). Acquire and
-- other postings do not contribute. Eg for @-5 AAPL {$50} \@ $70@: gain
-- contribution is @-5 * ($50 - $70) = $100@.
--
-- Runs after 'journalCalculateLots' so that cost basis is populated on dispose
-- postings. The generated posting carries the @_generated-posting@ hidden tag,
-- visible as @generated-posting:@ in @print --verbose-tags@.
journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal
journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal
journalAddOrCheckGainPostings Bool
verbosetags Journal
j = do
    txns' <- (Transaction -> Either String Transaction)
-> [Transaction] -> Either String [Transaction]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\Transaction
t -> (String -> String)
-> Either String Transaction -> Either String Transaction
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Transaction -> String -> String
appendPostingsReadAs Transaction
t) (Either String Transaction -> Either String Transaction)
-> Either String Transaction -> Either String Transaction
forall a b. (a -> b) -> a -> b
$ Transaction -> Either String Transaction
addOrCheck Transaction
t) (Journal -> [Transaction]
jtxns Journal
j)
    Right j{jtxns = txns'}
  where
    atypes :: Map CommoditySymbol AccountType
atypes = Journal -> Map CommoditySymbol AccountType
jaccounttypes Journal
j
    gainAccount :: CommoditySymbol
gainAccount = Journal -> CommoditySymbol
journalBaseGainAccount Journal
j

    -- Within a disposal, gain postings are identified by the _ptype:gain
    -- hidden tag (added by transactionTagGainPostings), or by account type
    -- (declared or inferred from name). Only real postings count, as in
    -- transactionTagGainPostings and the balancer.
    isGainTyped :: Posting -> Bool
isGainTyped Posting
p = Posting -> Bool
isReal Posting
p Bool -> Bool -> Bool
&& Map CommoditySymbol AccountType
-> CommoditySymbol -> Maybe AccountType
accountNameType Map CommoditySymbol AccountType
atypes (Posting -> CommoditySymbol
paccount Posting
p) Maybe AccountType -> Maybe AccountType -> Bool
forall a. Eq a => a -> a -> Bool
== AccountType -> Maybe AccountType
forall a. a -> Maybe a
Just AccountType
Gain
    isGain :: Posting -> Bool
isGain Posting
p = Posting -> Bool
isReal Posting
p Bool -> Bool -> Bool
&& (Posting -> Bool
isGainPosting Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
isGainTyped Posting
p)
    disposeHasPrice :: Posting -> Bool
disposeHasPrice Posting
p = Posting -> Bool
isDisposePosting Posting
p Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))

    addOrCheck :: Transaction -> Either String Transaction
addOrCheck Transaction
t
      | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isGainPosting [Posting]
ps           = Transaction -> Either String Transaction
fillOrCheck Transaction
t  -- tagged gain posting(s), possibly in a non-disposal (then the gain is zero)
      | Bool -> Bool
not ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
disposeHasPrice [Posting]
ps)   = Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
t
      | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isAmountlessGain [Posting]
ps        = String -> Either String Transaction
forall a b. a -> Either a b
Left (Transaction -> String
amountlessErr Transaction
t)
      | (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isGainTyped [Posting]
ps             = Transaction -> Either String Transaction
checkGain Transaction
t
      | Bool
otherwise                      = Transaction -> Either String Transaction
forall a b. b -> Either a b
Right (Transaction -> Transaction
addGain Transaction
t)
      where
        ps :: [Posting]
ps = Transaction -> [Posting]
tpostings Transaction
t
        -- An untagged gain posting the user left amountless: the disposal was
        -- not recognisable when the balancer tagged gain postings, so it has
        -- inferred an amount for it by now, which can't be corrected; check
        -- the original posting. (Rare: balance assignments are resolved before
        -- tagging, so the #2686 shape no longer gets here.)
        isAmountlessGain :: Posting -> Bool
isAmountlessGain Posting
p = Posting -> Bool
isGainTyped Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasAmount (Posting -> Posting
originalPosting Posting
p))

    -- With tagged gain postings: if exactly one is amountless, set its amount
    -- to the calculated gain (less any other written gain amounts); otherwise
    -- check the written amount(s).
    fillOrCheck :: Transaction -> Either String Transaction
fillOrCheck Transaction
t = case (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Posting
p -> Posting -> Bool
isGain Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p)) (Transaction -> [Posting]
tpostings Transaction
t) of
      []  -> Transaction -> Either String Transaction
checkGain Transaction
t
      [Posting
_] -> Transaction -> Either String Transaction
forall a b. b -> Either a b
Right (Transaction -> Transaction
fillGain Transaction
t)
      [Posting]
_   -> String -> Either String Transaction
forall a b. a -> Either a b
Left (Transaction -> String
multipleAmountlessErr Transaction
t)

    fillGain :: Transaction -> Transaction
fillGain Transaction
t = Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = map fill (tpostings t)}
      where
        ps :: [Posting]
ps      = Transaction -> [Posting]
tpostings Transaction
t
        gain :: MixedAmount
gain    = (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
postingDisposalGain [Posting]
ps
        written :: MixedAmount
written = (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
pamount ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Posting
p -> Posting -> Bool
isGain Posting
p Bool -> Bool -> Bool
&& Posting -> Bool
hasAmount Posting
p) [Posting]
ps)
        amt :: MixedAmount
amt     = Transaction -> MixedAmount -> MixedAmount
setLocalGainPrecision Transaction
t (MixedAmount -> MixedAmount
maNegate MixedAmount
gain MixedAmount -> MixedAmount -> MixedAmount
forall a. Semigroup a => a -> a -> a
<> MixedAmount -> MixedAmount
maNegate MixedAmount
written)
        fill :: Posting -> Posting
fill Posting
p
          | Posting -> Bool
isGain Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p) = Posting
p{pamount = amt, poriginal = Just (originalPosting p)}
          | Bool
otherwise                      = Posting
p

    addGain :: Transaction -> Transaction
addGain Transaction
t
      | MixedAmount -> Bool
mixedAmountIsZero MixedAmount
gain = Transaction
t
      | Bool
otherwise = Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = tpostings t ++ [gainP]}
      where
        gain :: MixedAmount
gain   = (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
postingDisposalGain (Transaction -> [Posting]
tpostings Transaction
t)
        gainP :: Posting
gainP = Bool -> CommoditySymbol -> MixedAmount -> Posting
mkGeneratedGainPosting Bool
verbosetags CommoditySymbol
gainAccount (Transaction -> MixedAmount -> MixedAmount
setLocalGainPrecision Transaction
t (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount -> MixedAmount
maNegate MixedAmount
gain)

    -- Check that the user-written gain amount(s) sum to the calculated
    -- disposal gain (negated). The gain is zero when there is no priced
    -- disposal, eg a gain posting mistakenly written in a lot transfer.
    -- Like the balancer, this tolerates a difference below the precision
    -- chosen by setLocalGainPrecision; the written amounts are then made
    -- exact, so the difference isn't left unaccounted for.
    checkGain :: Transaction -> Either String Transaction
checkGain Transaction
t
      | MixedAmount -> Bool
mixedAmountLooksZero (Transaction -> MixedAmount -> MixedAmount
setLocalGainPrecision Transaction
t MixedAmount
diff) = Transaction -> Either String Transaction
forall a b. b -> Either a b
Right Transaction
exactGain
      | Bool
otherwise = String -> Either String Transaction
forall a b. a -> Either a b
Left (Transaction -> MixedAmount -> MixedAmount -> String
mismatchErr Transaction
t MixedAmount
gain MixedAmount
writtenGain)
      where
        ps :: [Posting]
ps          = Transaction -> [Posting]
tpostings Transaction
t
        gain :: MixedAmount
gain        = (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
postingDisposalGain [Posting]
ps
        writtenGain :: MixedAmount
writtenGain = (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
pamount ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter Posting -> Bool
isGain [Posting]
ps)
        diff :: MixedAmount
diff        = MixedAmount
writtenGain MixedAmount -> MixedAmount -> MixedAmount
forall a. Semigroup a => a -> a -> a
<> MixedAmount
gain  -- writtenGain should equal -gain
        exactGain :: Transaction
exactGain = case (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Quantity -> Bool) -> (Amount -> Quantity) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity) (MixedAmount -> [Amount]
amountsRaw MixedAmount
diff) of
          [] -> Transaction
t
          [Amount]
as -> Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = foldr subtractFromLastGain ps as}
        -- Subtract a small difference from the last gain posting in its commodity
        -- (or the last gain posting), keeping the written amount for print.
        subtractFromLastGain :: Amount -> [Posting] -> [Posting]
subtractFromLastGain Amount
a [Posting]
qs = [Posting] -> [Posting]
forall a. [a] -> [a]
reverse ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ case (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Posting -> Bool
target ([Posting] -> [Posting]
forall a. [a] -> [a]
reverse [Posting]
qs) of
          ([Posting]
xs, Posting
q:[Posting]
ys) -> [Posting]
xs [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ Posting
q{pamount = setLocalGainPrecision t (pamount q <> maNegate (mixedAmount a))
                               ,poriginal = Just (originalPosting q)} Posting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
: [Posting]
ys
          ([Posting]
xs, [])   -> [Posting]
xs
          where
            target :: Posting -> Bool
target = if (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
inCommodity [Posting]
qs then Posting -> Bool
inCommodity else Posting -> Bool
isGain
            inCommodity :: Posting -> Bool
inCommodity Posting
q = Posting -> Bool
isGain Posting
q Bool -> Bool -> Bool
&& Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> [CommoditySymbol] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (Amount -> CommoditySymbol) -> [Amount] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> CommoditySymbol
acommodity (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q))

    -- Set each component amount's display precision to the entry's local
    -- precision for that commodity.
    -- Special rule for the 0 decimals case (when the local precision is 0,
    -- or there are no amounts of the commodity present):
    -- display with 2 decimals if either of them is non-zero, otherwise
    -- display with 0 decimals.
    -- The full precision is preserved internally, so reports like
    -- `print -c '$1.0000' --round=soft` can still reveal sub-cent detail.
    setLocalGainPrecision :: Transaction -> MixedAmount -> MixedAmount
setLocalGainPrecision Transaction
t = (Amount -> Amount) -> MixedAmount -> MixedAmount
mapMixedAmount Amount -> Amount
setOne
      where
        styles :: Map CommoditySymbol AmountStyle
styles = Transaction -> Map CommoditySymbol AmountStyle
transactionCommodityStyles Transaction
t
        setOne :: Amount -> Amount
setOne a :: Amount
a@Amount{aquantity :: Amount -> Quantity
aquantity = Quantity
q, astyle :: Amount -> AmountStyle
astyle = AmountStyle
s} =
          case 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
            Just AmountStyle{asprecision :: AmountStyle -> AmountPrecision
asprecision = Precision Word8
n} | Word8
n Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
1 ->
              Amount
a{astyle = s{asprecision = Precision n}}
            Maybe AmountStyle
_ ->
              let q2 :: Quantity
q2 = Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
2 Quantity
q
              in if Word8 -> Quantity -> Quantity
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
0 Quantity
q2 Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
q2
                 then Amount
a{astyle = s{asprecision = Precision 0}}
                 else Amount
a{astyle = s{asprecision = Precision 2}}

    mismatchErr :: Transaction -> MixedAmount -> MixedAmount -> String
mismatchErr Transaction
t MixedAmount
gain MixedAmount
writtenGain =
      Transaction -> String
txnErrPrefix Transaction
t
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This disposal's realised gain amount is wrong.\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  written:    " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
writtenStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n"
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  calculated: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
calculatedStr
      where
        (String
writtenStr, String
calculatedStr) =
          AmountFormat -> MixedAmount -> MixedAmount -> (String, String)
showMixedAmountsDistinctly AmountFormat
oneLineNoCostFmt{displayZeroCommodity=True}
            MixedAmount
writtenGain (MixedAmount -> MixedAmount
maNegate MixedAmount
gain)

    -- | The realised-capital-gain contribution from a single posting.
    --
    -- Sums 'amountBasisVsTransactedGap' across the posting's amounts,
    -- treating each non-zero gap as realised gain on the lot units changing
    -- hands. Eg @assets:broker -5 AAPL {$50} \@ $70@ contributes
    -- @-5 * ($50 - $70) = $100@ — five shares sold at a $20 profit each.
    --
    -- Acquire postings are excluded: a fresh acquisition with
    -- @basis ≠ transacted@ is a carryover or bookkeeping imbalance, not
    -- realised gain, and is dealt with separately. Every other kind of
    -- posting contributes, including postings the lot classifier did not
    -- explicitly tag as @_ptype:dispose@ (eg a fee paid in lot-tracked
    -- stock — its disposal economics are real even without the tag).
    postingDisposalGain :: Posting -> MixedAmount
    postingDisposalGain :: Posting -> MixedAmount
postingDisposalGain Posting
p
      | Posting -> Bool
isAcquirePosting Posting
p = MixedAmount
nullmixedamt
      | Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p)  = MixedAmount
nullmixedamt
      | 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
amountBasisVsTransactedGap (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))

    -- | The per-amount cost-basis-vs-transacted-cost gap.
    --
    -- An amount can carry two unit prices: its /cost basis/ from a @{...}@
    -- annotation, and its /transacted cost/ from @\@@ or @\@\@@. When both
    -- are present, this returns @aquantity * (basis - transacted)@,
    -- equivalently the amount's value at cost basis minus its value at
    -- transacted cost. Returns 'nullmixedamt' if either side is missing.
    --
    -- Pure arithmetic; the caller decides what the gap /means/ in context
    -- (realised gain on a disposal, carryover/imbalance on an acquire, etc).
    amountBasisVsTransactedGap :: Amount -> MixedAmount
    amountBasisVsTransactedGap :: Amount -> MixedAmount
amountBasisVsTransactedGap Amount
a = case (Amount -> Maybe CostBasis
acostbasis Amount
a Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost, Amount -> Maybe AmountCost
acost Amount
a) of
      (Just Amount
basisCost, Just AmountCost
transactedCost) ->
        let basisVal :: MixedAmount
basisVal      = Amount -> MixedAmount
mixedAmount Amount
basisCost{aquantity = multiplyQuantities (aquantity a) (aquantity basisCost)}
            transactedVal :: MixedAmount
transactedVal = case AmountCost
transactedCost of
              UnitCost  Amount
c -> Amount -> MixedAmount
mixedAmount Amount
c{aquantity = multiplyQuantities (aquantity a) (aquantity c)}
              TotalCost Amount
c -> Amount -> MixedAmount
mixedAmount Amount
c
        in MixedAmount
basisVal MixedAmount -> MixedAmount -> MixedAmount
forall a. Semigroup a => a -> a -> a
<> MixedAmount -> MixedAmount
maNegate MixedAmount
transactedVal
      (Maybe Amount, Maybe AmountCost)
_ -> MixedAmount
nullmixedamt

-- | Collapse lot-tracking detail from a journal for display when --lots is off.
-- Makes these targeted changes to each transaction:
--
-- * drops postings tagged @_lot-parent-assertion@ (synthetic balance-assertion
--   carriers added when splitting a posting into lot subaccounts);
-- * strips any lot subaccount (the trailing @{...}@ component) from each remaining
--   posting's account name;
-- * merges per-lot split fragments back into one posting (see mergeLotSplits).
--
-- Lot-inferred cost basis annotations (@acostbasis@) are kept on the amounts:
-- 'print' shows them, so that lot entries are self-describing and can be
-- re-read without the commodity's @lots:@ declaration (under the default
-- method). A merged multi-lot posting gets an unspecified basis (@{}@),
-- meaning "lots selected by the account's method".
--
-- Postings tagged @_feesplit-posting@ (synthetic fee fragments from auto-split) are
-- retained so transactions stay balanced in reports like 'print'.
--
-- 'print' relies on its existing 'transactionWithMostlyOriginalPostings' logic to
-- revert pamount to 'poriginal' when displaying non-explicit output (carrying
-- the inferred basis over).
--
-- Journals with no lot content are returned unchanged.
journalCollapseLotDetail :: Journal -> Journal
journalCollapseLotDetail :: Journal -> Journal
journalCollapseLotDetail Journal
j
  | (Transaction -> Bool) -> [Transaction] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
needsCollapse ([Posting] -> Bool)
-> (Transaction -> [Posting]) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings) (Journal -> [Transaction]
jtxns Journal
j) = (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
collapseTransaction Journal
j
  | Bool
otherwise                                      = Journal
j
  where
    needsCollapse :: Posting -> Bool
needsCollapse Posting
p = CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
feesplitPostingTagName Posting
p
                   Bool -> Bool -> Bool
|| CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotsplitPostingTagName Posting
p
                   Bool -> Bool -> Bool
|| CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotParentAssertionTagName Posting
p
                   Bool -> Bool -> Bool
|| Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isJust (CommoditySymbol -> Maybe CommoditySymbol
lotSubaccountName (Posting -> CommoditySymbol
paccount Posting
p))

    collapseTransaction :: Transaction -> Transaction
collapseTransaction Transaction
t =
      Transaction -> Transaction
txnTieKnot Transaction
t{tpostings = mergeLotSplits (mapMaybe collapsePosting (tpostings t))}

    collapsePosting :: Posting -> Maybe Posting
collapsePosting Posting
p
      | CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotParentAssertionTagName Posting
p = Maybe Posting
forall a. Maybe a
Nothing
      | Bool
otherwise = Posting -> Maybe Posting
forall a. a -> Maybe a
Just Posting
p
          { paccount          = newAcct
          -- An assertion originally written on the base account (eg by CSV
          -- balanceN rules) targets the parent, which is what this collapsed
          -- posting shows again; keep it, so writing out the collapsed view
          -- (eg by import) preserves it. But an assertion the user wrote on
          -- the lot subaccount itself asserts that lot's balance, which was
          -- checked against the pre-collapse paccount during journalFinalise;
          -- drop it here so the collapsed view isn't re-validated against
          -- the parent total.
          , pbalanceassertion =
              if newAcct == paccount p || originalAcct == newAcct
              then pbalanceassertion p
              else Nothing
          }
      where
        newAcct :: CommoditySymbol
newAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
        -- The account the user actually wrote (before lot processing).
        originalAcct :: CommoditySymbol
originalAcct = Posting -> CommoditySymbol
paccount (Posting -> Posting
originalPosting Posting
p)

    -- Merge consecutive lotsplit-tagged postings that share the same original
    -- (poriginal) into one. The survivor's pamount is taken from its
    -- 'poriginal' (the user's full original amount); the lotsplit tag (and
    -- its visible copy, if --verbose-tags added one) is removed, so the rest
    -- of the pipeline sees a normal single posting.
    -- Sharing 'poriginal' identifies siblings from the same per-lot split,
    -- distinguishing them from unrelated lotsplit postings (eg the from- and
    -- to-side runs of a same-account transfer).
    mergeLotSplits :: [Posting] -> [Posting]
mergeLotSplits = [Posting] -> [Posting]
go
      where
        go :: [Posting] -> [Posting]
go [] = []
        go (Posting
p:[Posting]
ps)
          | CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotsplitPostingTagName Posting
p =
              let sameRun :: Posting -> Bool
sameRun Posting
q = CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotsplitPostingTagName Posting
q Bool -> Bool -> Bool
&& Posting -> Maybe Posting
poriginal Posting
q Maybe Posting -> Maybe Posting -> Bool
forall a. Eq a => a -> a -> Bool
== Posting -> Maybe Posting
poriginal Posting
p
                  ([Posting]
run, [Posting]
rest) = (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span Posting -> Bool
sameRun [Posting]
ps
                  -- The merged posting's amount is the sum of the run's
                  -- (already-collapsed) fragment amounts. This equals the
                  -- original's amount, except when the original had no amount
                  -- (elided or a balance assignment - using the original would
                  -- lose the amount entirely) or when a fee portion was split
                  -- off (using the original would double-count the retained
                  -- feesplit posting's amount). (#2692)
                  -- Summing several fragments drops their cost bases; show
                  -- instead the basis fields on which all the fragments'
                  -- lots agree (eg the date and cost, when only the labels
                  -- differ), as a selector which re-reads equivalently: it
                  -- is at least as specific as the user's, and the method
                  -- still picks the same lots first (#2843).
                  merged :: MixedAmount
merged = [MixedAmount] -> MixedAmount
forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum ((Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
pamount (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
run))
                  cbs :: [CostBasis]
cbs = [CostBasis
cb | Amount
a <- (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
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
run), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]]
                  survivor :: Posting
survivor = ((CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingRemoveHiddenAndVisibleTag (CommoditySymbol
lotsplitPostingTagName, CommoditySymbol
"") Posting
p){pamount = if null run || null cbs then merged else mapMixedAmount commonBasis merged}
                  commonBasis :: Amount -> Amount
commonBasis Amount
a = Amount
a{acostbasis = Just CostBasis
                    { cbDate  = agreed cbDate
                    , cbLabel = agreed cbLabel
                    , cbCost  = agreed cbCost
                    }}
                  agreed :: (CostBasis -> Maybe a) -> Maybe a
agreed CostBasis -> Maybe a
f = case (CostBasis -> Maybe a) -> [CostBasis] -> [Maybe a]
forall a b. (a -> b) -> [a] -> [b]
map CostBasis -> Maybe a
f [CostBasis]
cbs of
                    (Maybe a
v:[Maybe a]
vs) | (Maybe a -> Bool) -> [Maybe a] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Maybe a -> Maybe a -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe a
v) [Maybe a]
vs -> Maybe a
v
                    [Maybe a]
_ -> Maybe a
forall a. Maybe a
Nothing
              in Posting
survivor Posting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
: [Posting] -> [Posting]
go [Posting]
rest
          | Bool
otherwise = Posting
p Posting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
: [Posting] -> [Posting]
go [Posting]
ps

-- Posting type predicates

-- | When an implicit-lot-subaccount posting (one whose account was a plain account,
-- not already a lot subaccount) is converted to explicit lot subaccount posting(s),
-- and it had a balance assertion, move the assertion to a new zero-amount generated
-- posting on the original parent account, making it subaccount-inclusive (=* style).
-- This preserves the assertion's meaning when the output is re-read without --lots:
-- the assertion checks the total of all lot subaccounts rather than the (empty)
-- direct balance of the parent.
-- If the original account was already a lot subaccount, the split postings are
-- returned unchanged (the assertion already targets the right account).
preserveParentAssertion :: Bool -> AccountName -> Maybe BalanceAssertion -> [Posting] -> [Posting]
preserveParentAssertion :: Bool
-> CommoditySymbol
-> Maybe BalanceAssertion
-> [Posting]
-> [Posting]
preserveParentAssertion Bool
_           CommoditySymbol
_        Maybe BalanceAssertion
Nothing  [Posting]
ps = [Posting]
ps
preserveParentAssertion Bool
_           CommoditySymbol
origAcct (Just BalanceAssertion
_) [Posting]
ps
    | CommoditySymbol -> CommoditySymbol
lotBaseAccount CommoditySymbol
origAcct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
origAcct = [Posting]
ps  -- already an explicit lot subaccount; leave as-is
preserveParentAssertion Bool
verbosetags CommoditySymbol
origAcct (Just BalanceAssertion
ba) [Posting]
ps =
    (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (\Posting
p -> Posting
p{pbalanceassertion = Nothing}) [Posting]
ps
    [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ [ Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
lotParentAssertionTagName, CommoditySymbol
"")
       (Posting -> Posting) -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
generatedPostingTagName, CommoditySymbol
"")
           Posting
nullposting
             { paccount          = origAcct
             , pamount           = mixedAmount (baamount ba){aquantity = 0}
             , pbalanceassertion = Just ba{bainclusive = True}
             } ]

-- | Check if a posting has any lot-related ptype tag.
isLotPosting :: Posting -> Bool
isLotPosting :: Posting -> Bool
isLotPosting Posting
p = Posting -> Bool
isAcquirePosting Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
isDisposePosting Posting
p
             Bool -> Bool -> Bool
|| Posting -> Bool
isTransferFromPosting Posting
p Bool -> Bool -> Bool
|| Posting -> Bool
isTransferToPosting Posting
p
             Bool -> Bool -> Bool
|| Posting -> Bool
isGainPosting Posting
p

-- | True if this posting has any _ptype tag (was classified by lot classification,
-- or is a generated gain posting).
isClassifiedPosting :: Posting -> Bool
isClassifiedPosting :: Posting -> Bool
isClassifiedPosting Posting
p = ((CommoditySymbol, CommoditySymbol) -> Bool)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
"_ptype") (CommoditySymbol -> Bool)
-> ((CommoditySymbol, CommoditySymbol) -> CommoditySymbol)
-> (CommoditySymbol, CommoditySymbol)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol, CommoditySymbol) -> CommoditySymbol
forall a b. (a, b) -> a
fst) (Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p)

-- | Check if a posting is an acquire posting (has _ptype:acquire tag).
isAcquirePosting :: Posting -> Bool
isAcquirePosting :: Posting -> Bool
isAcquirePosting Posting
p = (CommoditySymbol
"_ptype", CommoditySymbol
"acquire") (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p

-- | Check if a posting is a dispose posting (has _ptype:dispose tag).
isDisposePosting :: Posting -> Bool
isDisposePosting :: Posting -> Bool
isDisposePosting Posting
p = (CommoditySymbol
"_ptype", CommoditySymbol
"dispose") (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p

-- | Check if a posting is a transfer-from posting (has _ptype:transfer-from tag).
isTransferFromPosting :: Posting -> Bool
isTransferFromPosting :: Posting -> Bool
isTransferFromPosting Posting
p = (CommoditySymbol
"_ptype", CommoditySymbol
"transfer-from") (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p

-- | Check if a posting is a transfer-to posting (has _ptype:transfer-to tag).
isTransferToPosting :: Posting -> Bool
isTransferToPosting :: Posting -> Bool
isTransferToPosting Posting
p = (CommoditySymbol
"_ptype", CommoditySymbol
"transfer-to") (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p

-- | Check if a posting is a gain posting (has _ptype:gain tag):
-- user-written and tagged by transactionTagGainPostings, or generated by
-- journalAddOrCheckGainPostings.
isGainPosting :: Posting -> Bool
isGainPosting :: Posting -> Bool
isGainPosting Posting
p = (CommoditySymbol
"_ptype", CommoditySymbol
"gain") (CommoditySymbol, CommoditySymbol)
-> [(CommoditySymbol, CommoditySymbol)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p

-- | Is this a gain posting which the transaction balancer should set aside ?
-- A disposal's gain posting is set aside so that the entry, with the disposal
-- counted at transacted cost, balances at cost basis (see
-- 'transactionTagGainPostings'). But when the entry has equity conversion
-- postings (a posting tagged as a cost posting), the disposal's cost is
-- ignored and the conversion postings carry the cost basis instead, so the
-- gain posting counts like any other.
isSetAsideGainPosting :: Transaction -> Posting -> Bool
isSetAsideGainPosting :: Transaction -> Posting -> Bool
isSetAsideGainPosting Transaction
t = \Posting
p -> Posting -> Bool
isGainPosting Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
hascostpostings  -- partially applied, the scan is shared
  where hascostpostings :: Bool
hascostpostings = Transaction -> Bool
transactionHasCostPostings Transaction
t

-- | Does this transaction have a posting tagged as a cost posting,
-- ie one whose cost is represented by equity conversion postings ?
transactionHasCostPostings :: Transaction -> Bool
transactionHasCostPostings :: Transaction -> Bool
transactionHasCostPostings = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
costPostingTagName) ([Posting] -> Bool)
-> (Transaction -> [Posting]) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings

-- | Does this posting carry a cost basis annotation that was copied into it
-- by the transaction balancer, rather than written by the user ?
-- True when the posting's amount was wholly inferred (its original had no
-- amount) yet carries a cost basis annotation: the balancer fills elided
-- postings with the negated sum of the other postings' amounts, and any
-- basis annotation rides along incidentally.
--
-- Such an annotation is not a lot selector - a cost basis annotation is
-- posting-specific user intent - but we deliberately keep it until lot
-- classification has run, when it identifies the elided destination or
-- source of a lot transfer (see 'isMirroredTransferCandidate' - the
-- mirrored posting of eg @stocks -5 AAPL {$50} / cash@ could equally be
-- the artifact of a sale missing its price, but the dispose reading would
-- fail for lack of a price, so the transfer reading is preferred).
-- Mirrored postings which can't be a transfer counterpart stay
-- unclassified and invisible to counterpart detection; afterwards
-- 'journalStripBalancerCopiedBases' removes their annotations, so
-- downstream code and reports only ever see user-written or
-- lot-machinery-derived cost bases.
hasBalancerCopiedBasis :: Posting -> Bool
hasBalancerCopiedBasis :: Posting -> Bool
hasBalancerCopiedBasis Posting
p =
  Bool -> Bool
not (Posting -> Bool
hasAmount (Posting -> Posting
originalPosting Posting
p)) Bool -> Bool -> Bool
&& (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CostBasis -> Bool)
-> (Amount -> Maybe CostBasis) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe CostBasis
acostbasis) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))

-- | Remove balancer-copied cost basis annotations (see
-- 'hasBalancerCopiedBasis') from postings that lot classification left
-- unclassified, now that lot processing has used them as evidence.
-- Lot-processed (classified) postings are left alone: lot calculation
-- legitimately gives machinery-derived cost bases to postings whose amounts
-- were inferred, eg the per-lot fragments of an elided transfer source.
journalStripBalancerCopiedBases :: Journal -> Journal
journalStripBalancerCopiedBases :: Journal -> Journal
journalStripBalancerCopiedBases = (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
strip
  where
    strip :: Posting -> Posting
strip Posting
p
      | Posting -> Bool
hasBalancerCopiedBasis Posting
p Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
isClassifiedPosting Posting
p) =
          Posting
p{pamount = mapMixedAmount (\Amount
a -> Amount
a{acostbasis = Nothing}) (pamount p)}
      | Bool
otherwise = Posting
p

-- | True if this posting involves a lotful commodity in an asset account
-- but has no _ptype tag (wasn't classified as acquire/dispose/transfer/gain).
-- Postings with zero amount in the lotful commodity are exempt (no lot tracking needed).
isUnclassifiedLotfulPosting :: Journal -> Posting -> Bool
isUnclassifiedLotfulPosting :: Journal -> Posting -> Bool
isUnclassifiedLotfulPosting Journal
j Posting
p =
  Posting -> Bool
isReal Posting
p
  Bool -> Bool -> Bool
&& Posting -> Bool
hasAmount Posting
p
  Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
isLotPosting Posting
p)
  Bool -> Bool -> Bool
&& Maybe LotDirection -> Bool
forall a. Maybe a -> Bool
isJust (Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j (Posting -> CommoditySymbol
paccount Posting
p))  -- an asset or liability account
  -- lots: NONE accounts' postings are exempt (not lot-tracked).
  Bool -> Bool -> Bool
&& Bool -> Bool
not (Journal -> CommoditySymbol -> Bool
journalAccountUsesNoLots Journal
j (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)))
  Bool -> Bool -> Bool
&& Bool
hasNonzeroLotfulAmount
  -- Postings with balancer-copied basis annotations are deliberately left
  -- unclassified (see 'hasBalancerCopiedBasis'); the posting they mirror
  -- produces the relevant error.
  Bool -> Bool -> Bool
&& Bool -> Bool
not (Posting -> Bool
hasBalancerCopiedBasis Posting
p)
  where
    lotfulAmts :: [Amount]
lotfulAmts = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Journal -> CommoditySymbol -> Bool
journalCommodityUsesLots Journal
j (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p))
    -- Flag only when the lotful commodity itself has nonzero quantity.
    hasNonzeroLotfulAmount :: Bool
hasNonzeroLotfulAmount = (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
0) (Quantity -> Bool) -> (Amount -> Quantity) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Quantity
aquantity) [Amount]
lotfulAmts

-- | Build an error message for an unclassified lotful posting.
-- Takes the transaction and the 0-based posting index for precise source location.
-- The excerpt shows the transaction as the user wrote it: postings are
-- reverted to their original (parse time) form and generated postings are
-- dropped, so it matches the journal file rather than the processed
-- in-memory entry (#2686). When the problem posting's amount was inferred
-- (and so is not visible in the excerpt), it is mentioned in the message.
unclassifiedLotWarning :: Journal -> Transaction -> Int -> Posting -> String
unclassifiedLotWarning :: Journal -> Transaction -> Int -> Posting -> String
unclassifiedLotWarning Journal
j Transaction
t Int
idx Posting
p =
  let amts :: [Amount]
amts = MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      lotfulCommodities :: [CommoditySymbol]
lotfulCommodities = [Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- [Amount]
amts, Journal -> CommoditySymbol -> Bool
journalCommodityUsesLots Journal
j (Amount -> CommoditySymbol
acommodity Amount
a)]
      source :: String
source = case [CommoditySymbol]
lotfulCommodities of
        (CommoditySymbol
c:[CommoditySymbol]
_) -> CommoditySymbol -> String
T.unpack CommoditySymbol
c String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" is declared lotful (commodity lots: tag)"
        []    -> String
"this posting involves a lotful commodity"
      inferrednote :: String
inferrednote = if Posting -> Bool
hasAmount (Posting -> Posting
originalPosting Posting
p) then String
"" else
        String
" (with inferred amount " String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showMixedAmountOneLine (Posting -> MixedAmount
pamount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")"
      (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) = Transaction
-> Int
-> Maybe (Int, Maybe Int)
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makePostingErrorExcerptByIndex (Transaction -> Transaction
transactionAsWritten Transaction
t) (Transaction -> Int -> Int
asWrittenPostingIndex Transaction
t Int
idx) Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing
      shortnote :: String
shortnote
        | Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j (Posting -> CommoditySymbol
paccount Posting
p) Maybe LotDirection -> Maybe LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection -> Maybe LotDirection
forall a. a -> Maybe a
Just LotDirection
Short =
            String
"\n(Liability accounts hold short positions, and transferring those between\n"
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"accounts is not supported yet: cover the position in one account and\n"
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"open it in the other, with prices.)"
        | Bool
otherwise = String
""
  in String -> String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" String
f Int
line CommoditySymbol
ex
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
source String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" but this posting" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
inferrednote String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" was not classified as\n"
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"acquire, dispose, or transfer. Lot state will not be updated.\n"
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Possible fixes: add a cost basis ({$X}), a price (@ $X),\n"
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"or check the account type declaration."
     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
shortnote

-- Validation and label generation

-- | Validate that user-provided labels don't create duplicate lot ids.
validateUserLabels :: [Transaction] -> Either String ()
validateUserLabels :: [Transaction] -> Either String ()
validateUserLabels [Transaction]
txns =
    case Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
-> [((CommoditySymbol, Day, CommoditySymbol), [Transaction])]
forall k a. Map k a -> [(k, a)]
M.toList Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
duplicates of
      [] -> () -> Either String ()
forall a b. b -> Either a b
Right ()
      (((CommoditySymbol
c, Day
d, CommoditySymbol
l), Transaction
t2:[Transaction]
_):[((CommoditySymbol, Day, CommoditySymbol), [Transaction])]
_) ->
        let (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) = Transaction
-> (Transaction -> Maybe (Int, Maybe Int))
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeTransactionErrorExcerpt Transaction
t2 (Maybe (Int, Maybe Int) -> Transaction -> Maybe (Int, Maybe Int)
forall a b. a -> b -> a
const Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing)
        in String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
-> String
-> Int
-> CommoditySymbol
-> String
-> String
-> String
-> String
forall r. PrintfType r => String -> r
printf ([String] -> String
unlines [
              String
"%s:%d:"
             ,String
"%s"
             ,String
"lot id is not unique: commodity %s, date %s, label \"%s\""
             ]) String
f Int
line CommoditySymbol
ex (CommoditySymbol -> String
T.unpack CommoditySymbol
c) (Day -> String
forall a. Show a => a -> String
show Day
d) (CommoditySymbol -> String
T.unpack CommoditySymbol
l)
      [((CommoditySymbol, Day, CommoditySymbol), [Transaction])]
_ -> () -> Either String ()
forall a b. b -> Either a b
Right ()  -- shouldn't happen
  where
    labeled :: [((CommoditySymbol, Day, CommoditySymbol), Transaction)]
labeled = [ ((Amount -> CommoditySymbol
acommodity Amount
a, Transaction -> CostBasis -> Day
getLotDate Transaction
t CostBasis
cb, CommoditySymbol
l), Transaction
t)
              | Transaction
t <- [Transaction]
txns
              , Posting
p <- Transaction -> [Posting]
tpostings Transaction
t
              , Posting -> Bool
isAcquirePosting Posting
p
              , Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
              , Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]
              , Just CommoditySymbol
l  <- [CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
cb]
              ]
    txnsByKey :: Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
txnsByKey = (Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
 -> ((CommoditySymbol, Day, CommoditySymbol), Transaction)
 -> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction])
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
-> [((CommoditySymbol, Day, CommoditySymbol), Transaction)]
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
m ((CommoditySymbol, Day, CommoditySymbol)
k, Transaction
t) -> ([Transaction] -> [Transaction] -> [Transaction])
-> (CommoditySymbol, Day, CommoditySymbol)
-> [Transaction]
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith [Transaction] -> [Transaction] -> [Transaction]
forall a. [a] -> [a] -> [a]
(++) (CommoditySymbol, Day, CommoditySymbol)
k [Transaction
t] Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
m) Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
forall k a. Map k a
M.empty [((CommoditySymbol, Day, CommoditySymbol), Transaction)]
labeled
    duplicates :: Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
duplicates = ([Transaction] -> Bool)
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
-> Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (\[Transaction]
ts -> [Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
ts Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) Map (CommoditySymbol, Day, CommoditySymbol) [Transaction]
txnsByKey

-- | Find (commodity, date) pairs where there are multiple unlabeled
-- acquisitions, and thus need auto-generated labels to disambiguate.
-- Acquisitions with a user-provided label are already unique by that label,
-- so they don't force unlabeled siblings on the same date to be labelled.
-- (Duplicate user labels on the same date are caught later by the
-- duplicate-lot-id check in 'processAcquirePosting'.)
-- Bare acquire postings (no acostbasis) use the transaction date.
findDatesNeedingLabels :: [Transaction] -> S.Set (CommoditySymbol, Day)
findDatesNeedingLabels :: [Transaction] -> Set (CommoditySymbol, Day)
findDatesNeedingLabels [Transaction]
txns =
    Map (CommoditySymbol, Day) Int -> Set (CommoditySymbol, Day)
forall k a. Map k a -> Set k
M.keysSet (Map (CommoditySymbol, Day) Int -> Set (CommoditySymbol, Day))
-> Map (CommoditySymbol, Day) Int -> Set (CommoditySymbol, Day)
forall a b. (a -> b) -> a -> b
$ (Int -> Bool)
-> Map (CommoditySymbol, Day) Int -> Map (CommoditySymbol, Day) Int
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) Map (CommoditySymbol, Day) Int
counts
  where
    counts :: Map (CommoditySymbol, Day) Int
counts = (Map (CommoditySymbol, Day) Int
 -> (CommoditySymbol, Day) -> Map (CommoditySymbol, Day) Int)
-> Map (CommoditySymbol, Day) Int
-> [(CommoditySymbol, Day)]
-> Map (CommoditySymbol, Day) Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map (CommoditySymbol, Day) Int
-> (CommoditySymbol, Day) -> Map (CommoditySymbol, Day) Int
forall {a} {b}.
(Ord a, Ord b) =>
Map (a, b) Int -> (a, b) -> Map (a, b) Int
countAcquire Map (CommoditySymbol, Day) Int
forall k a. Map k a
M.empty
      [ (Amount -> CommoditySymbol
acommodity Amount
a, Transaction -> Amount -> Day
acquireDate Transaction
t Amount
a)
      | Transaction
t <- [Transaction]
txns
      , Posting
p <- Transaction -> [Posting]
tpostings Transaction
t
      , Posting -> Bool
isAcquirePosting Posting
p
      , Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
      , Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe CostBasis
acostbasis Amount
a Maybe CostBasis
-> (CostBasis -> Maybe CommoditySymbol) -> Maybe CommoditySymbol
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe CommoditySymbol
cbLabel)   -- only count unlabeled
      ]
    countAcquire :: Map (a, b) Int -> (a, b) -> Map (a, b) Int
countAcquire Map (a, b) Int
m (a
c, b
d) = (Int -> Int -> Int)
-> (a, b) -> Int -> Map (a, b) Int -> Map (a, b) Int
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) (a
c, b
d) (Int
1 :: Int) Map (a, b) Int
m
    acquireDate :: Transaction -> Amount -> Day
acquireDate Transaction
t Amount
a = case Amount -> Maybe CostBasis
acostbasis Amount
a of
      Just CostBasis
cb -> Transaction -> CostBasis -> Day
getLotDate Transaction
t CostBasis
cb
      Maybe CostBasis
Nothing -> Transaction -> Day
tdate Transaction
t

-- | Revert a transaction to (approximately) the form the user wrote, for
-- error display: postings are reverted to their original parse-time form,
-- and generated postings are dropped. This keeps error excerpts looking
-- like the journal file rather than the processed in-memory entry (#2686).
transactionAsWritten :: Transaction -> Transaction
transactionAsWritten :: Transaction -> Transaction
transactionAsWritten Transaction
t =
  Transaction
t{tpostings = [originalPosting q | q <- tpostings t, not (isGeneratedPosting q)]}

-- | Map a 0-based index into a transaction's postings to the corresponding
-- index in the 'transactionAsWritten' form (which omits generated postings).
asWrittenPostingIndex :: Transaction -> Int -> Int
asWrittenPostingIndex :: Transaction -> Int -> Int
asWrittenPostingIndex Transaction
t Int
idx = [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [() | Posting
q <- Int -> [Posting] -> [Posting]
forall a. Int -> [a] -> [a]
take Int
idx (Transaction -> [Posting]
tpostings Transaction
t), Bool -> Bool
not (Posting -> Bool
isGeneratedPosting Posting
q)]

-- | True if this posting was generated by processing (has the _generated-posting tag).
isGeneratedPosting :: Posting -> Bool
isGeneratedPosting :: Posting -> Bool
isGeneratedPosting = CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
generatedPostingTagName

-- | A one-line summary of how lot classification read a transaction's
-- postings, to include at the end of error messages about it (see 'appendPostingsReadAs'):
-- each non-generated posting's classification ("_ptype" tag value, or
-- "unclassified") in posting order, plus a count of any generated postings.
-- Returns "" when classification hasn't run yet (no posting has a ptype
-- tag), eg for errors raised at earlier pipeline stages.
-- The excerpt always shows what the user wrote; this line shows how
-- hledger interpreted it, since the interpretation (and any error arising
-- from it) may not be obvious from the entry alone.
postingsReadAs :: Transaction -> String
postingsReadAs :: Transaction -> String
postingsReadAs Transaction
t
  | Bool -> Bool
not ((Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
isClassifiedPosting [Posting]
ps) = String
""
  | Bool
otherwise =
      String
"Postings were read as: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " ((Posting -> String) -> [Posting] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> String
readAs [Posting]
written)
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ (case [Posting]
generated of
            [] -> String
""
            [Posting]
gs -> String
"; and generated: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " ((Posting -> String) -> [Posting] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> String
readAs [Posting]
gs))
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"."
  where
    ps :: [Posting]
ps = Transaction -> [Posting]
tpostings Transaction
t
    ([Posting]
generated, [Posting]
written) = (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Posting -> Bool
isGeneratedPosting [Posting]
ps
    readAs :: Posting -> String
readAs Posting
p = case CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)] -> Maybe CommoditySymbol
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup CommoditySymbol
"_ptype" (Posting -> [(CommoditySymbol, CommoditySymbol)]
ptags Posting
p) of
      Just CommoditySymbol
ptype -> CommoditySymbol -> String
T.unpack CommoditySymbol
ptype
      Maybe CommoditySymbol
Nothing | CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
lotParentAssertionTagName Posting
p -> String
"balance-assertion"
              | Bool
otherwise -> String
"unclassified"

-- | Append a summary of how a transaction's postings were classified ('postingsReadAs'),
-- if they were, as the last line of a lot error message about that transaction.
-- (It goes last, so the explanation comes first, eg as the first line of a flycheck message.)
appendPostingsReadAs :: Transaction -> String -> String
appendPostingsReadAs :: Transaction -> String -> String
appendPostingsReadAs Transaction
t String
msg = case Transaction -> String
postingsReadAs Transaction
t of
  String
"" -> String
msg
  String
r  -> (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n') String
msg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
r

-- | Format a verbose error prefix for a transaction: "file:line:\nexcerpt\n\n".
-- Prepend to an error message to show source position and a transaction excerpt,
-- rendered as the user wrote it ('transactionAsWritten').
txnErrPrefix :: Transaction -> String
txnErrPrefix :: Transaction -> String
txnErrPrefix Transaction
t = String -> String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" String
f Int
line CommoditySymbol
ex
  where (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) = Transaction
-> (Transaction -> Maybe (Int, Maybe Int))
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeTransactionErrorExcerpt (Transaction -> Transaction
transactionAsWritten Transaction
t) (Maybe (Int, Maybe Int) -> Transaction -> Maybe (Int, Maybe Int)
forall a b. a -> b -> a
const Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing)

-- | Format a verbose error prefix for a posting: "file:line:\nexcerpt\n\n",
-- like 'txnErrPrefix', but marking the
-- specific posting's line, found by comparing cost-stripped postings
-- (falling back to the transaction line if the posting can't be identified).
postingErrPrefix :: Posting -> String
postingErrPrefix :: Posting -> String
postingErrPrefix Posting
p = case Posting -> Maybe Transaction
ptransaction Posting
p of
  Maybe Transaction
Nothing -> String -> String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" (String
"-"::String) (Int
0::Int) (CommoditySymbol
""::Text)
  Just Transaction
t  -> case (Posting -> Bool) -> Transaction -> Maybe Int
transactionFindPostingIndex ((Posting -> Posting -> Bool
forall a. Eq a => a -> a -> Bool
== Posting -> Posting
postingStripCosts Posting
p) (Posting -> Bool) -> (Posting -> Posting) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> Posting
postingStripCosts) Transaction
t of
    Maybe Int
Nothing -> Transaction -> String
txnErrPrefix Transaction
t
    Just Int
i1 -> Transaction -> Int -> String
postingAtErrPrefix Transaction
t (Int
i1Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)

-- | Like 'postingErrPrefix', for the posting at this (0-based) index in the transaction.
postingAtErrPrefix :: Transaction -> Int -> String
postingAtErrPrefix :: Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
i = String -> String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n" String
f Int
line CommoditySymbol
ex
  where (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) = Transaction
-> Int
-> Maybe (Int, Maybe Int)
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makePostingErrorExcerptByIndex (Transaction -> Transaction
transactionAsWritten Transaction
t) (Transaction -> Int -> Int
asWrittenPostingIndex Transaction
t Int
i) Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing

-- | Emit a dbg5 trace for a lot operation: "lots: FILE:LINE DATE DESC: message".
lotDbg :: Transaction -> String -> a -> a
lotDbg :: forall a. Transaction -> String -> a -> a
lotDbg Transaction
t String
msg = (a -> String) -> a -> a
forall a. (a -> String) -> a -> a
dbg5With (\a
_ -> String
"lots: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Transaction -> String
txnDbgPrefix Transaction
t String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
msg)

-- | Format a one-line transaction summary for debug traces: "FILE:LINE DATE DESC".
txnDbgPrefix :: Transaction -> String
txnDbgPrefix :: Transaction -> String
txnDbgPrefix Transaction
t = String -> String -> Int -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d %s %s" String
f Int
line (Day -> String
forall a. Show a => a -> String
show (Transaction -> Day
tdate Transaction
t)) (CommoditySymbol -> String
T.unpack (Transaction -> CommoditySymbol
tdescription Transaction
t))
  where (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
_) = Transaction
-> (Transaction -> Maybe (Int, Maybe Int))
-> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makeTransactionErrorExcerpt Transaction
t (Maybe (Int, Maybe Int) -> Transaction -> Maybe (Int, Maybe Int)
forall a b. a -> b -> a
const Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing)

-- | Get the lot date from cost basis, falling back to the transaction date.
getLotDate :: Transaction -> CostBasis -> Day
getLotDate :: Transaction -> CostBasis -> Day
getLotDate Transaction
t CostBasis
cb = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (Transaction -> Day
tdate Transaction
t) (CostBasis -> Maybe Day
cbDate CostBasis
cb)

-- | Generate a label for a lot that needs one (due to same-date collision).
-- Uses the smallest sequence number, formatted as four (or more) digits
-- ("0001", "0002", ...), that isn't already a label of an existing same-date
-- lot. Skipping used numbers avoids colliding with user-provided labels
-- that happen to be in the same format. Fully disposed lots remain visible
-- here as tombstones (see 'reduceLotState'), so their labels are not reused.
generateLabel :: CommoditySymbol -> Day -> LotState -> T.Text
generateLabel :: CommoditySymbol -> Day -> LotState -> CommoditySymbol
generateLabel CommoditySymbol
commodity Day
date LotState
lotState = Int -> CommoditySymbol
nextFree Int
1
  where
    existingLots :: Map LotId (Map CommoditySymbol Amount)
existingLots = Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState
    -- Use takeWhileAntitone/dropWhileAntitone for O(log n) range extraction.
    -- LotId is ordered by date first, so same-date lots form a contiguous range.
    sameDate :: Map LotId (Map CommoditySymbol Amount)
sameDate = (LotId -> Bool)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall k a. (k -> Bool) -> Map k a -> Map k a
M.takeWhileAntitone (\(LotId Day
d Maybe CommoditySymbol
_) -> Day
d Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
== Day
date)
             (Map LotId (Map CommoditySymbol Amount)
 -> Map LotId (Map CommoditySymbol Amount))
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall a b. (a -> b) -> a -> b
$ (LotId -> Bool)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall k a. (k -> Bool) -> Map k a -> Map k a
M.dropWhileAntitone (\(LotId Day
d Maybe CommoditySymbol
_) -> Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
< Day
date) Map LotId (Map CommoditySymbol Amount)
existingLots
    usedLabels :: Set CommoditySymbol
usedLabels = [CommoditySymbol] -> Set CommoditySymbol
forall a. Ord a => [a] -> Set a
S.fromList ([CommoditySymbol] -> Set CommoditySymbol)
-> [CommoditySymbol] -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (LotId -> Maybe CommoditySymbol) -> [LotId] -> [CommoditySymbol]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (\(LotId Day
_ Maybe CommoditySymbol
ml) -> Maybe CommoditySymbol
ml) (Map LotId (Map CommoditySymbol Amount) -> [LotId]
forall k a. Map k a -> [k]
M.keys Map LotId (Map CommoditySymbol Amount)
sameDate)
    nextFree :: Int -> T.Text
    nextFree :: Int -> CommoditySymbol
nextFree Int
n =
      let l :: CommoditySymbol
l = String -> CommoditySymbol
T.pack (String -> Int -> String
forall r. PrintfType r => String -> r
printf String
"%04d" Int
n)
      in if CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
S.notMember CommoditySymbol
l Set CommoditySymbol
usedLabels then CommoditySymbol
l else Int -> CommoditySymbol
nextFree (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

-- Transaction dispatch

-- | Process a single transaction: transform its acquire, dispose, and transfer postings.
-- Transfer pairs are processed first (so that transferred lots are available for
-- subsequent disposals in the same transaction), then acquire and dispose postings.
-- Accumulates (LotState, [Transaction]) — transactions in reverse order.
processTransaction :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> S.Set (CommoditySymbol, Day) -> (LotState, [Transaction]) -> Transaction
                       -> Either String (LotState, [Transaction])
processTransaction :: Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Set (CommoditySymbol, Day)
-> (LotState, [Transaction])
-> Transaction
-> Either String (LotState, [Transaction])
processTransaction Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Set (CommoditySymbol, Day)
needsLabels (LotState
ls, [Transaction]
acc) Transaction
t = do
    -- Partition postings into transfer pairs and others
    let ([Posting]
transferFroms, [Posting]
transferTos, [Posting]
otherPs) = [Posting] -> ([Posting], [Posting], [Posting])
partitionTransferPostings (Transaction -> [Posting]
tpostings Transaction
t)
        hasEquityOther :: Bool
hasEquityOther = (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Journal -> Posting -> Bool
isEquityPosting Journal
j) [Posting]
otherPs
    -- Closing equity transfer: transfer-from postings with no transfer-to counterpart,
    -- where an equity posting receives the lots (e.g. close --clopen --lots).
    -- Reduce lots from state, and rewrite each transfer-from posting onto the
    -- selected lots' subaccounts; pass other postings through unchanged (equity does not track lots).
    if Bool -> Bool
not ([Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
transferFroms) Bool -> Bool -> Bool
&& [Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
transferTos Bool -> Bool -> Bool
&& Bool
hasEquityOther
      then do
        (ls', allPsR) <- ((LotState, [Posting])
 -> Posting -> Either String (LotState, [Posting]))
-> (LotState, [Posting])
-> [Posting]
-> Either String (LotState, [Posting])
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (\(LotState
st, [Posting]
qs) Posting
p ->
            if Posting -> Bool
isTransferFromPosting Posting
p
            then do
              (st', ps') <- Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> Posting
-> Either String (LotState, [Posting])
reduceLotTransferToEquity Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
st Posting
p
              return (st', reverse ps' ++ qs)
            else (LotState, [Posting]) -> Either String (LotState, [Posting])
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (LotState
st, Posting
p Posting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
: [Posting]
qs)
          ) (LotState
ls, []) (Transaction -> [Posting]
tpostings Transaction
t)
        return (ls', t{tpostings = reverse allPsR} : acc)
    -- Opening equity transfer: transfer-to postings with no transfer-from counterpart,
    -- where an equity posting is the source (e.g. opening balances from close --clopen --lots).
    -- Process transfer-to postings as acquires to add lots to the state.
    else if [Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
transferFroms Bool -> Bool -> Bool
&& Bool -> Bool
not ([Posting] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
transferTos) Bool -> Bool -> Bool
&& Bool
hasEquityOther
      then do
        -- Build map of processed transfer-to postings, then reconstruct in original order.
        let indexedTos :: [(Int, Posting)]
indexedTos = [(Int
i, Posting
p) | (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t), Posting -> Bool
isTransferToPosting Posting
p]
        (ls', toMap) <- ((LotState, Map Int Posting)
 -> (Int, Posting) -> Either String (LotState, Map Int Posting))
-> (LotState, Map Int Posting)
-> [(Int, Posting)]
-> Either String (LotState, Map Int Posting)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (\(LotState
st, Map Int Posting
m) (Int
i, Posting
p) -> do
            (st', p') <- Map CommoditySymbol AmountStyle
-> Journal
-> Set (CommoditySymbol, Day)
-> Day
-> Transaction
-> LotState
-> Int
-> Posting
-> Either String (LotState, Posting)
processAcquirePosting Map CommoditySymbol AmountStyle
styles Journal
j Set (CommoditySymbol, Day)
needsLabels Day
txnDate Transaction
t LotState
st Int
i Posting
p
            return (st', M.insert i p' m)
          ) (LotState
ls, Map Int Posting
forall k a. Map k a
M.empty) [(Int, Posting)]
indexedTos
        let allPs = [Posting -> (Posting -> Posting) -> Maybe Posting -> Posting
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Posting
p Posting -> Posting
forall a. a -> a
id (Int -> Map Int Posting -> Maybe Posting
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Int
i Map Int Posting
toMap) | (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t)]
        return (ls', t{tpostings = allPs} : acc)
    else do
        let indexedFroms :: [(Int, Posting)]
indexedFroms = [(Int
i, Posting
p) | (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t), Posting -> Bool
isTransferFromPosting Posting
p]
            indexedTos :: [(Int, Posting)]
indexedTos   = [(Int
i, Posting
p) | (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t), Posting -> Bool
isTransferToPosting Posting
p]
            -- Fee-split dispose postings, which are by construction in the
            -- transfer source account (where the lots already exist).
            indexedFeeDisposes :: [(Int, Posting)]
indexedFeeDisposes =
              [(Int
i, Posting
p) | (Int
i, Posting
p) <- [Int] -> [Posting] -> [(Int, Posting)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0..] (Transaction -> [Posting]
tpostings Transaction
t)
                      , Posting -> Bool
isDisposePosting Posting
p, CommoditySymbol -> Posting -> Bool
postingHasTag CommoditySymbol
feesplitPostingTagName Posting
p]
        -- Process fee-split disposes before the transfer pairs, so the
        -- disposal method in effect (FIFO, LIFO, ...) selects from the full
        -- pre-transfer lot set - eg under FIFO a transfer fee consumes the
        -- oldest lot - and the transfer carries the remainder. (#2692)
        (ls0, disposeMap) <- ((LotState, Map Int [Posting])
 -> (Int, Posting) -> Either String (LotState, Map Int [Posting]))
-> (LotState, Map Int [Posting])
-> [(Int, Posting)]
-> Either String (LotState, Map Int [Posting])
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (LotState, Map Int [Posting])
-> (Int, Posting) -> Either String (LotState, Map Int [Posting])
forall {k}.
Ord k =>
(LotState, Map k [Posting])
-> (k, Posting) -> Either String (LotState, Map k [Posting])
processOneFeeDispose (LotState
ls, Map Int [Posting]
forall k a. Map k a
M.empty) [(Int, Posting)]
indexedFeeDisposes
        groups <- groupIndexedTransferPostings t indexedFroms indexedTos
        -- Then walk all postings in original order, processing each transfer
        -- group when its first posting is reached, and substituting expanded results.
        let groupsByFirst = [(Int, (CommoditySymbol, [(Int, Posting)], [(Int, Posting)]))]
-> Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(Int
i, (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
g) | g :: (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
g@(CommoditySymbol
_, [(Int, Posting)]
ifroms, [(Int, Posting)]
itos) <- [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]
groups, Int
i <- Int -> [Int] -> [Int]
forall a. Int -> [a] -> [a]
take Int
1 ([Int] -> [Int]
forall a. Ord a => [a] -> [a]
sort (((Int, Posting) -> Int) -> [(Int, Posting)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Posting) -> Int
forall a b. (a, b) -> a
fst ([(Int, Posting)]
ifroms [(Int, Posting)] -> [(Int, Posting)] -> [(Int, Posting)]
forall a. [a] -> [a] -> [a]
++ [(Int, Posting)]
itos)))]
        (ls'', allPs) <- foldMPostings ls0 [] (zip [0..] (tpostings t)) disposeMap groupsByFirst
        return (ls'', t{tpostings = reverse allPs} : acc)
  where
    txnDate :: Day
txnDate = Transaction -> Day
tdate Transaction
t

    -- Process a fee-split dispose posting; record expanded postings keyed by original index.
    processOneFeeDispose :: (LotState, Map k [Posting])
-> (k, Posting) -> Either String (LotState, Map k [Posting])
processOneFeeDispose (LotState
st, Map k [Posting]
m) (k
i, Posting
p) = do
      (st', newPs) <- Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> Posting
-> Either String (LotState, [Posting])
processDisposePosting Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
st Posting
p
      return (st', M.insert i newPs m)

    -- Walk postings in original order, looking up already-processed results,
    -- processing a transfer group when its first posting is reached, or
    -- processing the posting normally.
    foldMPostings :: LotState -> [Posting] -> [(Int, Posting)] -> M.Map Int [Posting] -> M.Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
                  -> Either String (LotState, [Posting])
    foldMPostings :: LotState
-> [Posting]
-> [(Int, Posting)]
-> Map Int [Posting]
-> Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either String (LotState, [Posting])
foldMPostings LotState
st [Posting]
acc' [] Map Int [Posting]
_ Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
_ = (LotState, [Posting]) -> Either String (LotState, [Posting])
forall a b. b -> Either a b
Right (LotState
st, [Posting]
acc')
    foldMPostings LotState
st [Posting]
acc' ips :: [(Int, Posting)]
ips@((Int
i,Posting
p):[(Int, Posting)]
ps) Map Int [Posting]
tmap Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
groups
      | Just (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
g <- Int
-> Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Maybe (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Int
i Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
groups = do
          (st', m') <- Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either String (LotState, Map Int [Posting])
processTransferGroup Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
st (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
g
          foldMPostings st' acc' ips (M.union tmap m') (M.delete i groups)
      | Just [Posting]
expanded <- Int -> Map Int [Posting] -> Maybe [Posting]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Int
i Map Int [Posting]
tmap =
          LotState
-> [Posting]
-> [(Int, Posting)]
-> Map Int [Posting]
-> Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either String (LotState, [Posting])
foldMPostings LotState
st ([Posting] -> [Posting]
forall a. [a] -> [a]
reverse [Posting]
expanded [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ [Posting]
acc') [(Int, Posting)]
ps Map Int [Posting]
tmap Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
groups
      | Posting -> Bool
isAcquirePosting Posting
p = do
          (st', p') <- Map CommoditySymbol AmountStyle
-> Journal
-> Set (CommoditySymbol, Day)
-> Day
-> Transaction
-> LotState
-> Int
-> Posting
-> Either String (LotState, Posting)
processAcquirePosting Map CommoditySymbol AmountStyle
styles Journal
j Set (CommoditySymbol, Day)
needsLabels Day
txnDate Transaction
t LotState
st Int
i Posting
p
          foldMPostings st' (p':acc') ps tmap groups
      | Posting -> Bool
isDisposePosting Posting
p = do
          (st', newPs) <- Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> Posting
-> Either String (LotState, [Posting])
processDisposePosting Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
st Posting
p
          foldMPostings st' (reverse newPs ++ acc') ps tmap groups
      | Journal -> Posting -> Bool
isUnclassifiedLotfulPosting Journal
j Posting
p =
          String -> Either String (LotState, [Posting])
forall a b. a -> Either a b
Left (Journal -> Transaction -> Int -> Posting -> String
unclassifiedLotWarning Journal
j Transaction
t Int
i Posting
p)
      | Bool
otherwise =
          LotState
-> [Posting]
-> [(Int, Posting)]
-> Map Int [Posting]
-> Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either String (LotState, [Posting])
foldMPostings LotState
st (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
acc') [(Int, Posting)]
ps Map Int [Posting]
tmap Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
groups

-- | True if the posting is in an equity account.
isEquityPosting :: Journal -> Posting -> Bool
isEquityPosting :: Journal -> Posting -> Bool
isEquityPosting Journal
j Posting
p = Bool -> (AccountType -> Bool) -> Maybe AccountType -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False AccountType -> Bool
isEquityType (Journal -> CommoditySymbol -> Maybe AccountType
journalAccountType Journal
j (CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)))

-- | Reduce lots from the lot state for a transfer-from posting going to an equity account.
-- Used when lots are transferred to equity (e.g. close --clopen --lots): reduces the lots
-- without requiring a matching transfer-to posting, since equity does not track lots.
-- Like a paired transfer's source, the posting is rewritten onto the full name(s)
-- of the lot(s) it selects, so that account balances agree with the lot state
-- even when it was written with a partial lot subaccount name (eg without a label).
reduceLotTransferToEquity :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState -> Posting
                          -> Either String (LotState, [Posting])
reduceLotTransferToEquity :: Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> Posting
-> Either String (LotState, [Posting])
reduceLotTransferToEquity Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
ls Posting
p =
    case [(Amount
a, CostBasis
cb) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a], LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
a] of
      [(Amount
a, CostBasis
cb)] -> do
        let commodity :: CommoditySymbol
commodity = Amount -> CommoditySymbol
acommodity Amount
a
            qty :: Quantity
qty       = Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
a)
            acct :: CommoditySymbol
acct      = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
            (ReductionMethod
method, String
methodSource) = Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodWithSource Journal
j Posting
p CommoditySymbol
commodity
        selected <- (ReductionMethod, String)
-> String
-> String
-> Day
-> LotDirection
-> CommoditySymbol
-> CommoditySymbol
-> Quantity
-> CostBasis
-> LotState
-> Either String [(LotId, Amount, Quantity)]
selectLots (ReductionMethod
method, String
methodSource) (Posting -> String
postingErrPrefix Posting
p) String
"transfer" (Transaction -> Day
tdate Transaction
t) LotDirection
dir CommoditySymbol
acct CommoditySymbol
commodity Quantity
qty CostBasis
cb
                      (Journal -> LotDirection -> CommoditySymbol -> LotState -> LotState
lotStateForDirection Journal
j LotDirection
dir CommoditySymbol
commodity LotState
ls)
        ps <- mapM (mkLotPosting acct a method) selected
        let consumed = [(LotId
lotId, Quantity
qty') | (LotId
lotId, Amount
_, Quantity
qty') <- [(LotId, Amount, Quantity)]
selected]
            ps' = case [Posting]
ps of
              [Posting
_] -> [Posting]
ps
              [Posting]
_   -> (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
lotsplitPostingTagName, CommoditySymbol
"")) [Posting]
ps
        return $ lotDbg t ("equity-transfer " ++ show qty ++ " " ++ T.unpack commodity
                           ++ " from " ++ T.unpack acct
                           ++ " (lots: " ++ showSelectedLots selected ++ ")")
               (reduceLotState acct commodity consumed ls
               ,preserveParentAssertion verbosetags (paccount p) (pbalanceassertion p) ps')
      [(Amount, CostBasis)]
_ -> (LotState, [Posting]) -> Either String (LotState, [Posting])
forall a b. b -> Either a b
Right (LotState
ls, [Posting
p])  -- no single lot amount (e.g. cash posting): pass through
  where
    -- a liability account's short lots are sent to equity by a positive posting
    dir :: LotDirection
dir = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j (Posting -> CommoditySymbol
paccount Posting
p)
    mkLotPosting :: CommoditySymbol
-> Amount
-> ReductionMethod
-> (LotId, Amount, Quantity)
-> Either String Posting
mkLotPosting CommoditySymbol
acct Amount
a ReductionMethod
method (LotId
lotId, Amount
storedAmt, Quantity
qty) = case Amount -> Maybe CostBasis
acostbasis Amount
storedAmt Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost of
      Maybe Amount
Nothing -> String -> Either String Posting
forall a b. a -> Either a b
Left (String -> Either String Posting)
-> String -> Either String Posting
forall a b. (a -> b) -> a -> b
$ Transaction -> String
txnErrPrefix Transaction
t String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot " String -> String -> String
forall a. [a] -> [a] -> [a]
++ LotId -> String
forall a. Show a => a -> String
show LotId
lotId
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (Amount -> CommoditySymbol
acommodity Amount
a)
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no cost basis (internal error)"
      Just Amount
c  ->
        let lotCb :: CostBasis
lotCb = CostBasis{cbDate :: Maybe Day
cbDate = Day -> Maybe Day
forall a. a -> Maybe a
Just (LotId -> Day
lotDate LotId
lotId), cbLabel :: Maybe CommoditySymbol
cbLabel = LotId -> Maybe CommoditySymbol
lotLabel LotId
lotId, cbCost :: Maybe Amount
cbCost = Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
c}
            lotName :: CommoditySymbol
lotName = ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
method (Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
lotCb)
        in Posting -> Either String Posting
forall a b. b -> Either a b
Right Posting
p{ paccount  = acct <> ":" <> lotName
                  , pamount   = mixedAmount (amountSetQuantity (negate (lotDirectionSign dir) * qty) a){acostbasis = Just lotCb}
                  , poriginal = Just (originalPosting p)
                  }

-- | Partition a transaction's postings into transfer-from, transfer-to, and others.
partitionTransferPostings :: [Posting] -> ([Posting], [Posting], [Posting])
partitionTransferPostings :: [Posting] -> ([Posting], [Posting], [Posting])
partitionTransferPostings = [Posting]
-> [Posting]
-> [Posting]
-> [Posting]
-> ([Posting], [Posting], [Posting])
go [] [] []
  where
    go :: [Posting]
-> [Posting]
-> [Posting]
-> [Posting]
-> ([Posting], [Posting], [Posting])
go [Posting]
froms [Posting]
tos [Posting]
others [] = ([Posting] -> [Posting]
forall a. [a] -> [a]
reverse [Posting]
froms, [Posting] -> [Posting]
forall a. [a] -> [a]
reverse [Posting]
tos, [Posting] -> [Posting]
forall a. [a] -> [a]
reverse [Posting]
others)
    go [Posting]
froms [Posting]
tos [Posting]
others (Posting
p:[Posting]
ps)
      | Posting -> Bool
isTransferFromPosting Posting
p = [Posting]
-> [Posting]
-> [Posting]
-> [Posting]
-> ([Posting], [Posting], [Posting])
go (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
froms) [Posting]
tos [Posting]
others [Posting]
ps
      | Posting -> Bool
isTransferToPosting Posting
p   = [Posting]
-> [Posting]
-> [Posting]
-> [Posting]
-> ([Posting], [Posting], [Posting])
go [Posting]
froms (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
tos) [Posting]
others [Posting]
ps
      | Bool
otherwise               = [Posting]
-> [Posting]
-> [Posting]
-> [Posting]
-> ([Posting], [Posting], [Posting])
go [Posting]
froms [Posting]
tos (Posting
pPosting -> [Posting] -> [Posting]
forall a. a -> [a] -> [a]
:[Posting]
others) [Posting]
ps

-- | Group indexed transfer-from and transfer-to postings by commodity, and
-- check each group's consistency: both sides present, and total from/to
-- quantities equal (#2692). Transfer postings need not pair up one to one:
-- one source posting can feed several destinations, or several sources one
-- destination, as long as the totals match. Within each group, froms and
-- tos are sorted by cost basis fields (date, label, cost) so explicit
-- per-lot annotations align. Cost basis mismatches are caught later by
-- validation, not here.
groupIndexedTransferPostings :: Transaction -> [(Int, Posting)] -> [(Int, Posting)]
  -> Either String [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]
groupIndexedTransferPostings :: Transaction
-> [(Int, Posting)]
-> [(Int, Posting)]
-> Either
     String [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]
groupIndexedTransferPostings Transaction
_ [] [] = [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]
-> Either
     String [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]
forall a b. b -> Either a b
Right []
groupIndexedTransferPostings Transaction
t [(Int, Posting)]
froms [(Int, Posting)]
tos = do
    fromGroups <- String
-> [(Int, Posting)]
-> Either String (Map CommoditySymbol [(Int, Posting)])
groupByCommodity String
"transfer-from" [(Int, Posting)]
froms
    toGroups   <- groupByCommodity "transfer-to" tos
    let allComms = Set CommoditySymbol -> Set CommoditySymbol -> Set CommoditySymbol
forall a. Ord a => Set a -> Set a -> Set a
S.union (Map CommoditySymbol [(Int, Posting)] -> Set CommoditySymbol
forall k a. Map k a -> Set k
M.keysSet Map CommoditySymbol [(Int, Posting)]
fromGroups) (Map CommoditySymbol [(Int, Posting)] -> Set CommoditySymbol
forall k a. Map k a -> Set k
M.keysSet Map CommoditySymbol [(Int, Posting)]
toGroups)
    mapM (checkCommodityGroup fromGroups toGroups) (S.toList allComms)
  where
    showPos :: String
showPos = Transaction -> String
txnErrPrefix Transaction
t

    -- Group indexed postings by their lotful commodity.
    groupByCommodity :: String -> [(Int, Posting)] -> Either String (M.Map CommoditySymbol [(Int, Posting)])
    groupByCommodity :: String
-> [(Int, Posting)]
-> Either String (Map CommoditySymbol [(Int, Posting)])
groupByCommodity String
label [(Int, Posting)]
ips = do
      tagged <- ((Int, Posting) -> Either String (CommoditySymbol, (Int, Posting)))
-> [(Int, Posting)]
-> Either String [(CommoditySymbol, (Int, Posting))]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\(Int, Posting)
ip -> (,(Int, Posting)
ip) (CommoditySymbol -> (CommoditySymbol, (Int, Posting)))
-> Either String CommoditySymbol
-> Either String (CommoditySymbol, (Int, Posting))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> (Int, Posting) -> Either String CommoditySymbol
postingCommodity String
label (Int, Posting)
ip) [(Int, Posting)]
ips
      Right $ M.map reverse $ M.fromListWith (++) [(c, [ip]) | (c, ip) <- tagged]

    postingCommodity :: String -> (Int, Posting) -> Either String CommoditySymbol
    postingCommodity :: String -> (Int, Posting) -> Either String CommoditySymbol
postingCommodity String
label (Int
i, Posting
p) =
      case [Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isJust (Amount -> Maybe CostBasis
acostbasis Amount
a)] of
        [CommoditySymbol
c] -> CommoditySymbol -> Either String CommoditySymbol
forall a b. b -> Either a b
Right CommoditySymbol
c
        -- Transfer-to postings without {} have no cost basis; use the raw commodity.
        [CommoditySymbol]
_   -> case [Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)] of
                 [CommoditySymbol
c] -> CommoditySymbol -> Either String CommoditySymbol
forall a b. b -> Either a b
Right CommoditySymbol
c
                 [CommoditySymbol]
_   -> String -> Either String CommoditySymbol
forall a b. a -> Either a b
Left (String -> Either String CommoditySymbol)
-> String -> Either String CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
i
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
label String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" posting has amounts in several commodities ("
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ MixedAmount -> String
showMixedAmountOneLine (Posting -> MixedAmount
pamount Posting
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
").\n"
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"In a lot transfer, each posting should have just one commodity;\n"
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"please write these amounts on separate postings."

    -- Sort key for aligning explicit per-lot annotations within a commodity group.
    postingSortKey :: (Int, Posting) -> (Maybe Day, Maybe T.Text, Maybe (CommoditySymbol, Quantity))
    postingSortKey :: (Int, Posting)
-> (Maybe Day, Maybe CommoditySymbol,
    Maybe (CommoditySymbol, Quantity))
postingSortKey (Int
_, Posting
p) =
      case [CostBasis
cb | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]] of
        [CostBasis
cb] -> (CostBasis -> Maybe Day
cbDate CostBasis
cb, CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
cb,
                 (Amount -> (CommoditySymbol, Quantity))
-> Maybe Amount -> Maybe (CommoditySymbol, Quantity)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\Amount
a -> (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)) (CostBasis -> Maybe Amount
cbCost CostBasis
cb))
        [CostBasis]
_    -> (Maybe Day
forall a. Maybe a
Nothing, Maybe CommoditySymbol
forall a. Maybe a
Nothing, Maybe (CommoditySymbol, Quantity)
forall a. Maybe a
Nothing)

    checkCommodityGroup :: Map CommoditySymbol [(Int, Posting)]
-> Map CommoditySymbol [(Int, Posting)]
-> CommoditySymbol
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
checkCommodityGroup Map CommoditySymbol [(Int, Posting)]
fromGroups Map CommoditySymbol [(Int, Posting)]
toGroups CommoditySymbol
comm = do
      let fs :: [(Int, Posting)]
fs = [(Int, Posting)]
-> CommoditySymbol
-> Map CommoditySymbol [(Int, Posting)]
-> [(Int, Posting)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] CommoditySymbol
comm Map CommoditySymbol [(Int, Posting)]
fromGroups
          ts :: [(Int, Posting)]
ts = [(Int, Posting)]
-> CommoditySymbol
-> Map CommoditySymbol [(Int, Posting)]
-> [(Int, Posting)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] CommoditySymbol
comm Map CommoditySymbol [(Int, Posting)]
toGroups
      case ([(Int, Posting)]
fs, [(Int, Posting)]
ts) of
        ([], [(Int, Posting)]
_) -> String
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall a b. a -> Either a b
Left (String
 -> Either
      String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)]))
-> String
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"transfer-to posting for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
comm
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no matching transfer-from posting"
        ([(Int, Posting)]
_, []) -> String
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall a b. a -> Either a b
Left (String
 -> Either
      String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)]))
-> String
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"transfer-from posting for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
comm
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no matching transfer-to posting"
        ([(Int, Posting)], [(Int, Posting)])
_ -> do
          -- The total from/to quantities must agree; a difference indicates an
          -- analysis failure or an unrecorded fee (#2692). (Transfer fees
          -- should be recorded as their own posting(s) in the same commodity;
          -- hledger then splits off matching disposal(s) automatically.)
          let qtyTotal :: [(a, Posting)] -> Quantity
qtyTotal [(a, Posting)]
ips = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
a)
                                 | (a
_, Posting
p) <- [(a, Posting)]
ips, Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)
                                 , Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
comm ]
              fromTotal :: Quantity
fromTotal = [(Int, Posting)] -> Quantity
forall {a}. [(a, Posting)] -> Quantity
qtyTotal [(Int, Posting)]
fs
              toTotal :: Quantity
toTotal   = [(Int, Posting)] -> Quantity
forall {a}. [(a, Posting)] -> Quantity
qtyTotal [(Int, Posting)]
ts
          Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Quantity
fromTotal Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Quantity
toTotal) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
            String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Mismatched transfer quantities for lot-tracked commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
comm
                       String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show Quantity
fromTotal String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" transferred out but "
                       String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show Quantity
toTotal String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" received.\n"
                       String -> String -> String
forall a. [a] -> [a] -> [a]
++ if Quantity
toTotal Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
fromTotal
                          then String
"More was received than sent, which a fee can't explain;\n"
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"check the entry for sign errors or rounding adjustments."
                          else String
"If the difference is a fee, you can either\n"
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"- record the fee expense in the lot-tracked commodity, with posting(s)\n"
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  adding up to the missing quantity\n"
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"- or split the sending posting into a transfer part and fee part(s)\n"
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  matching the fee expense(s)."
          (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either
     String (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
forall a b. b -> Either a b
Right (CommoditySymbol
comm, ((Int, Posting)
 -> (Maybe Day, Maybe CommoditySymbol,
     Maybe (CommoditySymbol, Quantity)))
-> [(Int, Posting)] -> [(Int, Posting)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int, Posting)
-> (Maybe Day, Maybe CommoditySymbol,
    Maybe (CommoditySymbol, Quantity))
postingSortKey [(Int, Posting)]
fs, ((Int, Posting)
 -> (Maybe Day, Maybe CommoditySymbol,
     Maybe (CommoditySymbol, Quantity)))
-> [(Int, Posting)] -> [(Int, Posting)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int, Posting)
-> (Maybe Day, Maybe CommoditySymbol,
    Maybe (CommoditySymbol, Quantity))
postingSortKey [(Int, Posting)]
ts)

-- | Extract a per-unit cost Amount from an AmountCost, normalising TotalCost by quantity.
-- (A TotalCost carries the amount's sign, so dividing by the signed quantity
-- gives a positive unit cost for a negative posting too.)
-- If quantity is zero, returns the TotalCost amount as-is (avoiding division by zero).
-- Uses 'divideAmountAndUpdatePrecision' so the derived unit cost renders with the
-- quotient's digits rather than inheriting the total cost's narrower display style.
amountCostToUnitCost :: Quantity -> AmountCost -> Amount
amountCostToUnitCost :: Quantity -> AmountCost -> Amount
amountCostToUnitCost Quantity
_   (UnitCost Amount
c)  = Amount
c
amountCostToUnitCost Quantity
qty (TotalCost Amount
c) = Quantity -> Amount -> Amount
divideAmountAndUpdatePrecision Quantity
qty Amount
c

-- | Normalize an amount's transacted cost to UnitCost form (converting TotalCost by dividing by quantity).
-- Returns Nothing if the amount has no transacted cost.
amountNormalizeCostToUnit :: Amount -> Maybe AmountCost
amountNormalizeCostToUnit :: Amount -> Maybe AmountCost
amountNormalizeCostToUnit Amount
a = (AmountCost -> AmountCost) -> Maybe AmountCost -> Maybe AmountCost
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Amount -> AmountCost
UnitCost (Amount -> AmountCost)
-> (AmountCost -> Amount) -> AmountCost -> AmountCost
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Quantity -> AmountCost -> Amount
amountCostToUnitCost (Amount -> Quantity
aquantity Amount
a)) (Amount -> Maybe AmountCost
acost Amount
a)


-- Per-type posting processing

-- | Process a single acquire posting (at this index in the transaction): generate a lot name and append it as a subaccount.
processAcquirePosting :: M.Map CommoditySymbol AmountStyle -> Journal -> S.Set (CommoditySymbol, Day) -> Day -> Transaction -> LotState -> Int -> Posting
                      -> Either String (LotState, Posting)
processAcquirePosting :: Map CommoditySymbol AmountStyle
-> Journal
-> Set (CommoditySymbol, Day)
-> Day
-> Transaction
-> LotState
-> Int
-> Posting
-> Either String (LotState, Posting)
processAcquirePosting Map CommoditySymbol AmountStyle
styles Journal
j Set (CommoditySymbol, Day)
needsLabels Day
txnDate Transaction
t LotState
lotState Int
idx Posting
p = do
    let lotAmts :: [(Amount, CostBasis)]
lotAmts = [(Amount
a, CostBasis
cb) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]]
        -- Long (asset) accounts' lots are opened by positive postings,
        -- Short (liability) accounts' by negative ones.
        dir :: LotDirection
dir = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j (Posting -> CommoditySymbol
paccount Posting
p)
    (lotAmt, cb, isBare) <- case [(Amount, CostBasis)]
lotAmts of
      [(Amount, CostBasis)
x] -> (Amount, CostBasis, Bool)
-> Either String (Amount, CostBasis, Bool)
forall a b. b -> Either a b
Right ((Amount, CostBasis) -> Amount
forall a b. (a, b) -> a
fst (Amount, CostBasis)
x, (Amount, CostBasis) -> CostBasis
forall a b. (a, b) -> b
snd (Amount, CostBasis)
x, Bool
False)
      [(Amount, CostBasis)]
_   -> do
        let bareAmts :: [Amount]
bareAmts = [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Bool -> Bool
not (LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
a)]
        case [Amount]
bareAmts of
          [Amount
a] -> (Amount, CostBasis, Bool)
-> Either String (Amount, CostBasis, Bool)
forall a b. b -> Either a b
Right (Amount
a, Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing Maybe Amount
forall a. Maybe a
Nothing, Bool
True)
          [Amount]
_   -> String -> Either String (Amount, CostBasis, Bool)
forall a b. a -> Either a b
Left (String -> Either String (Amount, CostBasis, Bool))
-> String -> Either String (Amount, CostBasis, Bool)
forall a b. (a -> b) -> a -> b
$ Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
idx String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"acquire posting has no cost basis"

    let commodity = Amount -> CommoditySymbol
acommodity Amount
lotAmt
        date      = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe Day
txnDate (CostBasis -> Maybe Day
cbDate CostBasis
cb)

    -- Get the original (pre-balancing) amount to check for explicit transacted price.
    -- A unit cost on the original can be used directly as the cost basis;
    -- a total cost on the balanced amount is normalised to a per-unit cost basis.
    let origAmt = case Posting -> Maybe Posting
poriginal Posting
p of
          Just Posting
orig -> case [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
orig), Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
commodity] of
                         (Amount
a:[Amount]
_) -> Amount
a
                         []    -> Amount
lotAmt
          Maybe Posting
Nothing   -> Amount
lotAmt

    let maybeLotBasis = case CostBasis -> Maybe Amount
cbCost CostBasis
cb of
          Just Amount
c  -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
c
          Maybe Amount
Nothing
            | Just (UnitCost Amount
c) <- Amount -> Maybe AmountCost
acost Amount
origAmt -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
c
            | Just AmountCost
cost <- Amount -> Maybe AmountCost
acost Amount
lotAmt -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just (Amount -> Maybe Amount) -> Amount -> Maybe Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> AmountCost -> Amount
amountCostToUnitCost (Amount -> Quantity
aquantity Amount
lotAmt) AmountCost
cost
            | Bool
otherwise                 -> Maybe Amount
forall a. Maybe a
Nothing

    case maybeLotBasis of
      Maybe Amount
Nothing | Bool
isBare    -> String -> Either String (LotState, Posting)
forall a b. a -> Either a b
Left (String -> Either String (LotState, Posting))
-> String -> Either String (LotState, Posting)
forall a b. (a -> b) -> a -> b
$ Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
idx String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" is lotful but this acquire posting has no cost basis or price.\n"
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"No lot will be created."
              | Bool
otherwise -> String -> Either String (LotState, Posting)
forall a b. a -> Either a b
Left (String -> Either String (LotState, Posting))
-> String -> Either String (LotState, Posting)
forall a b. (a -> b) -> a -> b
$ Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
idx
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"This posting creates a new " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" lot, but its lot annotation "
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName CostBasis
cb) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no cost,\n"
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"and there is no price (@ or @@) to infer one from.\n"
                                      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Please add a per-unit cost to the annotation, eg " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
withExampleCost (CostBasis -> CommoditySymbol
showLotName CostBasis
cb) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"."
      Just Amount
lotBasis -> do
        let cbInferred :: Bool
cbInferred = Maybe Amount -> Bool
forall a. Maybe a -> Bool
isNothing (CostBasis -> Maybe Amount
cbCost CostBasis
cb)
            needsLabel :: Bool
needsLabel = (CommoditySymbol, Day) -> Set (CommoditySymbol, Day) -> Bool
forall a. Ord a => a -> Set a -> Bool
S.member (CommoditySymbol
commodity, Day
date) Set (CommoditySymbol, Day)
needsLabels
            lotLabel' :: Maybe CommoditySymbol
lotLabel'  = CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
cb Maybe CommoditySymbol
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> if Bool
needsLabel then CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just (CommoditySymbol -> Day -> LotState -> CommoditySymbol
generateLabel CommoditySymbol
commodity Day
date LotState
lotState) else Maybe CommoditySymbol
forall a. Maybe a
Nothing
            -- If the lot id already exists (e.g. an equity transfer-to on the same date
            -- as a regular acquire, not predicted by findDatesNeedingLabels), auto-generate
            -- a label to disambiguate.
            existingLots :: Map LotId (Map CommoditySymbol Amount)
existingLots = Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState
            lotId0 :: LotId
lotId0     = Day -> Maybe CommoditySymbol -> LotId
LotId Day
date Maybe CommoditySymbol
lotLabel'
            (LotId
lotId, Maybe CommoditySymbol
lotLabel'')
              | Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isNothing (CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
cb) Bool -> Bool -> Bool
&& LotId -> Map LotId (Map CommoditySymbol Amount) -> Bool
forall k a. Ord k => k -> Map k a -> Bool
M.member LotId
lotId0 Map LotId (Map CommoditySymbol Amount)
existingLots
                = let l :: CommoditySymbol
l = CommoditySymbol -> Day -> LotState -> CommoditySymbol
generateLabel CommoditySymbol
commodity Day
date LotState
lotState
                  in (Day -> Maybe CommoditySymbol -> LotId
LotId Day
date (CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
l), CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
l)
              | Bool
otherwise = (LotId
lotId0, Maybe CommoditySymbol
lotLabel')
            baseAcct :: CommoditySymbol
baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
            (ReductionMethod
method, String
_methodSource) = Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodWithSource Journal
j Posting
p CommoditySymbol
commodity
            -- AVERAGEALL pools all same-direction accounts' lots, AVERAGE this account's.
            inPool :: CommoditySymbol -> Bool
inPool CommoditySymbol
acct | ReductionMethod -> Bool
methodIsGlobal ReductionMethod
method = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j CommoditySymbol
acct LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
dir
                        | Bool
otherwise             = CommoditySymbol
acct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
baseAcct

        -- Under AVERAGE/AVERAGEALL, merge this acquisition into the running pool
        -- (returns the new shared per-unit cost and an updated LotState where
        -- every existing pool lot's cbCost has been rewritten to that new cost).
        (lotBasisStored, lotState0) <-
          if ReductionMethod -> Bool
methodIsAverage ReductionMethod
method
          then String
-> (CommoditySymbol -> Bool)
-> CommoditySymbol
-> Quantity
-> Amount
-> LotState
-> Either String (Amount, LotState)
updatePoolOnAcquire (Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
idx) CommoditySymbol -> Bool
inPool
                 CommoditySymbol
commodity (Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
lotAmt)) Amount
lotBasis LotState
lotState
          else (Amount, LotState) -> Either String (Amount, LotState)
forall a b. b -> Either a b
Right (Amount
lotBasis, LotState
lotState)

        let -- For an inferred cost, widen precision to the commodity style's
            -- declared minimum (eg 2.5 -> 2.50 with 'commodity €1.00'); for
            -- a user-written explicit cost, preserve their formatting.
            widenIfInferred = if Bool
cbInferred then Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
widenLotCbCost Map CommoditySymbol AmountStyle
styles else CostBasis -> CostBasis
forall a. a -> a
id
            -- The stored cost basis is styled/widened the same way as the lot
            -- subaccount name, so that later renderings of this lot's name
            -- (on dispose and transfer postings) match the acquire's.
            fullCb     = CostBasis -> CostBasis
widenIfInferred (CostBasis -> CostBasis) -> CostBasis -> CostBasis
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles
                           CostBasis{cbDate :: Maybe Day
cbDate = Day -> Maybe Day
forall a. a -> Maybe a
Just Day
date, cbLabel :: Maybe CommoditySymbol
cbLabel = Maybe CommoditySymbol
lotLabel'', cbCost :: Maybe Amount
cbCost = Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
lotBasisStored}
            lotName    = ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
method CostBasis
fullCb
            -- When cost basis was inferred, fill it in on the user's original cb
            -- so that print shows {$50} not {}. Style it the same way as the
            -- lot subaccount name.
            filledCb   = CostBasis -> CostBasis
widenIfInferred (CostBasis -> CostBasis) -> CostBasis -> CostBasis
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
cb{cbCost = Just lotBasis}
            -- The lot state stores the full cost basis (date/label/cost).
            -- Under AVERAGE this is the running pool cost; under other methods
            -- it is the original per-acquisition cost.
            -- Lot quantities are stored unsigned (a short lot's posting is
            -- negative; the account's direction supplies the sign).
            lotStateAmt = Amount
lotAmt{aquantity = abs (aquantity lotAmt), acostbasis = Just fullCb}
            -- The displayed posting amount preserves the user's literal cost
            -- annotation (filling in only when they wrote `{}`). Under AVERAGE
            -- the running pool cost is a derived state — surfaced via bal -B
            -- and visible on disposal postings (where the user wrote `{}`
            -- and the system fills in the lot's stored cost).
            postingAmt  = if Bool
cbInferred then Amount
lotAmt{acostbasis = Just filledCb} else Amount
lotAmt

        let hasExplicitLotAcct = CommoditySymbol
baseAcct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> CommoditySymbol
paccount Posting
p
            expectedAcct = CommoditySymbol
baseAcct CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
":" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
lotName

        -- If the user wrote an explicit lot subaccount, check that its parsed
        -- CostBasis is compatible with the resolved lot's.
        when hasExplicitLotAcct $
          case mergeCostBasisForMethod method cb fullCb of
            Right CostBasis
_ -> () -> Either String ()
forall a b. b -> Either a b
Right ()
            Left String
_  -> String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ Transaction -> Int -> String
postingAtErrPrefix Transaction
t Int
idx String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot subaccount " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (Posting -> CommoditySymbol
paccount Posting
p)
                              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" does not match the resolved lot " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
expectedAcct

        -- Only a live lot (with account entries) is a duplicate; a tombstone
        -- (fully disposed lot, see 'reduceLotState') may be revived by an
        -- explicitly-labelled acquisition, eg re-opening balances after
        -- close --clopen --lots.
        when (maybe False (not . M.null) (M.lookup lotId existingLots)) $
          Left $ postingAtErrPrefix t idx ++ "duplicate lot id: " ++ T.unpack lotName
                  ++ " for commodity " ++ T.unpack commodity

        let p' = Posting
p{paccount = expectedAcct
                   ,pamount  = mixedAmount postingAmt
                   ,poriginal = Just (originalPosting p)}
        let lotState' = CommoditySymbol
-> LotId -> CommoditySymbol -> Amount -> LotState -> LotState
addLotState CommoditySymbol
commodity LotId
lotId CommoditySymbol
baseAcct Amount
lotStateAmt LotState
lotState0
        return $ lotDbg t ("acquired " ++ show (aquantity lotAmt) ++ " "
                           ++ T.unpack commodity ++ " " ++ T.unpack lotName
                           ++ " on " ++ T.unpack baseAcct)
               (lotState', p')
  where
    -- A lot name with an example cost added (cost is shown last), eg {2026-01-01} -> {2026-01-01, $50}.
    withExampleCost :: CommoditySymbol -> String
withExampleCost CommoditySymbol
name
      | CommoditySymbol
name CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
"{}" = String
"{$50}"
      | Bool
otherwise    = CommoditySymbol -> String
T.unpack (Int -> CommoditySymbol -> CommoditySymbol
T.dropEnd Int
1 CommoditySymbol
name) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
", $50}"

-- | Process a dispose posting: match to existing lots using the resolved reduction method,
-- split into multiple postings if the disposal spans multiple lots.
-- Returns the list of resulting postings (one per matched lot).
processDisposePosting :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState -> Posting
                      -> Either String (LotState, [Posting])
processDisposePosting :: Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> Posting
-> Either String (LotState, [Posting])
processDisposePosting Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
lotState Posting
p = do
    -- Extract lotful amount and lot selector. When cost basis is present, use it directly.
    -- When absent (bare dispose on a lotful commodity), use a wildcard selector.
    let lotAmts :: [(Amount, CostBasis)]
lotAmts = [(Amount
a, CostBasis
cb) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]]
        -- Long (asset) accounts' lots are closed by negative postings,
        -- Short (liability) accounts' by positive ones (covering a short).
        dir :: LotDirection
dir = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j (Posting -> CommoditySymbol
paccount Posting
p)
        -- The sign of this posting's lot-closing quantities.
        closesign :: Quantity
closesign = Quantity -> Quantity
forall a. Num a => a -> a
negate (LotDirection -> Quantity
lotDirectionSign LotDirection
dir)
    (lotAmt, cb, isBare) <- case [(Amount, CostBasis)]
lotAmts of
      [(Amount, CostBasis)
x] -> (Amount, CostBasis, Bool)
-> Either String (Amount, CostBasis, Bool)
forall a b. b -> Either a b
Right ((Amount, CostBasis) -> Amount
forall a b. (a, b) -> a
fst (Amount, CostBasis)
x, (Amount, CostBasis) -> CostBasis
forall a b. (a, b) -> b
snd (Amount, CostBasis)
x, Bool
False)
      [(Amount, CostBasis)]
_   -> do
        let bareAmts :: [Amount]
bareAmts = [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p), LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
a]
        case [Amount]
bareAmts of
          [Amount
a] -> (Amount, CostBasis, Bool)
-> Either String (Amount, CostBasis, Bool)
forall a b. b -> Either a b
Right (Amount
a, Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing Maybe Amount
forall a. Maybe a
Nothing, Bool
True)
          [Amount]
_   -> String -> Either String (Amount, CostBasis, Bool)
forall a b. a -> Either a b
Left (String -> Either String (Amount, CostBasis, Bool))
-> String -> Either String (Amount, CostBasis, Bool)
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"dispose posting has no cost basis"

    let commodity = Amount -> CommoditySymbol
acommodity Amount
lotAmt

    -- Non-bare dispose (explicit {}) without price is an error - unless the
    -- entry's non-lot-account postings (not asset or liability) receive the
    -- same commodity in the same total quantity as its priceless disposals
    -- (an in-kind outflow: a transfer fee, a donation, etc): then it
    -- proceeds as a priceless disposal, like a bare one, with no gain
    -- calculated. This also lets print --lots output of unpriced-fee
    -- transfers (whose fee dispose fragment carries an explicit lot
    -- reference) round-trip (#2692).
    -- Bare dispose without price proceeds to lot matching (but skips gain generation).
    let holdsLots CommoditySymbol
acct = Maybe LotDirection -> Bool
forall a. Maybe a -> Bool
isJust (Journal -> CommoditySymbol -> Maybe LotDirection
journalLotDirection Journal
j CommoditySymbol
acct)
        nonLotAccountReceipts = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ Amount -> Quantity
aquantity Amount
a
                                    | Posting
q <- Transaction -> [Posting]
tpostings Transaction
t, Bool -> Bool
not (CommoditySymbol -> Bool
holdsLots (Posting -> CommoditySymbol
paccount Posting
q))
                                    , Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
                                    , Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
commodity, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 ]
        pricelessDisposals = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ Quantity -> Quantity
forall a. Num a => a -> a
negate (Amount -> Quantity
aquantity Amount
a)
                                 | Posting
q <- Transaction -> [Posting]
tpostings Transaction
t, Posting -> Bool
isDisposePosting Posting
q
                                 , Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
q)
                                 , Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
commodity, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0, Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
a) ]
        isInKindOutflow = Quantity
nonLotAccountReceipts Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 Bool -> Bool -> Bool
&& Quantity
nonLotAccountReceipts Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
pricelessDisposals
    case acost lotAmt of
      Maybe AmountCost
Nothing | Bool -> Bool
not Bool
isBare Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
isInKindOutflow ->
        String -> Either String (LotState, [Posting])
forall a b. a -> Either a b
Left (String -> Either String (LotState, [Posting]))
-> String -> Either String (LotState, [Posting])
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"dispose posting has no transacted price ("
               String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if LotDirection
dir LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
Short then String
"buying price, to cover the short" else String
"selling price")
               String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
") for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
      Maybe AmountCost
_ -> do

        Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (LotDirection -> Amount -> Bool
isLotOutflow LotDirection
dir Amount
lotAmt) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
          String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"dispose posting has "
                 String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if LotDirection
dir LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
Short then String
"non-positive quantity (a short position is covered by a positive posting)"
                                     else String
"non-negative quantity")
                 String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity

        let posQty :: Quantity
posQty = Quantity -> Quantity
forall a. Num a => a -> a
abs (Amount -> Quantity
aquantity Amount
lotAmt)
            (ReductionMethod
method, String
methodSource) = Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)
resolveReductionMethodWithSource Journal
j Posting
p CommoditySymbol
commodity
            -- All methods are per-account, scoped to the posting's base account
            -- (stripping any explicit lot subaccount the user may have written).
            scopeAcct :: CommoditySymbol
scopeAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)

        Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
isBare Bool -> Bool -> Bool
&& ReductionMethod
method ReductionMethod -> ReductionMethod -> Bool
forall a. Eq a => a -> a -> Bool
== ReductionMethod
SPECID) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
          String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"SPECID requires a lot selector on dispose postings"
                 String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nUsing SPECID (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
methodSource String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")."

        selected <- (ReductionMethod, String)
-> String
-> String
-> Day
-> LotDirection
-> CommoditySymbol
-> CommoditySymbol
-> Quantity
-> CostBasis
-> LotState
-> Either String [(LotId, Amount, Quantity)]
selectLots (ReductionMethod
method, String
methodSource) (Posting -> String
postingErrPrefix Posting
p) String
"disposal" (Transaction -> Day
tdate Transaction
t) LotDirection
dir CommoditySymbol
scopeAcct CommoditySymbol
commodity Quantity
posQty CostBasis
cb
                      (Journal -> LotDirection -> CommoditySymbol -> LotState -> LotState
lotStateForDirection Journal
j LotDirection
dir CommoditySymbol
commodity LotState
lotState)

        let baseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
p)
            hasExplicitLotAcct = CommoditySymbol
baseAcct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> CommoditySymbol
paccount Posting
p
            mkPosting (LotId
lotId, Amount
storedAmt, Quantity
consumedQty) = do
              -- Under AVERAGE/AVERAGEALL the stored cost is already the running
              -- pool cost (maintained in lock-step on each acquisition); for
              -- other methods it's the per-acquisition cost. Either way, just
              -- read it from the stored lot.
              origBasis <- case Amount -> Maybe CostBasis
acostbasis Amount
storedAmt Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost of
                Just Amount
c  -> Amount -> Either String Amount
forall a b. b -> Either a b
Right Amount
c
                Maybe Amount
Nothing -> String -> Either String Amount
forall a b. a -> Either a b
Left (String -> Either String Amount) -> String -> Either String Amount
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (String -> CommoditySymbol
T.pack (LotId -> String
forall a. Show a => a -> String
show LotId
lotId))
                                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
                                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no cost basis (internal error)"
              let lotCb = CostBasis
                    { cbDate :: Maybe Day
cbDate  = Day -> Maybe Day
forall a. a -> Maybe a
Just (LotId -> Day
lotDate LotId
lotId)
                    , cbLabel :: Maybe CommoditySymbol
cbLabel = LotId -> Maybe CommoditySymbol
lotLabel LotId
lotId
                    , cbCost :: Maybe Amount
cbCost  = Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
origBasis
                    }
                  lotName = ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
method (Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
lotCb)
                  expectedAcct = CommoditySymbol
baseAcct CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
":" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
lotName
              -- If the user wrote an explicit lot subaccount, check that its
              -- parsed CostBasis is compatible with the resolved lot's.
              when hasExplicitLotAcct $
                case mergeCostBasisForMethod method cb lotCb of
                  Right CostBasis
_ -> () -> Either String ()
forall a b. b -> Either a b
Right ()
                  Left String
_  -> String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot subaccount " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (Posting -> CommoditySymbol
paccount Posting
p)
                                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" does not match the resolved lot " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
expectedAcct
              let acctWithLot = CommoditySymbol
expectedAcct
                  -- Build the dispose amount: the consumed quantity with the
                  -- closing sign (negative; positive when covering a short),
                  -- keeping the original amount's commodity, style, cost, and cost basis.
                  disposeAmt = (Quantity -> Amount -> Amount
amountSetQuantity (Quantity
closesign Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
* Quantity
consumedQty) Amount
lotAmt){acostbasis = Just lotCb}
              let -- For bare disposes without a price (e.g. fee deductions), keep no cost.
                  -- When splitting across multiple lots, normalize TotalCost to UnitCost
                  -- (since TotalCost would be wrong for the split quantity) (#2839).
                  disposeAmt' | Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe AmountCost
acost Amount
lotAmt) = Amount
disposeAmt{acost = Nothing}
                              | [(LotId, Amount, Quantity)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(LotId, Amount, Quantity)]
selected Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1 = Amount
disposeAmt{acost = amountNormalizeCostToUnit lotAmt}
                              | Bool
otherwise = Amount
disposeAmt
              Right p{ paccount  = acctWithLot
                     , pamount   = mixedAmount disposeAmt'
                     , poriginal = Just (originalPosting p)
                     }

        newPostings0 <- mapM mkPosting selected
        -- For multi-lot disposals, tag each fragment as a per-lot split so
        -- journalCollapseLotDetail can merge them back to a single posting
        -- (when --lots is off). Single-lot disposals need no tag — they
        -- already represent the user's original posting.
        -- See also [better lot splitting].
        let taggedPostings = case [Posting]
newPostings0 of
              [Posting
_] -> [Posting]
newPostings0
              [Posting]
_   -> (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
lotsplitPostingTagName, CommoditySymbol
"")) [Posting]
newPostings0
        let consumed  = [(LotId
lotId, Quantity
qty) | (LotId
lotId, Amount
_, Quantity
qty) <- [(LotId, Amount, Quantity)]
selected]
            lotState' = CommoditySymbol
-> CommoditySymbol -> [(LotId, Quantity)] -> LotState -> LotState
reduceLotState CommoditySymbol
scopeAcct CommoditySymbol
commodity [(LotId, Quantity)]
consumed LotState
lotState
            -- A single-fragment dispose with no other lots remaining for this
            -- commodity on scopeAcct doesn't need the =* parent-assertion
            -- synthetic: the lot subaccount balance equals the parent balance,
            -- so the user's assertion is correct as-is on the single fragment.
            noOtherLots = (Map CommoditySymbol Amount -> Bool)
-> [Map CommoditySymbol Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (CommoditySymbol -> Map CommoditySymbol Amount -> Bool
forall k a. Ord k => k -> Map k a -> Bool
M.notMember CommoditySymbol
scopeAcct) ([Map CommoditySymbol Amount] -> Bool)
-> [Map CommoditySymbol Amount] -> Bool
forall a b. (a -> b) -> a -> b
$ Map LotId (Map CommoditySymbol Amount)
-> [Map CommoditySymbol Amount]
forall k a. Map k a -> [a]
M.elems
                        (Map LotId (Map CommoditySymbol Amount)
 -> [Map CommoditySymbol Amount])
-> Map LotId (Map CommoditySymbol Amount)
-> [Map CommoditySymbol Amount]
forall a b. (a -> b) -> a -> b
$ Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState'
            finalPostings = case [Posting]
taggedPostings of
              [Posting
_] | Bool
noOtherLots -> [Posting]
taggedPostings
              [Posting]
_ -> Bool
-> CommoditySymbol
-> Maybe BalanceAssertion
-> [Posting]
-> [Posting]
preserveParentAssertion Bool
verbosetags (Posting -> CommoditySymbol
paccount Posting
p) (Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p) [Posting]
taggedPostings

        return $ lotDbg t ("disposed " ++ show posQty ++ " " ++ T.unpack commodity
                           ++ " from " ++ T.unpack scopeAcct
                           ++ " (" ++ show method ++ ", lots: " ++ showSelectedLots selected ++ ")")
               (lotState', finalPostings)
  where
    showPos :: String
showPos = Transaction -> String
txnErrPrefix Transaction
t

-- [better lot splitting]
-- "If you want it bulletproof: the robust fix is a per-call group ID.
-- In processDisposePosting / the transfer caller, mint a small unique tag value 
-- (e.g. the source position string of p, or a counter, or T.pack (show (psourcepos p)))
-- and store it on each fragment as (lotsplitPostingTagName, groupId).
-- Then mergeLotSplits groups by tag value, not poriginal equality.
-- That removes the "Eq Posting must include something distinguishing" invariant entirely.

-- | Process one commodity's transfer group: select lots from each source
-- (transfer-from) posting's account, in group order, then distribute the
-- selected lots across the destination (transfer-to) postings in group
-- order, splitting lots at destination boundaries. Sources and destinations
-- need not pair up one to one; the group's total from/to quantities have
-- already been checked equal by 'groupIndexedTransferPostings'.
-- Returns the updated LotState and each original posting index's expanded postings.
processTransferGroup :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState
                     -> (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
                     -> Either String (LotState, M.Map Int [Posting])
processTransferGroup :: Map CommoditySymbol AmountStyle
-> Bool
-> Journal
-> Transaction
-> LotState
-> (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])
-> Either String (LotState, Map Int [Posting])
processTransferGroup Map CommoditySymbol AmountStyle
styles Bool
verbosetags Journal
j Transaction
t LotState
lotState0 (CommoditySymbol
commodity, [(Int, Posting)]
ifroms, [(Int, Posting)]
itos) = do
    -- Select lots for each transfer-from posting, reducing the lot state.
    (lotState1, fromDoneR) <- ((LotState, [(Int, Posting, Amount, [(LotId, Amount, Quantity)])])
 -> (Int, Posting)
 -> Either
      String
      (LotState, [(Int, Posting, Amount, [(LotId, Amount, Quantity)])]))
-> (LotState,
    [(Int, Posting, Amount, [(LotId, Amount, Quantity)])])
-> [(Int, Posting)]
-> Either
     String
     (LotState, [(Int, Posting, Amount, [(LotId, Amount, Quantity)])])
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (LotState, [(Int, Posting, Amount, [(LotId, Amount, Quantity)])])
-> (Int, Posting)
-> Either
     String
     (LotState, [(Int, Posting, Amount, [(LotId, Amount, Quantity)])])
forall {a}.
(LotState, [(a, Posting, Amount, [(LotId, Amount, Quantity)])])
-> (a, Posting)
-> Either
     String
     (LotState, [(a, Posting, Amount, [(LotId, Amount, Quantity)])])
doFrom (LotState
lotState0, []) [(Int, Posting)]
ifroms
    let fromDone = [(Int, Posting, Amount, [(LotId, Amount, Quantity)])]
-> [(Int, Posting, Amount, [(LotId, Amount, Quantity)])]
forall a. [a] -> [a]
reverse [(Int, Posting, Amount, [(LotId, Amount, Quantity)])]
fromDoneR
        -- All selected lot fragments, in group order, available for distribution.
        queue0 = [ (LotId
lotId, Amount
storedAmt, Quantity
qty, Amount
fromAmt)
                 | (Int
_, Posting
_, Amount
fromAmt, [(LotId, Amount, Quantity)]
selected) <- [(Int, Posting, Amount, [(LotId, Amount, Quantity)])]
fromDone
                 , (LotId
lotId, Amount
storedAmt, Quantity
qty) <- [(LotId, Amount, Quantity)]
selected ]
    -- Distribute the fragments across the transfer-to postings.
    (lotState2, toDoneR, rest) <- foldM doTo (lotState1, [], queue0) itos
    -- The group's totals are equal, so distribution must come out exact.
    unless (null rest) $
      Left $ showPos ++ "could not distribute transferred lots exactly (internal error)"
    fromEntries <- mapM mkFromEntry fromDone
    Right (lotState2, M.fromList (fromEntries ++ reverse toDoneR))
  where
    showPos :: String
showPos = Transaction -> String
txnErrPrefix Transaction
t

    -- Extract a from posting's lotful amount and lot selector, validate it,
    -- and select the lots it consumes from its account.
    doFrom :: (LotState, [(a, Posting, Amount, [(LotId, Amount, Quantity)])])
-> (a, Posting)
-> Either
     String
     (LotState, [(a, Posting, Amount, [(LotId, Amount, Quantity)])])
doFrom (LotState
st, [(a, Posting, Amount, [(LotId, Amount, Quantity)])]
acc) (a
i, Posting
fromP) = do
      -- When cost basis is present, use it directly as the lot selector.
      -- When absent (bare transfer on a lotful commodity), use a wildcard selector.
      (fromAmt, fromCb) <- case [(Amount
a, CostBasis
cb) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
fromP), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]] of
        [(Amount, CostBasis)
x] -> (Amount, CostBasis) -> Either String (Amount, CostBasis)
forall a b. b -> Either a b
Right (Amount, CostBasis)
x
        [(Amount, CostBasis)]
_   -> case [Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
fromP), Amount -> Bool
isNegativeAmount Amount
a] of
                 [Amount
a] -> (Amount, CostBasis) -> Either String (Amount, CostBasis)
forall a b. b -> Either a b
Right (Amount
a, Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing Maybe Amount
forall a. Maybe a
Nothing)
                 [Amount]
_   -> String -> Either String (Amount, CostBasis)
forall a b. a -> Either a b
Left (String -> Either String (Amount, CostBasis))
-> String -> Either String (Amount, CostBasis)
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"transfer-from posting has no cost basis"
      checkNoTransactedPrice fromP
      when (aquantity fromAmt >= 0) $
        Left $ showPos ++ "transfer-from posting has non-negative quantity for " ++ T.unpack commodity
      let fromQty = Quantity -> Quantity
forall a. Num a => a -> a
negate (Amount -> Quantity
aquantity Amount
fromAmt)
          -- Transfers are always per-account (scoped to source), but ordering follows the method.
          (method, methodSource) = resolveReductionMethodWithSource j fromP commodity
          fromBaseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
fromP)
      selected <- selectLots (method, methodSource) (postingErrPrefix fromP) "transfer" (tdate t) Long fromBaseAcct commodity fromQty fromCb
                    (lotStateForDirection j Long commodity st)
      let st' = CommoditySymbol
-> CommoditySymbol -> [(LotId, Quantity)] -> LotState -> LotState
reduceLotState CommoditySymbol
fromBaseAcct CommoditySymbol
commodity [(LotId
lid, Quantity
qty) | (LotId
lid, Amount
_, Quantity
qty) <- [(LotId, Amount, Quantity)]
selected] LotState
st
      return $ lotDbg t ("transferred out " ++ show fromQty ++ " " ++ T.unpack commodity
                          ++ " from " ++ T.unpack fromBaseAcct
                          ++ " (lots: " ++ showSelectedLots selected ++ ")")
             (st', (i, fromP, fromAmt, selected) : acc)

    -- Generate a from posting's per-lot display fragments.
    mkFromEntry :: (a, Posting, Amount, [(LotId, Amount, Quantity)])
-> Either String (a, [Posting])
mkFromEntry (a
i, Posting
fromP, Amount
fromAmt, [(LotId, Amount, Quantity)]
selected) = do
      ps <- ((LotId, Amount, Quantity) -> Either String Posting)
-> [(LotId, Amount, Quantity)] -> Either String [Posting]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (LotId, Amount, Quantity) -> Either String Posting
mk [(LotId, Amount, Quantity)]
selected
      Right (i, preserveParentAssertion verbosetags (paccount fromP) (pbalanceassertion fromP) (tagIfMulti ps))
      where
        mk :: (LotId, Amount, Quantity) -> Either String Posting
mk (LotId
lotId, Amount
storedAmt, Quantity
qty) = do
          lotCb <- LotId -> Amount -> Either String CostBasis
lotCbOf LotId
lotId Amount
storedAmt
          let (fromMethod, _) = resolveReductionMethodWithSource j fromP commodity
              lotName = ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
fromMethod (Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
lotCb)
              -- Use base accounts to avoid double-appending lot subaccounts.
              fromAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
fromP) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
":" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
lotName
              fromAmt' = (Quantity -> Amount -> Amount
amountSetQuantity (Quantity -> Quantity
forall a. Num a => a -> a
negate Quantity
qty) Amount
fromAmt){acostbasis = Just lotCb}
          -- poriginal preserves the user's original annotations, unmodified.
          Right fromP{ paccount = fromAcct
                     , pamount  = mixedAmount fromAmt'
                     , poriginal = Just (originalPosting fromP)
                     }

    -- Give a to posting its share of the selected lot fragments, generating
    -- its display fragments and re-adding the lots under its account.
    doTo :: (LotState, [(a, [Posting])], [(LotId, Amount, Quantity, Amount)])
-> (a, Posting)
-> Either
     String
     (LotState, [(a, [Posting])], [(LotId, Amount, Quantity, Amount)])
doTo (LotState
st, [(a, [Posting])]
acc, [(LotId, Amount, Quantity, Amount)]
queue) (a
i, Posting
toP) = do
      Posting -> Either String ()
checkNoTransactedPrice Posting
toP
      toQty <- case [Amount -> Quantity
aquantity Amount
a | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
toP), Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
commodity, Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0] of
        [Quantity
q] -> Quantity -> Either String Quantity
forall a b. b -> Either a b
Right Quantity
q
        [Quantity]
_   -> String -> Either String Quantity
forall a b. a -> Either a b
Left (String -> Either String Quantity)
-> String -> Either String Quantity
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"transfer-to posting has no single positive "
                        String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" amount"
      -- Extract the transfer-to cost basis for optional validation.
      let toCb = case [(Amount
a, CostBasis
cb) | Amount
a <- MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
toP), Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]] of
                   [(Amount
_, CostBasis
cb)] -> CostBasis -> Maybe CostBasis
forall a. a -> Maybe a
Just CostBasis
cb
                   [(Amount, CostBasis)]
_         -> Maybe CostBasis
forall a. Maybe a
Nothing
          (portions, queue') = drawFromQueue toQty queue
          (toMethod, _) = resolveReductionMethodWithSource j toP commodity
          toBaseAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
toP)
      when (sum [qty | (_, _, qty, _) <- portions] /= toQty) $
        Left $ showPos ++ "could not distribute transferred lots exactly (internal error)"
      toPs <- mapM (mkToPosting toMethod toP toCb) portions
      st' <- foldM (addTransferredLot toMethod toBaseAcct) st
                   [(lid, amt, qty) | (lid, amt, qty, _) <- portions]
      return $ lotDbg t ("transferred in " ++ show toQty ++ " " ++ T.unpack commodity
                          ++ " to " ++ T.unpack toBaseAcct)
             (st', (i, preserveParentAssertion verbosetags (paccount toP) (pbalanceassertion toP) (tagIfMulti toPs)) : acc, queue')

    mkToPosting :: ReductionMethod
-> Posting
-> Maybe CostBasis
-> (LotId, Amount, Quantity, Amount)
-> Either String Posting
mkToPosting ReductionMethod
toMethod Posting
toP Maybe CostBasis
toCb (LotId
lotId, Amount
storedAmt, Quantity
qty, Amount
fromAmt) = do
      lotCb <- LotId -> Amount -> Either String CostBasis
lotCbOf LotId
lotId Amount
storedAmt
      -- Validate transfer-to cost basis if it has specific fields
      validateToCb toMethod toCb lotCb
      let lotName = ReductionMethod -> CostBasis -> CommoditySymbol
showLotNameForMethod ReductionMethod
toMethod (Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis
styleLotCbCost Map CommoditySymbol AmountStyle
styles CostBasis
lotCb)
          toAcct = CommoditySymbol -> CommoditySymbol
lotBaseAccount (Posting -> CommoditySymbol
paccount Posting
toP) CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
":" CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
lotName
          toAmt' = (Quantity -> Amount -> Amount
amountSetQuantity Quantity
qty Amount
fromAmt){acostbasis = Just lotCb}
      Right toP{ paccount = toAcct
               , pamount  = mixedAmount toAmt'
               , poriginal = Just (originalPosting toP)
               }

    -- Take fragments totalling the given quantity from the front of the
    -- queue, splitting the boundary fragment if needed.
    drawFromQueue :: Quantity -> [(LotId, Amount, Quantity, Amount)]
                  -> ([(LotId, Amount, Quantity, Amount)], [(LotId, Amount, Quantity, Amount)])
    drawFromQueue :: Quantity
-> [(LotId, Amount, Quantity, Amount)]
-> ([(LotId, Amount, Quantity, Amount)],
    [(LotId, Amount, Quantity, Amount)])
drawFromQueue Quantity
0 [(LotId, Amount, Quantity, Amount)]
queue = ([], [(LotId, Amount, Quantity, Amount)]
queue)
    drawFromQueue Quantity
_ [] = ([], [])
    drawFromQueue Quantity
need ((LotId
lid, Amount
amt, Quantity
qty, Amount
fa):[(LotId, Amount, Quantity, Amount)]
rest)
      | Quantity
need Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
>= Quantity
qty = let ([(LotId, Amount, Quantity, Amount)]
taken, [(LotId, Amount, Quantity, Amount)]
rest') = Quantity
-> [(LotId, Amount, Quantity, Amount)]
-> ([(LotId, Amount, Quantity, Amount)],
    [(LotId, Amount, Quantity, Amount)])
drawFromQueue (Quantity
need Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
qty) [(LotId, Amount, Quantity, Amount)]
rest
                      in ((LotId
lid, Amount
amt, Quantity
qty, Amount
fa)(LotId, Amount, Quantity, Amount)
-> [(LotId, Amount, Quantity, Amount)]
-> [(LotId, Amount, Quantity, Amount)]
forall a. a -> [a] -> [a]
:[(LotId, Amount, Quantity, Amount)]
taken, [(LotId, Amount, Quantity, Amount)]
rest')
      | Bool
otherwise   = ([(LotId
lid, Amount
amt, Quantity
need, Amount
fa)], (LotId
lid, Amount
amt, Quantity
qty Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
need, Amount
fa)(LotId, Amount, Quantity, Amount)
-> [(LotId, Amount, Quantity, Amount)]
-> [(LotId, Amount, Quantity, Amount)]
forall a. a -> [a] -> [a]
:[(LotId, Amount, Quantity, Amount)]
rest)

    -- Check that a transfer posting has no user-written transacted price (@ or @@).
    -- Use originalPosting to distinguish user-written @ from pipeline-inferred acost.
    checkNoTransactedPrice :: Posting -> Either String ()
checkNoTransactedPrice Posting
p =
      Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) (MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
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)) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
        String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot transfers should have no transacted price"

    -- For multi-fragment postings, tag each fragment as a per-lot split so
    -- journalCollapseLotDetail can merge them back to a single posting when
    -- --lots is off. Single-fragment postings need no tag.
    tagIfMulti :: [Posting] -> [Posting]
tagIfMulti [Posting]
ps = case [Posting]
ps of
      [Posting
_] -> [Posting]
ps
      [Posting]
_   -> (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Bool
-> Bool -> (CommoditySymbol, CommoditySymbol) -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (CommoditySymbol
lotsplitPostingTagName, CommoditySymbol
"")) [Posting]
ps

    -- Reconstruct a lot's full cost basis from its id and stored amount.
    lotCbOf :: LotId -> Amount -> Either String CostBasis
lotCbOf LotId
lotId Amount
storedAmt = case Amount -> Maybe CostBasis
acostbasis Amount
storedAmt Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost of
      Just Amount
c  -> CostBasis -> Either String CostBasis
forall a b. b -> Either a b
Right CostBasis{cbDate :: Maybe Day
cbDate = Day -> Maybe Day
forall a. a -> Maybe a
Just (LotId -> Day
lotDate LotId
lotId), cbLabel :: Maybe CommoditySymbol
cbLabel = LotId -> Maybe CommoditySymbol
lotLabel LotId
lotId, cbCost :: Maybe Amount
cbCost = Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
c}
      Maybe Amount
Nothing -> String -> Either String CostBasis
forall a b. a -> Either a b
Left (String -> Either String CostBasis)
-> String -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot " String -> String -> String
forall a. [a] -> [a] -> [a]
++ LotId -> String
forall a. Show a => a -> String
show LotId
lotId
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" has no cost basis (internal error)"

    -- If the transfer-to posting has any attributes specified in a lot annotation,
    -- make sure they correspond to the source lot's attributes.
    -- Transfers are not allowed to change a lot's identity.
    -- Under an AVERAGE destination method the cost check is skipped:
    -- the pool's running cost legitimately differs from any written cost
    -- (cf mergeCostBasisForMethod).
    validateToCb :: ReductionMethod -> Maybe CostBasis -> CostBasis -> Either String ()
validateToCb ReductionMethod
_ Maybe CostBasis
Nothing CostBasis
_ = () -> Either String ()
forall a b. b -> Either a b
Right ()
    validateToCb ReductionMethod
method (Just CostBasis
toCb') CostBasis
lotCb =
        Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
dateMismatch Bool -> Bool -> Bool
|| Bool
labelMismatch Bool -> Bool -> Bool
|| Bool
costMismatch) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
          String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
showPos String -> String -> String
forall a. Semigroup a => a -> a -> a
<> [String] -> String
unlines
            [String
"Destination lot info " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName CostBasis
toCb') String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" does not match the source lot " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName CostBasis
lotCb) String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"."
            ,String
"Transfers must preserve the source lot's identity."
            ,String
"Remove the destination lot annotation, or make it match the source lot's info."
            ]

      where
        dateMismatch :: Bool
dateMismatch  = case CostBasis -> Maybe Day
cbDate CostBasis
toCb' of
          Just Day
d  -> CostBasis -> Maybe Day
cbDate CostBasis
lotCb Maybe Day -> Maybe Day -> Bool
forall a. Eq a => a -> a -> Bool
/= Day -> Maybe Day
forall a. a -> Maybe a
Just Day
d
          Maybe Day
Nothing -> Bool
False
        labelMismatch :: Bool
labelMismatch = case CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
toCb' of
          Just CommoditySymbol
l  -> CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
lotCb Maybe CommoditySymbol -> Maybe CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
l
          Maybe CommoditySymbol
Nothing -> Bool
False
        costMismatch :: Bool
costMismatch  = Bool -> Bool
not (ReductionMethod -> Bool
methodIsAverage ReductionMethod
method) Bool -> Bool -> Bool
&&
          case (CostBasis -> Maybe Amount
cbCost CostBasis
toCb', CostBasis -> Maybe Amount
cbCost CostBasis
lotCb) of
            (Just Amount
c, Just Amount
lc) -> Bool -> Bool
not (Amount -> Amount -> Bool
lotCostsMatch Amount
c Amount
lc)
            (Maybe Amount, Maybe Amount)
_                 -> Bool
False

    -- Re-add a transferred lot to LotState under the destination account.
    -- If the destination uses an AVERAGE method, first re-average its pool
    -- with the incoming quantity at its carried cost, like an acquisition;
    -- the incoming lot is then stored at the new pool cost. (Under
    -- AVERAGEALL this is a no-op: the lot never left the global pool, so
    -- the carried cost equals the pool cost.)
    addTransferredLot :: ReductionMethod
-> CommoditySymbol
-> LotState
-> (LotId, Amount, Quantity)
-> Either String LotState
addTransferredLot ReductionMethod
method CommoditySymbol
destAcct LotState
ls (LotId
lotId, Amount
storedAmt, Quantity
consumedQty)
      | ReductionMethod -> Bool
methodIsAverage ReductionMethod
method = do
          lotCb <- LotId -> Amount -> Either String CostBasis
lotCbOf LotId
lotId Amount
storedAmt
          carried <- maybe (Left $ showPos ++ "lot " ++ show lotId
                              ++ " has no carried cost (internal error)") Right (cbCost lotCb)
          -- (transfers are of long lots only, so AVERAGEALL pools the Long accounts)
          let inPool CommoditySymbol
acct | ReductionMethod -> Bool
methodIsGlobal ReductionMethod
method = Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j CommoditySymbol
acct LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
Long
                          | Bool
otherwise             = CommoditySymbol
acct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
destAcct
          (newAvg, ls') <- updatePoolOnAcquire showPos inPool commodity consumedQty carried ls
          let amt = Amount
storedAmt{aquantity = consumedQty, acostbasis = Just lotCb{cbCost = Just newAvg}}
          Right $ addLotState commodity lotId destAcct amt ls'
      | Bool
otherwise =
          let amt :: Amount
amt = Amount
storedAmt{aquantity = consumedQty}
          in LotState -> Either String LotState
forall a b. b -> Either a b
Right (LotState -> Either String LotState)
-> LotState -> Either String LotState
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
-> LotId -> CommoditySymbol -> Amount -> LotState -> LotState
addLotState CommoditySymbol
commodity LotId
lotId CommoditySymbol
destAcct Amount
amt LotState
ls

-- Lot state operations

-- | Add an amount to LotState for a specific account/commodity/lot.
-- If the lot already exists on that account, quantities are summed (not overwritten).
-- This can happen when the same lot is transferred to the same destination account
-- by multiple transactions (e.g. two transfers on the same date both move portions
-- of the same lot).
addLotState :: CommoditySymbol -> LotId -> AccountName -> Amount -> LotState -> LotState
addLotState :: CommoditySymbol
-> LotId -> CommoditySymbol -> Amount -> LotState -> LotState
addLotState CommoditySymbol
commodity LotId
lotId CommoditySymbol
account Amount
amt =
  (Map LotId (Map CommoditySymbol Amount)
 -> Map LotId (Map CommoditySymbol Amount)
 -> Map LotId (Map CommoditySymbol Amount))
-> CommoditySymbol
-> Map LotId (Map CommoditySymbol Amount)
-> LotState
-> LotState
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith ((Map CommoditySymbol Amount
 -> Map CommoditySymbol Amount -> Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith ((Amount -> Amount -> Amount)
-> Map CommoditySymbol Amount
-> Map CommoditySymbol Amount
-> Map CommoditySymbol Amount
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
M.unionWith Amount -> Amount -> Amount
addQty)) CommoditySymbol
commodity
    (LotId
-> Map CommoditySymbol Amount
-> Map LotId (Map CommoditySymbol Amount)
forall k a. k -> a -> Map k a
M.singleton LotId
lotId (CommoditySymbol -> Amount -> Map CommoditySymbol Amount
forall k a. k -> a -> Map k a
M.singleton CommoditySymbol
account Amount
amt))
  where addQty :: Amount -> Amount -> Amount
addQty Amount
a1 Amount
a2 = Amount
a1{aquantity = aquantity a1 + aquantity a2}


-- | Restrict one commodity's lots in a lot state to the accounts with the
-- given lot direction. Long lots (in asset accounts) and short lots (in
-- liability accounts) are separate pools: the global (*ALL) methods and the
-- "other accounts" error summaries should see only one of them.
lotStateForDirection :: Journal -> LotDirection -> CommoditySymbol -> LotState -> LotState
lotStateForDirection :: Journal -> LotDirection -> CommoditySymbol -> LotState -> LotState
lotStateForDirection Journal
j LotDirection
dir CommoditySymbol
commodity =
  (Map LotId (Map CommoditySymbol Amount)
 -> Map LotId (Map CommoditySymbol Amount))
-> CommoditySymbol -> LotState -> LotState
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
M.adjust ((Map CommoditySymbol Amount -> Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall a b k. (a -> b) -> Map k a -> Map k b
M.map ((CommoditySymbol -> Amount -> Bool)
-> Map CommoditySymbol Amount -> Map CommoditySymbol Amount
forall k a. (k -> a -> Bool) -> Map k a -> Map k a
M.filterWithKey (\CommoditySymbol
acct Amount
_ -> Journal -> CommoditySymbol -> LotDirection
journalLotDirectionOrLong Journal
j CommoditySymbol
acct LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
dir))) CommoditySymbol
commodity

-- | Select lots to consume using the given reduction method.
-- All methods select from the specified account only.
-- Ordering: FIFO\/FIFOALL oldest-first; LIFO\/LIFOALL newest-first;
-- HIFO\/HIFOALL highest per-unit cost first; AVERAGE\/AVERAGEALL FIFO order;
-- SPECID requires an explicit selector matching one lot.
-- The *ALL variants additionally validate that the selected lots would also be
-- chosen first if all accounts' lots were considered together (see 'validateGlobalCompliance').
-- The lot selector filters which lots are eligible: each non-Nothing field
-- in the selector must match the corresponding field in the lot's cost basis.
-- An all-Nothing selector (from @{}@) matches all lots.
-- Returns a list of (lot id, lot amount, quantity consumed from this lot).
-- Errors if total available quantity in matching lots is insufficient.
-- The lot direction is that of the account (the lot state should already be
-- restricted to that direction, see 'lotStateForDirection'); it is used to
-- suggest a liability account when a long account has no lots to dispose of.
selectLots :: (ReductionMethod, String) -> String -> String -> Day -> LotDirection -> AccountName -> CommoditySymbol
           -> Quantity -> CostBasis -> LotState
           -> Either String [(LotId, Amount, Quantity)]
selectLots :: (ReductionMethod, String)
-> String
-> String
-> Day
-> LotDirection
-> CommoditySymbol
-> CommoditySymbol
-> Quantity
-> CostBasis
-> LotState
-> Either String [(LotId, Amount, Quantity)]
selectLots (ReductionMethod
method, String
methodSource) String
posStr String
operation Day
date LotDirection
direction CommoditySymbol
account CommoditySymbol
commodity Quantity
qty CostBasis
selector LotState
lotState = do
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ReductionMethod
method ReductionMethod -> ReductionMethod -> Bool
forall a. Eq a => a -> a -> Bool
== ReductionMethod
SPECID Bool -> Bool -> Bool
&& CostBasis -> Bool
isWildcardSelector CostBasis
selector) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"SPECID requires an explicit lot selector" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
methodline
    let allLots :: Map LotId (Map CommoditySymbol Amount)
allLots = Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState
        -- Flatten to (LotId, Amount) pairs, taking only the specified account's balance.
        flatLots :: Map LotId Amount
flatLots = (Map CommoditySymbol Amount -> Maybe Amount)
-> Map LotId (Map CommoditySymbol Amount) -> Map LotId Amount
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
M.mapMaybe (CommoditySymbol -> Map CommoditySymbol Amount -> Maybe Amount
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
account) Map LotId (Map CommoditySymbol Amount)
allLots
        matchingLots :: Map LotId Amount
matchingLots = (Amount -> Bool) -> Map LotId Amount -> Map LotId Amount
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (CostBasis -> Amount -> Bool
lotMatchesSelector CostBasis
selector) Map LotId Amount
flatLots
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Map LotId Amount -> Bool
forall k a. Map k a -> Bool
M.null Map LotId Amount
matchingLots) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++
        if Map LotId Amount -> Bool
forall k a. Map k a -> Bool
M.null Map LotId Amount
flatLots
        then String
"no " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" lots available for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
operation
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" from account " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" on " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Day -> String
forall a. Show a => a -> String
show Day
date
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ Map LotId (Map CommoditySymbol Amount) -> String
showOtherAccountLots Map LotId (Map CommoditySymbol Amount)
allLots
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
shorthint
        else String
"no lots matching " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName CostBasis
selector)
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in account " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" on " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Day -> String
forall a. Show a => a -> String
show Day
date
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nAvailable lots in this account:" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Map LotId Amount -> String
showLotList Map LotId Amount
flatLots
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ReductionMethod
method ReductionMethod -> ReductionMethod -> Bool
forall a. Eq a => a -> a -> Bool
== ReductionMethod
SPECID Bool -> Bool -> Bool
&& Map LotId Amount -> Int
forall k a. Map k a -> Int
M.size Map LotId Amount
matchingLots Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"lot selector is ambiguous, matches " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show (Map LotId Amount -> Int
forall k a. Map k a -> Int
M.size Map LotId Amount
matchingLots)
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" lots in account " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ Map LotId Amount -> String
showLotList Map LotId Amount
matchingLots String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
methodline
    let available :: Quantity
available = [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Amount -> Quantity
aquantity Amount
a | Amount
a <- Map LotId Amount -> [Amount]
forall k a. Map k a -> [a]
M.elems Map LotId Amount
matchingLots]
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Quantity
available Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
qty) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"Insufficient lots for commodity " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in account " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": need " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show Quantity
qty String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" but only " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show Quantity
available String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" available"
              -- with an explicit lot selector, show what it matched;
              -- for a generic outflow the lot details wouldn't help
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if CostBasis -> Bool
isWildcardSelector CostBasis
selector then String
""
                  else String
"\nLots matching " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName CostBasis
selector) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":"
                        String -> String -> String
forall a. [a] -> [a] -> [a]
++ Map LotId Amount -> String
showLotList Map LotId Amount
matchingLots)
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ Map LotId (Map CommoditySymbol Amount) -> String
showOtherAccountLots Map LotId (Map CommoditySymbol Amount)
allLots
    let base :: ReductionMethod
base = ReductionMethod -> ReductionMethod
methodBaseOrdering ReductionMethod
method
        orderedLots :: [(LotId, Amount)]
orderedLots = case ReductionMethod
base of
          ReductionMethod
FIFO    -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
matchingLots
          ReductionMethod
LIFO    -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toDescList Map LotId Amount
matchingLots
          ReductionMethod
HIFO    -> ((LotId, Amount) -> Down Quantity)
-> [(LotId, Amount)] -> [(LotId, Amount)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity)
-> ((LotId, Amount) -> Quantity)
-> (LotId, Amount)
-> Down Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (LotId, Amount) -> Quantity
lotPerUnitCost) (Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toList Map LotId Amount
matchingLots)
          ReductionMethod
AVERAGE -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
matchingLots
          ReductionMethod
SPECID  -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
matchingLots
          ReductionMethod
_       -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
matchingLots  -- unreachable after methodBaseOrdering
        selected :: [(LotId, Amount, Quantity)]
selected = Quantity -> [(LotId, Amount)] -> [(LotId, Amount, Quantity)]
forall {a}. Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
go Quantity
qty [(LotId, Amount)]
orderedLots
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ReductionMethod -> Bool
methodIsGlobal ReductionMethod
method) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      (String -> String) -> Either String () -> Either String ()
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
methodline) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      ReductionMethod
-> String
-> CommoditySymbol
-> CommoditySymbol
-> Quantity
-> CostBasis
-> LotState
-> [(LotId, Amount, Quantity)]
-> Either String ()
validateGlobalCompliance ReductionMethod
method String
posStr CommoditySymbol
account CommoditySymbol
commodity Quantity
qty CostBasis
selector LotState
lotState [(LotId, Amount, Quantity)]
selected
    [(LotId, Amount, Quantity)]
-> Either String [(LotId, Amount, Quantity)]
forall a b. b -> Either a b
Right [(LotId, Amount, Quantity)]
selected
  where
    -- The reduction method and where it came from; appended to the errors
    -- where the method matters (the availability errors omit it).
    methodline :: String
methodline = String
"\nUsing " String -> String -> String
forall a. [a] -> [a] -> [a]
++ ReductionMethod -> String
forall a. Show a => a -> String
show ReductionMethod
method String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
methodSource String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")."

    -- A sale from an asset account holding none of the commodity may be a
    -- short sale, which belongs in a liability account.
    shorthint :: String
shorthint
      | LotDirection
direction LotDirection -> LotDirection -> Bool
forall a. Eq a => a -> a -> Bool
== LotDirection
Long Bool -> Bool -> Bool
&& String
operation String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"disposal" =
          String
"\n(To record a short position, use a liability account.)"
      | Bool
otherwise = String
""

    go :: Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
go Quantity
0 [(a, Amount)]
_ = []
    go Quantity
_ [] = []  -- shouldn't happen after the check above
    go Quantity
remaining ((a
lotId, Amount
lotAmt):[(a, Amount)]
rest)
      | Quantity
remaining Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
>= Quantity
lotBal = (a
lotId, Amount
lotAmt, Quantity
lotBal) (a, Amount, Quantity)
-> [(a, Amount, Quantity)] -> [(a, Amount, Quantity)]
forall a. a -> [a] -> [a]
: Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
go (Quantity
remaining Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Quantity
lotBal) [(a, Amount)]
rest
      | Bool
otherwise           = [(a
lotId, Amount
lotAmt, Quantity
remaining)]
      where lotBal :: Quantity
lotBal = Amount -> Quantity
aquantity Amount
lotAmt

    -- Show lots one per line, at most 10; a final line counts any more,
    -- and another shows the total quantity.
    showLotList :: M.Map LotId Amount -> String
    showLotList :: Map LotId Amount -> String
showLotList Map LotId Amount
lots = ((LotId, Amount) -> String) -> [(LotId, Amount)] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (LotId, Amount) -> String
fmt [(LotId, Amount)]
shown String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
more String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
totalline
      where
        ([(LotId, Amount)]
shown, [(LotId, Amount)]
rest) = Int -> [(LotId, Amount)] -> ([(LotId, Amount)], [(LotId, Amount)])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
10 (Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
lots)
        fmt :: (LotId, Amount) -> String
fmt (LotId
lid, Amount
a) = String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName (LotId -> Amount -> CostBasis
lotIdToCb LotId
lid Amount
a))
                        String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show (Amount -> Quantity
aquantity Amount
a)
        more :: String
more = case [(LotId, Amount)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(LotId, Amount)]
rest of
          Int
0 -> String
""
          Int
1 -> String
"\n  ...and 1 more lot"
          Int
n -> String
"\n  ...and " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
n String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" more lots"
        totalline :: String
totalline = String
"\n  Total: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show ([Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((Amount -> Quantity) -> [Amount] -> [Quantity]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Quantity
aquantity (Map LotId Amount -> [Amount]
forall k a. Map k a -> [a]
M.elems Map LotId Amount
lots)))
                     String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity

    -- Summarise this commodity's lots in accounts other than the specified
    -- one: for each account, the total quantity and number of lots; and
    -- when there are several accounts, the total quantity overall.
    showOtherAccountLots :: M.Map LotId (M.Map AccountName Amount) -> String
    showOtherAccountLots :: Map LotId (Map CommoditySymbol Amount) -> String
showOtherAccountLots Map LotId (Map CommoditySymbol Amount)
allLots' =
      let others :: [(CommoditySymbol, Amount)]
others = [(CommoditySymbol
acct, Amount
a) | (LotId
_, Map CommoditySymbol Amount
acctMap) <- Map LotId (Map CommoditySymbol Amount)
-> [(LotId, Map CommoditySymbol Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId (Map CommoditySymbol Amount)
allLots'
                              , (CommoditySymbol
acct, Amount
a) <- Map CommoditySymbol Amount -> [(CommoditySymbol, Amount)]
forall k a. Map k a -> [(k, a)]
M.toList Map CommoditySymbol Amount
acctMap, CommoditySymbol
acct CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
account]
          byAcct :: Map CommoditySymbol (Quantity, Int)
byAcct = ((Quantity, Int) -> (Quantity, Int) -> (Quantity, Int))
-> [(CommoditySymbol, (Quantity, Int))]
-> Map CommoditySymbol (Quantity, Int)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith (\(Quantity
q1, Int
n1) (Quantity
q2, Int
n2) -> (Quantity
q1 Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
+ Quantity
q2, Int
n1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
n2))
                     [(CommoditySymbol
acct, (Amount -> Quantity
aquantity Amount
a, Int
1 :: Int)) | (CommoditySymbol
acct, Amount
a) <- [(CommoditySymbol, Amount)]
others]
          totalline :: String
totalline
            | Map CommoditySymbol (Quantity, Int) -> Int
forall k a. Map k a -> Int
M.size Map CommoditySymbol (Quantity, Int)
byAcct Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 = String
""
            | Bool
otherwise = String
"\n  Total: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show ([Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Quantity
q | (Quantity
q, Int
_) <- Map CommoditySymbol (Quantity, Int) -> [(Quantity, Int)]
forall k a. Map k a -> [a]
M.elems Map CommoditySymbol (Quantity, Int)
byAcct])
                           String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
      in if Map CommoditySymbol (Quantity, Int) -> Bool
forall k a. Map k a -> Bool
M.null Map CommoditySymbol (Quantity, Int)
byAcct then String
""
         else String
"\nLots of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in other accounts:"
           String -> String -> String
forall a. [a] -> [a] -> [a]
++ ((CommoditySymbol, (Quantity, Int)) -> String)
-> [(CommoditySymbol, (Quantity, Int))] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (CommoditySymbol, (Quantity, Int)) -> String
forall {a} {a}.
(Show a, Show a, Eq a, Num a) =>
(CommoditySymbol, (a, a)) -> String
fmtAcct (Map CommoditySymbol (Quantity, Int)
-> [(CommoditySymbol, (Quantity, Int))]
forall k a. Map k a -> [(k, a)]
M.toAscList Map CommoditySymbol (Quantity, Int)
byAcct)
           String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
totalline
      where fmtAcct :: (CommoditySymbol, (a, a)) -> String
fmtAcct (CommoditySymbol
acct, (a
q, a
n)) = String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
acct String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": "
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
q String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
commodity
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
n String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if a
n a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
1 then String
" lot" else String
" lots")

-- | Extract the per-unit cost quantity from a lot entry, for HIFO sorting.
lotPerUnitCost :: (LotId, Amount) -> Quantity
lotPerUnitCost :: (LotId, Amount) -> Quantity
lotPerUnitCost (LotId
_, Amount
a) = Quantity -> (Amount -> Quantity) -> Maybe Amount -> Quantity
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Quantity
0 Amount -> Quantity
aquantity (Amount -> Maybe CostBasis
acostbasis Amount
a Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost)

-- | Whether a reduction method uses weighted average cost basis for disposals.
methodIsAverage :: ReductionMethod -> Bool
methodIsAverage :: ReductionMethod -> Bool
methodIsAverage ReductionMethod
AVERAGE    = Bool
True
methodIsAverage ReductionMethod
AVERAGEALL = Bool
True
methodIsAverage ReductionMethod
_          = Bool
False

-- | Whether a reduction method requires global validation across all accounts.
methodIsGlobal :: ReductionMethod -> Bool
methodIsGlobal :: ReductionMethod -> Bool
methodIsGlobal ReductionMethod
FIFOALL    = Bool
True
methodIsGlobal ReductionMethod
LIFOALL    = Bool
True
methodIsGlobal ReductionMethod
HIFOALL    = Bool
True
methodIsGlobal ReductionMethod
AVERAGEALL = Bool
True
methodIsGlobal ReductionMethod
_          = Bool
False

-- | Map a *ALL method to its base ordering, or return the method unchanged.
methodBaseOrdering :: ReductionMethod -> ReductionMethod
methodBaseOrdering :: ReductionMethod -> ReductionMethod
methodBaseOrdering ReductionMethod
FIFOALL    = ReductionMethod
FIFO
methodBaseOrdering ReductionMethod
LIFOALL    = ReductionMethod
LIFO
methodBaseOrdering ReductionMethod
HIFOALL    = ReductionMethod
HIFO
methodBaseOrdering ReductionMethod
AVERAGEALL = ReductionMethod
AVERAGE
methodBaseOrdering ReductionMethod
m          = ReductionMethod
m

-- | Flatten lots across all accounts, summing quantities for shared lot IDs.
-- From @Map LotId (Map AccountName Amount)@ to @Map LotId Amount@,
-- combining quantities across accounts (taking the first Amount's metadata).
flattenAllAccountLots :: M.Map LotId (M.Map AccountName Amount) -> M.Map LotId Amount
flattenAllAccountLots :: Map LotId (Map CommoditySymbol Amount) -> Map LotId Amount
flattenAllAccountLots = (Map CommoditySymbol Amount -> Maybe Amount)
-> Map LotId (Map CommoditySymbol Amount) -> Map LotId Amount
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
M.mapMaybe Map CommoditySymbol Amount -> Maybe Amount
forall {k}. Map k Amount -> Maybe Amount
flattenAccts
  where
    flattenAccts :: Map k Amount -> Maybe Amount
flattenAccts Map k Amount
acctMap =
      case Map k Amount -> [Amount]
forall k a. Map k a -> [a]
M.elems Map k Amount
acctMap of
        []       -> Maybe Amount
forall a. Maybe a
Nothing
        (Amount
a:[Amount]
rest) -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
a{aquantity = aquantity a + sum (map aquantity rest)}

-- | Validate that the per-account selected lots would also be chosen first
-- under a global ordering across all accounts. Errors if lots on other accounts
-- have higher priority than the selected lots.
validateGlobalCompliance :: ReductionMethod -> String -> AccountName -> CommoditySymbol
                         -> Quantity -> CostBasis -> LotState
                         -> [(LotId, Amount, Quantity)] -> Either String ()
validateGlobalCompliance :: ReductionMethod
-> String
-> CommoditySymbol
-> CommoditySymbol
-> Quantity
-> CostBasis
-> LotState
-> [(LotId, Amount, Quantity)]
-> Either String ()
validateGlobalCompliance ReductionMethod
method String
posStr CommoditySymbol
account CommoditySymbol
commodity Quantity
qty CostBasis
selector LotState
lotState [(LotId, Amount, Quantity)]
selected = do
    let allLots :: Map LotId (Map CommoditySymbol Amount)
allLots = Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState
        globalFlat :: Map LotId Amount
globalFlat = Map LotId (Map CommoditySymbol Amount) -> Map LotId Amount
flattenAllAccountLots Map LotId (Map CommoditySymbol Amount)
allLots
        globalMatching :: Map LotId Amount
globalMatching = (Amount -> Bool) -> Map LotId Amount -> Map LotId Amount
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (CostBasis -> Amount -> Bool
lotMatchesSelector CostBasis
selector) Map LotId Amount
globalFlat
        base :: ReductionMethod
base = ReductionMethod -> ReductionMethod
methodBaseOrdering ReductionMethod
method
        globalOrdered :: [(LotId, Amount)]
globalOrdered = case ReductionMethod
base of
          ReductionMethod
FIFO    -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
globalMatching
          ReductionMethod
LIFO    -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toDescList Map LotId Amount
globalMatching
          ReductionMethod
HIFO    -> ((LotId, Amount) -> Down Quantity)
-> [(LotId, Amount)] -> [(LotId, Amount)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Quantity -> Down Quantity
forall a. a -> Down a
Down (Quantity -> Down Quantity)
-> ((LotId, Amount) -> Quantity)
-> (LotId, Amount)
-> Down Quantity
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (LotId, Amount) -> Quantity
lotPerUnitCost) (Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toList Map LotId Amount
globalMatching)
          ReductionMethod
AVERAGE -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
globalMatching
          ReductionMethod
_       -> Map LotId Amount -> [(LotId, Amount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map LotId Amount
globalMatching
        -- Greedily consume qty from the globally-ordered list
        globalSelectedIds :: Set LotId
globalSelectedIds = [LotId] -> Set LotId
forall a. Ord a => [a] -> Set a
S.fromList ([LotId] -> Set LotId) -> [LotId] -> Set LotId
forall a b. (a -> b) -> a -> b
$ ((LotId, Amount, Quantity) -> LotId)
-> [(LotId, Amount, Quantity)] -> [LotId]
forall a b. (a -> b) -> [a] -> [b]
map (LotId, Amount, Quantity) -> LotId
forall {a} {b} {c}. (a, b, c) -> a
fst3 ([(LotId, Amount, Quantity)] -> [LotId])
-> [(LotId, Amount, Quantity)] -> [LotId]
forall a b. (a -> b) -> a -> b
$ Quantity -> [(LotId, Amount)] -> [(LotId, Amount, Quantity)]
forall {a}. Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
goConsume Quantity
qty [(LotId, Amount)]
globalOrdered
        selectedIds :: Set LotId
selectedIds = [LotId] -> Set LotId
forall a. Ord a => [a] -> Set a
S.fromList [LotId
lid | (LotId
lid, Amount
_, Quantity
_) <- [(LotId, Amount, Quantity)]
selected]
        -- Lot IDs that would be globally selected but are NOT in the per-account selection
        -- (i.e. they exist on other accounts and have higher priority)
        higherPriorityElsewhere :: Set LotId
higherPriorityElsewhere = Set LotId -> Set LotId -> Set LotId
forall a. Ord a => Set a -> Set a -> Set a
S.difference Set LotId
globalSelectedIds Set LotId
selectedIds
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set LotId -> Bool
forall a. Set a -> Bool
S.null Set LotId
higherPriorityElsewhere) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$ do
      -- Build detailed error showing which accounts hold the higher-priority lots
      let otherLots :: [(CommoditySymbol, LotId, Amount)]
otherLots = [(CommoditySymbol
acct, LotId
lid, Amount
a)
                      | LotId
lid <- Set LotId -> [LotId]
forall a. Set a -> [a]
S.toList Set LotId
higherPriorityElsewhere
                      , Just Map CommoditySymbol Amount
acctMap <- [LotId
-> Map LotId (Map CommoditySymbol Amount)
-> Maybe (Map CommoditySymbol Amount)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup LotId
lid Map LotId (Map CommoditySymbol Amount)
allLots]
                      , (CommoditySymbol
acct, Amount
a) <- Map CommoditySymbol Amount -> [(CommoditySymbol, Amount)]
forall k a. Map k a -> [(k, a)]
M.toList Map CommoditySymbol Amount
acctMap]
          byAcct :: Map CommoditySymbol [(LotId, Amount)]
byAcct = ([(LotId, Amount)] -> [(LotId, Amount)] -> [(LotId, Amount)])
-> [(CommoditySymbol, [(LotId, Amount)])]
-> Map CommoditySymbol [(LotId, Amount)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [(LotId, Amount)] -> [(LotId, Amount)] -> [(LotId, Amount)]
forall a. [a] -> [a] -> [a]
(++) [(CommoditySymbol
acct, [(LotId
lid, Amount
a)]) | (CommoditySymbol
acct, LotId
lid, Amount
a) <- [(CommoditySymbol, LotId, Amount)]
otherLots]
          fmtAcct :: (CommoditySymbol, [(LotId, Amount)]) -> String
fmtAcct (CommoditySymbol
acct, [(LotId, Amount)]
lots) = String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
acct String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": "
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName (LotId -> Amount -> CostBasis
lotIdToCb LotId
lid Amount
a)) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show (Amount -> Quantity
aquantity Amount
a)
                                | (LotId
lid, Amount
a) <- [(LotId, Amount)]
lots]
          fmtSelected :: String
fmtSelected = ((LotId, Amount, Quantity) -> String)
-> [(LotId, Amount, Quantity)] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(LotId
lid, Amount
a, Quantity
q) -> String
"\n  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName (LotId -> Amount -> CostBasis
lotIdToCb LotId
lid Amount
a))
                                                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Quantity -> String
forall a. Show a => a -> String
show Quantity
q) [(LotId, Amount, Quantity)]
selected
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ ReductionMethod -> String
forall a. Show a => a -> String
show ReductionMethod
method String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": lot(s) on other account(s) have higher priority than the lots in "
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ ((CommoditySymbol, [(LotId, Amount)]) -> String)
-> [(CommoditySymbol, [(LotId, Amount)])] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (CommoditySymbol, [(LotId, Amount)]) -> String
fmtAcct (Map CommoditySymbol [(LotId, Amount)]
-> [(CommoditySymbol, [(LotId, Amount)])]
forall k a. Map k a -> [(k, a)]
M.toAscList Map CommoditySymbol [(LotId, Amount)]
byAcct)
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nSelected from " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
account String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":"
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
fmtSelected
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nConsider disposing from the account(s) listed above first, or use "
              String -> String -> String
forall a. [a] -> [a] -> [a]
++ ReductionMethod -> String
forall a. Show a => a -> String
show (ReductionMethod -> ReductionMethod
methodBaseOrdering ReductionMethod
method) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" for per-account scope."
  where
    goConsume :: Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
goConsume Quantity
0 [(a, Amount)]
_ = []
    goConsume Quantity
_ [] = []
    goConsume Quantity
remaining ((a
lotId, Amount
lotAmt):[(a, Amount)]
rest)
      | Quantity
remaining Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
>= Amount -> Quantity
aquantity Amount
lotAmt = (a
lotId, Amount
lotAmt, Amount -> Quantity
aquantity Amount
lotAmt) (a, Amount, Quantity)
-> [(a, Amount, Quantity)] -> [(a, Amount, Quantity)]
forall a. a -> [a] -> [a]
: Quantity -> [(a, Amount)] -> [(a, Amount, Quantity)]
goConsume (Quantity
remaining Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
- Amount -> Quantity
aquantity Amount
lotAmt) [(a, Amount)]
rest
      | Bool
otherwise = [(a
lotId, Amount
lotAmt, Quantity
remaining)]
    fst3 :: (a, b, c) -> a
fst3 (a
x, b
_, c
_) = a
x

-- | Under AVERAGE / AVERAGEALL: integrate a new acquisition into the running
-- pool and return (new shared per-unit cost, lot state with every existing
-- pool lot's stored cbCost updated to that new cost).
--
-- @inPool@ says which accounts' lots make up the pool: for AVERAGEALL, all
-- accounts holding this commodity in the same lot direction (long lots in
-- asset accounts, or short lots in liability accounts); for AVERAGE, just
-- the acquiring account, other accounts having their own independent pools.
updatePoolOnAcquire
  :: String                 -- ^ error-message position prefix
  -> (AccountName -> Bool)  -- ^ inPool: do this account's lots belong to the pool ?
  -> CommoditySymbol
  -> Quantity         -- ^ this acquisition's quantity
  -> Amount           -- ^ this acquisition's per-unit cost
  -> LotState
  -> Either String (Amount, LotState)
updatePoolOnAcquire :: String
-> (CommoditySymbol -> Bool)
-> CommoditySymbol
-> Quantity
-> Amount
-> LotState
-> Either String (Amount, LotState)
updatePoolOnAcquire String
posStr CommoditySymbol -> Bool
inPool CommoditySymbol
commodity Quantity
acqQty Amount
acqCost LotState
lotState = do
    let commLots :: Map LotId (Map CommoditySymbol Amount)
commLots = Map LotId (Map CommoditySymbol Amount)
-> CommoditySymbol
-> LotState
-> Map LotId (Map CommoditySymbol Amount)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Map LotId (Map CommoditySymbol Amount)
forall k a. Map k a
M.empty CommoditySymbol
commodity LotState
lotState
        -- The per-LotId Amounts belonging to the pool.
        poolAmts :: Map CommoditySymbol a -> [a]
poolAmts Map CommoditySymbol a
accts = Map CommoditySymbol a -> [a]
forall k a. Map k a -> [a]
M.elems ((CommoditySymbol -> a -> Bool)
-> Map CommoditySymbol a -> Map CommoditySymbol a
forall k a. (k -> a -> Bool) -> Map k a -> Map k a
M.filterWithKey (\CommoditySymbol
acct a
_ -> CommoditySymbol -> Bool
inPool CommoditySymbol
acct) Map CommoditySymbol a
accts)
        existingEntries :: [(Quantity, Amount)]
existingEntries = [(Amount -> Quantity
aquantity Amount
a, Amount
c) | Map CommoditySymbol Amount
accts <- Map LotId (Map CommoditySymbol Amount)
-> [Map CommoditySymbol Amount]
forall k a. Map k a -> [a]
M.elems Map LotId (Map CommoditySymbol Amount)
commLots
                                            , Amount
a     <- Map CommoditySymbol Amount -> [Amount]
forall {a}. Map CommoditySymbol a -> [a]
poolAmts Map CommoditySymbol Amount
accts
                                            , Just CostBasis
cb <- [Amount -> Maybe CostBasis
acostbasis Amount
a]
                                            , Just Amount
c  <- [CostBasis -> Maybe Amount
cbCost CostBasis
cb]]
    -- All pool entries (including this acquisition) must agree on cost commodity.
    case [(Quantity, Amount)] -> Maybe (Quantity, Amount)
forall a. [a] -> Maybe a
listToMaybe [(Quantity, Amount)]
existingEntries of
      Just (Quantity
_, Amount
firstCost) | Amount -> CommoditySymbol
acommodity Amount
firstCost CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Amount -> CommoditySymbol
acommodity Amount
acqCost ->
        String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"cannot average lots with different cost commodities"
      Maybe (Quantity, Amount)
_ -> () -> Either String ()
forall a b. b -> Either a b
Right ()
    let totalQty :: Quantity
totalQty  = Quantity
acqQty Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
+ [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Quantity
q | (Quantity
q, Amount
_) <- [(Quantity, Amount)]
existingEntries]
        totalCost :: Quantity
totalCost = Quantity -> Quantity -> Quantity
multiplyQuantities Quantity
acqQty (Amount -> Quantity
aquantity Amount
acqCost)
                  Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
+ [Quantity] -> Quantity
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Quantity -> Quantity -> Quantity
multiplyQuantities Quantity
q (Amount -> Quantity
aquantity Amount
c) | (Quantity
q, Amount
c) <- [(Quantity, Amount)]
existingEntries]
    Bool -> Either String () -> Either String ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Quantity
totalQty Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
0) (Either String () -> Either String ())
-> Either String () -> Either String ()
forall a b. (a -> b) -> a -> b
$
      String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ String
posStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"cannot average lots with zero total quantity"
    let newAvg :: Amount
newAvg = Amount
acqCost{aquantity = totalCost / totalQty}
        rewriteAmt :: Amount -> Amount
rewriteAmt Amount
a = case Amount -> Maybe CostBasis
acostbasis Amount
a of
          Maybe CostBasis
Nothing -> Amount
a
          Just CostBasis
cb -> Amount
a{acostbasis = Just cb{cbCost = Just newAvg}}
        rewriteAccts :: Map CommoditySymbol Amount -> Map CommoditySymbol Amount
rewriteAccts = (CommoditySymbol -> Amount -> Amount)
-> Map CommoditySymbol Amount -> Map CommoditySymbol Amount
forall k a b. (k -> a -> b) -> Map k a -> Map k b
M.mapWithKey (\CommoditySymbol
acct Amount
a -> if CommoditySymbol -> Bool
inPool CommoditySymbol
acct then Amount -> Amount
rewriteAmt Amount
a else Amount
a)
        lotState' :: LotState
lotState' = CommoditySymbol
-> Map LotId (Map CommoditySymbol Amount) -> LotState -> LotState
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert CommoditySymbol
commodity ((Map CommoditySymbol Amount -> Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
forall a b k. (a -> b) -> Map k a -> Map k b
M.map Map CommoditySymbol Amount -> Map CommoditySymbol Amount
rewriteAccts Map LotId (Map CommoditySymbol Amount)
commLots) LotState
lotState
    (Amount, LotState) -> Either String (Amount, LotState)
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (Amount
newAvg, LotState
lotState')

-- | Is this an all-Nothing (wildcard) lot selector, i.e. from @{}@?
isWildcardSelector :: CostBasis -> Bool
isWildcardSelector :: CostBasis -> Bool
isWildcardSelector (CostBasis Maybe Day
Nothing Maybe CommoditySymbol
Nothing Maybe Amount
Nothing) = Bool
True
isWildcardSelector CostBasis
_ = Bool
False

-- | Does a lot match a lot selector?
-- Each non-Nothing field in the selector must match the lot's stored cost basis.
lotMatchesSelector :: CostBasis -> Amount -> Bool
lotMatchesSelector :: CostBasis -> Amount -> Bool
lotMatchesSelector CostBasis
selector Amount
a =
    case Amount -> Maybe CostBasis
acostbasis Amount
a of
      Maybe CostBasis
Nothing    -> Bool
False
      Just CostBasis
lotCb -> Maybe Amount -> Maybe Amount -> Bool
matchCost (CostBasis -> Maybe Amount
cbCost CostBasis
selector) (CostBasis -> Maybe Amount
cbCost CostBasis
lotCb)
                 Bool -> Bool -> Bool
&& (CostBasis -> Maybe Day) -> CostBasis -> CostBasis -> Bool
forall b.
Eq b =>
(CostBasis -> Maybe b) -> CostBasis -> CostBasis -> Bool
matchField CostBasis -> Maybe Day
cbDate CostBasis
selector CostBasis
lotCb
                 Bool -> Bool -> Bool
&& (CostBasis -> Maybe CommoditySymbol)
-> CostBasis -> CostBasis -> Bool
forall b.
Eq b =>
(CostBasis -> Maybe b) -> CostBasis -> CostBasis -> Bool
matchField CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
selector CostBasis
lotCb
  where
    matchField :: Eq b => (CostBasis -> Maybe b) -> CostBasis -> CostBasis -> Bool
    matchField :: forall b.
Eq b =>
(CostBasis -> Maybe b) -> CostBasis -> CostBasis -> Bool
matchField CostBasis -> Maybe b
f CostBasis
sel CostBasis
lot = case CostBasis -> Maybe b
f CostBasis
sel of
      Maybe b
Nothing -> Bool
True   -- selector doesn't constrain this field
      Just b
v  -> CostBasis -> Maybe b
f CostBasis
lot Maybe b -> Maybe b -> Bool
forall a. Eq a => a -> a -> Bool
== b -> Maybe b
forall a. a -> Maybe a
Just b
v
    -- Compare costs by commodity and quantity, ignoring style differences
    -- (but accepting a display-rounded rendering, see 'lotCostsMatch').
    matchCost :: Maybe Amount -> Maybe Amount -> Bool
    matchCost :: Maybe Amount -> Maybe Amount -> Bool
matchCost Maybe Amount
Nothing    Maybe Amount
_          = Bool
True
    matchCost (Just Amount
_)   Maybe Amount
Nothing    = Bool
False
    matchCost (Just Amount
sel) (Just Amount
lot) = Amount -> Amount -> Bool
lotCostsMatch Amount
sel Amount
lot

-- | Subtract consumed quantities from LotState for a specific account.
-- Removes lot-account entries whose balance reaches zero.
-- A fully consumed lot's id is kept as a tombstone (a lot with no account
-- entries), so that its label is never reused by a later same-date
-- acquisition ('generateLabel'), keeping lot histories unambiguous.
-- Tombstones are invisible elsewhere: lot selection, transfers, and pool
-- updates all look only at lots' per-account amounts.
reduceLotState :: AccountName -> CommoditySymbol -> [(LotId, Quantity)] -> LotState -> LotState
reduceLotState :: CommoditySymbol
-> CommoditySymbol -> [(LotId, Quantity)] -> LotState -> LotState
reduceLotState CommoditySymbol
account CommoditySymbol
commodity [(LotId, Quantity)]
consumed = (Map LotId (Map CommoditySymbol Amount)
 -> Map LotId (Map CommoditySymbol Amount))
-> CommoditySymbol -> LotState -> LotState
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
M.adjust Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
adjustCommodity CommoditySymbol
commodity
  where
    adjustCommodity :: Map LotId (Map CommoditySymbol Amount)
-> Map LotId (Map CommoditySymbol Amount)
adjustCommodity Map LotId (Map CommoditySymbol Amount)
lots = (Map LotId (Map CommoditySymbol Amount)
 -> (LotId, Quantity) -> Map LotId (Map CommoditySymbol Amount))
-> Map LotId (Map CommoditySymbol Amount)
-> [(LotId, Quantity)]
-> Map LotId (Map CommoditySymbol Amount)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map LotId (Map CommoditySymbol Amount)
-> (LotId, Quantity) -> Map LotId (Map CommoditySymbol Amount)
forall {k}.
Ord k =>
Map k (Map CommoditySymbol Amount)
-> (k, Quantity) -> Map k (Map CommoditySymbol Amount)
reduceLot Map LotId (Map CommoditySymbol Amount)
lots [(LotId, Quantity)]
consumed
    reduceLot :: Map k (Map CommoditySymbol Amount)
-> (k, Quantity) -> Map k (Map CommoditySymbol Amount)
reduceLot Map k (Map CommoditySymbol Amount)
lots (k
lotId, Quantity
qty) = (Map CommoditySymbol Amount -> Map CommoditySymbol Amount)
-> k
-> Map k (Map CommoditySymbol Amount)
-> Map k (Map CommoditySymbol Amount)
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
M.adjust Map CommoditySymbol Amount -> Map CommoditySymbol Amount
shrinkLot k
lotId Map k (Map CommoditySymbol Amount)
lots
      where
        shrinkLot :: Map CommoditySymbol Amount -> Map CommoditySymbol Amount
shrinkLot = (Amount -> Maybe Amount)
-> CommoditySymbol
-> Map CommoditySymbol Amount
-> Map CommoditySymbol Amount
forall k a. Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
M.update (Quantity -> Amount -> Maybe Amount
shrinkAmt Quantity
qty) CommoditySymbol
account
        shrinkAmt :: Quantity -> Amount -> Maybe Amount
shrinkAmt Quantity
q Amount
a
          | Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
<= Quantity
q = Maybe Amount
forall a. Maybe a
Nothing
          | Bool
otherwise        = Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
a{aquantity = aquantity a - q}

-- Debug trace helpers

-- | Reconstruct a CostBasis from a LotId and a stored Amount (for display in trace messages).
lotIdToCb :: LotId -> Amount -> CostBasis
lotIdToCb :: LotId -> Amount -> CostBasis
lotIdToCb LotId
lid Amount
a = Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis (Day -> Maybe Day
forall a. a -> Maybe a
Just (LotId -> Day
lotDate LotId
lid)) (LotId -> Maybe CommoditySymbol
lotLabel LotId
lid) (Amount -> Maybe CostBasis
acostbasis Amount
a Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost)

-- | Show selected lots for trace messages: "{2026-01-15, $50} 5, {2026-02-01, $60} 3"
showSelectedLots :: [(LotId, Amount, Quantity)] -> String
showSelectedLots :: [(LotId, Amount, Quantity)] -> String
showSelectedLots = String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " ([String] -> String)
-> ([(LotId, Amount, Quantity)] -> [String])
-> [(LotId, Amount, Quantity)]
-> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((LotId, Amount, Quantity) -> String)
-> [(LotId, Amount, Quantity)] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (LotId, Amount, Quantity) -> String
forall {a}. Show a => (LotId, Amount, a) -> String
fmt
  where fmt :: (LotId, Amount, a) -> String
fmt (LotId
lid, Amount
a, a
qty) = CommoditySymbol -> String
T.unpack (CostBasis -> CommoditySymbol
showLotName (LotId -> Amount -> CostBasis
lotIdToCb LotId
lid Amount
a)) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
qty