{-|

A ledger-compatible @print@ command.

-}

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

module Hledger.Cli.Commands.Print (
  printmode
 ,print'
 ,journalApplyMatchOpt
 ,entriesReportAsTextHelper
 ,roundFlag
 ,roundFromRawOpts
 ,amountStylesSetRoundingFromRawOpts
 ,layoutFlag
 ,layoutFromRawOpts
 ,transactionWithMostlyOriginalPostings
)
where


import Data.Function ((&))
import Data.List (intersperse, intercalate)
import Data.Text (Text)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Lens.Micro ((^.), _Just, has)
import Safe (lastMay, readMay)
import System.Console.CmdArgs.Explicit

import Hledger
import Hledger.Write.Beancount (showTransactionBeancount, beancountTransactions, beancountRenameAccounts, beancountDirectives, beancountItemRenderer)
import Hledger.Write.Ledger (showTransactionLedger, ledgerItemRenderer)
import Hledger.Write.Journal (ItemRenderer(..), journalItemRenderer, journalItemsAsText)
import Hledger.Write.Csv (CSV, printCSV, printTSV)
import Hledger.Write.Ods (printFods)
import Hledger.Write.Html (styledTableHtml, htmlAsLazyText, toHtml)
import Hledger.Write.Spreadsheet qualified as Spr
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils
import Hledger.Cli.Anchor (setAccountAnchor)
import System.IO qualified as IO
import Data.Maybe (isJust, isNothing)

printmode :: Mode RawOpts
printmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Print.txt")
  ([
   [String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"all",String
"a"] (String -> RawOpts -> RawOpts
setboolopt String
"explicit" (RawOpts -> RawOpts) -> (RawOpts -> RawOpts) -> RawOpts -> RawOpts
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> RawOpts -> RawOpts
setboolopt String
"lots" (RawOpts -> RawOpts) -> (RawOpts -> RawOpts) -> RawOpts -> RawOpts
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> RawOpts -> RawOpts
setboolopt String
"verbose-tags")
    String
"show all details (--explicit --lots --verbose-tags)"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"explicit",String
"x"] (String -> RawOpts -> RawOpts
setboolopt String
"explicit") String
"show all inferred info explicitly"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"verbose-tags"] (String -> RawOpts -> RawOpts
setboolopt String
"verbose-tags") String
"add tags indicating generated/modified data"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"invert"] (String -> RawOpts -> RawOpts
setboolopt String
"invert") String
"display all amounts with reversed sign"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"locations"] (String -> RawOpts -> RawOpts
setboolopt String
"locations") String
"add tags showing file paths and line numbers"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"export"] (String -> RawOpts -> RawOpts
setboolopt String
"export") String
"reproduce the whole journal, with directives and comments preserved and included files inlined"
  ,let arg :: String
arg = String
"DESC" in
   [String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"match",String
"m"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"match" String
s RawOpts
opts) String
arg
    (String
"fuzzy search for one recent transaction with description closest to "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
arg)
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"new"] (String -> RawOpts -> RawOpts
setboolopt String
"new") String
"show only newer-dated transactions added in each file since last run"
  ,Flag RawOpts
roundFlag
  ,Flag RawOpts
layoutFlag
  ,[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"base-url"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"base-url" String
s RawOpts
opts) String
"URLPREFIX"
    String
"in html output, generate links to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"
  ,[String] -> Flag RawOpts
outputFormatFlag [String
"journal",String
"ledger",String
"beancount",String
"csv",String
"tsv",String
"html",String
"fods",String
"json",String
"sql"]
  ,Flag RawOpts
outputFileFlag
  ,Flag RawOpts
outputViewFlag
  ])
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"[QUERY]")

roundFlag :: Flag RawOpts
roundFlag = [String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"round"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"round" String
s RawOpts
opts) String
"TYPE" (String -> Flag RawOpts) -> String -> Flag RawOpts
forall a b. (a -> b) -> a -> b
$
  String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"\n"
  [String
"how much rounding or padding should be done when displaying amounts ?"
  ,String
"none - show original decimal digits,"
  ,String
"       as in journal (default)"
  ,String
"soft - just add or remove decimal zeros"
  ,String
"       to match precision"
  ,String
"hard - round posting amounts to precision"
  ,String
"       (can unbalance transactions)"
  ,String
"all  - also round cost amounts to precision"
  ,String
"       (can unbalance transactions)"
  ]

-- | Get the --round option's value, if any. Can fail with a parse error.
roundFromRawOpts :: RawOpts -> Maybe Rounding
roundFromRawOpts :: RawOpts -> Maybe Rounding
roundFromRawOpts = [Rounding] -> Maybe Rounding
forall a. [a] -> Maybe a
lastMay ([Rounding] -> Maybe Rounding)
-> (RawOpts -> [Rounding]) -> RawOpts -> Maybe Rounding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String, String) -> Maybe Rounding) -> RawOpts -> [Rounding]
forall a. ((String, String) -> Maybe a) -> RawOpts -> [a]
collectopts (String, String) -> Maybe Rounding
forall {a}. (Eq a, IsString a) => (a, String) -> Maybe Rounding
roundfromrawopt
  where
    roundfromrawopt :: (a, String) -> Maybe Rounding
roundfromrawopt (a
n,String
v)
      | a
na -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
"round", String
vString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"none" = Rounding -> Maybe Rounding
forall a. a -> Maybe a
Just Rounding
NoRounding
      | a
na -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
"round", String
vString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"soft" = Rounding -> Maybe Rounding
forall a. a -> Maybe a
Just Rounding
SoftRounding
      | a
na -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
"round", String
vString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"hard" = Rounding -> Maybe Rounding
forall a. a -> Maybe a
Just Rounding
HardRounding
      | a
na -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
"round", String
vString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"all"  = Rounding -> Maybe Rounding
forall a. a -> Maybe a
Just Rounding
AllRounding
      | a
na -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
"round"            = String -> Maybe Rounding
forall a. String -> a
error' (String -> Maybe Rounding) -> String -> Maybe Rounding
forall a b. (a -> b) -> a -> b
$ String
"--round's value should be none, soft, hard or all; got: "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
v
      | Bool
otherwise             = Maybe Rounding
forall a. Maybe a
Nothing

-- | Set these amount styles' rounding strategy when they are being applied to amounts,
-- according to the value of the --round option, if any.
amountStylesSetRoundingFromRawOpts :: RawOpts -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle
amountStylesSetRoundingFromRawOpts :: RawOpts -> Map Text AmountStyle -> Map Text AmountStyle
amountStylesSetRoundingFromRawOpts RawOpts
rawopts Map Text AmountStyle
styles =
  case RawOpts -> Maybe Rounding
