hledger-lib
Safe HaskellNone
LanguageGHC2021

Hledger.Data.Journal

Description

A Journal is a set of transactions, plus optional related data. This is hledger's primary data object. It is usually parsed from a journal file or other data format (see Hledger.Read).

Synopsis

Parsing helpers

type JournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text m) a Source #

A parser of text that runs in some monad, keeping a Journal as state.

type ErroringJournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a Source #

A parser of text that runs in some monad, keeping a Journal as state, that can throw an exception to end parsing, preventing further parser backtracking.

addJournalItem :: JournalItem -> Journal -> Journal Source #

Add a journal item, evaluated first (its fields are strict) so no parse-time thunks are retained. Consecutive blank line items are collapsed into one.

addTransactionItem :: Transaction -> Journal -> Journal Source #

Add a transaction parsed from a journal file, and a placeholder item for it. Any comment lines immediately preceding it (the JIComment items on top of jitems) are moved into the transaction's tprecedingcomment.

journalDbg :: Journal -> String Source #

journalInferMarketPricesFromTransactions :: Journal -> Journal Source #

Infer transaction-implied market prices from commodity-exchanging transactions, if any. It's best to call this after transactions have been balanced and posting amounts have appropriate prices attached.

journalApplyCommodityAliases :: Journal -> Either String Journal Source #

Convert all amounts written in a commodity alias to the commodity it is an alias of. For an alias with a quantity (other than 1), amount quantities are divided by it, and unit costs, cost bases and market prices of the alias are multiplied by it (but if an amount or its unit cost converts inexactly, the unit cost is replaced by the exact total cost). This is done for posting amounts, with their costs, cost bases and balance assertions; periodic transaction and auto posting rules (whose multipliers' symbols are just renamed); and price directives. A converted posting keeps its original form in poriginal, for print.

Returns Left with a verbose error if the same alias is declared on more than one commodity, or if an alias is also declared as a commodity with aliases of its own.

type CommodityAliases = Map CommoditySymbol (CommoditySymbol, Quantity, Maybe AmountStyle) Source #

Commodity aliases: each alias symbol, with its commodity, its quantity (the number of alias units equal to one unit of the commodity), and the commodity's display style if known.

journalCommodityAliases :: Journal -> CommodityAliases Source #

The commodity aliases declared in this journal.

convertAliasAmount :: CommodityAliases -> Amount -> (Amount, Quantity) Source #

Convert an amount written in one of these commodity aliases to its commodity, also returning the alias quantity (or 1). The converted amount gets the commodity's display style. For a plain alias, it keeps its display precision; for an alias with a quantity, it gets the commodity's display precision (or more, if needed to show an exactly converted amount fully; or if that's unknown, all its decimal places up to 8).

commodityAliases :: Commodity -> [CommoditySymbol] Source #

Aliases declared on a commodity directive by its alias: tags.

commodityRedeclare :: Commodity -> Commodity -> Commodity Source #

Update a commodity's declaration with a later declaration of it, in the same file tree. The later declaration adds to the earlier one rather than replacing it: aliases are combined, a display style replaces the earlier one only if the later declaration has one, and the later tags come first (so they win, for tags looked up by their first value). The comment and source position are the later declaration's.

commodityCombine :: Commodity -> Commodity -> Commodity Source #

Combine two declarations of a commodity from different journals (file trees, or a file and its included file), the first being the later one. Like commodityRedeclare, this keeps the later one's comment, source position, and display style if it has one, and the aliases (in reading order) and tags (the later one's first) of both.

commoditiesAndAliases :: Journal -> Set CommoditySymbol Source #

All commodity symbols that this journal treats as declared: both the canonical jdeclaredcommodities keys and any 'alias:' values declared on those commodity directives.

journalInferCommodityStyles :: Journal -> Either String Journal Source #

Collect and save inferred amount styles for each commodity based on P directive amounts, posting amounts but not cost amounts, and maybe the last D amount, in that commodity. Styles inferred previously for commodities which no longer appear in these are kept (eg for commodity aliases, whose amounts have been converted, so that print can show them as written). Can return an error message eg if inconsistent number formats are found.

journalStyleAmounts :: Journal -> Either String Journal Source #

Apply this journal's commodity display styles to all of its posting amounts. This does no display rounding, keeping decimal digits as they were; it is suitable for an early cleanup pass before calculations. Reports may want to do additional rounding/styling at render time. Price directives' amounts are left as written (though they still influence the inferred styles), so that error messages and get's rewritten price files show them that way; commands which list prices, like prices and print, style them when rendering. This can return an error message eg if inconsistent number formats are found.

journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle Source #

Get the canonical amount styles for this journal, whether (in order of precedence): set globally in InputOpts, declared by commodity directives, declared by a default commodity (D) directive, or inferred from posting amounts, as a map from symbol to style. Styles from directives are assumed to specify the decimal mark.

journalCommodityStylesWith :: Rounding -> Journal -> Map CommoditySymbol AmountStyle Source #

Like journalCommodityStyles, but attach a particular rounding strategy to the styles, affecting how they will affect display precisions when applied.

journalToCost :: ConversionOp -> Journal -> Journal Source #

Convert all this journal's amounts to cost using their attached prices, if any.

journalInferEquityFromCosts :: Bool -> Journal -> Journal Source #

Add equity postings inferred from costs, where needed and possible. See hledger manual > Cost reporting.

journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either String Journal Source #

Identify and tag (1) equity conversion postings and (2) postings which have (or could have ?) redundant costs. And if the addcosts flag is true, also add any costs which can be inferred from equity conversion postings. This is always called before transaction balancing to tag the redundant-cost postings so they can be ignored. With --infer-costs, it is called again after transaction balancing (when it has more information to work with) to infer costs from equity postings. See transactionTagCostsAndEquityAndMaybeInferCosts for more details, and hledger manual > Cost reporting for more background.

journalReverse :: Journal -> Journal Source #

Reverse all lists of parsed items, which during parsing were prepended to, so that the items are in parse order. Part of post-parse finalisation.

journalSetLastReadTime :: POSIXTime -> Journal -> Journal Source #

Set this journal's last read time, ie when its files were last read.

journalRenumberAccountDeclarations :: Journal -> Journal Source #

Renumber all the account declarations. This is useful to call when finalising or concatenating Journals, to give account declarations a total order across files.

journalPivot :: Text -> Journal -> Journal Source #

Apply the pivot transformation to all postings in a journal, replacing their account name by their value for the given field or tag.

journalPostingsAddAccountTags :: Journal -> Journal Source #

To all postings in the journal, add any tags from their account (including those inherited from parent accounts). Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output). If a tag already exists on the posting, it is not changed (the account tag will be ignored).

