| 1 |
{-# LANGUAGE OverloadedStrings #-} |
| 2 |
{-# LANGUAGE TemplateHaskell #-} |
| 3 |
{-# LANGUAGE MultiWayIf #-} |
| 4 |
|
| 5 |
module Hledger.Cli.Commands.Close ( |
| 6 |
closemode |
| 7 |
,close |
| 8 |
) |
| 9 |
where |
| 10 |
|
| 11 |
import Data.Function (on) |
| 12 |
import Data.List (groupBy) |
| 13 |
import Data.Maybe (fromMaybe) |
| 14 |
import Data.Text qualified as T |
| 15 |
import Data.Text.IO qualified as T |
| 16 |
import Data.Time.Calendar (addDays) |
| 17 |
import System.Console.CmdArgs.Explicit as C |
| 18 |
|
| 19 |
import Hledger |
| 20 |
import Hledger.Cli.CliOptions |
| 21 |
import Safe (lastDef, readMay, readDef) |
| 22 |
import System.FilePath (takeBaseName) |
| 23 |
import Data.Char (isDigit) |
| 24 |
import Hledger.Read.RulesReader (parseBalanceAssertionType) |
| 25 |
import Hledger.Cli.Commands.Print (roundFlag, amountStylesSetRoundingFromRawOpts) |
| 26 |
|
| 27 |
defclosedesc = "closing balances" |
| 28 |
defopendesc = "opening balances" |
| 29 |
defretaindesc = "retain earnings" |
| 30 |
|
| 31 |
defcloseacct = "equity:opening/closing balances" |
| 32 |
defretainacct = "equity:retained earnings" |
| 33 |
|
| 34 |
closemode = hledgerCommandMode |
| 35 |
$(embedFileRelative "Hledger/Cli/Commands/Close.txt") |
| 36 |
[flagOpt "" ["clopen"] (\s opts -> Right $ setopt "clopen" s opts) "TAGVAL" "show closing and opening balances transactions, for AL accounts by default" |
| 37 |
,flagOpt "" ["close"] (\s opts -> Right $ setopt "close" s opts) "TAGVAL" "show just a closing balances transaction" |
| 38 |
,flagOpt "" ["open"] (\s opts -> Right $ setopt "open" s opts) "TAGVAL" "show just an opening balances transaction" |
| 39 |
,flagOpt "" ["assert"] (\s opts -> Right $ setopt "assert" s opts) "TAGVAL" "show a balance assertions transaction" |
| 40 |
,flagOpt "" ["assign"] (\s opts -> Right $ setopt "assign" s opts) "TAGVAL" "show a balance assignments transaction" |
| 41 |
,flagOpt "" ["retain"] (\s opts -> Right $ setopt "retain" s opts) "TAGVAL" "show a retain earnings transaction, for RX accounts by default" |
| 42 |
,flagNone ["explicit","x"] (setboolopt "explicit") "show all amounts explicitly" |
| 43 |
,flagNone ["show-costs"] (setboolopt "show-costs") "show amounts with different costs separately" |
| 44 |
,flagNone ["interleaved"] (setboolopt "interleaved") "show source and destination postings together" |
| 45 |
,flagReq ["assertion-type"] (\s opts -> Right $ setopt "assertion-type" s opts) "TYPE" "=, ==, =* or ==*" |
| 46 |
,flagReq ["close-desc"] (\s opts -> Right $ setopt "close-desc" s opts) "DESC" "set closing transaction's description" |
| 47 |
,flagReq ["close-acct"] (\s opts -> Right $ setopt "close-acct" s opts) "ACCT" "set closing transaction's destination account" |
| 48 |
,flagReq ["open-desc"] (\s opts -> Right $ setopt "open-desc" s opts) "DESC" "set opening transaction's description" |
| 49 |
,flagReq ["open-acct"] (\s opts -> Right $ setopt "open-acct" s opts) "ACCT" "set opening transaction's source account" |
| 50 |
,roundFlag |
| 51 |
] |
| 52 |
cligeneralflagsgroups1 |
| 53 |
(hiddenflags |
| 54 |
++ -- keep supporting old flag names for compatibility |
| 55 |
[flagNone ["closing"] (setboolopt "close") "old spelling of --close" |
| 56 |
,flagNone ["opening"] (setboolopt "open") "old spelling of --open" |
| 57 |
,flagNone ["migrate"] (setboolopt "clopen") "old spelling of --clopen" |
| 58 |
,flagReq ["close-to"] (\s opts -> Right $ setopt "close-acct" s opts) "ACCT" "old spelling of --close-acct" |
| 59 |
,flagReq ["open-from"] (\s opts -> Right $ setopt "open-acct" s opts) "ACCT" "old spelling of --open-acct" |
| 60 |
] |
| 61 |
) |
| 62 |
([], Just $ argsFlag "[--close|--open|--clopen|--assign|--assert|--retain] [ACCTQUERY]") |
| 63 |
|
| 64 |
-- | The close command's mode (subcommand). |
| 65 |
-- The code depends on these spellings. |
| 66 |
data CloseMode = Clopen | Close | Open | Assign | Assert | Retain deriving (Eq,Show,Read) |
| 67 |
|
| 68 |
-- | Pick the rightmost flag spelled like a CloseMode (--clopen, --close, --open, etc), or default to Close. |
| 69 |
closeModeFromRawOpts :: RawOpts -> CloseMode |
| 70 |
closeModeFromRawOpts rawopts = lastDef Close $ collectopts (\(name,_) -> readMay (capitalise name)) rawopts |
| 71 |
|
| 72 |
-- Debugger, beware: close is incredibly devious; simple rules combine to make a horrid maze. |
| 73 |
-- Tests are in hledger/test/close.test. |
| 74 |
close CliOpts{rawopts_=rawopts, reportspec_=rspec0} j = do |
| 75 |
let |
| 76 |
mode_ = closeModeFromRawOpts rawopts |
| 77 |
defacctsq_ = if mode_ == Retain then Type [Revenue, Expense] else Type [Asset, Liability] |
| 78 |
defcloseacct_ = if mode_ == Retain then defretainacct else defcloseacct |
| 79 |
closeacct = T.pack $ fromMaybe defcloseacct_ $ maybestringopt "close-acct" rawopts |
| 80 |
openacct = maybe closeacct T.pack $ maybestringopt "open-acct" rawopts |
| 81 |
|
| 82 |
-- For easy matching and exclusion, a recognisable tag is added to all generated transactions |
| 83 |
tagval = fromMaybe "" $ maybestringopt modeflag rawopts where modeflag = lowercase $ show mode_ |
| 84 |
comment = T.pack $ if |
| 85 |
| mode_ == Assert -> "assert:" <> tagval |
| 86 |
| mode_ == Assign -> "assign:" <> tagval |
| 87 |
| mode_ == Retain -> "retain:" <> tagval |
| 88 |
| otherwise -> "clopen:" <> if null tagval then inferredval else tagval |
| 89 |
where |
| 90 |
inferredval = newfilebasename |
| 91 |
where |
| 92 |
oldfilebasename = takeBaseName $ journalFilePath j |
| 93 |
(nonnum, rest) = break isDigit $ reverse oldfilebasename |
| 94 |
(oldnum, rest2) = span isDigit rest |
| 95 |
newfilebasename = case oldnum of |
| 96 |
[] -> "" |
| 97 |
_ -> reverse rest2 <> newnum <> reverse nonnum |
| 98 |
where |
| 99 |
newnum = show $ 1 + readDef err (reverse oldnum) -- PARTIAL: should not fail |
| 100 |
where err = error' $ "could not read " <> show oldnum <> " as a number in Hledger.Cli.Commands.Close.close" |
| 101 |
|
| 102 |
ropts = (_rsReportOpts rspec0){balanceaccum_=Historical, accountlistmode_=ALFlat} |
| 103 |
rspec1 = setDefaultConversionOp NoConversionOp rspec0{_rsReportOpts=ropts} |
| 104 |
|
| 105 |
-- Dates of the closing and opening transactions. |
| 106 |
-- "The default closing date is yesterday, or the journal's end date, whichever is later. |
| 107 |
-- You can change this by specifying a [report end date](#report-start--end-date) with `-e`. |
| 108 |
-- The last day of the report period will be the closing date, eg `-e 2024` means "close on 2023-12-31". |
| 109 |
-- The opening date is always the day after the closing date." |
| 110 |
argsq = _rsQuery rspec1 |
| 111 |
yesterday = addDays (-1) $ _rsDay rspec1 |
| 112 |
yesterdayorjournalend = case journalLastDay False j of |
| 113 |
Just journalend -> max yesterday journalend |
| 114 |
Nothing -> yesterday |
| 115 |
mreportlastday = addDays (-1) <$> queryEndDate False argsq |
| 116 |
closedate = fromMaybe yesterdayorjournalend mreportlastday |
| 117 |
opendate = addDays 1 closedate |
| 118 |
|
| 119 |
-- should we show the amount(s) on the equity posting(s) ? |
| 120 |
explicit = boolopt "explicit" rawopts |
| 121 |
|
| 122 |
-- the accounts to close |
| 123 |
argsacctq = filterQuery (\q -> queryIsAcct q || queryIsType q) argsq |
| 124 |
q2 = if queryIsNull argsacctq then And [argsq, defacctsq_] else argsq |
| 125 |
-- always exclude the balancing equity account |
| 126 |
q3 = And [q2, Not $ Acct $ accountNameToAccountOnlyRegex closeacct] |
| 127 |
-- the balances to close |
| 128 |
rspec3 = rspec1{_rsQuery=q3} |
| 129 |
(acctbals',_) = balanceReport rspec3 j |
| 130 |
acctbals = map (\(a,_,_,b) -> (a, if show_costs_ ropts then b else mixedAmountStripCosts b)) acctbals' |
| 131 |
totalamt = maSum $ map snd acctbals |
| 132 |
|
| 133 |
-- since balance assertion amounts are required to be exact, the |
| 134 |
-- amounts in opening/closing transactions should be too (#941, #1137) |
| 135 |
precise = amountSetFullPrecision |
| 136 |
|
| 137 |
-- interleave equity postings next to the corresponding closing posting, or put them all at the end ? |
| 138 |
interleaved = boolopt "interleaved" rawopts |
| 139 |
|
| 140 |
-- a balance assertion template of the right type |
| 141 |
assertion = |
| 142 |
case maybestringopt "assertion-type" rawopts >>= parseBalanceAssertionType of |
| 143 |
Nothing -> nullassertion |
| 144 |
Just (total, inclusive) -> nullassertion{batotal=total, bainclusive=inclusive} |
| 145 |
|
| 146 |
-- the closing (balance-asserting or balance-zeroing) transaction |
| 147 |
mclosetxn |
| 148 |
| mode_ `notElem` [Clopen, Close, Assert, Retain] = Nothing |
| 149 |
| otherwise = Just nulltransaction{ |
| 150 |
tdate=closedate, tdescription=closedesc, tcomment=comment, tpostings=closeps |
| 151 |
} |
| 152 |
where |
| 153 |
closedesc = T.pack $ fromMaybe defclosedesc_ $ maybestringopt "close-desc" rawopts |
| 154 |
where |
| 155 |
defclosedesc_ |
| 156 |
| mode_ == Retain = defretaindesc |
| 157 |
| mode_ == Assert = "assert balances" |
| 158 |
| otherwise = defclosedesc |
| 159 |
closeps |
| 160 |
-- XXX some duplication |
| 161 |
| mode_ == Assert = |
| 162 |
[ posting{ |
| 163 |
paccount = a |
| 164 |
,pamount = mixedAmount $ precise b{aquantity=0, acost=Nothing} |
| 165 |
-- after each commodity's last posting, assert 0 balance (#1035) |
| 166 |
-- balance assertion amounts are unpriced (#824) |
| 167 |
,pbalanceassertion = |
| 168 |
if islast |
| 169 |
then Just assertion{baamount=precise b} |
| 170 |
else Nothing |
| 171 |
} |
| 172 |
| -- get the balances for each commodity and transaction price |
| 173 |
(a,mb) <- acctbals |
| 174 |
, let bs0 = amounts mb |
| 175 |
-- mark the last balance in each commodity with True |
| 176 |
, let bs2 = concat [reverse $ zip (reverse bs1) (True : repeat False) |
| 177 |
| bs1 <- groupBy ((==) `on` acommodity) bs0] |
| 178 |
, (b, islast) <- bs2 |
| 179 |
] |
| 180 |
|
| 181 |
| otherwise = |
| 182 |
concat [ |
| 183 |
posting{paccount = a |
| 184 |
,pamount = mixedAmount . precise $ negate b |
| 185 |
-- after each commodity's last posting, assert 0 balance (#1035) |
| 186 |
-- balance assertion amounts are unpriced (#824) |
| 187 |
,pbalanceassertion = |
| 188 |
if islast |
| 189 |
then Just assertion{baamount=precise b{aquantity=0, acost=Nothing}} |
| 190 |
else Nothing |
| 191 |
} |
| 192 |
|
| 193 |
-- maybe an interleaved posting transferring this balance to equity |
| 194 |
: [posting{paccount=closeacct, pamount=mixedAmount $ precise b} | interleaved] |
| 195 |
|
| 196 |
| -- get the balances for each commodity and transaction price |
| 197 |
(a,mb) <- acctbals |
| 198 |
, let bs0 = amounts mb |
| 199 |
-- mark the last balance in each commodity with True |
| 200 |
, let bs2 = concat [reverse $ zip (reverse bs1) (True : repeat False) |
| 201 |
| bs1 <- groupBy ((==) `on` acommodity) bs0] |
| 202 |
, (b, islast) <- bs2 |
| 203 |
] |
| 204 |
|
| 205 |
-- or a final multicommodity posting transferring all balances to equity |
| 206 |
-- (print will show this as multiple single-commodity postings) |
| 207 |
++ [posting{paccount=closeacct, pamount=if explicit then mixedAmountSetFullPrecision totalamt else missingmixedamt} | not interleaved] |
| 208 |
|
| 209 |
-- the opening (balance-assigning or balance-unzeroing) transaction |
| 210 |
mopentxn |
| 211 |
| mode_ `notElem` [Clopen, Open, Assign] = Nothing |
| 212 |
| otherwise = Just nulltransaction{ |
| 213 |
tdate=opendate, tdescription=opendesc, tcomment=comment, tpostings=openps |
| 214 |
} |
| 215 |
where |
| 216 |
opendesc = T.pack $ fromMaybe defopendesc $ maybestringopt "open-desc" rawopts |
| 217 |
openps |
| 218 |
| mode_ == Assign = |
| 219 |
[ posting{paccount = a |
| 220 |
,pamount = missingmixedamt |
| 221 |
,pbalanceassertion = Just assertion{baamount=b} |
| 222 |
-- case mcommoditysum of |
| 223 |
-- Just s -> Just nullassertion{baamount=precise s} |
| 224 |
-- Nothing -> Nothing |
| 225 |
} |
| 226 |
|
| 227 |
| (a,mb) <- acctbals |
| 228 |
, let bs0 = amounts mb |
| 229 |
-- mark the last balance in each commodity with the unpriced sum in that commodity (for a balance assertion) |
| 230 |
, let bs2 = concat [reverse $ zip (reverse bs1) (Just commoditysum : repeat Nothing) |
| 231 |
| bs1 <- groupBy ((==) `on` acommodity) bs0 |
| 232 |
, let commoditysum = (sum bs1)] |
| 233 |
, (b, _mcommoditysum) <- bs2 |
| 234 |
] |
| 235 |
++ [posting{paccount=openacct, pamount=if explicit then mixedAmountSetFullPrecision (maNegate totalamt) else missingmixedamt} | not interleaved] |
| 236 |
|
| 237 |
| otherwise = |
| 238 |
concat [ |
| 239 |
posting{paccount = a |
| 240 |
,pamount = mixedAmount $ precise b |
| 241 |
,pbalanceassertion = |
| 242 |
case mcommoditysum of |
| 243 |
Just s -> Just assertion{baamount=precise s{acost=Nothing}} |
| 244 |
Nothing -> Nothing |
| 245 |
} |
| 246 |
: [posting{paccount=openacct, pamount=mixedAmount . precise $ negate b} | interleaved] |
| 247 |
|
| 248 |
| (a,mb) <- acctbals |
| 249 |
, let bs0 = amounts mb |
| 250 |
-- mark the last balance in each commodity with the unpriced sum in that commodity (for a balance assertion) |
| 251 |
, let bs2 = concat [reverse $ zip (reverse bs1) (Just commoditysum : repeat Nothing) |
| 252 |
| bs1 <- groupBy ((==) `on` acommodity) bs0 |
| 253 |
, let commoditysum = (sum bs1)] |
| 254 |
, (b, mcommoditysum) <- bs2 |
| 255 |
] |
| 256 |
++ [posting{paccount=openacct, pamount=if explicit then mixedAmountSetFullPrecision (maNegate totalamt) else missingmixedamt} | not interleaved] |
| 257 |
|
| 258 |
-- print them |
| 259 |
-- allow user-specified rounding with --round, like print |
| 260 |
let styles = amountStylesSetRoundingFromRawOpts rawopts $ journalCommodityStyles j |
| 261 |
maybe (pure ()) (T.putStr . showTransaction . styleAmounts styles) mclosetxn |
| 262 |
maybe (pure ()) (T.putStr . showTransaction . styleAmounts styles) mopentxn |
| 263 |
|