roundFromRawOpts RawOpts
rawopts of
    Just Rounding
r  -> Rounding -> Map Text AmountStyle -> Map Text AmountStyle
amountStylesSetRounding Rounding
r Map Text AmountStyle
styles
    Maybe Rounding
Nothing -> Map Text AmountStyle
styles

-- | The --layout flag for the print command, selecting how posting lines are aligned.
layoutFlag :: Flag RawOpts
layoutFlag :: Flag RawOpts
layoutFlag = [String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq [String
"layout"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"layout" String
s RawOpts
opts) String
"hledger1|COL" (String -> Flag RawOpts) -> String -> Flag RawOpts
forall a b. (a -> b) -> a -> b
$
  String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"\n"
  [String
"how should posting amounts be aligned ?"
  ,String
"hledger1 - right-align amounts, as in hledger 1"
  ,String
"COL      - align decimal marks at column COL (default: 53)"
  ]

-- | Parse the --layout option. Defaults to 'defaultPostingLayout' if absent.
-- Errors with a clear message if the value is neither \"hledger1\" nor a positive integer.
layoutFromRawOpts :: RawOpts -> PostingLayout
layoutFromRawOpts :: RawOpts -> PostingLayout
layoutFromRawOpts RawOpts
rawopts = case String -> RawOpts -> Maybe String
maybestringopt String
"layout" RawOpts
rawopts of
  Maybe String
Nothing         -> PostingLayout
defaultPostingLayout
  Just String
"hledger1" -> PostingLayout
LayoutHledger1
  Just String
s -> case String -> Maybe Int
forall a. Read a => String -> Maybe a
readMay String
s of
    Just Int
n | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0 -> Int -> PostingLayout
LayoutDecimal Int
n
    Maybe Int
_ -> String -> PostingLayout
forall a. String -> a
error' (String -> PostingLayout) -> String -> PostingLayout
forall a b. (a -> b) -> a -> b
$ String
"--layout's value should be 'hledger1' or a positive integer column number; got: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s

-- | Print journal transactions in standard format.
print' :: CliOpts -> Journal -> IO ()
print' :: CliOpts -> Journal -> IO ()
print' opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
  -- The print command should show all amounts with their original decimal places,
  -- but as part of journal reading the posting amounts have already been normalised
  -- according to commodity display styles, and currently it's not easy to avoid
  -- that. For now we try to reverse it by increasing all amounts' decimal places
  -- sufficiently to show the amount exactly. The displayed amounts may have minor
  -- differences from the originals, such as trailing zeroes added.
  -- An amount with a repeating decimal (from division, rounded at the 255th decimal place)
  -- is shown with 8 decimal places, not all 255.
  -- But, we skip this for inferred postings.
  -- This avoids eg showing too many decimals by default for inferred gain amounts.
  let
    -- lbl = lbl_ "print'"
    hasPtype :: Text -> Posting -> Bool
hasPtype Text
t Posting
p = (Text
"_ptype", Text
t) (Text, Text) -> [(Text, Text)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Posting -> [(Text, Text)]
ptags Posting
p
    isGeneratedGainPosting :: Posting -> Bool
isGeneratedGainPosting Posting
p = Text -> Posting -> Bool
hasPtype Text
"gain" Posting
p
    setFullPrecisionExceptGain :: Posting -> Posting
setFullPrecisionExceptGain Posting
p
      | Posting -> Bool
isGeneratedGainPosting Posting
p = Posting
p
      | Bool
otherwise = (MixedAmount -> MixedAmount) -> Posting -> Posting
postingTransformAmount MixedAmount -> MixedAmount
mixedAmountSetFullPrecisionCapped Posting
p
    j' :: Journal
j' = Journal
j
      -- & dbg9With (lbl "amounts before setting full precision".showJournalPostingAmountsDebug)
      Journal -> (Journal -> Journal) -> Journal
forall a b. a -> (a -> b) -> b
& (Posting -> Posting) -> Journal -> Journal
journalMapPostings Posting -> Posting
setFullPrecisionExceptGain
      -- & dbg9With (lbl "amounts after  setting full precision: ".showJournalPostingAmountsDebug)
      Journal -> (Journal -> Journal) -> Journal
forall a b. a -> (a -> b) -> b
& if String -> RawOpts -> Bool
boolopt String
"locations" RawOpts
rawopts then (Transaction -> Transaction) -> Journal -> Journal
journalMapTransactions Transaction -> Transaction
addLocationTag else Journal -> Journal
forall a. a -> a
id

  CliOpts -> Journal -> IO ()
printEntries CliOpts
opts (Journal -> IO ()) -> Journal -> IO ()
forall a b. (a -> b) -> a -> b
$ CliOpts -> Journal -> Journal
journalApplyMatchOpt CliOpts
opts Journal
j'

-- | With --match DESC, keep only the one recent transaction whose description
-- is most similar to DESC, erroring if there is none. Otherwise, return the journal unchanged.
-- XXX should match similarly to register --match
journalApplyMatchOpt :: CliOpts -> Journal -> Journal
journalApplyMatchOpt :: CliOpts -> Journal -> Journal
journalApplyMatchOpt CliOpts
opts Journal
j =
  case String -> RawOpts -> Maybe String
maybestringopt String
"match" (RawOpts -> Maybe String) -> RawOpts -> Maybe String
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts of
    Maybe String
Nothing   -> Journal
j
    Just String
desc ->
      case CliOpts -> Journal -> Text -> Maybe Transaction
journalSimilarTransaction CliOpts
opts Journal
j (String -> Text -> Text
forall a. Show a => String -> a -> a
dbg1 String
"finding best match for description" (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack String
desc) of
        Just Transaction
t  -> Journal
j{jtxns=[t]}
        Maybe Transaction
Nothing -> String -> Journal
forall a. String -> a
error' (String -> Journal) -> String -> Journal
forall a b. (a -> b) -> a -> b
$ String
"no transactions found with descriptions like " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String -> String
forall a. Show a => a -> String
show String
desc

printEntries :: CliOpts -> Journal -> IO ()
printEntries :: CliOpts -> Journal -> IO ()
printEntries opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts, reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec} Journal
j =
  CliOpts -> Text -> IO ()
writeOutputLazyText CliOpts
opts (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$
    if String -> RawOpts -> Bool
boolopt String
"export" RawOpts
rawopts
    then [Transaction] -> Text
renderExport ([Transaction] -> Text) -> [Transaction] -> Text
forall a b. (a -> b) -> a -> b
$ ReportSpec -> Journal -> [Transaction]
entriesReportUnsorted ReportSpec
rspec Journal
j
    else [Transaction] -> Text
render ([Transaction] -> Text) -> [Transaction] -> Text
forall a b. (a -> b) -> a -> b
$ ReportSpec -> Journal -> [Transaction]
entriesReport ReportSpec
rspec Journal
j
  where
    -- print does user-specified rounding or (by default) no rounding, in all output formats
    styles :: Map Text AmountStyle
styles = RawOpts -> Map Text AmountStyle -> Map Text AmountStyle
amountStylesSetRoundingFromRawOpts RawOpts
rawopts (Map Text AmountStyle -> Map Text AmountStyle)
-> Map Text AmountStyle -> Map Text AmountStyle
forall a b. (a -> b) -> a -> b
$ Journal -> Map Text AmountStyle
journalCommodityStyles Journal
j
    styledPrices :: [PriceDirective]
styledPrices = (PriceDirective -> PriceDirective)
-> [PriceDirective] -> [PriceDirective]
forall a b. (a -> b) -> [a] -> [b]
map (\PriceDirective
pd -> PriceDirective
pd{pdamount = styleAmounts styles $ pdamount pd}) ([PriceDirective] -> [PriceDirective])
-> [PriceDirective] -> [PriceDirective]
forall a b. (a -> b) -> a -> b
$ Journal -> [PriceDirective]
jpricedirectives Journal
j

    -- txt is an unlisted alias for journal, the default (outputFormatFromOpts calls it txt)
    fmt :: String
fmt = case CliOpts -> String
outputFormatFromOpts CliOpts
opts of
      String
"txt" -> String
"journal"
      String
f     -> String
f
    baseUrl :: Maybe Text
baseUrl = ReportOpts -> Maybe Text
balance_base_url_ (ReportOpts -> Maybe Text) -> ReportOpts -> Maybe Text
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec
    query :: [Text]
query = ReportOpts -> [Text]
querystring_ (ReportOpts -> [Text]) -> ReportOpts -> [Text]
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec
    postinglayout :: PostingLayout
postinglayout = RawOpts -> PostingLayout
layoutFromRawOpts RawOpts
rawopts

    -- With --export, reproduce the journal file(s): directives and comments verbatim,
    -- the (filtered, processed) transactions in their original positions, and blank lines normalised.
    -- Transactions and postings generated by --forecast, --auto etc. are included when those flags
    -- are used, and then the periodic transaction rules / auto posting rules which generated them are dropped.
    renderExport :: [Transaction] -> Text
renderExport
      | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"journal" = ItemRenderer -> [Transaction] -> Text
exportWith ((Transaction -> Text) -> ItemRenderer
journalItemRenderer ((Transaction -> Text) -> ItemRenderer)
-> (Transaction -> Text) -> ItemRenderer
forall a b. (a -> b) -> a -> b
$ PostingLayout -> Transaction -> Text
showTransactionWithLayout PostingLayout
postinglayout)
      | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"ledger"  = ItemRenderer -> [Transaction] -> Text
exportWith ItemRenderer
ledgerItemRenderer
      | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"beancount" = \[Transaction]
ts ->
          let (Journal
j', [Transaction]
ts') = Journal -> [Transaction] -> (Journal, [Transaction])
beancountRenameAccounts Journal
j{jpricedirectives=styledPrices} ([Transaction] -> (Journal, [Transaction]))
-> [Transaction] -> (Journal, [Transaction])
forall a b. (a -> b) -> a -> b
$ [Transaction] -> [Transaction]
beancountTransactions ([Transaction] -> [Transaction]) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles ([Transaction] -> [Transaction]) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Transaction
fillBalanceAssignments [Transaction]
ts
          -- (beancountItemRenderer drops all directives, including rules; anything generated is exported)
          in Journal -> [Transaction] -> Text
beancountDirectives Journal
j' [Transaction]
ts' Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ItemRenderer -> [JournalItem] -> [Transaction] -> Text
journalItemsAsText ItemRenderer
beancountItemRenderer (Journal -> [JournalItem]
jitems Journal
j') [Transaction]
ts'
      | Bool
otherwise     = String -> [Transaction] -> Text
forall a. String -> a
error' String
"print --export supports only the journal, ledger and beancount output formats"  -- PARTIAL:
      where
        exportWith :: ItemRenderer -> [Transaction] -> Text
exportWith ItemRenderer
renderer = ItemRenderer -> [JournalItem] -> [Transaction] -> Text
journalItemsAsText (ItemRenderer -> ItemRenderer
withoutAppliedRules ItemRenderer
renderer) (Journal -> [JournalItem]
jitems Journal
j) ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles ([Transaction] -> [Transaction])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map (Bool -> Transaction -> Transaction
maybeoriginalamountsWith Bool
False)
        withoutAppliedRules :: ItemRenderer -> ItemRenderer
withoutAppliedRules ItemRenderer
renderer = ItemRenderer
renderer{irDirective = \Text
txt -> if Text -> Bool
isAppliedRule Text
txt then Maybe Text
forall a. Maybe a
Nothing else ItemRenderer -> Text -> Maybe Text
irDirective ItemRenderer
renderer Text
txt}
        isAppliedRule :: Text -> Bool
isAppliedRule Text
txt = (Bool
forecasting Bool -> Bool -> Bool
&& Text
"~" Text -> Text -> Bool
`T.isPrefixOf` Text
txt) Bool -> Bool -> Bool
|| (Bool
autoposting Bool -> Bool -> Bool
&& Text
"=" Text -> Text -> Bool
`T.isPrefixOf` Text
txt)
        forecasting :: Bool
forecasting = Maybe DateSpan -> Bool
forall a. Maybe a -> Bool
isJust (Maybe DateSpan -> Bool) -> Maybe DateSpan -> Bool
forall a b. (a -> b) -> a -> b
$ InputOpts -> Maybe DateSpan
forecast_ (InputOpts -> Maybe DateSpan) -> InputOpts -> Maybe DateSpan
forall a b. (a -> b) -> a -> b
$ CliOpts -> InputOpts
inputopts_ CliOpts
opts
        autoposting :: Bool
autoposting = InputOpts -> Bool
auto_ (InputOpts -> Bool) -> InputOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> InputOpts
inputopts_ CliOpts
opts

    render :: [Transaction] -> Text
render | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"journal"   = ReportOpts -> Text -> Text
withTitle (ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec) (Text -> Text) -> ([Transaction] -> Text) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Text) -> [Transaction] -> Text
entriesReportAsTextHelper (PostingLayout -> Transaction -> Text
showTransactionWithLayout PostingLayout
postinglayout) ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles ([Transaction] -> [Transaction])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Transaction
maybeoriginalamounts
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"ledger"   = ReportOpts -> Text -> Text
withTitle (ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec) (Text -> Text) -> ([Transaction] -> Text) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Text) -> [Transaction] -> Text
entriesReportAsTextHelper Transaction -> Text
showTransactionLedger ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles ([Transaction] -> [Transaction])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Transaction
maybeoriginalamounts
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"beancount" = (Transaction -> Text) -> [Transaction] -> Text
entriesReportAsTextHelper Transaction -> Text
showTransactionBeancount ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Journal, [Transaction]) -> [Transaction]
forall a b. (a, b) -> b
snd ((Journal, [Transaction]) -> [Transaction])
-> ([Transaction] -> (Journal, [Transaction]))
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [Transaction] -> (Journal, [Transaction])
beancountRenameAccounts Journal
j ([Transaction] -> (Journal, [Transaction]))
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> (Journal, [Transaction])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Transaction] -> [Transaction]
beancountTransactions ([Transaction] -> [Transaction])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles ([Transaction] -> [Transaction])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Transaction
fillBalanceAssignments
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"csv"       = CSV -> Text
printCSV (CSV -> Text) -> ([Transaction] -> CSV) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Transaction] -> CSV
entriesReportAsCsv ([Transaction] -> CSV)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> CSV
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"tsv"       = CSV -> Text
printTSV (CSV -> Text) -> ([Transaction] -> CSV) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Transaction] -> CSV
entriesReportAsCsv ([Transaction] -> CSV)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> CSV
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"json"      = [Transaction] -> Text
forall a. ToJSON a => a -> Text
toJsonText                    ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"sql"       = [Transaction] -> Text
entriesReportAsSql            ([Transaction] -> Text)
-> ([Transaction] -> [Transaction]) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"html" =
                (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
"\n") (Text -> Text) -> ([Transaction] -> Text) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Html -> Text
htmlAsLazyText (Html -> Text) -> ([Transaction] -> Html) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[Cell NumLines Html]] -> Html
forall border. Lines border => [[Cell border Html]] -> Html
styledTableHtml ([[Cell NumLines Html]] -> Html)
-> ([Transaction] -> [[Cell NumLines Html]])
-> [Transaction]
-> Html
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                ([Cell NumLines Text] -> [Cell NumLines Html])
-> [[Cell NumLines Text]] -> [[Cell NumLines Html]]
forall a b. (a -> b) -> [a] -> [b]
map ((Cell NumLines Text -> Cell NumLines Html)
-> [Cell NumLines Text] -> [Cell NumLines Html]
forall a b. (a -> b) -> [a] -> [b]
map ((Text -> Html) -> Cell NumLines Text -> Cell NumLines Html
forall a b. (a -> b) -> Cell NumLines a -> Cell NumLines b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Text -> Html
forall a. ToMarkup a => a -> Html
toHtml)) ([[Cell NumLines Text]] -> [[Cell NumLines Html]])
-> ([Transaction] -> [[Cell NumLines Text]])
-> [Transaction]
-> [[Cell NumLines Html]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                AmountFormat
-> Maybe Text -> [Text] -> [Transaction] -> [[Cell NumLines Text]]
entriesReportAsSpreadsheet AmountFormat
oneLineNoCostFmt Maybe Text
baseUrl [Text]
query ([Transaction] -> [[Cell NumLines Text]])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [[Cell NumLines Text]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | String
fmtString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"fods" =
                TextEncoding
-> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
printFods TextEncoding
IO.localeEncoding (Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text)
-> ([Transaction] -> Map Text ((Int, Int), [[Cell NumLines Text]]))
-> [Transaction]
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text
-> ((Int, Int), [[Cell NumLines Text]])
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall k a. k -> a -> Map k a
Map.singleton Text
"Print" (((Int, Int), [[Cell NumLines Text]])
 -> Map Text ((Int, Int), [[Cell NumLines Text]]))
-> ([Transaction] -> ((Int, Int), [[Cell NumLines Text]]))
-> [Transaction]
-> Map Text ((Int, Int), [[Cell NumLines Text]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                (,) (Int
1,Int
0) ([[Cell NumLines Text]] -> ((Int, Int), [[Cell NumLines Text]]))
-> ([Transaction] -> [[Cell NumLines Text]])
-> [Transaction]
-> ((Int, Int), [[Cell NumLines Text]])
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                AmountFormat
-> Maybe Text -> [Text] -> [Transaction] -> [[Cell NumLines Text]]
entriesReportAsSpreadsheet AmountFormat
oneLineNoCostFmt Maybe Text
baseUrl [Text]
query ([Transaction] -> [[Cell NumLines Text]])
-> ([Transaction] -> [Transaction])
-> [Transaction]
-> [[Cell NumLines Text]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                Map Text AmountStyle -> [Transaction] -> [Transaction]
forall a. HasAmounts a => Map Text AmountStyle -> a -> a
styleAmounts Map Text AmountStyle
styles
           | Bool
otherwise = String -> [Transaction] -> Text
forall a. String -> a
error' (String -> [Transaction] -> Text)
-> String -> [Transaction] -> Text
forall a b. (a -> b) -> a -> b
$ String -> String
unsupportedOutputFormatError String
fmt  -- PARTIAL:

    -- For plain print, lot postings also get the cost basis annotation inferred
    -- by lot processing, making the output self-describing; not for --export,
    -- which reproduces the journal's directives instead and keeps entries as written.
    maybeoriginalamounts :: Transaction -> Transaction
maybeoriginalamounts = Bool -> Transaction -> Transaction
maybeoriginalamountsWith Bool
True
    maybeoriginalamountsWith :: Bool -> Transaction -> Transaction
maybeoriginalamountsWith Bool
showinferredbasis
      -- Use the fully inferred and amount-styled/rounded transaction in the following situations:
      -- with -x/--explicit:
      | String -> RawOpts -> Bool
boolopt String
"explicit" (CliOpts -> RawOpts
rawopts_ CliOpts
opts) = Transaction -> Transaction
forall a. a -> a
id
      -- with --infer-costs
      | CliOpts
opts CliOpts -> Getting Bool CliOpts Bool -> Bool
forall s a. s -> Getting a s a -> a
^. Getting Bool CliOpts Bool
forall c. HasInputOpts c => Lens' c Bool
Lens' CliOpts Bool
infer_costs = Transaction -> Transaction
forall a. a -> a
id
      -- with -B/-V/-X/--value ("because of #551, and because of print -V valuing only one posting when there's an implicit txn price.")
      | Getting Any CliOpts ValuationType -> CliOpts -> Bool
forall s a. Getting Any s a -> s -> Bool
has ((Maybe ValuationType -> Const Any (Maybe ValuationType))
-> CliOpts -> Const Any CliOpts
forall c. HasReportOptsNoUpdate c => Lens' c (Maybe ValuationType)
Lens' CliOpts (Maybe ValuationType)
value ((Maybe ValuationType -> Const Any (Maybe ValuationType))
 -> CliOpts -> Const Any CliOpts)
-> ((ValuationType -> Const Any ValuationType)
    -> Maybe ValuationType -> Const Any (Maybe ValuationType))
-> Getting Any CliOpts ValuationType
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ValuationType -> Const Any ValuationType)
-> Maybe ValuationType -> Const Any (Maybe ValuationType)
forall a a' (f :: * -> *).
Applicative f =>
(a -> f a') -> Maybe a -> f (Maybe a')
_Just) CliOpts
opts = Transaction -> Transaction
forall a. a -> a
id
      | Maybe ConversionOp -> Bool
forall a. Maybe a -> Bool
isJust (ReportOpts -> Maybe ConversionOp
conversionop_ (ReportOpts -> Maybe ConversionOp)
-> ReportOpts -> Maybe ConversionOp
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec) = Transaction -> Transaction
forall a. a -> a
id
      -- For transactions containing priced auto-split postings (from lot transfer
      -- auto-split), keep the explicit form: reverting to the original would drop
      -- the priced dispose fragment while keeping its generated gain postings,
      -- leaving an unbalanced entry. (Priceless fee fragments generate no gain
      -- postings, so those transactions can safely revert to the user's original
      -- entry - except with --lots, where fragments must be kept to round-trip.)
      -- Otherwise, keep the transaction's amounts close to how they were written in the journal.
      | Bool
otherwise = \Transaction
t ->
          if (Posting -> Bool) -> [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Posting -> Bool
keptFeesplit (Transaction -> [Posting]
tpostings Transaction
t)
          then Transaction
t
          else Bool -> Transaction -> Transaction
transactionWithMostlyOriginalPostings Bool
showinferredbasis Transaction
t
      where
        hasTag :: Text -> Posting -> Bool
hasTag Text
name Posting
p = Text
name Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ((Text, Text) -> Text) -> [(Text, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Text) -> Text
forall a b. (a, b) -> a
fst (Posting -> [(Text, Text)]
ptags Posting
p)
        keptFeesplit :: Posting -> Bool
keptFeesplit Posting
p = Text -> Posting -> Bool
hasTag Text
feesplitPostingTagName Posting
p
          Bool -> Bool -> Bool
&& (String -> RawOpts -> Bool
boolopt String
"lots" (CliOpts -> RawOpts
rawopts_ CliOpts
opts) Bool -> Bool -> Bool
|| (Amount -> Bool) -> [Amount] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isJust (Maybe AmountCost -> Bool)
-> (Amount -> Maybe AmountCost) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Maybe AmountCost
acost) (MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)))

    -- Like maybeoriginalamounts, but also keeps the inferred amount for
    -- balance assignment postings (which had no explicit amount).
    -- Beancount requires all amounts to be explicit.
    fillBalanceAssignments :: Transaction -> Transaction
fillBalanceAssignments Transaction
t = (Bool -> Transaction -> Transaction
maybeoriginalamountsWith Bool
False Transaction
t)
      { tpostings = zipWith fillIfBalAssign (tpostings t) (tpostings $ maybeoriginalamountsWith False t) }
      where
        fillIfBalAssign :: Posting -> Posting -> Posting
fillIfBalAssign Posting
inferred Posting
reverted
          | Maybe BalanceAssertion -> Bool
forall a. Maybe a -> Bool
isJust (Posting -> Maybe BalanceAssertion
pbalanceassertion Posting
orig) Bool -> Bool -> Bool
&& MixedAmount -> Bool
isMissingMixedAmount (Posting -> MixedAmount
pamount Posting
orig) = Posting
reverted { pamount = pamount inferred }
          | Bool
otherwise = Posting
reverted
          where orig :: Posting
orig = Posting -> Posting
originalPosting Posting
inferred

-- | Replace this transaction's postings with the original postings if any, but keep the
-- current possibly rewritten account names, and the inferred values of any auto postings.
-- Drops postings tagged 'feesplitPostingTagName' (synthetic fragments carved off other
-- postings, eg by lot transfer auto-split), so the user sees their original entry.
-- Postings tagged 'lotsplitPostingTagName' (per-lot dispose/transfer split fragments)
-- are retained, keeping their fragment 'pamount' rather than reverting to 'poriginal' —
-- so 'print --lots' shows the per-lot detail, while 'journalCollapseLotDetail' has
-- already merged them down to one posting when --lots is off.
-- With a true first argument, lot postings whose original amount had no cost basis
-- annotation get the one inferred by lot processing (see withInferredBasis below).
-- This is mainly for showing transactions with the amounts in their original journal format.
transactionWithMostlyOriginalPostings :: Bool -> Transaction -> Transaction
transactionWithMostlyOriginalPostings :: Bool -> Transaction -> Transaction
transactionWithMostlyOriginalPostings Bool
showinferredbasis Transaction
t =
  (Posting -> Posting) -> Transaction -> Transaction
transactionMapPostings Posting -> Posting
postingMostlyOriginal
    Transaction
t{tpostings = filter (not . hasTag feesplitPostingTagName) (tpostings t)}
  where
    postingMostlyOriginal :: Posting -> Posting
postingMostlyOriginal Posting
p = Posting
orig
        { paccount = paccount p
        , pamount = newAmt
        -- Keep the current comment and tags: journal processing only appends
        -- to these (eg visible ptype tags added by lot classification, which
        -- runs after the original was snapshotted), never rewrites the
        -- user's text.
        , pcomment = pcomment p
        , ptags = ptags p
        -- When paccount equals the original (no collapse), trust the
        -- original's assertion. When paccount has been changed (eg a lot
        -- subaccount was collapsed away), use the current state's
        -- assertion — which 'journalCollapseLotDetail' has already cleared
        -- if the assertion targeted the now-hidden lot subaccount.
        , pbalanceassertion =
            if paccount orig == paccount p
            then pbalanceassertion orig
            else pbalanceassertion p }
      where
        orig :: Posting
orig = Posting -> Posting
originalPosting Posting
p
        newAmt :: MixedAmount
newAmt
          | Text -> Posting -> Bool
hasTag Text
generatedPostingTagName Posting
p = Posting -> MixedAmount
pamount Posting
p
          -- For per-lot dispose/transfer fragments, use the user's original
          -- amount but with the fragment's quantity (so 'print --lots' shows
          -- e.g. "-1 A {} @ $60" rather than the full inferred form).
          -- When the original was elided or a balance assignment (no amount),
          -- show the fragment's current amount: several sibling fragments
          -- can't re-infer their amounts on re-reading (#2692).
          | Text -> Posting -> Bool
hasTag Text
lotsplitPostingTagName Posting
p  =
              MixedAmount -> MixedAmount
withInferredBasis (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ if Posting -> Bool
hasAmount Posting
orig then MixedAmount -> MixedAmount -> MixedAmount
scaleToFragment (Posting -> MixedAmount
pamount Posting
orig) (Posting -> MixedAmount
pamount Posting
p) else Posting -> MixedAmount
pamount Posting
p
          | Bool
otherwise                        = MixedAmount -> MixedAmount
withInferredBasis (Posting -> MixedAmount
pamount Posting
orig)
        -- Show the cost basis annotation inferred by lot processing, when the
        -- user didn't write one, so lot entries are self-describing (they can
        -- be re-read without the commodity's lots: declaration, under the
        -- default method). Not needed with --lots, where the lot subaccount
        -- name already carries it.
        withInferredBasis :: MixedAmount -> MixedAmount
withInferredBasis MixedAmount
ma
          | Bool -> Bool
not Bool
showinferredbasis = MixedAmount
ma
          | Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Text -> Maybe Text
lotSubaccountName (Posting -> Text
paccount Posting
p)) = MixedAmount
ma
          | Bool
otherwise = case (MixedAmount -> [Amount]
amountsRaw MixedAmount
ma, MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)) of
              ([Amount
oa], [Amount
ca]) | Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isNothing (Amount -> Maybe CostBasis
acostbasis Amount
oa), Just CostBasis
cb <- Amount -> Maybe CostBasis
acostbasis Amount
ca -> Amount -> MixedAmount
mixedAmount Amount
oa{acostbasis = Just cb}
              ([Amount], [Amount])
