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

module Hledger.Cli.Commands.Close (
  closemode
 ,close
)
where

import Control.Monad (when)
import Data.Function (on)
import Data.List (groupBy)
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Time.Calendar (addDays)
import Lens.Micro ((^.))
import System.Console.CmdArgs.Explicit as C

import Hledger
import Hledger.Cli.CliOptions

defretaindesc :: String
defretaindesc = String
"retain earnings"
defclosedesc :: String
defclosedesc  = String
"closing balances"
defopendesc :: String
defopendesc   = String
"opening balances"
defretainacct :: String
defretainacct = String
"equity:retained earnings"
defcloseacct :: String
defcloseacct  = String
"equity:opening/closing balances"

closemode :: Mode RawOpts
closemode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Close.txt")
  [forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"close"]        (String -> RawOpts -> RawOpts
setboolopt String
"close")   String
"show a closing transaction (default)"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"open"]         (String -> RawOpts -> RawOpts
setboolopt String
"open")    String
"show an opening transaction"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"migrate"]      (String -> RawOpts -> RawOpts
setboolopt String
"migrate") String
"show both closing and opening transactions"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"retain"]       (String -> RawOpts -> RawOpts
setboolopt String
"retain")  String
"show a retain earnings transaction (for RX accounts)"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"explicit",String
"x"] (String -> RawOpts -> RawOpts
setboolopt String
"explicit") String
"show all amounts explicitly"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"show-costs"]   (String -> RawOpts -> RawOpts
setboolopt String
"show-costs") String
"show amounts with different costs separately"
  ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"interleaved"]  (String -> RawOpts -> RawOpts
setboolopt String
"interleaved") String
"show source and destination postings together"
  ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"close-desc"]   (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"close-desc" String
s RawOpts
opts) String
"DESC" String
"set closing transaction's description"
  ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"close-acct"]   (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"close-acct" String
s RawOpts
opts) String
"ACCT" String
"set closing transaction's destination account"
  ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"open-desc"]    (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"open-desc"  String
s RawOpts
opts) String
"DESC" String
"set opening transaction's description"
  ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"open-acct"]    (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"open-acct"  String
s RawOpts
opts) String
"ACCT" String
"set opening transaction's source account"
  ]
  [(String, [Flag RawOpts])
generalflagsgroup1]
  ([Flag RawOpts]
hiddenflags
    forall a. [a] -> [a] -> [a]
++  -- keep supporting old flag names for compatibility
    [forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"closing"]   (String -> RawOpts -> RawOpts
setboolopt String
"close")                                   String
"old spelling of --close"
    ,forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"opening"]   (String -> RawOpts -> RawOpts
setboolopt String
"open")                                    String
"old spelling of --open"
    ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"close-to"]  (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"close-acct" String
s RawOpts
opts) String
"ACCT" String
"old spelling of --close-acct"
    ,forall a. [String] -> Update a -> String -> String -> Flag a
flagReq  [String
"open-from"] (\String
s RawOpts
opts -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"open-acct"  String
s RawOpts
opts) String
"ACCT" String
"old spelling of --open-acct"
    ]
  )
  ([], forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"[--close | --open | --migrate | --retain] [ACCTQUERY]")

-- Debugger, beware: close is incredibly devious; simple rules combine to make a horrid maze.
-- Tests are in hledger/test/close.test.
-- This code is also used by the close command.
close :: CliOpts -> Journal -> IO ()
close copts :: CliOpts
copts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts, reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec0} Journal
j = do
  let
    (Bool
close_, Bool
open_, String
defclosedesc_, String
defopendesc_, String
defcloseacct_, Query
defacctsq_) = if
      | String -> RawOpts -> Bool
boolopt String
"retain"  RawOpts
rawopts -> (Bool
True,  Bool
False, String
defretaindesc, forall a. HasCallStack => a
undefined,   String
defretainacct, [AccountType] -> Query
Type [AccountType
Revenue, AccountType
Expense])
      | String -> RawOpts -> Bool