journalPostingsKeepAccountTagsOnly :: Journal -> Journal Source #

Remove all tags from the journal's postings except those provided by their account. This is useful for the accounts report. It does not remove tag declarations from the posting comments.

journalPostingsAddCommodityTags :: Journal -> Journal Source #

To all postings in the journal, add any tags from their amount's commodities. Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output). If a tag already exists on the posting, it is not changed (the commodity tag will be ignored).

journalInferPostingsTransactedCost :: Journal -> Journal Source #

For lot-opening postings with a cost basis (positive; or negative in a liability account, which holds short lots), which don't look like lot transfer destinations, infer transacted cost from cost basis. This runs before transaction balancing (the inferred cost lets an acquire entry with an elided cash amount balance at cost), so lot classification hasn't happened yet; transfer destinations - which must not get a transacted cost - are recognised by shape: a positive cost-basis posting is skipped when the transaction has an explicit negative amount of the same commodity and quantity in another account, or unpriced in the same account (a transfer-from counterpart), or the commodity's unpriced negative and positive quantities sum to matching totals (a split or consolidating transfer group, possibly minus a fee), or an equity posting with no cost-basis amounts (an equity transfer, eg close --clopen --lots style opening balances).

journalCommodityUsesLots :: Journal -> CommoditySymbol -> Bool Source #

Does this commodity have a 'lots:' tag declared ?

journalAccountUsesNoLots :: Journal -> AccountName -> Bool Source #

Does this account opt out of lot tracking, via a NONE-valued lots: tag on its own or an ancestor's declaration ? The nearest declaration wins, so a subaccount can re-enable tracking with its own lots: method tag. Postings with explicit cost basis annotations are still lot-tracked regardless (the more specific declaration wins).