_ -> MixedAmount
ma
    scaleToFragment :: MixedAmount -> MixedAmount -> MixedAmount
scaleToFragment MixedAmount
origAmt MixedAmount
curAmt = case (MixedAmount -> [Amount]
amountsRaw MixedAmount
origAmt, MixedAmount -> [Amount]
amountsRaw MixedAmount
curAmt) of
      ([Amount
oa], [Amount
ca]) -> Amount -> MixedAmount
mixedAmount Amount
oa{aquantity = aquantity ca}
      ([Amount], [Amount])
_            -> MixedAmount
curAmt
    hasTag :: Text -> Posting -> Bool
hasTag Text
name Posting
p = Text
name Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ((Text, Text) -> Text) -> [(Text, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Text) -> Text
forall a b. (a, b) -> a
fst (Posting -> [(Text, Text)]
ptags Posting
p)

entriesReportAsTextHelper :: (Transaction -> T.Text) -> EntriesReport -> TL.Text
entriesReportAsTextHelper :: (Transaction -> Text) -> [Transaction] -> Text
entriesReportAsTextHelper Transaction -> Text
showtxn = Builder -> Text
TB.toLazyText (Builder -> Text)
-> ([Transaction] -> Builder) -> [Transaction] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Builder) -> [Transaction] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Text -> Builder
TB.fromText (Text -> Builder)
-> (Transaction -> Text) -> Transaction -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Text
showtxn)

