{-|

A 'Posting' represents a change (by some 'MixedAmount') of the balance in
some 'Account'.  Each 'Transaction' contains two or more postings which
should add up to 0. Postings reference their parent transaction, so we can
look up the date or description there.

-}

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

module Hledger.Data.Posting (
  -- * Posting
  nullposting,
  posting,
  post,
  vpost,
  post',
  vpost',
  nullassertion,
  balassert,
  balassertTot,
  balassertParInc,
  balassertTotInc,
  -- * operations
  originalPosting,
  postingStatus,
  isReal,
  isVirtual,
  isBalancedVirtual,
  isEmptyPosting,
  hasBalanceAssignment,
  hasAmount,
  isExplicitAmount,
  postingAllTags,
  transactionAllTags,
  relatedPostings,
  postingStripCosts,
  postingApplyAliases,
  postingApplyCommodityStyles,
  postingStyleAmounts,
  postingAddTags,
  postingAddHiddenAndMaybeVisibleTag,
  postingRemoveHiddenAndVisibleTag,
  -- * date operations
  postingDate,
  postingDate2,
  postingDateOrDate2,
  -- * account name operations
  accountNamesFromPostings,
  -- * comment/tag operations
  commentJoin,
  commentAddTag,
  commentAddTagUnspaced,
  commentAddTagNextLine,
  commentPrependTag,
  generatedTransactionTagName,
  modifiedTransactionTagName,
  generatedPostingTagName,
  feesplitPostingTagName,
  lotsplitPostingTagName,
  lotParentAssertionTagName,
  postingHasTag,
  costPostingTagName,
  conversionPostingTagName,
  imbalancePostingTagName,

  -- * arithmetic
  sumPostings,
  postingNegate,
  postingNegateMainAmount,
  -- * rendering
  showPosting,
  showPostingLines,
  postingAsLines,
  postingsAsLines,
  postingsAsLinesWithLayout,
  postingIndent,
  showAccountName,
  renderCommentLines,
  showBalanceAssertion,
  balanceAssertionOperatorB,
  balanceAssertionAmountB,
  PostingLayout(..),
  defaultPostingLayout,
  defaultDecimalMarkColumn,
  PostingWidths(..),
  AmountCols(..),
  amountIntegerWidth,
  -- * misc.
  postingTransformAmount,
  postingApplyValuation,
  postingToCost,
  postingAddInferredEquityPostings,
  postingsAddInferredEquityPostings,
  postingPriceDirectivesFromCost,
  postingCommodities,
  tests_Posting
)
where

import Data.Default (def)
import Data.Foldable (asum)
import Data.Function ((&))
import Data.Map qualified as M
import Data.Maybe (fromMaybe, isJust, mapMaybe)
import Data.List (nub, sort, union)
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Data.Time.Calendar (Day)
import Safe (maximumBound)
import Text.DocLayout (realLength)
import Text.Tabular.AsciiWide hiding (render)

import Hledger.Utils
import Hledger.Data.Types
import Hledger.Data.Amount
import Hledger.Data.AccountName
import Hledger.Data.Dates (nulldate)
import Hledger.Data.Valuation


-- | Special tags hledger sometimes adds to mark various things.
-- These should be hidden tag names, beginning with _.
-- With --verbose-tags, the equivalent visible tags will also be added.
-- These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.
generatedTransactionTagName, modifiedTransactionTagName, costPostingTagName, conversionPostingTagName, imbalancePostingTagName, generatedPostingTagName, feesplitPostingTagName, lotsplitPostingTagName, lotParentAssertionTagName :: TagName
generatedTransactionTagName :: Text
generatedTransactionTagName = Text
"_generated-transaction"  -- transactions generated by a periodic txn rule
modifiedTransactionTagName :: Text
modifiedTransactionTagName  = Text
"_modified-transaction"   -- transactions modified by an auto posting rule
generatedPostingTagName :: Text
generatedPostingTagName     = Text
"_generated-posting"      -- postings generated by hledger for one reason or another
costPostingTagName :: Text
costPostingTagName          = Text
"_cost-posting"           -- postings which have or could have a cost that's equivalent to nearby conversion postings
conversionPostingTagName :: Text
conversionPostingTagName    = Text
"_conversion-posting"     -- postings to an equity account of Conversion type which have an amount that's equivalent to a nearby costful or potentially costful posting
imbalancePostingTagName :: Text
imbalancePostingTagName     = Text
"_imbalance-posting"      -- postings generated by --infer-imbalance, showing a transaction's tolerated imbalance
feesplitPostingTagName :: Text
feesplitPostingTagName      = Text
"_feesplit-posting"       -- a synthetic posting carved off an existing posting by lot transfer auto-split (the fee fragment); hidden by default in print
lotsplitPostingTagName :: Text
lotsplitPostingTagName      = Text
"_lotsplit-posting"       -- a tail fragment from a per-lot split, dropped when collapsing to the user's original form
lotParentAssertionTagName :: Text
lotParentAssertionTagName   = Text
"_lot-parent-assertion"   -- a synthetic zero-amount posting on the parent account, carrying a balance assertion relocated from a posting that was split into lot subaccounts

-- | True if the posting has a tag with the given name (hidden or visible).
postingHasTag :: TagName -> Posting -> Bool
postingHasTag :: Text -> Posting -> Bool
postingHasTag Text
name Posting
p = (Tag -> Bool) -> [Tag] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
==Text
name) (Text -> Bool) -> (Tag -> Text) -> Tag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tag -> Text
forall a b. (a, b) -> a
fst) (Posting -> [Tag]
ptags Posting
p)

instance HasAmounts BalanceAssertion where
  styleAmounts :: Map Text AmountStyle -> BalanceAssertion -> BalanceAssertion
styleAmounts Map Text AmountStyle
styles ba :: BalanceAssertion
ba@BalanceAssertion{Amount
baamount :: Amount
baamount :: BalanceAssertion -> Amount
baamount} = BalanceAssertion
ba{baamount=styleAmounts styles baamount}

instance HasAmounts Posting where
  styleAmounts :: Map Text AmountStyle -> Posting -> Posting
styleAmounts Map Text AmountStyle
styles p :: Posting
p@Posting{MixedAmount
pamount :: MixedAmount
pamount :: Posting -> MixedAmount
pamount, Maybe BalanceAssertion
pbalanceassertion :: Maybe BalanceAssertion
pbalanceassertion :: Posting -> Maybe BalanceAssertion
pbalanceassertion} =
    Posting
p{ pamount=styleAmounts styles pamount
      ,pbalanceassertion=styleAmounts styles pbalanceassertion 
      }

