Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
361 changes: 361 additions & 0 deletions doc/PLAN-balance-change-queries.md

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions hledger-lib/Hledger/Data/Balancing.hs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module Hledger.Data.Balancing
, balanceSingleTransaction
, balanceTransactionHelper
, transactionBalanceError
, transactionBalancingSum
, roundedPostingTagName
, transactionRoundCalculatedAmounts
, postingRoundCalculatedAmounts
Expand Down Expand Up @@ -224,6 +225,14 @@ postingBalancingAmountWith setaside p
| setaside p = nullmixedamt
| otherwise = mixedAmountCost $ pamount p

-- | The sum of all of this transaction's postings, converted to cost as when balancing it,
-- including any unbalanced virtual postings. For a balanced transaction this is zero
-- (or a tolerated imbalance; see transactionCheckBalanced) plus the unbalanced virtual postings' amounts.
-- This is the amount a sum: query tests for a transaction.
transactionBalancingSum :: Transaction -> MixedAmount
transactionBalancingSum t = foldMap (postingBalancingAmountWith setaside) $ tpostings t
where setaside = isSetAsideGainPosting t

-- | Postings which would show this balanced transaction's remaining imbalance
-- (tolerated because it's smaller than the balancing precision; see transactionCheckBalanced),
-- making the transaction balance exactly. These are postings to the given account,
Expand Down
243 changes: 226 additions & 17 deletions hledger-lib/Hledger/Query.hs

Large diffs are not rendered by default.

45 changes: 26 additions & 19 deletions hledger-lib/Hledger/Reports/AccountTransactionsReport.hs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,14 @@ accountTransactionsReportWithStart rspec@ReportSpec{_rsReportOpts=ropts} j thisa
| balanceaccum_ ropts /= Historical = (1, nullmixedamt)
| average_ ropts = (numpriorts + 1, divideMixedAmount (fromIntegral numpriorts) priorsum)
| otherwise = (numpriorts + 1, priorsum)
-- The account's postings before the report start, and their sum: the balance brought forward
-- in historical mode, and the starting point for the real balances tested by balance: query terms.
priorpss = dbg5 "priorpss" . filter (not . null) . map (filter hasAmount . tpostings) . jtxns $
filterJournalPostings priorq acctJournal
numpriorts = length priorpss
priorsum = sumPostings $ concat priorpss
priorq = dbg5 "priorq" $ And [thisacctq, tostartdateq, datelessreportq]
where
priorpss = dbg5 "priorpss" . filter (not . null) . map (filter hasAmount . tpostings) . jtxns $
filterJournalPostings priorq acctJournal
numpriorts = length priorpss
priorsum = sumPostings $ concat priorpss
priorq = dbg5 "priorq" $ And [thisacctq, tostartdateq, datelessreportq]
-- The postings before the report start, by whichever kind of date
-- the query's start date is: the report's kind if it has one,
-- else the other, so that a date2: term selects the prior postings
Expand All @@ -181,7 +183,7 @@ accountTransactionsReportWithStart rspec@ReportSpec{_rsReportOpts=ropts} j thisa
datelessreportq = filterQuery (not . queryIsDateOrDate2) reportq

items =
accountTransactionsReportItems reportq thisacctq (registerRunningCalculationFn ropts) startnum startbal maNegate (journalAccountType j)
accountTransactionsReportItems reportq (_rsRowQuery rspec) thisacctq (registerRunningCalculationFn ropts) startnum startbal priorsum maNegate (journalAccountType j)
-- sort by the transaction's register date, then index, for accurate starting balance
. dbg5With (("ts4:\n"++).pshowTransactions.map snd)
. sortBy (comparing (Down . fst) <> comparing (Down . tindex . snd))
Expand All @@ -193,29 +195,33 @@ pshowTransactions :: [Transaction] -> String
pshowTransactions = pshow . map (\t -> unwords [show $ tdate t, T.unpack $ tdescription t])

-- | Generate transactions report items from a list of transactions,
-- using the provided user-specified report query, a query specifying
-- using the provided user-specified report query, the report query's change:/balance:
-- terms (selecting items by their change to the account, or the account's real balance
-- after them; hidden items still count in the running total), a query specifying
-- which account to use as the focus, a running calculation function
-- (see registerRunningCalculationFn), the starting item number and
-- running total/average, and a sign-setting function.
-- (see registerRunningCalculationFn), the starting item number,
-- the running total/average and the real balance before the first item,
-- and a sign-setting function.
-- Each transaction is accompanied by the date that should be shown for it
-- in the report. This is not necessarily the transaction date - see
-- transactionRegisterDate.
accountTransactionsReportItems :: Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> Int -> MixedAmount -> (MixedAmount -> MixedAmount)
accountTransactionsReportItems :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> Int -> MixedAmount -> MixedAmount -> (MixedAmount -> MixedAmount)
-> (AccountName -> Maybe AccountType) -> [(Day, Transaction)]
-> [AccountTransactionsReportItem]
accountTransactionsReportItems reportq thisacctq runningcalc i bal signfn accttypefn =
catMaybes . snd . mapAccumR (accountTransactionsReportItem reportq thisacctq runningcalc signfn accttypefn) (i, bal)
accountTransactionsReportItems reportq rowq thisacctq runningcalc i bal realbal signfn accttypefn =
catMaybes . snd . mapAccumR (accountTransactionsReportItem reportq rowq thisacctq runningcalc signfn accttypefn) (i, bal, realbal)

accountTransactionsReportItem :: Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
accountTransactionsReportItem :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> (MixedAmount -> MixedAmount)
-> (AccountName -> Maybe AccountType) -> (Int, MixedAmount) -> (Day, Transaction)
-> ((Int, MixedAmount), Maybe AccountTransactionsReportItem)
accountTransactionsReportItem reportq thisacctq runningcalc signfn accttypefn (i, bal) (d, t)
-> (AccountName -> Maybe AccountType) -> (Int, MixedAmount, MixedAmount) -> (Day, Transaction)
-> ((Int, MixedAmount, MixedAmount), Maybe AccountTransactionsReportItem)
accountTransactionsReportItem reportq rowq thisacctq runningcalc signfn accttypefn (i, bal, realbal) (d, t)
-- 201407: I've lost my grip on this, let's just hope for the best
-- 201606: we now calculate change and balance from filtered postings, check this still works well for all callers XXX
| null reportps = ((i, bal), Nothing) -- no matched postings in this transaction, skip it
| otherwise = ((i + 1, bal'), Just (t, tacct{tdate=d}, numotheraccts > 1, otheraccts, amt, bal'))
| null reportps = ((i, bal, realbal), Nothing) -- no matched postings in this transaction, skip it
| not $ matchesRowAmounts rowq amt realbal' = ((i + 1, bal', realbal'), Nothing) -- its change/balance doesn't match the row terms: hide it, but count it
| otherwise = ((i + 1, bal', realbal'), Just (t, tacct{tdate=d}, numotheraccts > 1, otheraccts, amt, bal'))
where
tacct@Transaction{tpostings=reportps} = filterTransactionPostingsExtra accttypefn reportq t -- TODO needs to consider --date2, #1731
(thisacctps, otheracctps) = partition (matchesPosting thisacctq) reportps
Expand All @@ -231,6 +237,7 @@ accountTransactionsReportItem reportq thisacctq runningcalc signfn accttypefn (i
| null thisacctps = signfn $ sumPostings otheracctps
| otherwise = signfn . maNegate $ sumPostings thisacctps
bal' = runningcalc i bal amt
realbal' = if queryHasBalance rowq then maPlus realbal amt else nullmixedamt

-- TODO needs checking, cf #1731
-- | What date should be shown for a transaction in an account register report ?
Expand Down
27 changes: 23 additions & 4 deletions hledger-lib/Hledger/Reports/BudgetReport.hs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import Data.Bifunctor (bimap)
import Data.Foldable (toList)
import Data.List (find, maximumBy, intercalate)
import Data.Maybe (catMaybes, fromMaybe, isJust)
import Data.Map qualified as M
import Data.Ord (comparing)
import Data.Set qualified as S
import Data.Text qualified as T
Expand Down Expand Up @@ -84,7 +85,9 @@ budgetReport rspec bopts reportspan j = dbg4 "sortedbudgetreport" budgetreport

-- The report spec used for selecting budget goals, with the query terms
-- that describe actual transactions/postings dropped. (#2545)
budgetrspec = rspec{_rsQuery = budgetGoalQuery $ _rsQuery rspec}
-- The change:/balance: terms are applied below, to the combined rows.
budgetrspec = rspec{_rsQuery = budgetGoalQuery $ _rsQuery rspec, _rsRowQuery = Any}
actualrspec = rspec{_rsRowQuery = Any}

(_, actualspans) = dbg5 "actualspans" $ reportSpan actualj rspec
(_, budgetspans) = dbg5 "budgetspans" $ reportSpan budgetj budgetrspec
Expand All @@ -96,17 +99,33 @@ budgetReport rspec bopts reportspan j = dbg4 "sortedbudgetreport" budgetreport
(_, Nothing) -> actualspans
(_, Just bspan) -> unionDayPartitions bspan =<< actualspans

actualps = dbg5 "actualps" $ getPostings rspec actualj priceoracle reportspan
actualps = dbg5 "actualps" $ getPostings rspec actualj priceoracle reportspan -- rspec, so a balance: term fetches the earlier postings
budgetps = dbg5 "budgetps" $ getPostings budgetrspec budgetj priceoracle reportspan

actualAcct = dbg5 "actualAcct" $ generateMultiBalanceAccount rspec actualj priceoracle actualspans actualps
actualAcct = dbg5 "actualAcct" $ generateMultiBalanceAccount actualrspec actualj priceoracle actualspans actualps
budgetAcct = dbg5 "budgetAcct" $ generateMultiBalanceAccount budgetrspec budgetj priceoracle budgetspans budgetps

combinedAcct = dbg5 "combinedAcct" $ if null budgetps
combinedAcct = dbg5 "combinedAcct" . hideNonMatchingRows $ if null budgetps
-- If no budget postings, just use actual account, to avoid unnecssary budget zeros
then This <$> actualAcct
else mergeAccounts actualAcct budgetAcct

-- Apply the change:/balance: terms, if any, by hiding the rows whose actual change over the
-- report period, or actual balance at its end (including subaccounts), doesn't match.
-- Unlike other balance reports, this doesn't change the other rows or the totals,
-- since budget goals are often set on parent accounts.
hideNonMatchingRows
| queryIsNull rowq = id
| otherwise = mapAccounts $ \a -> if matches a then a else a{aboring = True}
where
rowq = _rsRowQuery rspec
matches a = uncurry (matchesRowAmounts rowq) $ inclusiveRowAmounts (aname a)
-- Each account's own change and end balance, from the actual postings (clipped as the report clips them),
inclusiveRowAmounts a = (maSum $ map fst amts, maSum $ map snd amts)
where amts = [cb | (n, cb) <- M.toList ownRowAmounts, n == a || (a <> ":") `T.isPrefixOf` n]
ownRowAmounts = accountRowAmounts rspec actualj priceoracle actualspans
[p{paccount = clipOrEllipsifyAccountName (queryDepth $ _rsQuery rspec) $ paccount p} | p <- actualps]

budgetreport = generateBudgetReport ropts allspans combinedAcct

-- | Reduce a report query to the terms which are meaningful for selecting budget goals:
Expand Down
8 changes: 6 additions & 2 deletions hledger-lib/Hledger/Reports/EntriesReport.hs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import Data.Ord (comparing)
import Data.Time (fromGregorian)

import Hledger.Data
import Hledger.Query (Query(..), filterQuery, queryIsDepth)
import Hledger.Query (Query(..), filterQuery, matchesRowAmounts, queryIsDepth, queryIsNull)
import Hledger.Reports.ReportOptions
import Hledger.Utils

Expand All @@ -39,12 +39,16 @@ entriesReport rspec@ReportSpec{_rsReportOpts=ropts} =
sortBy (comparing $ transactionDateFn ropts) . entriesReportUnsorted rspec

-- | Select transactions for an entries report, keeping their journal order.
-- The query's change: and balance: terms, if any, are both tested against each entry's sum of postings
-- (an entry has no balance), converted to cost as in transaction balancing (see 'transactionBalancingSum'),
-- regardless of valuation and --invert.
entriesReportUnsorted :: ReportSpec -> Journal -> EntriesReport
entriesReportUnsorted rspec@ReportSpec{_rsReportOpts=ropts} =
entriesReportUnsorted rspec@ReportSpec{_rsReportOpts=ropts, _rsRowQuery=rowq} =
map (if invert_ ropts then transactionNegate else id)
. jtxns
. journalApplyValuationFromOpts (setDefaultConversionOp NoConversionOp rspec)
. filterJournalTransactions (filterQuery (not.queryIsDepth) $ _rsQuery rspec)
. (if queryIsNull rowq then id else \j -> j{jtxns = filter (\t -> let s = transactionBalancingSum t in matchesRowAmounts rowq s s) $ jtxns j})

tests_EntriesReport = testGroup "EntriesReport" [
testGroup "entriesReport" [
Expand Down
Loading