entriesReportAsSql :: EntriesReport -> TL.Text
entriesReportAsSql :: [Transaction] -> Text
entriesReportAsSql [Transaction]
txns = Builder -> Text
TB.toLazyText (Builder -> Text) -> Builder -> Text
forall a b. (a -> b) -> a -> b
$ [Builder] -> Builder
forall a. Monoid a => [a] -> a
mconcat
    [ Text -> Builder
TB.fromText Text
"create table if not exists postings(id serial,txnidx int,date1 date,date2 date,status text,code text,description text,comment text,account text,amount numeric,commodity text,debit numeric,credit numeric,posting_status text,posting_comment text);\n"
    , Text -> Builder
TB.fromText Text
"insert into postings(txnidx,date1,date2,status,code,description,comment,account,amount,commodity,debit,credit,posting_status,posting_comment) values\n"
    , [Builder] -> Builder
forall a. Monoid a => [a] -> a
mconcat ([Builder] -> Builder)
-> ([Builder] -> [Builder]) -> [Builder] -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Builder -> [Builder] -> [Builder]
forall a. a -> [a] -> [a]
intersperse (Text -> Builder
TB.fromText Text
",") ([Builder] -> Builder) -> [Builder] -> Builder
forall a b. (a -> b) -> a -> b
$ ([Text] -> Builder) -> CSV -> [Builder]
forall a b. (a -> b) -> [a] -> [b]
map [Text] -> Builder
values CSV
csv
    , Text -> Builder
TB.fromText Text
";\n"
    ]
  where
    values :: [Text] -> Builder