{-# DEPRECATED postingApplyCommodityStyles "please use styleAmounts instead" #-}
-- | Find and apply the appropriate display style to the posting amounts
-- in each commodity (see journalCommodityStyles).
-- Main amount precisions may be set or not according to the styles, but cost precisions are not set.
postingApplyCommodityStyles :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting
postingApplyCommodityStyles :: Map Text AmountStyle -> Posting -> Posting
postingApplyCommodityStyles = Map Text AmountStyle -> Posting -> Posting
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts

{-# DEPRECATED postingStyleAmounts "please use styleAmounts instead" #-}
-- | Like postingApplyCommodityStyles, but neither
-- main amount precisions or cost precisions are set.
postingStyleAmounts :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting
postingStyleAmounts :: Map Text AmountStyle -> Posting -> Posting
postingStyleAmounts = Map Text AmountStyle -> Posting -> Posting
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts

nullposting, posting :: Posting
nullposting :: Posting
nullposting = Posting
                {pdate :: Maybe Day
pdate=Maybe Day
forall a. Maybe a
Nothing
                ,pdate2 :: Maybe Day
pdate2=Maybe Day
forall a. Maybe a
Nothing
                ,pstatus :: Status
pstatus=Status
Unmarked
                ,paccount :: Text
paccount=Text
""
                ,pamount :: MixedAmount
pamount=MixedAmount
nullmixedamt
                ,pcomment :: Text
pcomment=Text
""
                ,preal :: PostingRealness
preal=PostingRealness
RealPosting
                ,ptags :: [Tag]
ptags=[]
                ,pbalanceassertion :: Maybe BalanceAssertion
pbalanceassertion=Maybe BalanceAssertion
forall a. Maybe a
Nothing
                ,ptransaction :: Maybe Transaction
ptransaction=Maybe Transaction
forall a. Maybe a
Nothing
                ,poriginal :: Maybe Posting
poriginal=Maybe Posting
forall a. Maybe a
Nothing
                }
posting :: Posting
posting = Posting
nullposting

-- constructors

-- | Make a posting to an account.
post :: AccountName -> Amount -> Posting
post :: Text -> Amount -> Posting
post Text
acc Amount
amt = Posting
posting {paccount=acc, pamount=mixedAmount amt}

-- | Make a virtual (unbalanced) posting to an account.
vpost :: AccountName -> Amount -> Posting
vpost :: Text -> Amount -> Posting
vpost Text
acc Amount
amt = (Text -> Amount -> Posting
post Text
acc Amount
amt){preal=VirtualPosting}

-- | Make a posting to an account, maybe with a balance assertion.
post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
post' :: Text -> Amount -> Maybe BalanceAssertion -> Posting
post' Text
acc Amount
amt Maybe BalanceAssertion
ass = Posting
posting {paccount=acc, pamount=mixedAmount amt, pbalanceassertion=ass}

-- | Make a virtual (unbalanced) posting to an account, maybe with a balance assertion.
vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
vpost' :: Text -> Amount -> Maybe BalanceAssertion -> Posting
vpost' Text
acc Amount
amt Maybe BalanceAssertion
ass = (Text -> Amount -> Maybe BalanceAssertion -> Posting
post' Text
acc Amount
amt Maybe BalanceAssertion
ass){preal=VirtualPosting, pbalanceassertion=ass}

nullassertion :: BalanceAssertion
nullassertion :: BalanceAssertion
nullassertion = BalanceAssertion
                  {baamount :: Amount
baamount=Amount
nullamt
                  ,batotal :: Bool
batotal=Bool
False
                  ,bainclusive :: Bool
bainclusive=Bool
False
                  ,baposition :: SourcePos
baposition=String -> SourcePos
initialPos String
""
                  }

-- | Make a partial, exclusive balance assertion.
balassert :: Amount -> Maybe BalanceAssertion
balassert :: Amount -> Maybe BalanceAssertion
balassert Amount
amt = BalanceAssertion -> Maybe BalanceAssertion
forall a. a -> Maybe a
Just (BalanceAssertion -> Maybe BalanceAssertion)
-> BalanceAssertion -> Maybe BalanceAssertion
forall a b. (a -> b) -> a -> b
$ BalanceAssertion
nullassertion{baamount=amt}

-- | Make a total, exclusive balance assertion.
balassertTot :: Amount -> Maybe BalanceAssertion
balassertTot :: Amount -> Maybe BalanceAssertion
balassertTot Amount
amt = BalanceAssertion -> Maybe BalanceAssertion
forall a. a -> Maybe a
Just (BalanceAssertion -> Maybe BalanceAssertion)
-> BalanceAssertion -> Maybe BalanceAssertion
forall a b. (a -> b) -> a -> b
$ BalanceAssertion
nullassertion{baamount=amt, batotal=True}

-- | Make a partial, inclusive balance assertion.
balassertParInc :: Amount -> Maybe BalanceAssertion
balassertParInc :: Amount -> Maybe BalanceAssertion
balassertParInc Amount
amt = BalanceAssertion -> Maybe BalanceAssertion
forall a. a -> Maybe a
Just (BalanceAssertion -> Maybe BalanceAssertion)
-> BalanceAssertion -> Maybe BalanceAssertion
forall a b. (a -> b) -> a -> b
$ BalanceAssertion
nullassertion{baamount=amt, bainclusive=True}

-- | Make a total, inclusive balance assertion.
balassertTotInc :: Amount -> Maybe BalanceAssertion
balassertTotInc :: Amount -> Maybe BalanceAssertion
balassertTotInc Amount
amt = BalanceAssertion -> Maybe BalanceAssertion
forall a. a -> Maybe a
Just (BalanceAssertion -> Maybe BalanceAssertion)
-> BalanceAssertion -> Maybe BalanceAssertion
forall a b. (a -> b) -> a -> b
$ BalanceAssertion
nullassertion{baamount=amt, batotal=True, bainclusive=True}

-- | Render the balance-assertion operator glyph: \"=\", \"==\", \"=*\", or \"==*\".
balanceAssertionOperatorB :: BalanceAssertion -> WideBuilder
balanceAssertionOperatorB :: BalanceAssertion -> WideBuilder
balanceAssertionOperatorB BalanceAssertion
ba =
    Char -> WideBuilder
singleton Char
'=' WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> WideBuilder
eq WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> WideBuilder
ast
  where
    eq :: WideBuilder
eq  = if BalanceAssertion -> Bool
batotal BalanceAssertion
ba     then Char -> WideBuilder
singleton Char
'=' else WideBuilder
forall a. Monoid a => a
mempty
    ast :: WideBuilder
ast = if BalanceAssertion -> Bool
bainclusive BalanceAssertion
ba then Char -> WideBuilder
singleton Char
'*' else WideBuilder
forall a. Monoid a => a
mempty
    singleton :: Char -> WideBuilder
singleton Char
c = Builder -> Int -> WideBuilder
WideBuilder (Char -> Builder
TB.singleton Char
c) Int
1

-- | Render a balance assertion's expected amount, using the given AmountFormat.
balanceAssertionAmountB :: AmountFormat -> BalanceAssertion -> WideBuilder
balanceAssertionAmountB :: AmountFormat -> BalanceAssertion -> WideBuilder
balanceAssertionAmountB AmountFormat
fmt = AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
fmt (Amount -> WideBuilder)
-> (BalanceAssertion -> Amount) -> BalanceAssertion -> WideBuilder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BalanceAssertion -> Amount
baamount

-- | Render a balance assertion, as the =[=][*] symbol and expected amount,
-- separated by a single space. Used by the legacy hledger 1.x layout path;
-- the decimal-aligned path renders the operator and amount separately so it
-- can pad between them.
showBalanceAssertion :: BalanceAssertion -> WideBuilder
showBalanceAssertion :: BalanceAssertion -> WideBuilder
showBalanceAssertion BalanceAssertion
ba =
    BalanceAssertion -> WideBuilder
balanceAssertionOperatorB BalanceAssertion
ba
    WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> Builder -> Int -> WideBuilder
WideBuilder (Char -> Builder
TB.singleton Char
' ') Int
1
    WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> AmountFormat -> BalanceAssertion -> WideBuilder
balanceAssertionAmountB AmountFormat
forall a. Default a => a
def{displayZeroCommodity=True, displayForceDecimalMark=True} BalanceAssertion
ba

-- Get the original posting, if any.
originalPosting :: Posting -> Posting
originalPosting :: Posting -> Posting
originalPosting Posting
p = Posting -> Maybe Posting -> Posting
forall a. a -> Maybe a -> a
fromMaybe Posting
p (Maybe Posting -> Posting) -> Maybe Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Posting
poriginal Posting
p

showPosting :: Posting -> String
showPosting :: Posting -> String
showPosting Posting
p = Text -> String
T.unpack (Text -> String) -> ([Text] -> Text) -> [Text] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Text
T.unlines ([Text] -> String) -> [Text] -> String
forall a b. (a -> b) -> a -> b
$ AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLines AmountFormat
defaultFmt Bool
False [Posting
p]

-- | How posting lines should be aligned by 'postingsAsLines' / 'showTransaction'.
data PostingLayout
  = LayoutHledger1            -- ^ Right-align amounts in a 12+-char field, as in hledger 1.x.
  | LayoutDecimal !Int        -- ^ Align the first decimal mark of each amount at the given target column.
  deriving (PostingLayout -> PostingLayout -> Bool
(PostingLayout -> PostingLayout -> Bool)
-> (PostingLayout -> PostingLayout -> Bool) -> Eq PostingLayout
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PostingLayout -> PostingLayout -> Bool
== :: PostingLayout -> PostingLayout -> Bool
$c/= :: PostingLayout -> PostingLayout -> Bool
/= :: PostingLayout -> PostingLayout -> Bool
Eq, Int -> PostingLayout -> ShowS
[PostingLayout] -> ShowS
PostingLayout -> String
(Int -> PostingLayout -> ShowS)
-> (PostingLayout -> String)
-> ([PostingLayout] -> ShowS)
-> Show PostingLayout
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PostingLayout -> ShowS
showsPrec :: Int -> PostingLayout -> ShowS
$cshow :: PostingLayout -> String
show :: PostingLayout -> String
$cshowList :: [PostingLayout] -> ShowS
showList :: [PostingLayout] -> ShowS
Show)

-- | Default visible column (1-indexed) where posting amount decimal marks
-- should be aligned in `print` output. Used as the target unless a
-- transaction's account names + amount widths force amounts further right.
defaultDecimalMarkColumn :: Int
defaultDecimalMarkColumn :: Int
defaultDecimalMarkColumn = Int
53

-- | Default posting layout: decimal-mark alignment at column 'defaultDecimalMarkColumn'.
defaultPostingLayout :: PostingLayout
defaultPostingLayout :: PostingLayout
defaultPostingLayout = Int -> PostingLayout
LayoutDecimal Int
defaultDecimalMarkColumn

-- | Visible-character widths derived from one posting, for cross-posting
-- alignment in 'postingsAsLinesDecimal'. All fields are independent of
-- layout (decimalcol etc.), so they can be safely consumed inside the
-- lazy knot that decides those columns.
data PostingWidths = PostingWidths
  { PostingWidths -> Int
pwAcct     :: !Int
    -- ^ Account-name visible width. Used to size the account/status field
    --   so all postings' account names line up.
  , PostingWidths -> Int
pwLeft     :: !Int
    -- ^ Main amount's integer-side width: characters from the start of the
    --   rendered amount up to (but not including) the decimal mark.
    --   Includes any L-side commodity prefix (e.g. \"$\") and sign.
    --   Computed by 'amountIntegerWidth'. For a multi-commodity amount
    --   rendered on multiple lines, this is the max across rows.
    --   Used to position the decimal mark column.
  , PostingWidths -> Int
pwRight    :: !Int
    -- ^ Main amount's post-decimal width: characters from the decimal mark
    --   (inclusive) to the end of the rendered amount, including any cost
    --   annotation (\"\@ 1.20 USD\") and any R-side commodity suffix.
    --   Equivalent to @wbWidth wb - lw@ per amount row, taken as the max
    --   across rows. Used to position the assertion @=@ column one space
    --   past the rightmost amount.
  , PostingWidths -> Int
pwOperator   :: !Int
    -- ^ Visible width of this posting's balance-assertion operator:
    --   1 (@=@), 2 (@==@ or @=*@), 3 (@==*@), or 0 if the posting has no
    --   @pbalanceassertion@. Used to position the assertion-amount column
    --   one space past the widest operator.
  , PostingWidths -> Int
pwAsnLeft  :: !Int
    -- ^ Assertion amount's integer-side width, computed via
    --   'amountIntegerWidth' on @baamount@ with the same display options
    --   used for the main amount. 0 if no assertion. Used to decimal-align
    --   the assertion amounts.
  }
  deriving (PostingWidths -> PostingWidths -> Bool
(PostingWidths -> PostingWidths -> Bool)
-> (PostingWidths -> PostingWidths -> Bool) -> Eq PostingWidths
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PostingWidths -> PostingWidths -> Bool
== :: PostingWidths -> PostingWidths -> Bool
$c/= :: PostingWidths -> PostingWidths -> Bool
/= :: PostingWidths -> PostingWidths -> Bool
Eq, Int -> PostingWidths -> ShowS
[PostingWidths] -> ShowS
PostingWidths -> String
(Int -> PostingWidths -> ShowS)
-> (PostingWidths -> String)
-> ([PostingWidths] -> ShowS)
-> Show PostingWidths
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PostingWidths -> ShowS
showsPrec :: Int -> PostingWidths -> ShowS
$cshow :: PostingWidths -> String
show :: PostingWidths -> String
$cshowList :: [PostingWidths] -> ShowS
showList :: [PostingWidths] -> ShowS
Show)

-- | The three target columns derived in the knot of 'postingsAsLinesDecimal'
-- and consumed by 'postingAsLines' for aligning the main amount, the @=@ glyph,
-- and the assertion amount. @acEquals@ and @acAssDecMark@ are 0 when no posting in
-- the group has a balance assertion (in which case the renderer never
-- consults them).
data AmountCols = AmountCols
  { AmountCols -> Int
acDecMark    :: !Int  -- ^ Column for the main amount's decimal mark.
  , AmountCols -> Int
acEquals     :: !Int  -- ^ Column for the first @=@ of the balance assertion/assignment.
  , AmountCols -> Int
acAssDecMark :: !Int  -- ^ Column for the assertion amount's decimal mark.
  }
  deriving (AmountCols -> AmountCols -> Bool
(AmountCols -> AmountCols -> Bool)
-> (AmountCols -> AmountCols -> Bool) -> Eq AmountCols
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AmountCols -> AmountCols -> Bool
== :: AmountCols -> AmountCols -> Bool
$c/= :: AmountCols -> AmountCols -> Bool
/= :: AmountCols -> AmountCols -> Bool
Eq, Int -> AmountCols -> ShowS
[AmountCols] -> ShowS
AmountCols -> String
(Int -> AmountCols -> ShowS)
-> (AmountCols -> String)
-> ([AmountCols] -> ShowS)
-> Show AmountCols
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AmountCols -> ShowS
showsPrec :: Int -> AmountCols -> ShowS
$cshow :: AmountCols -> String
show :: AmountCols -> String
$cshowList :: [AmountCols] -> ShowS
showList :: [AmountCols] -> ShowS
Show)

-- | Visible width of the part of a rendered amount that appears before its
-- (real or virtual) decimal mark — i.e. from the start of the amount through
-- the last digit of the integer portion (including any L-side commodity
-- prefix). Computed structurally from the 'Amount' data rather than by
-- parsing the rendered text, so it is unaffected by trailing cost annotations,
-- lot syntax, comments, or digits that may appear inside a commodity name.
-- Used to align integer-ends across postings at decimalcol-1.
amountIntegerWidth :: AmountFormat -> Amount -> Int
amountIntegerWidth :: AmountFormat -> Amount -> Int
amountIntegerWidth AmountFormat
opts Amount
a
    -- The "AUTO" commodity marks a missing amount; showAmountB renders it as
    -- empty, so its left-width is 0.
    | Amount -> Text
acommodity Amount
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"AUTO" = Int
0
    | Bool
otherwise              = Int
commodityPrefixW Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
quantityIntegerW
  where
    s :: AmountStyle
s = Amount -> AmountStyle
astyle Amount
a
    -- Width of the integer portion of the rendered quantity. Renders the amount
    -- truncated to integer with precision 0; the result has no decimal mark or
    -- fractional digits, so its width is exactly sign + integer-digits + group-seps.
    -- Sign is added explicitly to handle the -0.x → 0 truncation case — but only
    -- when the rendered amount will actually show a sign (i.e., it has fractional
    -- digits). At Precision 0 a value rounding to 0 shows as "0" with no sign,
    -- so no extra slot is reserved.
    quantityIntegerW :: Int
quantityIntegerW =
        let intAmt :: Amount
intAmt   = Amount
a{ aquantity = fromInteger (truncate (aquantity a) :: Integer)
                        , astyle    = s{asprecision = Precision 0}
                        }
            w :: Int
w        = WideBuilder -> Int
wbWidth (Bool -> Amount -> WideBuilder
showAmountQuantity Bool
False Amount
intAmt)
            showsFractional :: Bool
showsFractional = case AmountStyle -> AmountPrecision
asprecision AmountStyle
s of
                Precision Word8
0 -> Bool
False
                AmountPrecision
_           -> Bool
True
            signLost :: Bool
signLost = Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0 Bool -> Bool -> Bool
&& (Quantity -> Integer
forall b. Integral b => Quantity -> b
forall a b. (RealFrac a, Integral b) => a -> b
truncate (Amount -> Quantity
aquantity Amount
a) :: Integer) Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
0
                    Bool -> Bool -> Bool
&& Bool
showsFractional
        in Int
w Int -> Int -> Int
forall a. Num a => a -> a -> a
+ (if Bool
signLost then Int
1 else Int
0)
    -- Width of the commodity portion when it appears as a prefix (L-side).
    commodityPrefixW :: Int
commodityPrefixW
      | AmountStyle -> Side
ascommodityside AmountStyle
s Side -> Side -> Bool
forall a. Eq a => a -> a -> Bool
== Side
L =
          let comm :: Text
comm   = (if AmountFormat -> Bool
displayQuotes AmountFormat
opts then Text -> Text
quoteCommoditySymbolIfNeeded else Text -> Text
forall a. a -> a
id) (Amount -> Text
acommodity Amount
a)
              spaceW :: Int
spaceW = if Bool -> Bool
not (Text -> Bool
T.null Text
comm) Bool -> Bool -> Bool
&& AmountStyle -> Bool
ascommodityspaced AmountStyle
s then Int
1 else Int
0
          in Text -> Int
forall a. HasChars a => a -> Int
realLength Text
comm Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
spaceW
      | Bool
otherwise = Int
0

-- | Visible width of a posting's status prefix (e.g. \"* \" or \"! \"), or 0
-- if it has no status flag. Used to compute account-field width per transaction.
postingStatusWidth :: Posting -> Int
postingStatusWidth :: Posting -> Int
postingStatusWidth Posting
p = case Posting -> Status
pstatus Posting
p of
    Status
Unmarked -> Int
0
    Status
_        -> Int
2

-- | Render a posting, at the appropriate width for aligning with
-- its siblings if any. Used by the rewrite command.
showPostingLines :: Posting -> [Text]
showPostingLines :: Posting -> [Text]
showPostingLines Posting
p = ([Text], PostingWidths) -> [Text]
forall a b. (a, b) -> a
fst (([Text], PostingWidths) -> [Text])
-> ([Text], PostingWidths) -> [Text]
forall a b. (a -> b) -> a -> b
$ AmountFormat
-> Bool
-> Bool
-> Int
-> Int
-> AmountCols
-> Posting
-> ([Text], PostingWidths)
postingAsLines AmountFormat
defaultFmt Bool
False Bool
False Int
maxstatuswidth Int
maxacctwidth AmountCols
dc Posting
p
  where
    siblings :: [Posting]
siblings = [Posting]
-> (Transaction -> [Posting]) -> Maybe Transaction -> [Posting]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [Posting
p] Transaction -> [Posting]
tpostings (Maybe Transaction -> [Posting]) -> Maybe Transaction -> [Posting]
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Transaction
ptransaction Posting
p
    linesWithWidths :: [([Text], PostingWidths)]
linesWithWidths = (Posting -> ([Text], PostingWidths))
-> [Posting] -> [([Text], PostingWidths)]
forall a b. (a -> b) -> [a] -> [b]
map (AmountFormat
-> Bool
-> Bool
-> Int
-> Int
-> AmountCols
-> Posting
-> ([Text], PostingWidths)
postingAsLines AmountFormat
defaultFmt Bool
False Bool
False Int
maxstatuswidth Int
maxacctwidth AmountCols
dc) [Posting]
siblings
    maxstatuswidth :: Int
maxstatuswidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (Posting -> Int) -> [Posting] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Int
postingStatusWidth [Posting]
siblings
    pws :: [PostingWidths]
pws = (([Text], PostingWidths) -> PostingWidths)
-> [([Text], PostingWidths)] -> [PostingWidths]
forall a b. (a -> b) -> [a] -> [b]
map ([Text], PostingWidths) -> PostingWidths
forall a b. (a, b) -> b
snd [([Text], PostingWidths)]
linesWithWidths
    maxacctwidth :: Int
maxacctwidth   = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwAcct    [PostingWidths]
pws
    maxleftwidth :: Int
maxleftwidth   = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwLeft    [PostingWidths]
pws
    maxrightwidth :: Int
maxrightwidth  = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwRight   [PostingWidths]
pws
    maxoperatorwidth :: Int
maxoperatorwidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwOperator  [PostingWidths]
pws
    maxasnleftwidth :: Int
maxasnleftwidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwAsnLeft [PostingWidths]
pws
    decimalcol :: Int
decimalcol    = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
defaultDecimalMarkColumn (Int
maxacctwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxstatuswidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxleftwidth)
    eqcol :: Int
eqcol         = Int
decimalcol Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxrightwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    asndecimalcol :: Int
asndecimalcol = Int
eqcol Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxoperatorwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxasnleftwidth
    dc :: AmountCols
dc = Int -> Int -> Int -> AmountCols
AmountCols Int
decimalcol Int
eqcol Int
asndecimalcol

-- | Render a transaction's postings as indented lines, suitable for `print` output,
-- using the default posting layout (decimal-mark alignment at column 53).
--
-- Normally these will be in valid journal syntax which hledger can reparse
-- (though they may include no-longer-valid balance assertions).
-- Explicit amounts are shown, implicit amounts are not.
--
-- Postings with multicommodity explicit amounts are handled as follows:
-- if onelineamounts is true, these amounts are shown on one line,
-- comma-separated, and the output will not be valid journal syntax.
-- Otherwise, they are shown as several similar postings, one per commodity.
-- When the posting has a balance assertion, it is attached to the last of these postings.
--
-- Note: a few fields of the caller's @AmountFormat@ are overridden internally;
-- see 'postingAsLines' for details.
--
postingsAsLines :: AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLines :: AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLines AmountFormat
basefmt Bool
onelineamounts =
    AmountFormat -> Bool -> PostingLayout -> [Posting] -> [Text]
postingsAsLinesWithLayout AmountFormat
basefmt Bool
onelineamounts PostingLayout
defaultPostingLayout

-- | Like 'postingsAsLines' but with an explicit 'PostingLayout': either the
-- new decimal-mark alignment (with a target column) or the older hledger 1.x
-- right-aligned layout.
postingsAsLinesWithLayout :: AmountFormat -> Bool -> PostingLayout -> [Posting] -> [Text]
postingsAsLinesWithLayout :: AmountFormat -> Bool -> PostingLayout -> [Posting] -> [Text]
postingsAsLinesWithLayout AmountFormat
basefmt Bool
onelineamounts PostingLayout
layout [Posting]
ps = case PostingLayout
layout of
    LayoutDecimal Int
targetcol -> AmountFormat -> Bool -> Int -> [Posting] -> [Text]
postingsAsLinesDecimal AmountFormat
basefmt Bool
onelineamounts Int
targetcol [Posting]
ps
    PostingLayout
LayoutHledger1          -> AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLinesHledger1 AmountFormat
basefmt Bool
onelineamounts [Posting]
ps

-- | Decimal-mark-aligned layout (the new default). The target column is bumped
-- right per-transaction if needed to keep at least 2 spaces between each
-- account name and amount.
postingsAsLinesDecimal :: AmountFormat -> Bool -> Int -> [Posting] -> [Text]
postingsAsLinesDecimal :: AmountFormat -> Bool -> Int -> [Posting] -> [Text]
postingsAsLinesDecimal AmountFormat
basefmt Bool
onelineamounts Int
targetcol [Posting]
ps = (([Text], PostingWidths) -> [Text])
-> [([Text], PostingWidths)] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Text], PostingWidths) -> [Text]
forall a b. (a, b) -> a
fst [([Text], PostingWidths)]
linesWithWidths
  where
    -- Lazy knot: postingAsLines takes the layout columns (AmountCols) and
    -- returns this posting's PostingWidths; the layout columns are computed
    -- from the cross-posting maxes of those widths. This terminates only
    -- because PostingWidths fields do NOT depend on AmountCols — they are
    -- structural widths of the posting's amount/account/assertion data, while
    -- AmountCols only affects the rendered text (the first element of each
    -- linesWithWidths pair, which we don't force until concatMap fst above).
    -- If any PostingWidths field ever started depending on AmountCols this
    -- would diverge. Keep that invariant when changing postingAsLines.
    linesWithWidths :: [([Text], PostingWidths)]
linesWithWidths = (Posting -> ([Text], PostingWidths))
-> [Posting] -> [([Text], PostingWidths)]
forall a b. (a -> b) -> [a] -> [b]
map (AmountFormat
-> Bool
-> Bool
-> Int
-> Int
-> AmountCols
-> Posting
-> ([Text], PostingWidths)
postingAsLines AmountFormat
basefmt Bool
False Bool
onelineamounts Int
maxstatuswidth Int
maxacctwidth AmountCols
dc) [Posting]
ps
    maxstatuswidth :: Int
maxstatuswidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (Posting -> Int) -> [Posting] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Int
postingStatusWidth [Posting]
ps
    pws :: [PostingWidths]
pws = (([Text], PostingWidths) -> PostingWidths)
-> [([Text], PostingWidths)] -> [PostingWidths]
forall a b. (a -> b) -> [a] -> [b]
map ([Text], PostingWidths) -> PostingWidths
forall a b. (a, b) -> b
snd [([Text], PostingWidths)]
linesWithWidths
    maxacctwidth :: Int
maxacctwidth    = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwAcct    [PostingWidths]
pws
    maxleftwidth :: Int
maxleftwidth    = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwLeft    [PostingWidths]
pws
    maxrightwidth :: Int
maxrightwidth   = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwRight   [PostingWidths]
pws
    maxoperatorwidth :: Int
maxoperatorwidth  = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwOperator  [PostingWidths]
pws
    maxasnleftwidth :: Int
maxasnleftwidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (PostingWidths -> Int) -> [PostingWidths] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PostingWidths -> Int
pwAsnLeft [PostingWidths]
pws
    decimalcol :: Int
decimalcol    = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
targetcol (Int
maxacctwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxstatuswidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxleftwidth)
    -- eqcol / asndecimalcol are 0 (and unused by the renderer) when no
    -- posting in the group has a balance assertion.
    hasAssertion :: Bool
hasAssertion  = Int
maxoperatorwidth Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0
    eqcol :: Int
eqcol         = if Bool
hasAssertion then Int
decimalcol Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxrightwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 else Int
0
    asndecimalcol :: Int
asndecimalcol = if Bool
hasAssertion then Int
eqcol Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxoperatorwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
maxasnleftwidth else Int
0
    dc :: AmountCols
dc            = Int -> Int -> Int -> AmountCols
AmountCols Int
decimalcol Int
eqcol Int
asndecimalcol

-- | hledger 1.x layout: right-align amounts within a 12+-char field, lifted
-- verbatim from the pre-decimal-alignment code. Kept as an escape hatch for
-- users who prefer the old appearance via @print --layout=hledger1@.
postingsAsLinesHledger1 :: AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLinesHledger1 :: AmountFormat -> Bool -> [Posting] -> [Text]
postingsAsLinesHledger1 AmountFormat
basefmt Bool
onelineamounts [Posting]
ps = (([Text], Int, Int) -> [Text]) -> [([Text], Int, Int)] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Text], Int, Int) -> [Text]
forall {a} {b} {c}. (a, b, c) -> a
first3 [([Text], Int, Int)]
linesWithWidths
  where
    linesWithWidths :: [([Text], Int, Int)]
linesWithWidths = (Posting -> ([Text], Int, Int))
-> [Posting] -> [([Text], Int, Int)]
forall a b. (a -> b) -> [a] -> [b]
map (AmountFormat
-> Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
postingAsLinesHledger1 AmountFormat
basefmt Bool
False Bool
onelineamounts Int
maxacctwidth Int
maxamtwidth) [Posting]
ps
    maxacctwidth :: Int
maxacctwidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (([Text], Int, Int) -> Int) -> [([Text], Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ([Text], Int, Int) -> Int
forall {a} {b} {c}. (a, b, c) -> b
second3 [([Text], Int, Int)]
linesWithWidths
    maxamtwidth :: Int
maxamtwidth  = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (([Text], Int, Int) -> Int) -> [([Text], Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ([Text], Int, Int) -> Int
forall {a} {b} {c}. (a, b, c) -> c
third3 [([Text], Int, Int)]
linesWithWidths

-- | hledger 1.x per-posting renderer: right-aligned amounts.
-- This is the pre-decimal-alignment 'postingAsLines' body, restored verbatim.
postingAsLinesHledger1 :: AmountFormat -> Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
postingAsLinesHledger1 :: AmountFormat
-> Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
postingAsLinesHledger1 AmountFormat
basefmt Bool
elideamount Bool
onelineamounts Int
acctwidth Int
amtwidth Posting
p =
    (([Text] -> [Text]) -> [[Text]] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text]
newlinecomments) [[Text]]
postingblocks, Int
thisacctwidth, Int
thisamtwidth)
  where
    postingblocks :: [[Text]]
postingblocks = [(Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
T.stripEnd ([Text] -> [Text]) -> (Text -> [Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
T.lines (Text -> [Text]) -> (Text -> Text) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
TL.toStrict (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$
                       [Cell] -> Text
render [ Align -> Text -> Cell
textCell Align
BottomLeft Text
statusandaccount
                              , Align -> Text -> Cell
textCell Align
BottomLeft Text
"  "
                              , Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [WideBuilder -> WideBuilder
pad WideBuilder
amt]
                              , Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [WideBuilder
assertion]
                              , Align -> Text -> Cell
textCell Align
BottomLeft Text
samelinecomment
                              ]
                    | (WideBuilder
amt,WideBuilder
assertion) <- [(WideBuilder, WideBuilder)]
shownAmountsAssertions]
    render :: [Cell] -> Text
render = TableOpts -> Header Cell -> Text
renderRow TableOpts
forall a. Default a => a
def{tableBorders=False, borderSpaces=False} (Header Cell -> Text) -> ([Cell] -> Header Cell) -> [Cell] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Properties -> [Header Cell] -> Header Cell
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Cell] -> Header Cell)
-> ([Cell] -> [Header Cell]) -> [Cell] -> Header Cell
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Cell -> Header Cell) -> [Cell] -> [Header Cell]
forall a b. (a -> b) -> [a] -> [b]
map Cell -> Header Cell
forall h. h -> Header h
Header
    pad :: WideBuilder -> WideBuilder
pad WideBuilder
amt = Builder -> Int -> WideBuilder
WideBuilder (Text -> Builder
TB.fromText (Text -> Builder) -> Text -> Builder
forall a b. (a -> b) -> a -> b
$ Int -> Text -> Text
T.replicate Int
w Text
" ") Int
w WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> WideBuilder
amt
      where w :: Int
w = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
12 Int
amtwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- WideBuilder -> Int
wbWidth WideBuilder
amt  -- min. 12 for backwards compatibility

    pacctstr :: Posting -> Text
pacctstr Posting
p' = Maybe Int -> PostingRealness -> Text -> Text
showAccountName Maybe Int
forall a. Maybe a
Nothing (Posting -> PostingRealness
preal Posting
p') (Posting -> Text
paccount Posting
p')
    pstatusandacct :: Posting -> Text
pstatusandacct Posting
p' = Posting -> Text
pstatusprefix Posting
p' Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Posting -> Text
pacctstr Posting
p'
    pstatusprefix :: Posting -> Text
pstatusprefix Posting
p' = case Posting -> Status
pstatus Posting
p' of
        Status
Unmarked -> Text
""
        Status
s        -> String -> Text
T.pack (Status -> String
forall a. Show a => a -> String
show Status
s) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" "

    -- prices are considered part of the amount string when right-aligning amounts.
    -- The knot between amtwidth and thisamtwidth is tied via lazy evaluation, so
    -- thisamtwidth must not depend on amtwidth.
    shownAmounts :: [WideBuilder]
shownAmounts
      | Bool
elideamount = [WideBuilder
forall a. Monoid a => a
mempty]
      | Bool
otherwise   = AmountFormat -> MixedAmount -> [WideBuilder]
showMixedAmountLinesB AmountFormat
displayopts (MixedAmount -> [WideBuilder]) -> MixedAmount -> [WideBuilder]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
      where displayopts :: AmountFormat
displayopts = AmountFormat
basefmt{
          displayZeroCommodity=True, displayForceDecimalMark=True, displayOneLine=onelineamounts
          }
    thisamtwidth :: Int
thisamtwidth = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (WideBuilder -> Int) -> [WideBuilder] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map WideBuilder -> Int
wbWidth [WideBuilder]
shownAmounts

    shownAmountsAssertions :: [(WideBuilder, WideBuilder)]
shownAmountsAssertions = [WideBuilder] -> [WideBuilder] -> [(WideBuilder, WideBuilder)]
forall a b. [a] -> [b] -> [(a, b)]
zip [WideBuilder]
shownAmounts [WideBuilder]
shownAssertions
      where
        shownAssertions :: [WideBuilder]
shownAssertions = Int -> WideBuilder -> [WideBuilder]
forall a. Int -> a -> [a]
replicate ([WideBuilder] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [WideBuilder]
shownAmounts Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) WideBuilder
forall a. Monoid a => a
mempty [WideBuilder] -> [WideBuilder] -> [WideBuilder]
forall a. [a] -> [a] -> [a]
++ [WideBuilder
assertion]
        assertion :: WideBuilder
assertion = WideBuilder
-> (BalanceAssertion -> WideBuilder)
-> Maybe BalanceAssertion
-> WideBuilder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe WideBuilder
forall a. Monoid a => a
mempty ((Builder -> Int -> WideBuilder
WideBuilder (Char -> Builder
TB.singleton Char
' ') Int
1 WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<>)(WideBuilder -> WideBuilder)
-> (BalanceAssertion -> WideBuilder)
-> BalanceAssertion
-> WideBuilder
forall b c a. (b -> c) -> (a -> b) -> a -> c
.BalanceAssertion -> WideBuilder
showBalanceAssertion) (Maybe BalanceAssertion -> WideBuilder)
-> Maybe BalanceAssertion -> WideBuilder
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p

    statusandaccount :: Text
statusandaccount = Text -> Text
postingIndent (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just (Int -> Maybe Int) -> Int -> Maybe Int
forall a b. (a -> b) -> a -> b
$ Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
acctwidth) Maybe Int
forall a. Maybe a
Nothing Bool
False Bool
True (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
pstatusandacct Posting
p
    thisacctwidth :: Int
thisacctwidth = Text -> Int
forall a. HasChars a => a -> Int
realLength (Text -> Int) -> Text -> Int
forall a b. (a -> b) -> a -> b
$ Posting -> Text
pacctstr Posting
p

    (Text
samelinecomment, [Text]
newlinecomments) =
      case Text -> [Text]
renderCommentLines (Posting -> Text
pcomment Posting
p) of []   -> (Text
"",[])
                                              Text
c:[Text]
cs -> (Text
c,[Text]
cs)

-- | Render one posting, on one or more lines, suitable for `print` output.
-- Also returns the 'PostingWidths' computed from this posting's structural
-- data (account name, main amount, assertion operator / amount), used by the
-- caller's lazy knot to derive the layout columns.
--
-- There will be an indented account name, plus one or more of status flag,
-- posting amount, balance assertion, same-line comment, next-line comments.
--
-- If the posting's amount is implicit or if elideamount is true, no amount is shown.
-- If the posting's amount is explicit and multi-commodity, multiple similar
-- postings are shown, one for each commodity, to help produce parseable journal syntax.
-- Or if onelineamounts is true, such amounts are shown on one line, comma-separated
-- (and the output will not be valid journal syntax).
--
-- If an amount is zero, any commodity symbol attached to it is shown
-- (and the corresponding commodity display style is used).
--
-- Three target columns are supplied via 'AmountCols':
--
-- * @acDecMark@ — the main amount's decimal mark is left-padded to land here.
--   With multi-commodity postings rendered on multiple lines, every line is
--   aligned at this column. Callers (postingsAsLines, showPostingLines) pick
--   it so that at least 2 spaces remain between the widest account name and
--   the start of the amount area.
-- * @acEquals@ — the first @=@ of any balance-assertion operator (@=@, @==@, @=*@,
--   or @==*@) is padded to land here, one space past the rightmost main
--   amount across all postings.
-- * @acAssDecMark@ — the assertion amount's decimal mark is padded to land
--   here. The leftmost assertion amount starts one space past the widest
--   operator; narrower-operator postings get extra space so all assertion
--   amounts line up on their decimals.
--
-- @acEquals@ and @acAssDecMark@ are unused (and may be 0) when no posting in the
-- group has a balance assertion.
--
-- Note: this function overrides four fields of the caller's @AmountFormat@:
--
-- * @displayZeroCommodity = True@ — always show the commodity on zero amounts
--   so they participate in alignment.
-- * @displayForceDecimalMark = True@ — force a decimal mark when digit groups
--   are shown, for unambiguous display.
-- * @displayOneLine = onelineamounts@ — driven by this function's parameter.
-- * @displayMinWidth = Nothing@ — disable the legacy right-alignment of
--   multi-commodity amount lines, since this function provides its own
--   decimal-mark alignment.
--
postingAsLines :: AmountFormat -> Bool -> Bool -> Int -> Int -> AmountCols -> Posting -> ([Text], PostingWidths)
postingAsLines :: AmountFormat
-> Bool
-> Bool
-> Int
-> Int
-> AmountCols
-> Posting
-> ([Text], PostingWidths)
postingAsLines AmountFormat
basefmt Bool
elideamount Bool
onelineamounts Int
statuswidth Int
acctwidth AmountCols
dc Posting
p =
    (([Text] -> [Text]) -> [[Text]] -> [Text]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text]
newlinecomments) [[Text]]
postingblocks, PostingWidths
widths)
  where
    AmountCols{acDecMark :: AmountCols -> Int
acDecMark=Int
decimalcol, acEquals :: AmountCols -> Int
acEquals=Int
eqcol, acAssDecMark :: AmountCols -> Int
acAssDecMark=Int
asndecimalcol} = AmountCols
dc

    widths :: PostingWidths
widths = PostingWidths
      { pwAcct :: Int
pwAcct     = Int
thisacctwidth
      , pwLeft :: Int
pwLeft     = Int
thisleftwidth
      , pwRight :: Int
pwRight    = Int
thisrightwidth
      , pwOperator :: Int
pwOperator = Int
thisoperatorwidth
      , pwAsnLeft :: Int
pwAsnLeft  = Int
thisasnleftwidth
      }

    -- This needs to be converted to strict Text in order to strip trailing
    -- spaces. This adds a small amount of inefficiency, and the only difference
    -- is whether there are trailing spaces in print (and related) reports. This
    -- could be removed and we could just keep everything as a Text Builder, but
    -- would require adding trailing spaces to 42 failing tests.
    postingblocks :: [[Text]]
postingblocks = [(Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
T.stripEnd ([Text] -> [Text]) -> (Text -> [Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
T.lines (Text -> [Text]) -> (Text -> Text) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
TL.toStrict (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$
                       [Cell] -> Text
render [ Align -> Text -> Cell
textCell Align
BottomLeft Text
statusandaccount
                              , Align -> Text -> Cell
textCell Align
BottomLeft Text
"  "
                              , Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [Int -> WideBuilder -> WideBuilder
padLeft (Int
decimalcol Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
acctwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
statuswidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
7 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
lw) WideBuilder
amt]
                              , Align -> [WideBuilder] -> Cell
Cell Align
BottomLeft [WideBuilder
asn]
                              , Align -> Text -> Cell
textCell Align
BottomLeft Text
samelinecomment
                              ]
                    | (WideBuilder
amt, Int
lw, WideBuilder
asn) <- [(WideBuilder, Int, WideBuilder)]
amountAssertionRows]
    render :: [Cell] -> Text
render = TableOpts -> Header Cell -> Text
renderRow TableOpts
forall a. Default a => a
def{tableBorders=False, borderSpaces=False} (Header Cell -> Text) -> ([Cell] -> Header Cell) -> [Cell] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Properties -> [Header Cell] -> Header Cell
forall h. Properties -> [Header h] -> Header h
Group Properties
NoLine ([Header Cell] -> Header Cell)
-> ([Cell] -> [Header Cell]) -> [Cell] -> Header Cell
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Cell -> Header Cell) -> [Cell] -> [Header Cell]
forall a b. (a -> b) -> [a] -> [b]
map Cell -> Header Cell
forall h. h -> Header h
Header

    -- Prepend N space characters to a WideBuilder; N is floored at 0.
    -- The amount area starts at column (acctwidth + statuswidth + 7) (1-indexed):
    -- 4 indent + (statuswidth + acctwidth) status/account field + 2 separator.
    -- For the main amount, a pre-decimal width lw means we want the decimal
    -- at column (acctwidth + statuswidth + 7 + lw + N), so N =
    -- decimalcol - (acctwidth + statuswidth + 7 + lw).
    padLeft :: Int -> WideBuilder -> WideBuilder
padLeft Int
n WideBuilder
b = Builder -> Int -> WideBuilder
WideBuilder (Text -> Builder
TB.fromText (Text -> Builder) -> Text -> Builder
forall a b. (a -> b) -> a -> b
$ Int -> Text -> Text
T.replicate Int
w Text
" ") Int
w WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> WideBuilder
b
      where w :: Int
w = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 Int
n

    pacctstr :: Posting -> Text
pacctstr Posting
p' = Maybe Int -> PostingRealness -> Text -> Text
showAccountName Maybe Int
forall a. Maybe a
Nothing (Posting -> PostingRealness
preal Posting
p') (Posting -> Text
paccount Posting
p')
    pstatusandacct :: Posting -> Text
pstatusandacct Posting
p' = Posting -> Text
pstatusprefix Posting
p' Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Posting -> Text
pacctstr Posting
p'
    pstatusprefix :: Posting -> Text
pstatusprefix Posting
p' = case Posting -> Status
pstatus Posting
p' of
        Status
Unmarked -> Text
""
        Status
s        -> String -> Text
T.pack (Status -> String
forall a. Show a => a -> String
show Status
s) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" "

    -- Display options used to render BOTH the main amount and the assertion
    -- amount, so their lw / rw computations match the rendered text and the
    -- two amounts share commodity styling within a transaction.
    -- See postingAsLines's haddock for which fields of basefmt are overridden.
    displayopts :: AmountFormat
displayopts = AmountFormat
basefmt{
        displayZeroCommodity    = True
      , displayForceDecimalMark = True
      , displayOneLine          = onelineamounts
      , displayMinWidth         = Nothing
      }

    -- Per-amount-row triples (wb, lw, rw): the rendered builder, its
    -- integer-side visible width left of the decimal, and its post-decimal
    -- visible width (rw = wbWidth wb - lw). All structural; must remain
    -- independent of any layout column (see the lazy knot in
    -- postingsAsLinesDecimal).
    amountRows :: [(WideBuilder, Int, Int)]
amountRows
      | Bool
elideamount = [(WideBuilder
forall a. Monoid a => a
mempty, Int
0, Int
0)]
      | Bool
otherwise   = case AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]
showMixedAmountLinesPartsB AmountFormat
displayopts (Posting -> MixedAmount
pamount Posting
p) of
                        [] -> [(WideBuilder
forall a. Monoid a => a
mempty, Int
0, Int
0)]
                        [(WideBuilder, Amount)]
xs -> [ (WideBuilder
wb, Int
lw, WideBuilder -> Int
wbWidth WideBuilder
wb Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
lw)
                              | (WideBuilder
wb, Amount
a) <- [(WideBuilder, Amount)]
xs
                              , let lw :: Int
lw = AmountFormat -> Amount -> Int
amountIntegerWidth AmountFormat
displayopts Amount
a]

    thisleftwidth :: Int
thisleftwidth   = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 [Int
lw | (WideBuilder
_, Int
lw, Int
_) <- [(WideBuilder, Int, Int)]
amountRows]
    thisrightwidth :: Int
thisrightwidth  = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumBound Int
0 [Int
rw | (WideBuilder
_, Int
_, Int
rw) <- [(WideBuilder, Int, Int)]
amountRows]

    -- Per-posting balance-assertion widths (0 if the posting has no assertion).
    (Int
thisoperatorwidth, Int
thisasnleftwidth) = case Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p of
        Maybe BalanceAssertion
Nothing -> (Int
0, Int
0)
        Just BalanceAssertion
ba -> ( WideBuilder -> Int
wbWidth (BalanceAssertion -> WideBuilder
balanceAssertionOperatorB BalanceAssertion
ba)
                   , AmountFormat -> Amount -> Int
amountIntegerWidth AmountFormat
displayopts (BalanceAssertion -> Amount
baamount BalanceAssertion
ba)
                   )

    -- The balance-assertion cell on the last amount row (if there's an
    -- assertion). Lays out as: pad1 + operator + pad2 + amount, where pad1
    -- lifts the operator to eqcol and pad2 lifts the assertion amount's
    -- decimal mark to asndecimalcol. By construction in the knot, pad1 and
    -- pad2 are >= 1 when any sibling has the maximum value; floor at 1
    -- defensively in case of a single-posting context with no cross-sibling
    -- alignment to satisfy.
    assertionWB :: WideBuilder
assertionWB = case Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p of
        Maybe BalanceAssertion
Nothing -> WideBuilder
forall a. Monoid a => a
mempty
        Just BalanceAssertion
ba ->
          let pad1Len :: Int
pad1Len = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 (Int
eqcol Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
decimalcol Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
thisrightwidth)
              pad2Len :: Int
pad2Len = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 (Int
asndecimalcol Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
eqcol Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
thisoperatorwidth Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
thisasnleftwidth)
          in Int -> WideBuilder -> WideBuilder
padLeft Int
pad1Len (BalanceAssertion -> WideBuilder
balanceAssertionOperatorB BalanceAssertion
ba)
             WideBuilder -> WideBuilder -> WideBuilder
forall a. Semigroup a => a -> a -> a
<> Int -> WideBuilder -> WideBuilder
padLeft Int
pad2Len (AmountFormat -> BalanceAssertion -> WideBuilder
balanceAssertionAmountB AmountFormat
displayopts BalanceAssertion
ba)

    -- Pair each amount row with its assertion (only on the last row).
    amountAssertionRows :: [(WideBuilder, Int, WideBuilder)]
amountAssertionRows =
        [(WideBuilder
wb, Int
lw, WideBuilder
asn) | ((WideBuilder
wb, Int
lw, Int
_), WideBuilder
asn) <- [(WideBuilder, Int, Int)]
-> [WideBuilder] -> [((WideBuilder, Int, Int), WideBuilder)]
forall a b. [a] -> [b] -> [(a, b)]
zip [(WideBuilder, Int, Int)]
amountRows [WideBuilder]
shownAssertions]
      where
        shownAssertions :: [WideBuilder]
shownAssertions = Int -> WideBuilder -> [WideBuilder]
forall a. Int -> a -> [a]
replicate ([(WideBuilder, Int, Int)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(WideBuilder, Int, Int)]
amountRows Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) WideBuilder
forall a. Monoid a => a
mempty [WideBuilder] -> [WideBuilder] -> [WideBuilder]
forall a. [a] -> [a] -> [a]
++ [WideBuilder
assertionWB]

    -- pad to the maximum account name width, plus statuswidth chars to leave
    -- room for status flags (where any sibling has one), to keep amounts aligned
    statusandaccount :: Text
statusandaccount = Text -> Text
postingIndent (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just (Int -> Maybe Int) -> Int -> Maybe Int
forall a b. (a -> b) -> a -> b
$ Int
statuswidth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
acctwidth) Maybe Int
forall a. Maybe a
Nothing Bool
False Bool
True (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
pstatusandacct Posting
p
    thisacctwidth :: Int
thisacctwidth = Text -> Int
forall a. HasChars a => a -> Int
realLength (Text -> Int) -> Text -> Int
forall a b. (a -> b) -> a -> b
$ Posting -> Text
pacctstr Posting
p

    (Text
samelinecomment, [Text]
newlinecomments) =
      case Text -> [Text]
renderCommentLines (Posting -> Text
pcomment Posting
p) of []   -> (Text
"",[])
                                              Text
c:[Text]
cs -> (Text
c,[Text]
cs)

-- | Show an account name, clipped to the given width if any, and
-- appropriately bracketed/parenthesised for the given posting realness.
showAccountName :: Maybe Int -> PostingRealness -> AccountName -> Text
showAccountName :: Maybe Int -> PostingRealness -> Text -> Text
showAccountName Maybe Int
w = PostingRealness -> Text -> Text
fmt
  where
    fmt :: PostingRealness -> Text -> Text
fmt PostingRealness
RealPosting            = (Text -> Text)
-> (Int -> Text -> Text) -> Maybe Int -> Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text -> Text
forall a. a -> a
id Int -> Text -> Text
T.take Maybe Int
w
    fmt PostingRealness
VirtualPosting         = Text -> Text -> Text -> Text
wrap Text
"(" Text
")" (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Text)
-> (Int -> Text -> Text) -> Maybe Int -> Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text -> Text
forall a. a -> a
id (Int -> Text -> Text
T.takeEnd (Int -> Text -> Text) -> (Int -> Int) -> Int -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int -> Int
forall a. Num a => a -> a -> a
subtract Int
2) Maybe Int
w
    fmt PostingRealness
BalancedVirtualPosting = Text -> Text -> Text -> Text
wrap Text
"[" Text
"]" (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Text)
-> (Int -> Text -> Text) -> Maybe Int -> Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text -> Text
forall a. a -> a
id (Int -> Text -> Text
T.takeEnd (Int -> Text -> Text) -> (Int -> Int) -> Int -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int -> Int
forall a. Num a => a -> a -> a
subtract Int
2) Maybe Int
w

-- | Render a transaction or posting's comment as indented, semicolon-prefixed comment lines.
-- The first line (unless empty) will have leading space, subsequent lines will have a larger indent.
renderCommentLines :: Text -> [Text]
renderCommentLines :: Text -> [Text]
renderCommentLines Text
t =
  case Text -> [Text]
T.lines Text
t of
    []      -> []
    [Text
l]     -> [Text -> Text
commentSpace (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
comment Text
l]        -- single-line comment
    (Text
"":[Text]
ls) -> Text
"" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
postingIndent (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
comment) [Text]
ls  -- multi-line comment with empty first line
    (Text
l:[Text]
ls)  -> Text -> Text
commentSpace (Text -> Text
comment Text
l) Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
postingIndent (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
comment) [Text]
ls
  where
    comment :: Text -> Text
comment = (Text
"; "Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>)

-- | Prepend a suitable indent for a posting (or transaction/posting comment) line.
postingIndent :: Text -> Text
postingIndent :: Text -> Text
postingIndent = (Text
"    "Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>)

-- | Prepend the space required before a same-line comment.
commentSpace :: Text -> Text
commentSpace :: Text -> Text
commentSpace = (Text
"  "Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>)


isReal :: Posting -> Bool
isReal :: Posting -> Bool
isReal Posting
p = Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
RealPosting

isVirtual :: Posting -> Bool
isVirtual :: Posting -> Bool
isVirtual Posting
p = Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
VirtualPosting

isBalancedVirtual :: Posting -> Bool
isBalancedVirtual :: Posting -> Bool
isBalancedVirtual Posting
p = Posting -> PostingRealness
preal Posting
p PostingRealness -> PostingRealness -> Bool
forall a. Eq a => a -> a -> Bool
== PostingRealness
BalancedVirtualPosting

hasAmount :: Posting -> Bool
hasAmount :: Posting -> Bool
hasAmount = Bool -> Bool
not (Bool -> Bool) -> (Posting -> Bool) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> Bool
isMissingMixedAmount (MixedAmount -> Bool)
-> (Posting -> MixedAmount) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount

-- | Was this posting's amount explicitly written by the user, rather than
-- inferred by hledger ? Amounts inferred from a balance assignment are
-- also counted as explicit, since they are the same as what the user wrote.
-- Inferred postings are recognised by their preserved original posting having a missing amount.
isExplicitAmount :: Posting -> Bool
isExplicitAmount :: Posting -> Bool
isExplicitAmount Posting
p =
  let orig :: Posting
orig = Posting -> Posting
originalPosting Posting
p
  in Bool -> Bool
not (MixedAmount -> Bool
isMissingMixedAmount (Posting -> MixedAmount
pamount Posting
orig)) Bool -> Bool -> Bool
|| Maybe BalanceAssertion -> Bool
forall a. Maybe a -> Bool
isJust (Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
orig)

hasBalanceAssignment :: Posting -> Bool
hasBalanceAssignment :: Posting -> Bool
hasBalanceAssignment Posting
p = Bool -> Bool
not (Posting -> Bool
hasAmount Posting
p) Bool -> Bool -> Bool
&& Maybe BalanceAssertion -> Bool
forall a. Maybe a -> Bool
isJust (Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
p)

-- | Sorted unique account names referenced by these postings.
accountNamesFromPostings :: [Posting] -> [AccountName]
accountNamesFromPostings :: [Posting] -> [Text]
accountNamesFromPostings = Set Text -> [Text]
forall a. Set a -> [a]
S.toList (Set Text -> [Text])
-> ([Posting] -> Set Text) -> [Posting] -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList ([Text] -> Set Text)
-> ([Posting] -> [Text]) -> [Posting] -> Set Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> Text) -> [Posting] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Text
paccount

-- | Sum all amounts from a list of postings.
sumPostings :: [Posting] -> MixedAmount
sumPostings :: [Posting] -> MixedAmount
sumPostings = (MixedAmount -> Posting -> MixedAmount)
-> MixedAmount -> [Posting] -> MixedAmount
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\MixedAmount
amt Posting
p -> MixedAmount -> MixedAmount -> MixedAmount
maPlus MixedAmount
amt (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p) MixedAmount
nullmixedamt

-- | Negate the posting's main amount and balance assertion amount if any.
postingNegate :: Posting -> Posting
postingNegate :: Posting -> Posting
postingNegate p :: Posting
p@Posting{pamount :: Posting -> MixedAmount
pamount=MixedAmount
a, pbalanceassertion :: Posting -> Maybe BalanceAssertion
pbalanceassertion=Maybe BalanceAssertion
mb} =
  Posting
p{pamount=negate a, pbalanceassertion=fmap balanceAssertionNegate mb}
  where
    balanceAssertionNegate :: BalanceAssertion -> BalanceAssertion
balanceAssertionNegate b :: BalanceAssertion
b@BalanceAssertion{baamount :: BalanceAssertion -> Amount
baamount=Amount
ba} = BalanceAssertion
b{baamount=negate ba}

-- | Negate the posting's main amount but not the balance assertion amount.
postingNegateMainAmount :: Posting -> Posting
postingNegateMainAmount :: Posting -> Posting
postingNegateMainAmount p :: Posting
p@Posting{pamount :: Posting -> MixedAmount
pamount=MixedAmount
a} = Posting
p{pamount=negate a}

-- | Strip all prices from a Posting.
postingStripCosts :: Posting -> Posting
postingStripCosts :: Posting -> Posting
postingStripCosts = (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount MixedAmount -> MixedAmount
mixedAmountStripCosts

-- | Get a posting's (primary) date - it's own primary date if specified,
-- otherwise the parent transaction's primary date, or the null date if
-- there is no parent transaction.
postingDate :: Posting -> Day
postingDate :: Posting -> Day
postingDate Posting
p = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe Day
nulldate (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ [Maybe Day] -> Maybe Day
forall (t :: * -> *) (f :: * -> *) a.
(Foldable t, Alternative f) =>
t (f a) -> f a
asum [Maybe Day]
dates
    where dates :: [Maybe Day]
dates = [ Posting -> Maybe Day
pdate Posting
p, Transaction -> Day
tdate (Transaction -> Day) -> Maybe Transaction -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Posting -> Maybe Transaction
ptransaction Posting
p ]

-- | Get a posting's secondary (secondary) date, which is the first of:
-- posting's secondary date, transaction's secondary date, posting's
-- primary date, transaction's primary date, or the null date if there is
-- no parent transaction.
postingDate2 :: Posting -> Day
postingDate2 :: Posting -> Day
postingDate2 Posting
p = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe Day
nulldate (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ [Maybe Day] -> Maybe Day
forall (t :: * -> *) (f :: * -> *) a.
(Foldable t, Alternative f) =>
t (f a) -> f a
asum [Maybe Day]
dates
  where dates :: [Maybe Day]
dates = [ Posting -> Maybe Day
pdate2 Posting
p
                , Transaction -> Maybe Day
tdate2 (Transaction -> Maybe Day) -> Maybe Transaction -> Maybe Day
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Posting -> Maybe Transaction
ptransaction Posting
p
                , Posting -> Maybe Day
pdate Posting
p
                , Transaction -> Day
tdate (Transaction -> Day) -> Maybe Transaction -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Posting -> Maybe Transaction
ptransaction Posting
p
                ]

-- | Get a posting's primary or secondary date, as specified.
postingDateOrDate2 :: WhichDate -> Posting -> Day
postingDateOrDate2 :: WhichDate -> Posting -> Day
postingDateOrDate2 WhichDate
PrimaryDate   = Posting -> Day
postingDate
postingDateOrDate2 WhichDate
SecondaryDate = Posting -> Day
postingDate2

-- | Get a posting's status. This is cleared or pending if those are
-- explicitly set on the posting, otherwise the status of its parent
-- transaction, or unmarked if there is no parent transaction. (Note
-- the ambiguity, unmarked can mean "posting and transaction are both
-- unmarked" or "posting is unmarked and don't know about the transaction".
postingStatus :: Posting -> Status
postingStatus :: Posting -> Status
postingStatus Posting{pstatus :: Posting -> Status
pstatus=Status
s, ptransaction :: Posting -> Maybe Transaction
ptransaction=Maybe Transaction
mt} = case Status
s of
    Status
Unmarked -> Status -> (Transaction -> Status) -> Maybe Transaction -> Status
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Status
Unmarked Transaction -> Status
tstatus Maybe Transaction
mt
    Status
_ -> Status
s

-- | Get the commodity symbols used in a posting's amounts (not including costs).
postingCommodities :: Posting -> [CommoditySymbol]
postingCommodities :: Posting -> [Text]
postingCommodities = (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Text
acommodity ([Amount] -> [Text]) -> (Posting -> [Amount]) -> Posting -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Bool
isMissingAmount) ([Amount] -> [Amount])
-> (Posting -> [Amount]) -> Posting -> [Amount]
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
  where isMissingAmount :: Amount -> Bool
isMissingAmount Amount
a = Amount -> Text
acommodity Amount
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"AUTO"

-- | Tags for this posting including any inherited from its parent transaction.
postingAllTags :: Posting -> [Tag]
postingAllTags :: Posting -> [Tag]
postingAllTags Posting
p = Posting -> [Tag]
ptags Posting
p [Tag] -> [Tag] -> [Tag]
forall a. [a] -> [a] -> [a]
++ [Tag] -> (Transaction -> [Tag]) -> Maybe Transaction -> [Tag]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Transaction -> [Tag]
ttags (Posting -> Maybe Transaction
ptransaction Posting
p)

-- | Tags for this transaction including any from its postings (which includes any from the postings' accounts).
transactionAllTags :: Transaction -> [Tag]
transactionAllTags :: Transaction -> [Tag]
transactionAllTags Transaction
t = Transaction -> [Tag]
ttags Transaction
t [Tag] -> [Tag] -> [Tag]
forall a. [a] -> [a] -> [a]
++ (Posting -> [Tag]) -> [Posting] -> [Tag]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Posting -> [Tag]
ptags (Transaction -> [Posting]
tpostings Transaction
t)

-- Get the other postings from this posting's transaction.
relatedPostings :: Posting -> [Posting]
relatedPostings :: Posting -> [Posting]
relatedPostings p :: Posting
p@Posting{ptransaction :: Posting -> Maybe Transaction
ptransaction=Just Transaction
t} = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Posting -> Posting -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting
p) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings Transaction
t
relatedPostings Posting
_ = []

isEmptyPosting :: Posting -> Bool
isEmptyPosting :: Posting -> Bool
isEmptyPosting = MixedAmount -> Bool
mixedAmountLooksZero (MixedAmount -> Bool)
-> (Posting -> MixedAmount) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount

-- | Apply some account aliases to the posting's account name, as described by accountNameApplyAliases.
-- This can fail due to a bad replacement pattern in a regular expression alias.
postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting
postingApplyAliases :: [AccountAlias] -> Posting -> Either String Posting
postingApplyAliases [AccountAlias]
aliases p :: Posting
p@Posting{Text
paccount :: Posting -> Text
paccount :: Text
paccount} =
  case [AccountAlias] -> Text -> Either String Text
accountNameApplyAliases [AccountAlias]
aliases Text
paccount of
    Right Text
a -> Posting -> Either String Posting
forall a b. b -> Either a b
Right Posting
p{paccount=a}
    Left String
e  -> String -> Either String Posting
forall a b. a -> Either a b
Left String
err
      where
        err :: String
err = String
"problem while applying account aliases:\n" String -> ShowS
forall a. [a] -> [a] -> [a]
++ [AccountAlias] -> String
forall a. Show a => a -> String
pshow [AccountAlias]
aliases
          String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
"\n to account name: "String -> ShowS
forall a. [a] -> [a] -> [a]
++Text -> String
T.unpack Text
paccountString -> ShowS
forall a. [a] -> [a] -> [a]
++String
"\n "String -> ShowS
forall a. [a] -> [a] -> [a]
++String
e

-- | Add tags to a posting, discarding any for which the posting already has a value.
-- Note this does not add tags to the posting's comment.
postingAddTags :: Posting -> [Tag] -> Posting
postingAddTags :: Posting -> [Tag] -> Posting
postingAddTags p :: Posting
p@Posting{[Tag]
ptags :: Posting -> [Tag]
ptags :: [Tag]
ptags} [Tag]
tags = Posting
p{ptags=ptags `union` tags}

-- | Add the given hidden tag to a posting; and with a true argument,
-- also add the equivalent visible tag to the posting's tags and comment fields.
-- If the posting already has these tags (with any value), do nothing.
postingAddHiddenAndMaybeVisibleTag :: Bool -> Bool -> HiddenTag -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag :: Bool -> Bool -> Tag -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
prepend Bool
verbosetags Tag
ht p :: Posting
p@Posting{pcomment :: Posting -> Text
pcomment=Text
c, [Tag]
ptags :: Posting -> [Tag]
ptags :: [Tag]
ptags} =
  (Posting
p Posting -> [Tag] -> Posting
`postingAddTags` ([Tag
ht] [Tag] -> [Tag] -> [Tag]
forall a. Semigroup a => a -> a -> a
<> [Tag
vt |Bool
verbosetags]))
  {pcomment=if verbosetags && not hadtag then addFn c vt else c}
  where
    addFn :: Text -> Tag -> Text
addFn = if Bool
prepend then Text -> Tag -> Text
commentPrependTag else Text -> Tag -> Text
commentAddTag
    vt :: Tag
vt@(Text
vname,Text
_) = Tag -> Tag
toVisibleTag Tag
ht
    hadtag :: Bool
hadtag = (Tag -> Bool) -> [Tag] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== (Text -> Text
T.toLower Text
vname)) (Text -> Bool) -> (Tag -> Text) -> Tag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
T.toLower (Text -> Text) -> (Tag -> Text) -> Tag -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tag -> Text
forall a b. (a, b) -> a
fst) [Tag]
ptags  -- XXX should regex-quote vname

-- | Remove the given hidden tag from a posting, and the equivalent visible tag
-- if 'postingAddHiddenAndMaybeVisibleTag' added one: from the posting's tags,
-- and from its comment, where it appears as @NAME: VALUE@, comma-separated from
-- any other content.
postingRemoveHiddenAndVisibleTag :: HiddenTag -> Posting -> Posting
postingRemoveHiddenAndVisibleTag :: Tag -> Posting -> Posting
postingRemoveHiddenAndVisibleTag (Text
hname,Text
_) p :: Posting
p@Posting{Text
pcomment :: Posting -> Text
pcomment :: Text
pcomment, [Tag]
ptags :: Posting -> [Tag]
ptags :: [Tag]
ptags} =
  Posting
p{ptags = filter ((`notElem` [hname, vname]) . fst) ptags, pcomment = maybe pcomment removeFromComment $ lookup vname ptags}
  where
    vname :: Text
vname = Text -> Text
toVisibleTagName Text
hname
    removeFromComment :: Text -> Text
removeFromComment Text
v
      | Text
c' Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
pcomment = Text
c'
      | Bool
otherwise      = Text -> [Text] -> Text
T.intercalate Text
"\n" ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
dropCommaPrefix (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
t Text
"") ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Text -> [Text]
T.lines Text
pcomment
      where
        t :: Text
t  = Text
vname Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
v
        c' :: Text
c' = HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace (Text
", " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
t) Text
"" Text
pcomment
        dropCommaPrefix :: Text -> Text
dropCommaPrefix Text
l = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
l (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
", " Text
l

-- | Apply a specified valuation to this posting's amount, using the
-- provided price oracle, commodity styles, and reference dates.
-- See amountApplyValuation.
postingApplyValuation :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting
postingApplyValuation :: PriceOracle
-> Map Text AmountStyle
-> Day
-> Day
-> ValuationType
-> Posting
-> Posting
postingApplyValuation PriceOracle
priceoracle Map Text AmountStyle
styles Day
periodlast Day
today ValuationType
v Posting
p =
    (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount (PriceOracle
-> Map Text AmountStyle
-> Day
-> Day
-> Day
-> ValuationType
-> MixedAmount
-> MixedAmount
mixedAmountApplyValuation PriceOracle
priceoracle Map Text AmountStyle
styles Day
periodlast Day
today (Posting -> Day
postingDate Posting
p) ValuationType
v) Posting
p

-- | Maybe convert this 'Posting's amount to cost: to cost basis where known,
-- else transacted cost (ToCost); or to transacted cost (ToTransactedCost).
postingToCost :: ConversionOp -> Posting -> Maybe Posting
postingToCost :: ConversionOp -> Posting -> Maybe Posting
postingToCost ConversionOp
NoConversionOp   Posting
p = Posting -> Maybe Posting
forall a. a -> Maybe a
Just Posting
p
postingToCost ConversionOp
ToCost           Posting
p = (MixedAmount -> MixedAmount) -> Posting -> Maybe Posting
postingToCostWith MixedAmount -> MixedAmount
mixedAmountCostBasis Posting
p
postingToCost ConversionOp
ToTransactedCost Posting
p = (MixedAmount -> MixedAmount) -> Posting -> Maybe Posting
postingToCostWith MixedAmount -> MixedAmount
mixedAmountCost Posting
p

postingToCostWith :: (MixedAmount -> MixedAmount) -> Posting -> Maybe Posting
postingToCostWith :: (MixedAmount -> MixedAmount) -> Posting -> Maybe Posting
postingToCostWith MixedAmount -> MixedAmount
tocost Posting
p
  -- If this is an equity conversion posting with an associated cost nearby, ignore it
  | Text
conversionPostingTagName Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (Tag -> Text) -> [Tag] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Tag -> Text
forall a b. (a, b) -> a
fst (Posting -> [Tag]
ptags Posting
p) Bool -> Bool -> Bool
&& Bool
nocosts = Maybe Posting
forall a. Maybe a
Nothing
  | Bool
otherwise = Posting -> Maybe Posting
forall a. a -> Maybe a
Just (Posting -> Maybe Posting) -> Posting -> Maybe Posting
forall a b. (a -> b) -> a -> b
$ (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount MixedAmount -> MixedAmount
tocost Posting
p
  where
    nocosts :: Bool
nocosts = (Bool -> Bool
not (Bool -> Bool) -> (MixedAmount -> Bool) -> MixedAmount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (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] -> Bool)
-> (MixedAmount -> [Amount]) -> MixedAmount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> [Amount]
amountsRaw) (MixedAmount -> Bool) -> MixedAmount -> Bool
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p

-- | Given a posting with costs, tag it as a cost posting and add
-- equity conversion postings after it, one pair per cost: one removing
-- the quantity transacted, one adding what it cost. See
-- 'postingsAddInferredEquityPostings'.
postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]
postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]
postingAddInferredEquityPostings Bool
verbosetags Text
equityAcct Posting
p = Bool -> Text -> [Posting] -> [Posting]
postingsAddInferredEquityPostings Bool
verbosetags Text
equityAcct [Posting
p]

-- | Like 'postingAddInferredEquityPostings', for a posting or for the
-- consecutive per-lot fragments of one posting (cf 'transactionInferEquityPostings'):
-- postings with costs are tagged as cost postings, and one pair of equity
-- conversion postings is added after them for each (commodity, cost commodity)
-- pair, with the fragments' quantities and costs summed, so that collapsing
-- lot detail can still merge the fragments.
--
-- The cost used is the cost basis where known (a lot disposal, after lot
-- processing), otherwise the transacted cost. So a disposal's conversion
-- postings record the disposed units at what they cost, keeping the entry
-- balanced at cost basis, and the difference from the proceeds stays in the
-- realised gain posting.
--
-- Postings already tagged as cost postings (having conversion postings) are left alone.
postingsAddInferredEquityPostings :: Bool -> Text -> [Posting] -> [Posting]
postingsAddInferredEquityPostings :: Bool -> Text -> [Posting] -> [Posting]
postingsAddInferredEquityPostings Bool
_ Text
_ [] = []
postingsAddInferredEquityPostings Bool
verbosetags Text
equityAcct ps :: [Posting]
ps@(Posting
p:[Posting]
_)
  | [Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Amount]
costfulamounts = [Posting]
ps
  | Bool
otherwise = (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Posting
tagIfCostful [Posting]
ps [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
++ (Tag -> [Posting]) -> [Tag] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Tag -> [Posting]
makeConversionPostings ([Tag] -> [Tag]
forall a. Eq a => [a] -> [a]
nub ([Tag] -> [Tag]) -> [Tag] -> [Tag]
forall a b. (a -> b) -> a -> b
$ (Amount -> Tag) -> [Amount] -> [Tag]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Tag
commodityPair [Amount]
costfulamounts)
  where
    costfulamounts :: [Amount]
costfulamounts = (Posting -> [Amount]) -> [Posting] -> [Amount]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Posting -> [Amount]
postingCostfulAmounts [Posting]
ps
    postingCostfulAmounts :: Posting -> [Amount]
postingCostfulAmounts Posting
q
      | Text
costPostingTagName Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (Tag -> Text) -> [Tag] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Tag -> Text
forall a b. (a, b) -> a
fst (Posting -> [Tag]
ptags Posting
q) = []
      | Bool
otherwise = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter (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] -> [Amount])
-> (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
q
    tagIfCostful :: Posting -> Posting
tagIfCostful Posting
q
      | [Amount] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Posting -> [Amount]
postingCostfulAmounts Posting
q) = Posting
q
      | Bool
otherwise = Bool -> Bool -> Tag -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (Text
costPostingTagName,Text
"") Posting
q
    commodityPair :: Amount -> Tag
commodityPair Amount
a = (Amount -> Text
commodity Amount
a, Amount -> Text
commodity (Amount -> Amount
amountCost Amount
a))
    makeConversionPostings :: Tag -> [Posting]
makeConversionPostings pair :: Tag
pair@(Text
amtCommodity, Text
costCommodity) =
      [ Posting
convp{ paccount = accountPrefix <> amtCommodity
             , pamount = maNegate $ maSum [mixedAmount (amountStripCost a){acostbasis = Nothing} | a <- as]
             }
      , Posting
convp{ paccount = accountPrefix <> costCommodity
             , pamount = maSum [mixedAmount (amountCostBasis a) | a <- as]
             }
      ]
      where
        as :: [Amount]
as = (Amount -> Bool) -> [Amount] -> [Amount]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Tag -> Tag -> Bool
forall a. Eq a => a -> a -> Bool
== Tag
pair) (Tag -> Bool) -> (Amount -> Tag) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Tag
commodityPair) [Amount]
costfulamounts
        accountPrefix :: Text
accountPrefix = [Text] -> Text
forall a. Monoid a => [a] -> a
mconcat [ Text
equityAcct, Text
":", Text -> [Text] -> Text
T.intercalate Text
"-" ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text] -> [Text]
forall a. Ord a => [a] -> [a]
sort [Text
amtCommodity, Text
costCommodity], Text
":"]
    convp :: Posting
convp = Posting
nullposting{pdate=pdate p, pdate2=pdate2 p, pstatus=pstatus p, ptransaction=ptransaction p}
      Posting -> (Posting -> Posting) -> Posting
forall a b. a -> (a -> b) -> b
& Bool -> Bool -> Tag -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (Text
conversionPostingTagName,Text
"")
      Posting -> (Posting -> Posting) -> Posting
forall a b. a -> (a -> b) -> b
& Bool -> Bool -> Tag -> Posting -> Posting
postingAddHiddenAndMaybeVisibleTag Bool
False Bool
verbosetags (Text
generatedPostingTagName, Text
"")
    -- Take the commodity of an amount and collapse consecutive spaces to a single space
    commodity :: Amount -> Text
commodity = [Text] -> Text
T.unwords ([Text] -> Text) -> (Amount -> [Text]) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) ([Text] -> [Text]) -> (Amount -> [Text]) -> Amount -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
T.words (Text -> [Text]) -> (Amount -> Text) -> Amount -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Text
acommodity

-- | Make a market price equivalent to this posting's amount's unit
-- price, if any.
postingPriceDirectivesFromCost :: Posting -> [PriceDirective]
postingPriceDirectivesFromCost :: Posting -> [PriceDirective]
postingPriceDirectivesFromCost p :: Posting
p@Posting{MixedAmount
pamount :: Posting -> MixedAmount
pamount :: MixedAmount
pamount} =
    (Amount -> Maybe PriceDirective) -> [Amount] -> [PriceDirective]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Day -> Amount -> Maybe PriceDirective
amountPriceDirectiveFromCost (Day -> Amount -> Maybe PriceDirective)
-> Day -> Amount -> Maybe PriceDirective
forall a b. (a -> b) -> a -> b
$ Posting -> Day
postingDate Posting
p) ([Amount] -> [PriceDirective]) -> [Amount] -> [PriceDirective]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw MixedAmount
pamount

-- | Apply a transform function to this posting's main amount (but not its balance assertion amount).
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount MixedAmount -> MixedAmount
f p :: Posting
p@Posting{pamount :: Posting -> MixedAmount
pamount=MixedAmount
a} = Posting
p{pamount=f a}

-- | Join two parts of a comment, eg a tag and another tag, or a tag
-- and a non-tag, on a single line. Interpolates a comma and space
-- unless one of the parts is empty.
commentJoin :: Text -> Text -> Text
commentJoin :: Text -> Text -> Text
commentJoin Text
c1 Text
c2
  | Text -> Bool
T.null Text
c1 = Text
c2
  | Text -> Bool
T.null Text
c2 = Text
c1
  | Bool
otherwise = Text
c1 Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
c2

-- | Add a tag to a comment, comma-separated from any prior content.
-- A space is inserted following the colon, before the value.
commentAddTag :: Text -> Tag -> Text
commentAddTag :: Text -> Tag -> Text
commentAddTag Text
c (Text
t,Text
v)
  | Text -> Bool
T.null Text
c' = Text
tag
  | Bool
otherwise = Text
c' Text -> Text -> Text
`commentJoin` Text
tag
  where
    c' :: Text
c'  = Text -> Text
T.stripEnd Text
c
    tag :: Text
tag = Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
v

-- | Add a tag at the start of a comment, comma-separated from any prior content.
-- A space is inserted following the colon, before the value.
commentPrependTag :: Text -> Tag -> Text
commentPrependTag :: Text -> Tag -> Text
commentPrependTag Text
c (Text
t,Text
v)
  | Text -> Bool
T.null Text
c' = Text
tag
  | Bool
otherwise = Text
tag Text -> Text -> Text
`commentJoin` Text
c'
  where
    c' :: Text
c'  = Text -> Text
T.stripEnd Text
c
    tag :: Text
tag = Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
v

-- | Like commentAddTag, but omits the space after the colon.
commentAddTagUnspaced :: Text -> Tag -> Text
commentAddTagUnspaced :: Text -> Tag -> Text
commentAddTagUnspaced Text
c (Text
t,Text
v)
  | Text -> Bool
T.null Text
c' = Text
tag
  | Bool
otherwise = Text
c' Text -> Text -> Text
`commentJoin` Text
tag
  where
    c' :: Text
c'  = Text -> Text
T.stripEnd Text
c
    tag :: Text
tag = Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
v

-- | Add a tag on its own line to a comment, preserving any prior content.
-- A space is inserted following the colon, before the value.
commentAddTagNextLine :: Text -> Tag -> Text
commentAddTagNextLine :: Text -> Tag -> Text
commentAddTagNextLine Text
cmt (Text
t,Text
v) =
  Text
cmt Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Text
"\n" Text -> Text -> Bool
`T.isSuffixOf` Text
cmt then Text
"" else Text
"\n") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
v


-- tests

tests_Posting :: TestTree
tests_Posting = String -> [TestTree] -> TestTree
testGroup String
"Posting" [

  String -> Assertion -> TestTree
testCase String
"accountNamePostingType" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    Text -> PostingRealness
accountNamePostingType Text
"a" PostingRealness -> PostingRealness -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= PostingRealness
RealPosting
    Text -> PostingRealness
accountNamePostingType Text
"(a)" PostingRealness -> PostingRealness -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= PostingRealness
VirtualPosting
    Text -> PostingRealness
accountNamePostingType Text
"[a]" PostingRealness -> PostingRealness -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= PostingRealness
BalancedVirtualPosting

 ,String -> Assertion -> TestTree
testCase String
"accountNameWithoutPostingType" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    Text -> Text
accountNameWithoutPostingType Text
"(a)" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"a"

 ,String -> Assertion -> TestTree
testCase String
"accountNameWithPostingType" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    PostingRealness -> Text -> Text
accountNameWithPostingType PostingRealness
VirtualPosting Text
"[a]" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"(a)"

 ,String -> Assertion -> TestTree
testCase String
"joinAccountNames" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    Text
"a" Text -> Text -> Text
`joinAccountNames` Text
"b:c" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"a:b:c"
    Text
"a" Text -> Text -> Text
`joinAccountNames` Text
"(b:c)" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"(a:b:c)"
    Text
"[a]" Text -> Text -> Text
`joinAccountNames` Text
"(b:c)" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"[a:b:c]"
    Text
"" Text -> Text -> Text
`joinAccountNames` Text
"a" Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"a"

 ,String -> Assertion -> TestTree
testCase String
"concatAccountNames" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    [Text] -> Text
concatAccountNames [] Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
""
    [Text] -> Text
concatAccountNames [Text
"a",Text
"(b)",Text
"[c:d]"] Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"(a:b:c:d)"

 ,String -> Assertion -> TestTree
testCase String
"commentAddTag" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    Text -> Tag -> Text
commentAddTag Text
"" (Text
"a",Text
"") Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"a: "
    Text -> Tag -> Text
commentAddTag Text
"[1/2]" (Text
"a",Text
"") Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"[1/2], a: "

 ,String -> Assertion -> TestTree
testCase String
"commentAddTagNextLine" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    Text -> Tag -> Text
commentAddTagNextLine Text
"" (Text
"a",Text
"") Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"\na: "
    Text -> Tag -> Text
commentAddTagNextLine Text
"[1/2]" (Text
"a",Text
"") Text -> Text -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Text
"[1/2]\na: "

 ]