journalAccountLotsTags :: Journal -> Map AccountName Text Source #

The declared lots: tag values by account (the first value, if an account somehow has several).

accountUsesNoLotsWith :: Map AccountName Text -> AccountName -> Bool Source #

Like journalAccountUsesNoLots, but taking the journalAccountLotsTags map (useful where no Journal is at hand, eg during balancing).

journalLotfulCommodities :: Journal -> Set CommoditySymbol Source #

All commodities with a 'lots:' tag declared.

journalCommodityLotsMethod :: Journal -> CommoditySymbol -> Maybe ReductionMethod Source #

Get the reduction method from a commodity's lots: tag value, if any.

postingLotsMethod :: Posting -> Maybe ReductionMethod Source #

Get the reduction method from a posting's lots: tag value (typically inherited from its account), if any.

parseReductionMethod :: Text -> Maybe ReductionMethod Source #

Parse a reduction method name from a lots: tag value.

journalCheckLotsTagValues :: Journal -> Either String Journal Source #

Check that all lots: tag values on commodity and account declarations are recognised. On a commodity declaration, an empty value (bare lots: tag) is valid, declaring the commodity lotful with the default FIFO reduction method; a non-empty value must be one of the known reduction methods. On an account declaration, the tag only sets the reduction method for lotful commodities in that account, so a method value is required.

Filtering

filterJournalTransactions :: Query -> Journal -> Journal Source #

Keep only transactions matching the query expression.

filterJournalPostings :: Query -> Journal -> Journal Source #

Keep only postings matching the query expression. This can leave unbalanced transactions.

filterJournalRelatedPostings :: Query -> Journal -> Journal Source #

Keep only postings which do not match the query expression, but for which a related posting does. This can leave unbalanced transactions.

filterJournalAmounts :: Query -> Journal -> Journal Source #

Within each posting's amount, keep only the parts matching the query, and remove any postings with all amounts removed. This can leave unbalanced transactions.

filterTransactionAmounts :: Query -> Transaction -> Transaction Source #

Filter out all parts of this transaction's amounts which do not match the query, and remove any postings with all amounts removed. This can leave the transaction unbalanced.

filterPostingAmount :: Query -> Posting -> Maybe Posting Source #

Filter out all parts of this posting's amount which do not match the query, and remove the posting if this removes all amounts.

Mapping

journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal Source #

Apply a transformation to a journal's transactions.

journalMapPostings :: (Posting -> Posting) -> Journal -> Journal Source #

Apply a transformation to a journal's postings.

journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal Source #

Apply a transformation to a journal's posting amounts.

Querying

journalAccountNamesUsed :: Journal -> [AccountName] Source #

Sorted unique account names posted to by this journal's transactions.

journalAccountNamesImplied :: Journal -> [AccountName] Source #

Sorted unique account names implied by this journal's transactions - accounts posted to and all their implied parent accounts.

journalAccountNamesDeclared :: Journal -> [AccountName] Source #

Sorted unique account names declared by account directives in this journal.

journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName] Source #

Sorted unique account names declared by account directives or posted to by transactions in this journal.

journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName] Source #

Sorted unique account names declared by account directives, or posted to or implied as parents by transactions in this journal.

journalAccountNames :: Journal -> [AccountName] Source #

Convenience/compatibility alias for journalAccountNamesDeclaredOrImplied.

journalLeafAccountNames :: Journal -> [AccountName] Source #

Sorted unique account names declared or implied in this journal which have no children.

journalAccountTags :: Journal -> AccountName -> [Tag] Source #

Which tags have been declared explicitly for this account, if any ?

journalCommodityTags :: Journal -> CommoditySymbol -> [Tag] Source #

Get any tags declared for this commodity.

journalInheritedAccountTags :: Journal -> AccountName -> [Tag] Source #

Which tags are in effect for this account, including tags inherited from parent accounts ?

journalPayeesDeclared :: Journal -> [Payee] Source #

Sorted unique payees declared by payee directives in this journal.

journalPayeesUsed :: Journal -> [Payee] Source #

Sorted unique payees used by transactions in this journal.

journalPayeesDeclaredOrUsed :: Journal -> [Payee] Source #

Sorted unique payees used in transactions or declared by payee directives in this journal.

journalTagsDeclared :: Journal -> [TagName] Source #