boolopt String
"migrate" RawOpts
rawopts -> (Bool
True,  Bool
True,  String
defclosedesc,  String
defopendesc, String
defcloseacct,  [AccountType] -> Query
Type [AccountType
Asset, AccountType
Liability, AccountType
Equity])
      | String -> RawOpts -> Bool
boolopt String
"open"    RawOpts
rawopts -> (Bool
False, Bool
True,  forall a. HasCallStack => a
undefined,     String
defopendesc, String
defcloseacct,  [AccountType] -> Query
Type [AccountType
Asset, AccountType
Liability, AccountType
Equity])
      | Bool
otherwise                 -> (Bool
True,  Bool
False, String
defclosedesc,  forall a. HasCallStack => a
undefined,   String
defcloseacct,  [AccountType] -> Query
Type [AccountType
Asset, AccountType
Liability, AccountType
Equity])

    -- descriptions to use for the closing/opening transactions
    closedesc :: Text
closedesc = String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a -> a
fromMaybe String
defclosedesc_ forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> Maybe String
maybestringopt String
"close-desc" RawOpts
rawopts
    opendesc :: Text
opendesc  = String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a -> a
fromMaybe String
defopendesc_  forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> Maybe String
maybestringopt String
"open-desc"  RawOpts
rawopts

    -- equity/balancing accounts to use
    closeacct :: Text
closeacct = String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a -> a
fromMaybe String
defcloseacct_ forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> Maybe String
maybestringopt String
"close-acct" RawOpts
rawopts
    openacct :: Text
openacct  = forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
closeacct String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> Maybe String
maybestringopt String
"open-acct" RawOpts
rawopts

    ropts :: ReportOpts
ropts = (ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec0){balanceaccum_ :: BalanceAccumulation
balanceaccum_=BalanceAccumulation
Historical, accountlistmode_ :: AccountListMode
accountlistmode_=AccountListMode
ALFlat}
    rspec1 :: ReportSpec