values [Text]
vs = Text -> Builder
TB.fromText Text
"(" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> [Builder] -> Builder
forall a. Monoid a => [a] -> a
mconcat (Builder -> [Builder] -> [Builder]
forall a. a -> [a] -> [a]
intersperse (Text -> Builder
TB.fromText Text
",") ([Builder] -> [Builder]) -> [Builder] -> [Builder]
forall a b. (a -> b) -> a -> b
$ (Text -> Builder) -> [Text] -> [Builder]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Builder
toSql [Text]
vs) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Text -> Builder
TB.fromText Text
")\n"
    toSql :: Text -> Builder
toSql Text
"" = Text -> Builder
TB.fromText Text
"NULL"
    toSql Text
s  = Text -> Builder
TB.fromText Text
"'" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Text -> Builder
TB.fromText (HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"'" Text
"''" Text
s) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Text -> Builder
TB.fromText Text
"'"
    csv :: CSV
csv =
        [[Cell NumLines Text]] -> CSV
forall (f :: * -> *) border text.
Functor f =>
[f (Cell border text)] -> [f text]
Spr.rawTableContent ([[Cell NumLines Text]] -> CSV)
-> (Transaction -> [[Cell NumLines Text]]) -> Transaction -> CSV
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat
-> Maybe Text -> [Text] -> Transaction -> [[Cell NumLines Text]]
transactionToSpreadsheet AmountFormat
machineFmt Maybe Text
forall a. Maybe a
Nothing [] (Transaction -> [[Cell NumLines Text]])
-> (Transaction -> Transaction)
-> Transaction
-> [[Cell NumLines Text]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
        (MixedAmount -> MixedAmount) -> Transaction -> Transaction
transactionMapPostingAmounts ((Amount -> Amount) -> MixedAmount -> MixedAmount
mapMixedAmount Amount -> Amount
setDecimalPoint)
            (Transaction -> CSV) -> [Transaction] -> CSV
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Transaction]
txns
      where
        setDecimalPoint :: Amount -> Amount