Sorted unique tag names declared by tag directives in this journal.

journalTagsUsed :: Journal -> [TagName] Source #

Sorted unique tag names used in this journal (in account directives, transactions, postings..)

journalTagsDeclaredOrUsed :: Journal -> [TagName] Source #

Sorted unique tag names used in transactions or declared by tag directives in this journal.

journalAmounts :: Journal -> Set Amount Source #

All raw amounts appearing in this journal, with MixedAmounts flattened, in no particular order. (Including from posting amounts, cost amounts, P directives, and the last D directive.)

journalPostingAmounts :: Journal -> [MixedAmount] Source #

All posting amounts from this journal, in order.

journalPostingAndCostAmounts :: Journal -> [Amount] Source #

All raw amounts used in this journal's postings and costs, with MixedAmounts flattened, in parse order.

journalCommoditiesDeclared :: Journal -> [CommoditySymbol] Source #

Sorted unique commodity symbols declared by commodity directives in this journal.

journalCommoditiesUsed :: Journal -> [CommoditySymbol] Source #

Sorted unique commodity symbols used anywhere in this journal, including commodity directives, P directives, the last D directive, posting amounts and cost amounts.

journalCommodities :: Journal -> Set CommoditySymbol Source #

Sorted unique commodity symbols mentioned anywhere in this journal. (Including commodity directives, P directives, the last D directive, posting amounts and cost amounts.)

journalCommoditiesFromPriceDirectives :: Journal -> Set CommoditySymbol Source #

Sorted unique commodity symbols mentioned in this journal's P directives.

journalCommoditiesFromTransactions :: Journal -> Set CommoditySymbol Source #

Sorted unique commodity symbols used in transactions, in either posting or cost amounts.

journalBaseCurrency :: Journal -> Maybe (CommoditySymbol, CurrencyCode) Source #

Guess a base currency for this journal: Just the commodity symbol as used in the journal, and its ISO 4217 currency code if one is known (otherwise the symbol again), choosing as follows: 1. The "to" commodity that appears most often in P (price) directives, if any. 2. Otherwise, the commodity that appears most often in posting and cost amounts. 3. Otherwise, Nothing. Commodity symbols are normalised to ISO 4217 codes where possible, so that equivalent symbols are tallied together; the symbol returned is the first-occurring one that normalises to the winning code. Ties are broken by first occurrence order.

journalBaseCurrencyCode :: Journal -> CurrencyCode Source #

The ISO 4217 currency code of this journal's guessed base currency (journalBaseCurrency), defaulting to USD.

journalDateSpan :: Bool -> Journal -> DateSpan Source #

The fully specified exact date span enclosing the dates (primary or secondary) of all this journal's transactions and postings, or DateSpan Nothing Nothing if there are none.

journalDateSpanBothDates :: Journal -> DateSpan Source #

The fully specified date span enclosing the dates (primary and secondary) of all this journal's transactions and postings, or DateSpan Nothing Nothing if there are none.

journalStartDate :: Bool -> Journal -> Maybe Day Source #

The earliest of this journal's transaction and posting dates, or Nothing if there are none.

journalEndDate :: Bool -> Journal -> Maybe Day Source #

The "exclusive end date" of this journal: the day following its latest transaction or posting date, or Nothing if there are none.

journalLastDay :: Bool -> Journal -> Maybe Day Source #

The latest of this journal's transaction and posting dates, or Nothing if there are none.

journalDescriptions :: Journal -> [Text] Source #

Unique transaction descriptions used in this journal.

journalFilePaths :: Journal -> [FilePath] Source #

journalAllFilePaths :: Journal -> [FilePath] Source #

All the files this journal's data was read from: its data files (journalFilePaths) and any auxiliary files such as CSV rules files (jauxfiles). These are the files to watch for changes when reloading. Each file is listed once, even if it was read more than once (eg a file included twice, or a rules file used by several CSV files).

journalTransactionAt :: Journal -> Integer -> Maybe Transaction Source #

Get the transaction with this index (its 1-based position in the input stream), if any.

journalNextTransaction :: Journal -> Transaction -> Maybe Transaction Source #

Get the transaction that appeared immediately after this one in the input stream, if any.

journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction Source #