rspec1 = ConversionOp -> ReportSpec -> ReportSpec
setDefaultConversionOp ConversionOp
NoConversionOp ReportSpec
rspec0{_rsReportOpts :: ReportOpts
_rsReportOpts=ReportOpts
ropts}

    -- Dates of the closing and opening transactions.
    -- "The default closing date is yesterday, or the journal's end date, whichever is later.
    -- You can change this by specifying a [report end date](#report-start--end-date) with `-e`.
    -- The last day of the report period will be the closing date, eg `-e 2024` means "close on 2023-12-31".
    -- The opening date is always the day after the closing date."
    argsq :: Query
argsq = ReportSpec -> Query
_rsQuery ReportSpec
rspec1
    yesterday :: Day
yesterday = Integer -> Day -> Day
addDays (-Integer
1) forall a b. (a -> b) -> a -> b
$ ReportSpec -> Day
_rsDay ReportSpec
rspec1
    yesterdayorjournalend :: Day
yesterdayorjournalend = case Bool -> Journal -> Maybe Day
journalLastDay Bool
False Journal
j of
      Just Day
journalend -> forall a. Ord a => a -> a -> a
max Day
yesterday Day
journalend
      Maybe Day
Nothing         -> Day
yesterday
    mreportlastday :: Maybe Day
mreportlastday = Integer -> Day -> Day
addDays (-Integer
1) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Bool -> Query -> Maybe Day
queryEndDate Bool
False Query
argsq
    closedate :: Day
closedate = forall a. a -> Maybe a -> a
fromMaybe Day
yesterdayorjournalend  Maybe Day
mreportlastday
    opendate :: Day
opendate = Integer -> Day -> Day
addDays Integer
1 Day
closedate

    -- should we show the amount(s) on the equity posting(s) ?
    explicit :: Bool
explicit = String -> RawOpts -> Bool
boolopt String
"explicit" RawOpts
rawopts Bool -> Bool -> Bool
|| CliOpts
copts forall s a. s -> Getting a s a -> a
^. forall c. HasInputOpts c => Lens' c Bool
infer_costs

    -- the balances to close
    argsacctq :: Query
argsacctq = (Query -> Bool) -> Query -> Query
filterQuery (\Query
q -> Query -> Bool
queryIsAcct Query
q Bool -> Bool -> Bool
|| Query -> Bool
queryIsType Query
q) Query
argsq
    q2 :: Query
q2 = if Query -> Bool
queryIsNull Query
argsacctq then [Query] -> Query
And [Query
argsq, Query
defacctsq_] else Query
argsq
    rspec2 :: ReportSpec
rspec2 = ReportSpec
rspec1{_rsQuery :: Query
_rsQuery=Query
q2}
    ([BalanceReportItem]
acctbals',MixedAmount
_) = ReportSpec -> Journal -> ([BalanceReportItem], MixedAmount)
balanceReport ReportSpec
rspec2 Journal
j
    acctbals :: [(Text, MixedAmount)]
acctbals = forall a b. (a -> b) -> [a] -> [b]
map (\(Text
a,Text
_,Int
_,MixedAmount
b) -> (Text
a, if ReportOpts -> Bool
show_costs_ ReportOpts
ropts then MixedAmount
b else MixedAmount -> MixedAmount
mixedAmountStripPrices MixedAmount
b)) [BalanceReportItem]
acctbals'
    totalamt :: MixedAmount
totalamt = forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map forall a b. (a, b) -> b
snd [(Text, MixedAmount)]
acctbals

    -- since balance assertion amounts are required to be exact, the
    -- amounts in opening/closing transactions should be too (#941, #1137)
    precise :: Amount -> Amount
precise = Amount -> Amount
amountSetFullPrecision

    -- interleave equity postings next to the corresponding closing posting, or put them all at the end ?
    interleaved :: Bool
interleaved = String -> RawOpts -> Bool
boolopt String
"interleaved" RawOpts
rawopts

    -- the closing transaction
    closetxn :: Transaction
closetxn = Transaction
nulltransaction{tdate :: Day
tdate=Day
closedate, tdescription :: Text
tdescription=Text
closedesc, tpostings :: [Posting]
tpostings=[Posting]
closeps}
    closeps :: [Posting]
closeps =
      forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [
        Posting
posting{paccount :: Text
paccount          = Text
a
               ,pamount :: MixedAmount
pamount           = Amount -> MixedAmount
mixedAmount forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Amount
precise forall a b. (a -> b) -> a -> b
$ forall a. Num a => a -> a
negate Amount
b
               -- after each commodity's last posting, assert 0 balance (#1035)
               -- balance assertion amounts are unpriced (#824)
               ,pbalanceassertion :: Maybe BalanceAssertion
pbalanceassertion =
                   if Bool
islast
                   then forall a. a -> Maybe a
Just BalanceAssertion
nullassertion{baamount :: Amount
baamount=Amount -> Amount
precise Amount
b{aquantity :: Quantity
aquantity=Quantity
0, aprice :: Maybe AmountPrice
aprice=forall a. Maybe a
Nothing}}
                   else forall a. Maybe a
Nothing
               }

        -- maybe an interleaved posting transferring this balance to equity
        forall a. a -> [a] -> [a]
: [Posting
posting{paccount :: Text
paccount=Text
closeacct, pamount :: MixedAmount
pamount=Amount -> MixedAmount
mixedAmount forall a b. (a -> b) -> a -> b
$ Amount -> Amount
precise Amount
b} | Bool
interleaved]

        | -- get the balances for each commodity and transaction price
          (Text
a,MixedAmount
mb) <- [(Text, MixedAmount)]
acctbals
        , let bs0 :: [Amount]
bs0 = MixedAmount -> [Amount]
amounts MixedAmount
mb
          -- mark the last balance in each commodity with True
        , let bs2 :: [(Amount, Bool)]
bs2 = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [forall a. [a] -> [a]
reverse forall a b. (a -> b) -> a -> b
$ forall a b. [a] -> [b] -> [(a, b)]
zip (forall a. [a] -> [a]
reverse [Amount]
bs1) (Bool
True forall a. a -> [a] -> [a]
: forall a. a -> [a]
repeat Bool
False)
                           | [Amount]
bs1 <- forall a. (a -> a -> Bool) -> [a] -> [[a]]
groupBy (forall a. Eq a => a -> a -> Bool
(==) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` Amount -> Text
acommodity) [Amount]
bs0]
        , (Amount
b, Bool
islast) <- [(Amount, Bool)]
bs2
        ]

      -- or a final multicommodity posting transferring all balances to equity
      -- (print will show this as multiple single-commodity postings)
      forall a. [a] -> [a] -> [a]
++ [Posting
posting{paccount :: Text
paccount=Text
closeacct, pamount :: MixedAmount
pamount=if Bool
explicit then MixedAmount -> MixedAmount
mixedAmountSetFullPrecision MixedAmount
totalamt else MixedAmount
missingmixedamt} | Bool -> Bool
not Bool
interleaved]

    -- the opening transaction
    opentxn :: Transaction
opentxn = Transaction
nulltransaction{tdate :: Day
tdate=Day
opendate, tdescription :: Text
tdescription=Text
opendesc, tpostings :: [Posting]
tpostings=[Posting]
openps}
    openps :: [Posting]
openps =
      forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [
        Posting
posting{paccount :: Text
paccount          = Text
a
               ,pamount :: MixedAmount
pamount           = Amount -> MixedAmount
mixedAmount forall a b. (a -> b) -> a -> b
$ Amount -> Amount
precise Amount
b
               ,pbalanceassertion :: Maybe BalanceAssertion
pbalanceassertion =
                   case Maybe Amount
mcommoditysum of
                     Just Amount
s  -> forall a. a -> Maybe a
Just BalanceAssertion
nullassertion{baamount :: Amount
baamount=Amount -> Amount
precise Amount
s{aprice :: Maybe AmountPrice
aprice=forall a. Maybe a
Nothing}}
                     Maybe Amount
Nothing -> forall a. Maybe a
Nothing
               }
        forall a. a -> [a] -> [a]
: [Posting
posting{paccount :: Text
paccount=Text
openacct, pamount :: MixedAmount
pamount=Amount -> MixedAmount
mixedAmount forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Amount
precise forall a b. (a -> b) -> a -> b
$ forall a. Num a => a -> a
negate Amount
b} | Bool
interleaved]

        | (Text
a,MixedAmount
mb) <- [(Text, MixedAmount)]
acctbals
        , let bs0 :: [Amount]
bs0 = MixedAmount -> [Amount]
amounts MixedAmount
mb
          -- mark the last balance in each commodity with the unpriced sum in that commodity (for a balance assertion)
        , let bs2 :: [(Amount, Maybe Amount)]
bs2 = forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [forall a. [a] -> [a]
reverse forall a b. (a -> b) -> a -> b
$ forall a b. [a] -> [b] -> [(a, b)]
zip (forall a. [a] -> [a]
reverse [Amount]
bs1) (forall a. a -> Maybe a
Just Amount
commoditysum forall a. a -> [a] -> [a]
: forall a. a -> [a]
repeat forall a. Maybe a
Nothing)
                           | [Amount]
bs1 <- forall a. (a -> a -> Bool) -> [a] -> [[a]]
groupBy (forall a. Eq a => a -> a -> Bool
(==) forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` Amount -> Text
acommodity) [Amount]
bs0
                           , let commoditysum :: Amount
commoditysum = (forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Amount]
bs1)]
        , (Amount
b, Maybe Amount
mcommoditysum) <- [(Amount, Maybe Amount)]
bs2
        ]
      forall a. [a] -> [a] -> [a]
++ [Posting
posting{paccount :: Text
paccount=Text
openacct, pamount :: MixedAmount
pamount=if Bool
explicit then MixedAmount -> MixedAmount
mixedAmountSetFullPrecision (MixedAmount -> MixedAmount
maNegate MixedAmount
totalamt) else MixedAmount
missingmixedamt} | Bool -> Bool
not Bool
interleaved]

  -- print them
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
close_ forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> IO ()
T.putStr forall a b. (a -> b) -> a -> b
$ Transaction -> Text
showTransaction Transaction
closetxn
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
open_  forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> IO ()
T.putStr forall a b. (a -> b) -> a -> b
$ Transaction -> Text
showTransaction Transaction
opentxn