setDecimalPoint Amount
a = Amount
a{astyle=(astyle a){asdecimalmark=Just '.'}}

entriesReportAsCsv :: EntriesReport -> CSV
entriesReportAsCsv :: [Transaction] -> CSV
entriesReportAsCsv =
  [[Cell NumLines Text]] -> CSV
forall (f :: * -> *) border text.
Functor f =>
[f (Cell border text)] -> [f text]
Spr.rawTableContent ([[Cell NumLines Text]] -> CSV)
-> ([Transaction] -> [[Cell NumLines Text]])
-> [Transaction]
-> CSV
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AmountFormat
-> Maybe Text -> [Text] -> [Transaction] -> [[Cell NumLines Text]]
entriesReportAsSpreadsheet AmountFormat
machineFmt Maybe Text
forall a. Maybe a
Nothing []

entriesReportAsSpreadsheet ::
  AmountFormat -> Maybe Text -> [Text] ->
  EntriesReport -> [[Spr.Cell Spr.NumLines Text]]
entriesReportAsSpreadsheet :: AmountFormat
-> Maybe Text -> [Text] -> [Transaction] -> [[Cell NumLines Text]]
entriesReportAsSpreadsheet AmountFormat
fmt Maybe Text
baseUrl [Text]
query [Transaction]
txns =
  [Cell () Text] -> [Cell NumLines Text]