Get the transaction that appeared immediately before this one in the input stream, if any.

journalPostings :: Journal -> [Posting] Source #

All postings from this journal's transactions, in order.

showJournalPostingAmountsDebug :: Journal -> String Source #

Show the journal posting amounts rendered, suitable for debug logging.

journalTransactionsSimilarTo :: Journal -> Day -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, TimeDistance, SimilarityScore, Transaction)] Source #

Find up to N most similar and nearest-dated transactions matching the given transaction description and query and exceeding the given description similarity score (0 to 1, see compareDescriptions). The provided Day (today) is used as the reference date; transactions are penalised by their absolute distance from it in days (both past and future). Returns transactions along with their distance in days from today, their description similarity score, and a heuristically date-weighted variant of this that favours nearby transactions.

Account types

journalAccountTypes :: Journal -> Map AccountName AccountType Source #

Build a map of all known account types, explicitly declared or inferred from the account's parent or name.

journalAddAccountTypes :: Journal -> Journal Source #

Add a map of all known account types to the journal.

Conversion accounts

journalAccountForType :: AccountName -> AccountType -> Journal -> AccountName Source #

The account name to use for postings which hledger generates to an account of the given type: the first account declared with that type (by a type: tag), in declaration order; or if there is none, the alphabetically first account which has that type (inferred from its name, or a parent's); or if there is none, the given default account name.

journalBaseConversionAccount :: Journal -> AccountName Source #

The account name to use for conversion postings generated by --infer-equity (see journalAccountForType; the default is equity:conversion).

journalConversionAccounts :: Journal -> [AccountName] Source #

All the accounts in this journal which are declared or inferred as V/Conversion type. This does not include new account names which might be generated by --infer-equity, currently.

Gain accounts

defaultGainAccount :: IsString a => a Source #

journalBaseGainAccount :: Journal -> AccountName Source #

The account name to use for inferred gain postings (see journalAccountForType; the default is revenues:gain).

journalGainAccounts :: Journal -> [AccountName] Source #

All the accounts in this journal which are declared or inferred as G/Gain type, alphabetically.

Misc

journalConcat :: Journal -> Journal -> Journal Source #

Merge two journals into one. Transaction counts are summed, map fields are combined, the second's list fields are appended to the first's, the second's parse state is kept.

journalNumberTransactions :: Journal -> Journal Source #

Number (set the tindex field) this journal's transactions, counting upward from 1.

journalNumberAndTieTransactions :: Journal -> Journal Source #

Number this journal's transactions, counting upward from 1, and tie their knots, so that their postings refer to the renumbered transactions. If they are already numbered that way, the journal is returned unchanged (avoiding a new copy of every transaction).

journalTieTransactions :: Journal -> Journal Source #

Tie the knot in all of this journal's transactions, ensuring their postings refer to them. This should be done last, after any other transaction-modifying operations.

journalUntieTransactions :: Transaction -> Transaction Source #

Untie all transaction-posting knots in this journal, so that eg recursiveSize and GHCI's :sprint can work on it.

journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal Source #

Apply any transaction modifier rules in the journal (adding automated postings to transactions, eg). Or if a modifier rule fails to parse, return the error message. A reference date is provided to help interpret relative dates in transaction modifier queries. The first argument selects whether to add visible tags to generated postings & modified transactions.

journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal Source #

Apply some account aliases to all posting account names in the journal, as described by accountNameApplyAliases. This can fail due to a bad replacement pattern in a regular expression alias.

dbgJournalAcctDeclOrder :: String -> Journal -> Journal Source #

Debug log the ordering of a journal's account declarations (at debug level 7+).

Tests

Orphan instances

Default Journal Source # 
Instance details

Methods

def :: Journal

Semigroup Journal Source # 
Instance details

Methods

(<>) :: Journal -> Journal -> Journal

sconcat :: NonEmpty Journal -> Journal

stimes :: Integral b => b -> Journal -> Journal

Show AssertDirective Source # 
Instance details

Methods

showsPrec :: Int -> AssertDirective -> ShowS

show :: AssertDirective -> String

showList :: [AssertDirective] -> ShowS

Show Journal Source # 
Instance details

Methods

showsPrec :: Int -> Journal -> ShowS

show :: Journal -> String

showList :: [Journal] -> ShowS