forall (f :: * -> *) text.
Functor f =>
f (Cell () text) -> f (Cell NumLines text)
Spr.addHeaderBorders
    ((Text -> Cell () Text) -> [Text] -> [Cell () Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Cell () Text
forall borders. Lines borders => Text -> Cell borders Text
Spr.headerCell
        [Text
"txnidx",Text
"date",Text
"date2",Text
"status",Text
"code",Text
"description",Text
"comment",
         Text
"account",Text
"amount",Text
"commodity",Text
"debit",Text
"credit",
         Text
"posting-status",Text
"posting-comment"])
  [Cell NumLines Text]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall a. a -> [a] -> [a]
:
  (Transaction -> [[Cell NumLines Text]])
-> [Transaction] -> [[Cell NumLines Text]]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (AmountFormat
-> Maybe Text -> [Text] -> Transaction -> [[Cell NumLines Text]]
transactionToSpreadsheet AmountFormat
fmt Maybe Text
baseUrl [Text]
query) [Transaction]
txns

-- | Generate one record per posting, duplicating the common transaction fields.
-- The txnidx field (transaction index) allows postings to be grouped back into transactions.
transactionToSpreadsheet ::
  AmountFormat -> Maybe Text -> [Text] ->
  Transaction -> [[Spr.Cell Spr.NumLines Text]]
transactionToSpreadsheet :: AmountFormat
-> Maybe Text -> [Text] -> Transaction -> [[Cell NumLines Text]]
transactionToSpreadsheet AmountFormat
fmt Maybe Text
baseUrl [Text]
query Transaction
t =
  [Cell NumLines Text]
-> [[Cell NumLines Text]] -> [[Cell NumLines Text]]
forall border text.
[Cell border text] -> [[Cell border text]] -> [[Cell border text]]
addRowSpanHeader (Cell NumLines Text
idxCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
dCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
d2Cell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
statusCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
codeCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
descriptionCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:Cell NumLines Text
commentCell NumLines Text -> [Cell NumLines Text] -> [Cell NumLines Text]
forall a. a -> [a] -> [a]
:[])
    (AmountFormat
-> Maybe Text -> [Text] -> Posting -> [[Cell NumLines Text]]
forall border.
Lines border =>
AmountFormat
-> Maybe Text -> [Text] -> Posting -> [[Cell border Text]]
postingToSpreadsheet AmountFormat
fmt Maybe Text
baseUrl [Text]
query (Posting -> [[Cell NumLines Text]])
-> [Posting] -> [[Cell NumLines Text]]
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Transaction -> [Posting]
tpostings Transaction
t)
  where
    cell :: text -> Cell NumLines text
cell = text -> Cell NumLines text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell
    idx :: Cell NumLines Text
idx = Integer -> Cell NumLines Text
forall border. Lines border => Integer -> Cell border Text
Spr.integerCell (Integer -> Cell NumLines Text) -> Integer -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Integer
tindex Transaction
t
    description :: Cell NumLines Text
description = Text -> Cell NumLines Text
forall {text}. text -> Cell NumLines text
cell (Text -> Cell NumLines Text) -> Text -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Text
tdescription Transaction
t
    dateCell :: Day -> Cell border Text
dateCell Day
date =
        (Text -> Cell border Text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell (Text -> Cell border Text) -> Text -> Cell border Text
forall a b. (a -> b) -> a -> b
$ Day -> Text
showDate Day
date) {Spr.cellType = Spr.TypeDate}
    d :: Cell NumLines Text
d = Day -> Cell NumLines Text
forall {border}. Lines border => Day -> Cell border Text
dateCell (Day -> Cell NumLines Text) -> Day -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Day
tdate Transaction
t
    d2 :: Cell NumLines Text
d2 = Cell NumLines Text
-> (Day -> Cell NumLines Text) -> Maybe Day -> Cell NumLines Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Cell NumLines Text
forall border text. (Lines border, Monoid text) => Cell border text
Spr.emptyCell Day -> Cell NumLines Text
forall {border}. Lines border => Day -> Cell border Text
dateCell (Maybe Day -> Cell NumLines Text)
-> Maybe Day -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Maybe Day
tdate2 Transaction
t
    status :: Cell NumLines Text
status = Text -> Cell NumLines Text
forall {text}. text -> Cell NumLines text
cell (Text -> Cell NumLines Text) -> Text -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack (String -> Text) -> (Status -> String) -> Status -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Status -> String
forall a. Show a => a -> String
show (Status -> Text) -> Status -> Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Status
tstatus Transaction
t
    code :: Cell NumLines Text
code = Text -> Cell NumLines Text
forall {text}. text -> Cell NumLines text
cell (Text -> Cell NumLines Text) -> Text -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Text
tcode Transaction
t
    comment :: Cell NumLines Text
comment = Text -> Cell NumLines Text
forall {text}. text -> Cell NumLines text
cell (Text -> Cell NumLines Text) -> Text -> Cell NumLines Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Transaction -> Text
tcomment Transaction
t

addRowSpanHeader ::
    [Spr.Cell border text] ->
    [[Spr.Cell border text]] -> [[Spr.Cell border text]]
addRowSpanHeader :: forall border text.
[Cell border text] -> [[Cell border text]] -> [[Cell border text]]
addRowSpanHeader [Cell border text]
common [[Cell border text]]
rows =
    case [[Cell border text]]
rows of
        [] -> []
        [[Cell border text]
row] -> [[Cell border text]
common[Cell border text] -> [Cell border text] -> [Cell border text]
forall a. [a] -> [a] -> [a]
++[Cell border text]
row]
        [[Cell border text]]
_ ->
            let setSpan :: Span -> Cell border text -> Cell border text
setSpan Span
spn Cell border text
cell = Cell border text
cell{Spr.cellSpan = spn} in
            ([Cell border text] -> [Cell border text] -> [Cell border text])
-> [[Cell border text]]
-> [[Cell border text]]
-> [[Cell border text]]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith [Cell border text] -> [Cell border text] -> [Cell border text]
forall a. [a] -> [a] -> [a]
(++)
                ((Cell border text -> Cell border text)
-> [Cell border text] -> [Cell border text]
forall a b. (a -> b) -> [a] -> [b]
map (Span -> Cell border text -> Cell border text
forall {border} {text}.
Span -> Cell border text -> Cell border text
setSpan (Span -> Cell border text -> Cell border text)
-> Span -> Cell border text -> Cell border text
forall a b. (a -> b) -> a -> b
$ Int -> Span
Spr.SpanVertical (Int -> Span) -> Int -> Span
forall a b. (a -> b) -> a -> b
$ [[Cell border text]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[Cell border text]]
rows) [Cell border text]
common [Cell border text] -> [[Cell border text]] -> [[Cell border text]]
forall a. a -> [a] -> [a]
:
                 [Cell border text] -> [[Cell border text]]
forall a. a -> [a]
repeat ((Cell border text -> Cell border text)
-> [Cell border text] -> [Cell border text]
forall a b. (a -> b) -> [a] -> [b]
map (Span -> Cell border text -> Cell border text
forall {border} {text}.
Span -> Cell border text -> Cell border text
setSpan Span
Spr.Covered) [Cell border text]
common))
                [[Cell border text]]
rows

postingToSpreadsheet ::
  (Spr.Lines border) =>
  AmountFormat -> Maybe Text -> [Text] ->
  Posting -> [[Spr.Cell border Text]]
postingToSpreadsheet :: forall border.
Lines border =>
AmountFormat
-> Maybe Text -> [Text] -> Posting -> [[Cell border Text]]
postingToSpreadsheet AmountFormat
fmt Maybe Text
baseUrl [Text]
query Posting
p =
  (Amount -> [Cell border Text]) -> [Amount] -> [[Cell border Text]]
forall a b. (a -> b) -> [a] -> [b]
map (\(a :: Amount
a@(Amount {aquantity :: Amount -> Quantity
aquantity=Quantity
q,acommodity :: Amount -> Text
acommodity=Text
c})) ->
    -- commodity goes into separate column, so we suppress it, along with digit group
    -- separators and prices
    let a_ :: Amount
a_ = Amount -> Amount
amountStripCost Amount
a{acommodity=""} in
    let credit :: Cell border Text
credit = if Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
0 then Amount -> Cell border Text
forall {border}. Lines border => Amount -> Cell border Text
amountCell (Amount -> Cell border Text) -> Amount -> Cell border Text
forall a b. (a -> b) -> a -> b
$ Amount -> Amount
forall a. Num a => a -> a
negate Amount
a_ else Cell border Text
forall border text. (Lines border, Monoid text) => Cell border text
Spr.emptyCell in
    let debit :: Cell border Text
debit  = if Quantity
q Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
>= Quantity
0 then Amount -> Cell border Text
forall {border}. Lines border => Amount -> Cell border Text
amountCell Amount
a_ else Cell border Text
forall border text. (Lines border, Monoid text) => Cell border text
Spr.emptyCell in
    [Maybe Text
-> [Text] -> Text -> Cell border Text -> Cell border Text
forall border text.
Maybe Text
-> [Text] -> Text -> Cell border text -> Cell border text
setAccountAnchor Maybe Text
baseUrl [Text]
query (Posting -> Text
paccount Posting
p) (Cell border Text -> Cell border Text)
-> Cell border Text -> Cell border Text
forall a b. (a -> b) -> a -> b
$ Text -> Cell border Text
forall {text}. text -> Cell border text
cell Text
account,
     Amount -> Cell border Text
forall {border}. Lines border => Amount -> Cell border Text
amountCell Amount
a_, Text -> Cell border Text
forall {text}. text -> Cell border text
cell Text
c,
     Cell border Text
debit, Cell border Text
credit, Text -> Cell border Text
forall {text}. text -> Cell border text
cell Text
status, Text -> Cell border Text
forall {text}. text -> Cell border text
cell Text
comment])
    ([Amount] -> [[Cell border Text]])
-> (MixedAmount -> [Amount]) -> MixedAmount -> [[Cell border Text]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> [Amount]
amounts (MixedAmount -> [[Cell border Text]])
-> MixedAmount -> [[Cell border Text]]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p
  where
    cell :: text -> Cell border text
cell = text -> Cell border text
forall border text. Lines border => text -> Cell border text
Spr.defaultCell
    amountCell :: Amount -> Cell border Text
amountCell Amount
amt =
      AmountFormat -> (Class, (Text, Amount)) -> Cell border Text
forall border wb.
Lines border =>
AmountFormat -> (Class, (wb, Amount)) -> Cell border wb
Spr.cellFromAmount AmountFormat
fmt
        (Text -> Class
Spr.Class Text
"amount", (WideBuilder -> Text
wbToText (WideBuilder -> Text) -> WideBuilder -> Text
forall a b. (a -> b) -> a -> b
$ AmountFormat -> Amount -> WideBuilder
showAmountB AmountFormat
machineFmt Amount
amt, Amount
amt))
    status :: Text
status = String -> Text
T.pack (String -> Text) -> (Status -> String) -> Status -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Status -> String
forall a. Show a => a -> String
show (Status -> Text) -> Status -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Status
pstatus Posting
p
    account :: Text
account = Maybe Int -> PostingRealness -> Text -> Text
showAccountName Maybe Int
forall a. Maybe a
Nothing (Posting -> PostingRealness
preal Posting
p) (Posting -> Text
paccount Posting
p)
    comment :: Text
comment = Text -> Text
T.strip (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
pcomment Posting
p

addLocationTag :: Transaction -> Transaction
addLocationTag :: Transaction -> Transaction
addLocationTag Transaction
t = Transaction
t{tcomment = tcomment t `commentAddTagNextLine` loctag}
  where
    loctag :: (Text, Text)
loctag = (Text
"location", String -> Text
T.pack (String -> Text)
-> ((SourcePos, SourcePos) -> String)
-> (SourcePos, SourcePos)
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SourcePos, SourcePos) -> String
sourcePosPairPretty ((SourcePos, SourcePos) -> Text) -> (SourcePos, SourcePos) -> Text
forall a b. (a -> b) -> a -> b
$ Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t)