-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/

-- | A library providing the core functionality of hledger
--   
--   This library contains hledger's core functionality. It is used by most
--   hledger* packages so that they support the same command line options,
--   file formats, reports, etc.
--   
--   hledger is a robust, cross-platform set of tools for tracking money,
--   time, or any other commodity, using double-entry accounting and a
--   simple, editable file format, with command-line, terminal and web
--   interfaces. It is a Haskell rewrite of Ledger, and one of the leading
--   implementations of Plain Text Accounting.
--   
--   See also:
--   
--   
--   
- https://hledger.org - hledger's home page
--   
- https://hledger.org/dev.html - starting point for hledger's
--   developer docs
--   
--   
- https://hackage.haskell.org/package/hledger-lib/docs/Hledger.html
--   - starting point for hledger's haddock docs
--   
@package hledger-lib
@version 1.52.1

-- | Currency names, symbols and codes. Reference: -
--   https://www.xe.com/symbols - https://www.xe.com/currency
module Hledger.Data.Currency
currencies :: [([Char], CurrencyCode, CurrencySymbol)]

-- | Look for a ISO 4217 currency code corresponding to this currency
--   symbol.
--   
--   
--   >>> currencySymbolToCode ""
--   Nothing
--   
--   >>> currencySymbolToCode "$"
--   Just "USD"
--   
currencySymbolToCode :: CurrencySymbol -> Maybe CurrencyCode

-- | Look for a currency symbol corresponding to this ISO 4217 currency
--   code.
--   
--   
--   >>> currencyCodeToSymbol "CZK"  -- Just "Kč"
--   Just "K\269"
--   
currencyCodeToSymbol :: CurrencyCode -> Maybe CurrencySymbol

-- | Easy regular expression helpers, currently based on regex-tdfa. These
--   should:
--   
--   
--   
- be cross-platform, not requiring C libraries
--   
- support unicode
--   
- support extended regular expressions
--   
- support replacement, with backreferences etc.
--   
- support splitting
--   
- have mnemonic names
--   
- have simple monomorphic types
--   
- work with simple strings
--   
--   
--   Regex strings are automatically compiled into regular expressions the
--   first time they are seen, and these are cached. If you use a huge
--   number of unique regular expressions this might lead to increased
--   memory usage. Several functions have memoised variants (*Memo), which
--   also trade space for time.
--   
--   Currently two APIs are provided:
--   
--   
--   
- The old partial one (with ' suffixes') which will call error on
--   any problem (eg with malformed regexps). This comes from hledger's
--   origin as a command-line tool.
--   
- The new total one which will return an error message. This is
--   better for long-running apps like hledger-web.
--   
--   
--   Current limitations:
--   
--   
--   
- (?i) and similar are not supported
--   
module Hledger.Utils.Regex

-- | Regular expression. Extended regular expression-ish syntax ? But does
--   not support eg (?i) syntax.
data Regexp
toRegex :: Text -> Either RegexError Regexp
toRegexCI :: Text -> Either RegexError Regexp
toRegex' :: Text -> Regexp
toRegexCI' :: Text -> Regexp

-- | A replacement pattern. May include numeric backreferences (N).
type Replacement = String

-- | An error message arising during a regular expression operation. Eg:
--   trying to compile a malformed regular expression, or trying to apply a
--   malformed replacement pattern.
type RegexError = String

-- | Test whether a Regexp matches a String. This is an alias for
--   matchTest for consistent naming.
regexMatch :: Regexp -> String -> Bool

-- | Tests whether a Regexp matches a Text.
--   
--   This currently unpacks the Text to a String, to work around a
--   performance bug in regex-tdfa (#9), which may or may not be relevant
--   here.
regexMatchText :: Regexp -> Text -> Bool

-- | Return a (possibly empty) list of match groups derived by applying the
--   Regex to a Text.
regexMatchTextGroups :: Regexp -> Text -> [Text]

-- | A memoising version of regexReplace. Caches the result for each search
--   pattern, replacement pattern, target string tuple. This won't generate
--   a regular expression parsing error since that is pre-compiled
--   nowadays, but there can still be a runtime error from the replacement
--   pattern, eg with a backreference referring to a nonexistent match
--   group.
regexReplace :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceAllBy :: Regexp -> (String -> String) -> String -> String
instance GHC.Classes.Eq Hledger.Utils.Regex.Regexp
instance Control.DeepSeq.NFData Hledger.Utils.Regex.Regexp
instance GHC.Classes.Ord Hledger.Utils.Regex.Regexp
instance GHC.Internal.Read.Read Hledger.Utils.Regex.Regexp
instance Text.Regex.Base.RegexLike.RegexContext Hledger.Utils.Regex.Regexp GHC.Internal.Base.String GHC.Internal.Base.String
instance Text.Regex.Base.RegexLike.RegexLike Hledger.Utils.Regex.Regexp GHC.Internal.Base.String
instance GHC.Internal.Show.Show Hledger.Utils.Regex.Regexp
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Utils.Regex.Regexp

-- | Most data types are defined here to avoid import cycles. Here is an
--   overview of the hledger data model:
--   
--   
--   Journal                  -- a journal is read from one or more data files. It contains..
--    [Transaction]           -- journal transactions (aka entries), which have date, cleared status, code, description and..
--     [Posting]              -- multiple account postings, which have account name and amount
--    [MarketPrice]           -- historical market prices for commodities
--   
--   Ledger                   -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..
--    Journal                 -- a filtered copy of the original journal, containing only the transactions and postings we are interested in
--    [Account]               -- all accounts, in tree order beginning with a "root" account", with their balances and sub/parent accounts
--   
--   
--   For more detailed documentation on each type, see the corresponding
--   modules.
module Hledger.Data.Types
data Side
L :: Side
R :: Side
type Tag = (TagName, TagValue)
data AccountType
Asset :: AccountType
Liability :: AccountType
Equity :: AccountType
Revenue :: AccountType
Expense :: AccountType

-- | a subtype of Asset - liquid assets to show in cashflow report
Cash :: AccountType

-- | a subtype of Equity - account with which to balance commodity
--   conversions
Conversion :: AccountType

-- | a subtype of Revenue - realised capital gains/losses
Gain :: AccountType

-- | a subtype of Equity - accumulated unrealised capital gains/losses
--   (used by hledger 2)
UnrealisedGain :: AccountType

-- | One of the standard *-separated value file types known by hledger,
data SepFormat
Csv :: SepFormat
Tsv :: SepFormat
Ssv :: SepFormat

-- | The status of a transaction or posting, recorded with a status mark
--   (nothing, !, or *). What these mean is ultimately user defined.
data Status
Unmarked :: Status
Pending :: Status
Cleared :: Status
data Period
DayPeriod :: Day -> Period
WeekPeriod :: Day -> Period
MonthPeriod :: Year -> Month -> Period
QuarterPeriod :: Year -> Quarter -> Period
YearPeriod :: Year -> Period
PeriodBetween :: Day -> Day -> Period
PeriodFrom :: Day -> Period
PeriodTo :: Day -> Period
PeriodAll :: Period
data SmartInterval
Day :: SmartInterval
Week :: SmartInterval
Month :: SmartInterval
Quarter :: SmartInterval
Year :: SmartInterval
type YearDay = Int
type Month = Int
type MonthDay = Int
data Interval
NoInterval :: Interval
Days :: Int -> Interval
Weeks :: Int -> Interval
Months :: Int -> Interval
Quarters :: Int -> Interval
Years :: Int -> Interval
NthWeekdayOfMonth :: Int -> Int -> Interval
MonthDay :: Int -> Interval
MonthAndDay :: Int -> Int -> Interval
DaysOfWeek :: [Int] -> Interval
type Quarter = Int

-- | Stores the CommoditySymbol of the Amount, along with the
--   CommoditySymbol of the cost, and its unit cost if being used.
data MixedAmountKey
MixedAmountKeyNoCost :: !CommoditySymbol -> MixedAmountKey
MixedAmountKeyTotalCost :: !CommoditySymbol -> !CommoditySymbol -> MixedAmountKey
MixedAmountKeyUnitCost :: !CommoditySymbol -> !CommoditySymbol -> !Quantity -> MixedAmountKey
newtype MixedAmount
Mixed :: Map MixedAmountKey Amount -> MixedAmount

-- | An account within a hierarchy, with references to its parent and
--   subaccounts if any, and with per-report-period data of type
--   a. Only the name is required; the other fields may or may not
--   be present.
data Account a
Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account a] -> Maybe (Account a) -> Bool -> PeriodData a -> Account a

-- | full name
[aname] :: Account a -> AccountName

-- | optional extra info from account directives relationships in the tree
[adeclarationinfo] :: Account a -> Maybe AccountDeclarationInfo

-- | subaccounts
[asubs] :: Account a -> [Account a]

-- | parent account
[aparent] :: Account a -> Maybe (Account a)

-- | used in some reports to indicate elidable accounts
[aboring] :: Account a -> Bool

-- | associated data per report period
[adata] :: Account a -> PeriodData a
type AccountName = Text
data Amount
Amount :: !CommoditySymbol -> !Quantity -> !AmountStyle -> !Maybe AmountCost -> !Maybe CostBasis -> Amount
[acommodity] :: Amount -> !CommoditySymbol
[aquantity] :: Amount -> !Quantity
[astyle] :: Amount -> !AmountStyle

-- | transacted exchange rate - the unit or total cost, in another
--   commodity, used for this amount within its transaction
[acost] :: Amount -> !Maybe AmountCost

-- | the cost basis of an investment lot represented by this amount. Or, a
--   matcher to select such a lot from the available lots.
[acostbasis] :: Amount -> !Maybe CostBasis

-- | Data that's useful in "balance" reports: subaccount-exclusive and
--   -inclusive amounts, typically representing either a balance change or
--   an end balance; and a count of postings.
data BalanceData
BalanceData :: MixedAmount -> MixedAmount -> Int -> BalanceData

-- | balance data excluding subaccounts
[bdexcludingsubs] :: BalanceData -> MixedAmount

-- | balance data including subaccounts
[bdincludingsubs] :: BalanceData -> MixedAmount

-- | the number of postings
[bdnumpostings] :: BalanceData -> Int

-- | A journal, containing general ledger transactions; also directives and
--   various other things. This is hledger's main data model.
--   
--   During parsing, it is used as the type alias ParsedJournal. The
--   jparse* fields are mainly used during parsing and included here for
--   convenience. The list fields described as "in parse order" are usually
--   reversed for efficiency during parsing. After parsing,
--   "journalFinalise" converts ParsedJournal to a finalised
--   Journal, which has all lists correctly ordered, and much data
--   inference and validation applied.
data Journal
Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> POSIXTime -> Journal

-- | the current default year, specified by the most recent Y directive (or
--   current date)
[jparsedefaultyear] :: Journal -> Maybe Year

-- | the current default commodity and its format, specified by the most
--   recent D directive
[jparsedefaultcommodity] :: Journal -> Maybe (CommoditySymbol, AmountStyle)

-- | the character to always parse as decimal point, if set by CsvReader's
--   decimal-mark (or a future journal directive)
[jparsedecimalmark] :: Journal -> Maybe DecimalMark

-- | the current stack of parent account names, specified by apply account
--   directives
[jparseparentaccounts] :: Journal -> [AccountName]

-- | the current account name aliases in effect, specified by alias
--   directives (& options ?) ,jparsetransactioncount :: Integer -- ^
--   the current count of transactions parsed so far (only journal format
--   txns, currently)
[jparsealiases] :: Journal -> [AccountAlias]

-- | timeclock sessions which have not been clocked out
[jparsetimeclockentries] :: Journal -> [TimeclockEntry]

-- | (absolute path, canonical path) of included files, most recent first
--   principal data
[jincludefilestack] :: Journal -> [(FilePath, FilePath)]

-- | Payees declared by payee directives, in parse order.
[jdeclaredpayees] :: Journal -> [(Payee, PayeeDeclarationInfo)]

-- | Tags declared by tag directives, in parse order.
[jdeclaredtags] :: Journal -> [(TagName, TagDeclarationInfo)]

-- | Accounts declared by account directives, in parse order.
[jdeclaredaccounts] :: Journal -> [(AccountName, AccountDeclarationInfo)]

-- | Accounts which were declared with tags, and those tags.
[jdeclaredaccounttags] :: Journal -> Map AccountName [Tag]

-- | Accounts which were declared with a type: tag, grouped by the type.
[jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName]

-- | All the account types known, from account declarations or account
--   names or parent accounts.
[jaccounttypes] :: Journal -> Map AccountName AccountType

-- | Commodities (and their display styles) declared by commodity
--   directives, in parse order.
[jdeclaredcommodities] :: Journal -> Map CommoditySymbol Commodity

-- | Commodities which were declared with tags, and those tags.
[jdeclaredcommoditytags] :: Journal -> Map CommoditySymbol [Tag]

-- | Commodity display styles inferred from amounts in the journal.
[jinferredcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | Commodity display styles declared by command line options (sometimes
--   augmented, see the import command).
[jglobalcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | P (market price) directives in the journal, in parse order.
[jpricedirectives] :: Journal -> [PriceDirective]

-- | Market prices inferred from transactions in the journal, in parse
--   order.
[jinferredmarketprices] :: Journal -> [MarketPrice]

-- | Auto posting rules declared in the journal.
[jtxnmodifiers] :: Journal -> [TransactionModifier]

-- | Periodic transaction rules declared in the journal.
[jperiodictxns] :: Journal -> [PeriodicTransaction]

-- | Transactions recorded in the journal. The important bit.
[jtxns] :: Journal -> [Transaction]

-- | any final trailing comments in the (main) journal file
[jfinalcommentlines] :: Journal -> Text

-- | the file path and raw text of the main and any included journal files.
--   The main file is first, followed by any included files in the order
--   encountered. TODO: FilePath is a sloppy type here, don't assume it's a
--   real file; values like "" or "-" can be seen
[jfiles] :: Journal -> [(FilePath, Text)]

-- | when this journal was last read from its file(s) NOTE: after adding
--   new fields, eg involving account names, consider updating the Anon
--   instance in Hleger.Cli.Anon
[jlastreadtime] :: Journal -> POSIXTime

-- | A Ledger has the journal it derives from, and the accounts derived
--   from that. Accounts are accessible both list-wise and tree-wise, since
--   each one knows its parent and subs; the first account is the root of
--   the tree and always exists.
data Ledger
Ledger :: Journal -> [Account BalanceData] -> Ledger
[ljournal] :: Ledger -> Journal
[laccounts] :: Ledger -> [Account BalanceData]

-- | A general container for storing data values associated with zero or
--   more contiguous report (sub)periods, and with the (open ended)
--   pre-report period. The report periods are typically all the same
--   length, but need not be.
--   
--   Report periods are represented only by their start dates, used as the
--   keys of a Map.
data PeriodData a
PeriodData :: a -> Map Day a -> PeriodData a

-- | data for the period before the report
[pdpre] :: PeriodData a -> a

-- | data for each period within the report
[pdperiods] :: PeriodData a -> Map Day a

-- | A periodic transaction rule, describing a transaction that recurs.
data PeriodicTransaction
PeriodicTransaction :: Text -> Interval -> DateSpan -> (SourcePos, SourcePos) -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> PeriodicTransaction

-- | the period expression as written
[ptperiodexpr] :: PeriodicTransaction -> Text

-- | the interval at which this transaction recurs
[ptinterval] :: PeriodicTransaction -> Interval

-- | the (possibly unbounded) period during which this transaction recurs.
--   Contains a whole number of intervals.
[ptspan] :: PeriodicTransaction -> DateSpan

-- | the file position where the period expression starts, and where the
--   last posting ends
[ptsourcepos] :: PeriodicTransaction -> (SourcePos, SourcePos)

-- | some of Transaction's fields
[ptstatus] :: PeriodicTransaction -> Status
[ptcode] :: PeriodicTransaction -> Text
[ptdescription] :: PeriodicTransaction -> Text
[ptcomment] :: PeriodicTransaction -> Text
[pttags] :: PeriodicTransaction -> [Tag]
[ptpostings] :: PeriodicTransaction -> [Posting]
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting

-- | this posting's date, if different from the transaction's
[pdate] :: Posting -> Maybe Day

-- | this posting's secondary date, if different from the transaction's
[pdate2] :: Posting -> Maybe Day
[pstatus] :: Posting -> Status
[paccount] :: Posting -> AccountName
[pamount] :: Posting -> MixedAmount

-- | this posting's comment lines, as a single non-indented multi-line
--   string
[pcomment] :: Posting -> Text
[ptype] :: Posting -> PostingType

-- | tag names and values, extracted from the posting comment and (after
--   finalisation) the posting account's directive if any
[ptags] :: Posting -> [Tag]

-- | an expected balance in the account after this posting, in a single
--   commodity, excluding subaccounts.
[pbalanceassertion] :: Posting -> Maybe BalanceAssertion

-- | this posting's parent transaction (co-recursive types). Tying this
--   knot gets tedious, Maybe makes it easier/optional.
[ptransaction] :: Posting -> Maybe Transaction

-- | When this posting has been transformed in some way (eg its amount or
--   cost was inferred, or the account name was changed by a pivot or
--   budget report), this references the original untransformed posting
--   (which will have Nothing in this field).
[poriginal] :: Posting -> Maybe Posting

-- | The id of a data format understood by hledger, eg journal or
--   csv. The --output-format option selects one of these for
--   output.
data StorageFormat
Rules :: StorageFormat
Journal' :: StorageFormat
Ledger' :: StorageFormat
Timeclock :: StorageFormat
Timedot :: StorageFormat
Sep :: SepFormat -> StorageFormat
data Transaction
Transaction :: Integer -> Text -> (SourcePos, SourcePos) -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Transaction

-- | this transaction's 1-based position in the transaction stream, or 0
--   when not available
[tindex] :: Transaction -> Integer

-- | any comment lines immediately preceding this transaction
[tprecedingcomment] :: Transaction -> Text

-- | the file position where the date starts, and where the last posting
--   ends
[tsourcepos] :: Transaction -> (SourcePos, SourcePos)
[tdate] :: Transaction -> Day
[tdate2] :: Transaction -> Maybe Day
[tstatus] :: Transaction -> Status
[tcode] :: Transaction -> Text
[tdescription] :: Transaction -> Text

-- | this transaction's comment lines, as a single non-indented multi-line
--   string
[tcomment] :: Transaction -> Text

-- | tag names and values, extracted from the comment
[ttags] :: Transaction -> [Tag]

-- | this transaction's postings
[tpostings] :: Transaction -> [Posting]

-- | A transaction modifier rule. This has a query which matches postings
--   in the journal, and a list of transformations to apply to those
--   postings or their transactions. Currently there is one kind of
--   transformation: the TMPostingRule, which adds a posting ("auto
--   posting") to the transaction, optionally setting its amount to the
--   matched posting's amount multiplied by a constant.
data TransactionModifier
TransactionModifier :: Text -> [TMPostingRule] -> TransactionModifier
[tmquerytxt] :: TransactionModifier -> Text
[tmpostingrules] :: TransactionModifier -> [TMPostingRule]
fromEFDay :: EFDay -> Day
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
type CommoditySymbol = Text

-- | The "display precision" for a hledger amount, by which we mean the
--   number of decimal digits to display to the right of the decimal mark.
data AmountPrecision

-- | show this many decimal digits (0..255)
Precision :: !Word8 -> AmountPrecision

-- | show all significant decimal digits stored internally
NaturalPrecision :: AmountPrecision

-- | Display styles for amounts - things which can be detected during
--   parsing, such as commodity side and spacing, digit group marks,
--   decimal mark, number of decimal digits etc. Every Amount has an
--   AmountStyle. After amounts are parsed from the input, for each
--   Commodity a standard style is inferred and then used when
--   displaying amounts in that commodity. Related to AmountFormat
--   but higher level.
--   
--   See also: - hledger manual > Commodity styles - hledger manual >
--   Amounts - hledger manual > Commodity display style
data AmountStyle
AmountStyle :: !Side -> !Bool -> !Maybe DigitGroupStyle -> !Maybe Char -> !AmountPrecision -> !Rounding -> AmountStyle

-- | show the symbol on the left or the right ?
[ascommodityside] :: AmountStyle -> !Side

-- | show a space between symbol and quantity ?
[ascommodityspaced] :: AmountStyle -> !Bool

-- | show the integer part with these digit group marks, or not
[asdigitgroups] :: AmountStyle -> !Maybe DigitGroupStyle

-- | show this character (should be . or ,) as decimal mark, or use the
--   default (.)
[asdecimalmark] :: AmountStyle -> !Maybe Char

-- | "display precision" - show this number of digits after the decimal
--   point
[asprecision] :: AmountStyle -> !AmountPrecision

-- | "rounding strategy" - kept here for convenience, for now: when
--   displaying an amount, it is ignored, but when applying this style to
--   another amount, it determines how hard we should try to adjust that
--   amount's display precision.
[asrounding] :: AmountStyle -> !Rounding

-- | A date which is either exact or flexible. Flexible dates are allowed
--   to be adjusted in certain situations.
data EFDay
Exact :: Day -> EFDay
Flex :: Day -> EFDay
type YearWeek = Int
type MonthWeek = Int
type WeekDay = Int

-- | A possibly incomplete year-month-day date provided by the user, to be
--   interpreted as either a date or a date span depending on context.
--   Missing parts "on the left" will be filled from the provided reference
--   date, e.g. if the year and month are missing, the reference date's
--   year and month are used. Missing parts "on the right" are assumed,
--   when interpreting as a date, to be 1, (e.g. if the year and month are
--   present but the day is missing, it means first day of that month); or
--   when interpreting as a date span, to be a wildcard (so it would mean
--   all days of that month). See the smartdate parser for more
--   examples.
--   
--   Or, one of the standard periods and a numeric offset relative to the
--   reference date: (last|this|next) (day|week|month|quarter|year), where
--   "this" means the period containing the reference date.
--   
--   Or, (last|this|next) weekdayname, where "this" "next".
--   
--   Or, (last|this|next) monthname, where "this" means the previous 1st if
--   in that month, otherwise the start of the next occurrence of that
--   month.
data SmartDate
SmartCompleteDate :: Day -> SmartDate
SmartAssumeStart :: Year -> Maybe Month -> SmartDate
SmartFromReference :: Maybe Month -> MonthDay -> SmartDate
SmartMonth :: Month -> SmartDate
SmartRelative :: Integer -> SmartInterval -> SmartDate

-- | EQ will be treated like GT
SmartRelativeMonth :: Ordering -> Month -> SmartDate
SmartRelativeWeekDay :: Ordering -> WeekDay -> SmartDate
data WhichDate
PrimaryDate :: WhichDate
SecondaryDate :: WhichDate

-- | A possibly open-ended span of time, from an optional inclusive start
--   date to an optional exclusive end date. Each date can be either exact
--   or flexible. An "exact date span" is a Datepan with exact start and
--   end dates.
data DateSpan
DateSpan :: Maybe EFDay -> Maybe EFDay -> DateSpan
type Payee = Text
data DepthSpec
DepthSpec :: Maybe Int -> [(Regexp, Int)] -> DepthSpec
[dsFlatDepth] :: DepthSpec -> Maybe Int
[dsRegexpDepths] :: DepthSpec -> [(Regexp, Int)]
isBalanceSheetAccountType :: AccountType -> Bool
isIncomeStatementAccountType :: AccountType -> Bool

-- | Check whether the first argument is a subtype of the second: either
--   equal or one of the defined subtypes.
isAccountSubtypeOf :: AccountType -> AccountType -> Bool
data AccountAlias
BasicAlias :: AccountName -> AccountName -> AccountAlias
RegexAlias :: Regexp -> Replacement -> AccountAlias

-- | One of the decimal marks we support: either period or comma.
type DecimalMark = Char
isDecimalMark :: Char -> Bool

-- | The basic numeric type used in amounts.
type Quantity = Decimal

-- | An amount's per-unit or total cost/selling price in another commodity,
--   as recorded in the journal entry eg with  or @. Cost,
--   formerly AKA "transaction price". The amount is always positive.
data AmountCost
UnitCost :: !Amount -> AmountCost
TotalCost :: !Amount -> AmountCost

-- | A style for displaying digit groups in the integer part of a floating
--   point number. It consists of the character used to separate groups
--   (comma or period, whichever is not used as decimal point), and the
--   size of each group, starting with the one nearest the decimal point.
--   The last group size is assumed to repeat. Eg, comma between thousands
--   is DigitGroups ',' [3].
data DigitGroupStyle
DigitGroups :: !Char -> ![Word8] -> DigitGroupStyle

-- | "Rounding strategy" - how to apply an AmountStyle's display precision
--   to a posting amount (and its cost, if any). Mainly used to customise
--   print's output, with --round=none|soft|hard|all.
data Rounding

-- | keep display precisions unchanged in amt and cost
NoRounding :: Rounding

-- | do soft rounding of amt and cost amounts (show more or fewer decimal
--   zeros to approximate the target precision, but don't hide significant
--   digits)
SoftRounding :: Rounding

-- | do hard rounding of amt (use the exact target precision, possibly
--   hiding significant digits), and soft rounding of cost
HardRounding :: Rounding

-- | do hard rounding of amt and cost
AllRounding :: Rounding
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle

-- | any comment lines following the commodity directive
[ccomment] :: Commodity -> Text

-- | tags extracted from the comment, if any
[ctags] :: Commodity -> [Tag]

-- | The cost basis of an individual lot - some quantity of an asset
--   acquired at a given date and time. This can represent a definite cost
--   basis, which must have a cost and date; the label is optional. Or it
--   can represent a cost basis matcher for selecting lots. Note: cost is
--   always stored as a per-unit cost, even if the user specified total
--   cost with {{}}.
data CostBasis
CostBasis :: !Maybe Amount -> !Maybe Day -> !Maybe Text -> CostBasis

-- | nominal acquisition cost (per-unit)
[cbCost] :: CostBasis -> !Maybe Amount

-- | nominal acquisition date
[cbDate] :: CostBasis -> !Maybe Day

-- | a short label to ensure uniqueness, correct intra-day order, or
--   memorability, if needed
[cbLabel] :: CostBasis -> !Maybe Text

-- | Types with this class have one or more amounts, which can have display
--   styles applied to them.
class HasAmounts a
styleAmounts :: HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a

-- | Compare two MixedAmounts, substituting 0 for the quantity of any
--   missing commodities in either.
maCompare :: MixedAmount -> MixedAmount -> Ordering
data PostingType
RegularPosting :: PostingType
VirtualPosting :: PostingType
BalancedVirtualPosting :: PostingType
type TagName = Text
type TagValue = Text
type HiddenTag = Tag
type DateTag = (TagName, Day)

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTag :: Tag -> HiddenTag

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTagName :: TagName -> TagName

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTag :: HiddenTag -> Tag

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTagName :: TagName -> TagName

-- | Does this tag name begin with the hidden tag prefix (_) ?
isHiddenTagName :: TagName -> Bool
nullsourcepos :: SourcePos
nullsourcepospair :: (SourcePos, SourcePos)

-- | A balance assertion is a declaration about an account's expected
--   balance at a certain point (posting date and parse order). They
--   provide additional error checking and readability to a journal file.
--   
--   A balance assignments is an instruction to hledger to adjust an
--   account's balance to a certain amount at a certain point.
--   
--   The BalanceAssertion type is used for representing both of
--   these.
--   
--   hledger supports multiple kinds of balance assertions/assignments,
--   which differ in whether they refer to a single commodity or all
--   commodities, and the (subaccount-)inclusive or exclusive account
--   balance.
data BalanceAssertion
BalanceAssertion :: Amount -> Bool -> Bool -> SourcePos -> BalanceAssertion

-- | the expected balance in a particular commodity
[baamount] :: BalanceAssertion -> Amount

-- | disallow additional non-asserted commodities ?
[batotal] :: BalanceAssertion -> Bool

-- | include subaccounts when calculating the actual balance ?
[bainclusive] :: BalanceAssertion -> Bool

-- | the assertion's file position, for error reporting
[baposition] :: BalanceAssertion -> SourcePos

-- | A transaction modifier transformation, which adds an extra posting to
--   the matched posting's transaction. Can be like a regular posting, or
--   can have the tmprIsMultiplier flag set, indicating that it's a
--   multiplier for the matched posting's amount.
data TMPostingRule
TMPostingRule :: Posting -> Bool -> TMPostingRule
[tmprPosting] :: TMPostingRule -> Posting
[tmprIsMultiplier] :: TMPostingRule -> Bool
nulltransactionmodifier :: TransactionModifier
nullperiodictransaction :: PeriodicTransaction
data TimeclockCode
SetBalance :: TimeclockCode
SetRequiredHours :: TimeclockCode
In :: TimeclockCode
Out :: TimeclockCode
FinalOut :: TimeclockCode
data TimeclockEntry
TimeclockEntry :: SourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> Text -> [Tag] -> TimeclockEntry
[tlsourcepos] :: TimeclockEntry -> SourcePos
[tlcode] :: TimeclockEntry -> TimeclockCode
[tldatetime] :: TimeclockEntry -> LocalTime
[tlaccount] :: TimeclockEntry -> AccountName
[tldescription] :: TimeclockEntry -> Text
[tlcomment] :: TimeclockEntry -> Text
[tltags] :: TimeclockEntry -> [Tag]

-- | A market price declaration made by the journal format's P directive.
--   It declares two things: a historical exchange rate between two
--   commodities, and an amount display style for the second commodity.
data PriceDirective
PriceDirective :: SourcePos -> Day -> CommoditySymbol -> Amount -> PriceDirective
[pdsourcepos] :: PriceDirective -> SourcePos
[pddate] :: PriceDirective -> Day
[pdcommodity] :: PriceDirective -> CommoditySymbol
[pdamount] :: PriceDirective -> Amount

-- | A historical market price (exchange rate) from one commodity to
--   another. A more concise form of a PriceDirective, without the amount
--   display info.
data MarketPrice
MarketPrice :: Day -> CommoditySymbol -> CommoditySymbol -> Quantity -> MarketPrice

-- | Date on which this price becomes effective.
[mpdate] :: MarketPrice -> Day

-- | The commodity being converted from.
[mpfrom] :: MarketPrice -> CommoditySymbol

-- | The commodity being converted to.
[mpto] :: MarketPrice -> CommoditySymbol

-- | One unit of the "from" commodity is worth this quantity of the "to"
--   commodity.
[mprate] :: MarketPrice -> Quantity
showMarketPrice :: MarketPrice -> String
showMarketPrices :: [MarketPrice] -> [Char]

-- | Extra information found in a payee directive.
data PayeeDeclarationInfo
PayeeDeclarationInfo :: Text -> [Tag] -> PayeeDeclarationInfo

-- | any comment lines following the payee directive
[pdicomment] :: PayeeDeclarationInfo -> Text

-- | tags extracted from the comment, if any
[pditags] :: PayeeDeclarationInfo -> [Tag]

-- | Extra information found in a tag directive.
newtype TagDeclarationInfo
TagDeclarationInfo :: Text -> TagDeclarationInfo

-- | any comment lines following the tag directive. No tags allowed here.
[tdicomment] :: TagDeclarationInfo -> Text

-- | Extra information about an account that can be derived from its
--   account directive (and the other account directives).
data AccountDeclarationInfo
AccountDeclarationInfo :: Text -> [Tag] -> Int -> SourcePos -> AccountDeclarationInfo

-- | any comment lines following an account directive for this account
[adicomment] :: AccountDeclarationInfo -> Text

-- | tags extracted from the account comment, if any
[aditags] :: AccountDeclarationInfo -> [Tag]

-- | the order in which this account was declared, relative to other
--   account declarations, during parsing (1..)
[adideclarationorder] :: AccountDeclarationInfo -> Int

-- | source file and position
[adisourcepos] :: AccountDeclarationInfo -> SourcePos

-- | A journal in the process of being parsed, not yet finalised. The data
--   is partial, and list fields are in reverse order.
type ParsedJournal = Journal
nullpayeedeclarationinfo :: PayeeDeclarationInfo
nulltagdeclarationinfo :: TagDeclarationInfo
nullaccountdeclarationinfo :: AccountDeclarationInfo

-- | Whether an account's balance is normally a positive number (in
--   accounting terms, a debit balance) or a negative number (credit
--   balance). Assets and expenses are normally positive (debit), while
--   liabilities, equity and income are normally negative (credit).
--   https://en.wikipedia.org/wiki/Normal_balance
data NormalSign
NormallyPositive :: NormalSign
NormallyNegative :: NormalSign

-- | Year of Common Era (when positive).
type Year = Integer
instance GHC.Internal.Enum.Bounded Hledger.Data.Types.Status
instance Data.Default.Internal.Default Hledger.Data.Types.DateSpan
instance Data.Default.Internal.Default Hledger.Data.Types.Interval
instance Data.Default.Internal.Default Hledger.Data.Types.Period
instance GHC.Internal.Enum.Enum Hledger.Data.Types.Status
instance GHC.Classes.Eq Hledger.Data.Types.AccountAlias
instance GHC.Classes.Eq Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Classes.Eq Hledger.Data.Types.AccountType
instance GHC.Classes.Eq Hledger.Data.Types.Amount
instance GHC.Classes.Eq Hledger.Data.Types.AmountCost
instance GHC.Classes.Eq Hledger.Data.Types.AmountPrecision
instance GHC.Classes.Eq Hledger.Data.Types.AmountStyle
instance GHC.Classes.Eq Hledger.Data.Types.BalanceAssertion
instance GHC.Classes.Eq Hledger.Data.Types.BalanceData
instance GHC.Classes.Eq Hledger.Data.Types.Commodity
instance GHC.Classes.Eq Hledger.Data.Types.CostBasis
instance GHC.Classes.Eq Hledger.Data.Types.DateSpan
instance GHC.Classes.Eq Hledger.Data.Types.DepthSpec
instance GHC.Classes.Eq Hledger.Data.Types.DigitGroupStyle
instance GHC.Classes.Eq Hledger.Data.Types.EFDay
instance GHC.Classes.Eq Hledger.Data.Types.Interval
instance GHC.Classes.Eq Hledger.Data.Types.Journal
instance GHC.Classes.Eq Hledger.Data.Types.MarketPrice
instance GHC.Classes.Eq Hledger.Data.Types.MixedAmount
instance GHC.Classes.Eq Hledger.Data.Types.MixedAmountKey
instance GHC.Classes.Eq Hledger.Data.Types.NormalSign
instance GHC.Classes.Eq Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Classes.Eq Hledger.Data.Types.Period
instance GHC.Classes.Eq a => GHC.Classes.Eq (Hledger.Data.Types.PeriodData a)
instance GHC.Classes.Eq Hledger.Data.Types.PeriodicTransaction
instance GHC.Classes.Eq Hledger.Data.Types.Posting
instance GHC.Classes.Eq Hledger.Data.Types.PostingType
instance GHC.Classes.Eq Hledger.Data.Types.PriceDirective
instance GHC.Classes.Eq Hledger.Data.Types.Rounding
instance GHC.Classes.Eq Hledger.Data.Types.SepFormat
instance GHC.Classes.Eq Hledger.Data.Types.Side
instance GHC.Classes.Eq Hledger.Data.Types.Status
instance GHC.Classes.Eq Hledger.Data.Types.StorageFormat
instance GHC.Classes.Eq Hledger.Data.Types.TMPostingRule
instance GHC.Classes.Eq Hledger.Data.Types.TagDeclarationInfo
instance GHC.Classes.Eq Hledger.Data.Types.TimeclockCode
instance GHC.Classes.Eq Hledger.Data.Types.TimeclockEntry
instance GHC.Classes.Eq Hledger.Data.Types.Transaction
instance GHC.Classes.Eq Hledger.Data.Types.TransactionModifier
instance GHC.Classes.Eq Hledger.Data.Types.WhichDate
instance GHC.Internal.Base.Functor Hledger.Data.Types.Account
instance GHC.Internal.Base.Functor Hledger.Data.Types.PeriodData
instance GHC.Internal.Generics.Generic (Hledger.Data.Types.Account a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountAlias
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountType
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Amount
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountCost
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountStyle
instance GHC.Internal.Generics.Generic Hledger.Data.Types.BalanceAssertion
instance GHC.Internal.Generics.Generic Hledger.Data.Types.BalanceData
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Commodity
instance GHC.Internal.Generics.Generic Hledger.Data.Types.CostBasis
instance GHC.Internal.Generics.Generic Hledger.Data.Types.DateSpan
instance GHC.Internal.Generics.Generic (Data.Decimal.DecimalRaw a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Generics.Generic Hledger.Data.Types.EFDay
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Interval
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Journal
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Ledger
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MarketPrice
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MixedAmount
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Period
instance GHC.Internal.Generics.Generic (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PeriodicTransaction
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Posting
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PostingType
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PriceDirective
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Rounding
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Side
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Status
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TMPostingRule
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TagDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TimeclockEntry
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Transaction
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TransactionModifier
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts [a]
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (GHC.Internal.Maybe.Maybe a)
instance (Hledger.Data.Types.HasAmounts a, Hledger.Data.Types.HasAmounts b) => Hledger.Data.Types.HasAmounts (a, b)
instance GHC.Internal.Base.Monoid Hledger.Data.Types.DepthSpec
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountAlias
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountType
instance Control.DeepSeq.NFData Hledger.Data.Types.Amount
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountCost
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountPrecision
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.BalanceAssertion
instance Control.DeepSeq.NFData Hledger.Data.Types.Commodity
instance Control.DeepSeq.NFData Hledger.Data.Types.CostBasis
instance Control.DeepSeq.NFData Hledger.Data.Types.DateSpan
instance Control.DeepSeq.NFData Hledger.Data.Types.DigitGroupStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.EFDay
instance Control.DeepSeq.NFData Hledger.Data.Types.Interval
instance Control.DeepSeq.NFData Hledger.Data.Types.Journal
instance Control.DeepSeq.NFData Hledger.Data.Types.MarketPrice
instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmount
instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmountKey
instance Control.DeepSeq.NFData Hledger.Data.Types.PayeeDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.PeriodicTransaction
instance Control.DeepSeq.NFData Hledger.Data.Types.Posting
instance Control.DeepSeq.NFData Hledger.Data.Types.PostingType
instance Control.DeepSeq.NFData Hledger.Data.Types.PriceDirective
instance Control.DeepSeq.NFData Hledger.Data.Types.Rounding
instance Control.DeepSeq.NFData Hledger.Data.Types.Side
instance Control.DeepSeq.NFData Hledger.Data.Types.Status
instance Control.DeepSeq.NFData Hledger.Data.Types.TMPostingRule
instance Control.DeepSeq.NFData Hledger.Data.Types.TagDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockCode
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockEntry
instance Control.DeepSeq.NFData Hledger.Data.Types.Transaction
instance Control.DeepSeq.NFData Hledger.Data.Types.TransactionModifier
instance GHC.Classes.Ord Hledger.Data.Types.AccountAlias
instance GHC.Classes.Ord Hledger.Data.Types.AccountType
instance GHC.Classes.Ord Hledger.Data.Types.Amount
instance GHC.Classes.Ord Hledger.Data.Types.AmountCost
instance GHC.Classes.Ord Hledger.Data.Types.AmountPrecision
instance GHC.Classes.Ord Hledger.Data.Types.AmountStyle
instance GHC.Classes.Ord Hledger.Data.Types.CostBasis
instance GHC.Classes.Ord Hledger.Data.Types.DateSpan
instance GHC.Classes.Ord Hledger.Data.Types.DigitGroupStyle
instance GHC.Classes.Ord Hledger.Data.Types.EFDay
instance GHC.Classes.Ord Hledger.Data.Types.Interval
instance GHC.Classes.Ord Hledger.Data.Types.MarketPrice
instance GHC.Classes.Ord Hledger.Data.Types.MixedAmount
instance GHC.Classes.Ord Hledger.Data.Types.MixedAmountKey
instance GHC.Classes.Ord Hledger.Data.Types.Period
instance GHC.Classes.Ord a => GHC.Classes.Ord (Hledger.Data.Types.PeriodData a)
instance GHC.Classes.Ord Hledger.Data.Types.PriceDirective
instance GHC.Classes.Ord Hledger.Data.Types.Rounding
instance GHC.Classes.Ord Hledger.Data.Types.SepFormat
instance GHC.Classes.Ord Hledger.Data.Types.Side
instance GHC.Classes.Ord Hledger.Data.Types.Status
instance GHC.Classes.Ord Hledger.Data.Types.StorageFormat
instance GHC.Classes.Ord Hledger.Data.Types.TimeclockCode
instance GHC.Classes.Ord Hledger.Data.Types.TimeclockEntry
instance GHC.Internal.Read.Read Hledger.Data.Types.AccountAlias
instance GHC.Internal.Read.Read Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Read.Read Hledger.Data.Types.AmountStyle
instance GHC.Internal.Read.Read Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Read.Read Hledger.Data.Types.Rounding
instance GHC.Internal.Read.Read Hledger.Data.Types.Side
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.DepthSpec
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountAlias
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountType
instance GHC.Internal.Show.Show Hledger.Data.Types.Amount
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountCost
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountStyle
instance GHC.Internal.Show.Show Hledger.Data.Types.BalanceAssertion
instance GHC.Internal.Show.Show Hledger.Data.Types.Commodity
instance GHC.Internal.Show.Show Hledger.Data.Types.CostBasis
instance GHC.Internal.Show.Show Hledger.Data.Types.DepthSpec
instance GHC.Internal.Show.Show Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Show.Show Hledger.Data.Types.EFDay
instance GHC.Internal.Show.Show Hledger.Data.Types.Interval
instance GHC.Internal.Show.Show Hledger.Data.Types.MarketPrice
instance GHC.Internal.Show.Show Hledger.Data.Types.MixedAmount
instance GHC.Internal.Show.Show Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Show.Show Hledger.Data.Types.NormalSign
instance GHC.Internal.Show.Show Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.Period
instance GHC.Internal.Show.Show Hledger.Data.Types.Posting
instance GHC.Internal.Show.Show Hledger.Data.Types.PostingType
instance GHC.Internal.Show.Show Hledger.Data.Types.PriceDirective
instance GHC.Internal.Show.Show Hledger.Data.Types.Rounding
instance GHC.Internal.Show.Show Hledger.Data.Types.SepFormat
instance GHC.Internal.Show.Show Hledger.Data.Types.Side
instance GHC.Internal.Show.Show Hledger.Data.Types.SmartDate
instance GHC.Internal.Show.Show Hledger.Data.Types.SmartInterval
instance GHC.Internal.Show.Show Hledger.Data.Types.Status
instance GHC.Internal.Show.Show Hledger.Data.Types.StorageFormat
instance GHC.Internal.Show.Show Hledger.Data.Types.TMPostingRule
instance GHC.Internal.Show.Show Hledger.Data.Types.TagDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.Transaction
instance GHC.Internal.Show.Show Hledger.Data.Types.TransactionModifier
instance GHC.Internal.Show.Show Hledger.Data.Types.WhichDate
instance Text.Blaze.ToMarkup Hledger.Data.Types.Quantity

-- | Manipulate the time periods typically used for reports with Period, a
--   richer abstraction than DateSpan. See also Types and Dates.
module Hledger.Data.Period

-- | Convert Periods to exact DateSpans.
--   
--   
--   >>> periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ Flex $ fromGregorian 2000 1 1) (Just $ Flex $ fromGregorian 2000 2 1)
--   True
--   
periodAsDateSpan :: Period -> DateSpan

-- | Convert DateSpans to Periods.
--   
--   
--   >>> dateSpanAsPeriod $ DateSpan (Just $ Exact $ fromGregorian 2000 1 1) (Just $ Exact $ fromGregorian 2000 2 1)
--   MonthPeriod 2000 1
--   
dateSpanAsPeriod :: DateSpan -> Period

-- | Convert PeriodBetweens to a more abstract period where possible.
--   
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)
--   YearPeriod 1
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)
--   QuarterPeriod 2000 4
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)
--   MonthPeriod 2000 2
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)
--   WeekPeriod 2016-07-25
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)
--   DayPeriod 2000-01-01
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)
--   PeriodBetween 2000-02-28 2000-03-01
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)
--   DayPeriod 2000-02-29
--   
--   >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)
--   DayPeriod 2000-12-31
--   
simplifyPeriod :: Period -> Period
isLastDayOfMonth :: (Eq a1, Eq a2, Num a1, Num a2) => Year -> a1 -> a2 -> Bool

-- | Is this period a "standard" period, referencing a particular day,
--   week, month, quarter, or year ? Periods of other durations, or
--   infinite duration, or not starting on a standard period boundary, are
--   not.
isStandardPeriod :: Period -> Bool

-- | The width of a period of this type when displayed.
periodTextWidth :: Period -> Int

-- | Render a period as a compact display string suitable for user output.
--   
--   
--   >>> showPeriod (WeekPeriod (fromGregorian 2016 7 25))
--   "2016-W30"
--   
--   >>> showPeriod (WeekPeriod (fromGregorian 2024 12 30))
--   "2025-W01"
--   
showPeriod :: Period -> Text

-- | Like showPeriod, but if it's a month or week period show an
--   abbreviated form. >>> showPeriodAbbrev (WeekPeriod
--   (fromGregorian 2016 7 25)) W30 >>> showPeriodAbbrev
--   (WeekPeriod (fromGregorian 2024 12 30)) W01
showPeriodAbbrev :: Period -> Text
periodStart :: Period -> Maybe Day
periodEnd :: Period -> Maybe Day

-- | Move a standard period to the following period of same duration.
--   Non-standard periods are unaffected.
periodNext :: Period -> Period

-- | Move a standard period to the preceding period of same duration.
--   Non-standard periods are unaffected.
periodPrevious :: Period -> Period

-- | Move a standard period to the following period of same duration,
--   staying within enclosing dates. Non-standard periods are unaffected.
periodNextIn :: DateSpan -> Period -> Period

-- | Move a standard period to the preceding period of same duration,
--   staying within enclosing dates. Non-standard periods are unaffected.
periodPreviousIn :: DateSpan -> Period -> Period

-- | Move a standard period stepwise so that it encloses the given date.
--   Non-standard periods are unaffected.
periodMoveTo :: Day -> Period -> Period

-- | Enlarge a standard period to the next larger enclosing standard
--   period, if there is one. Eg, a day becomes the enclosing week. A week
--   becomes whichever month the week's thursday falls into. A year becomes
--   all (unlimited). Non-standard periods (arbitrary dates, or open-ended)
--   are unaffected.
periodGrow :: Period -> Period

-- | Shrink a period to the next smaller standard period inside it,
--   choosing the subperiod which contains today's date if possible,
--   otherwise the first subperiod. It goes like this: unbounded periods
--   and nonstandard periods (between two arbitrary dates) -> current
--   year -> current quarter if it's in selected year, otherwise first
--   quarter of selected year -> current month if it's in selected
--   quarter, otherwise first month of selected quarter -> current week
--   if it's in selected month, otherwise first week of selected month
--   -> today if it's in selected week, otherwise first day of selected
--   week, unless that's in previous month, in which case first day of
--   month containing selected week. Shrinking a day has no effect.
periodShrink :: Day -> Period -> Period
mondayBefore :: Day -> Day
thursdayOfWeekContaining :: Day -> Day
yearMonthContainingWeekStarting :: Day -> (Year, MonthOfYear)
quarterContainingMonth :: Integral a => a -> a
firstMonthOfQuarter :: Num a => a -> a
startOfFirstWeekInMonth :: Year -> MonthOfYear -> Day

-- | Helpers and CSS styles for HTML output.
module Hledger.Write.Html.Attribute
stylesheet :: [(Text, Text)] -> Text
concatStyles :: [Text] -> Text
tableStylesheet :: Text
tableStyle :: [(Text, Text)]
bold :: Text
doubleborder :: Text
topdoubleborder :: Text
bottomdoubleborder :: Text
alignright :: Text
alignleft :: Text
aligncenter :: Text
collapse :: Text
lpad :: Text
rpad :: Text
hpad :: Text
vpad :: Text

-- | Calculate the width of String and Text, being aware of wide
--   characters.
module Text.WideString

-- | Helper for constructing Builders while keeping track of text width.
data WideBuilder
WideBuilder :: !Builder -> !Int -> WideBuilder
[wbBuilder] :: WideBuilder -> !Builder
[wbWidth] :: WideBuilder -> !Int

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a strict Text to a WideBuilder.
wbFromText :: Text -> WideBuilder
instance GHC.Internal.Base.Monoid Text.WideString.WideBuilder
instance GHC.Internal.Base.Semigroup Text.WideString.WideBuilder
instance GHC.Internal.Show.Show Text.WideString.WideBuilder

-- | Text.Tabular.AsciiArt from tabular-0.2.2.7, modified to treat wide
--   characters as double width.
module Text.Tabular.AsciiWide

-- | The options to use for rendering a table.
data TableOpts
TableOpts :: Bool -> Bool -> Bool -> TableOpts

-- | Pretty tables
[prettyTable] :: TableOpts -> Bool

-- | Whether to display the outer borders
[tableBorders] :: TableOpts -> Bool

-- | Whether to display spaces around bars
[borderSpaces] :: TableOpts -> Bool

-- | Render a table according to common options, for backwards
--   compatibility
render :: Show a => Bool -> (rh -> Text) -> (ch -> Text) -> (a -> Text) -> Table rh ch a -> Text

-- | Render a table according to various cell specifications>
renderTable :: Show a => TableOpts -> (rh -> Cell) -> (ch -> Cell) -> (a -> Cell) -> Table rh ch a -> Text

-- | A version of renderTable which returns the underlying Builder.
renderTableB :: Show a => TableOpts -> (rh -> Cell) -> (ch -> Cell) -> (a -> Cell) -> Table rh ch a -> Builder

-- | A version of renderTable that operates on rows (including the
--   row of column headers) and returns the underlying Builder.
renderTableByRowsB :: Show a => TableOpts -> ([ch] -> [Cell]) -> ((rh, [a]) -> (Cell, [Cell])) -> Table rh ch a -> Builder

-- | Render a single row according to cell specifications.
renderRow :: TableOpts -> Header Cell -> Text

-- | A version of renderRow which returns the underlying Builder.
renderRowB :: TableOpts -> Header Cell -> Builder

-- | We stop rendering on the shortest list!
renderColumns :: TableOpts -> [Int] -> Header Cell -> Builder

-- | Cell contents along an alignment
data Cell
Cell :: Align -> [WideBuilder] -> Cell

-- | How to align text in a cell
data Align
TopRight :: Align
BottomRight :: Align
BottomLeft :: Align
TopLeft :: Align
emptyCell :: Cell

-- | Create a single-line cell from the given contents with its natural
--   width.
textCell :: Align -> Text -> Cell

-- | Create a multi-line cell from the given contents with its natural
--   width.
textsCell :: Align -> [Text] -> Cell

-- | Return the width of a Cell.
cellWidth :: Cell -> Int

-- | Add the second table below the first, discarding its column headings.
concatTables :: Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a
instance Data.Default.Internal.Default Text.Tabular.AsciiWide.TableOpts
instance GHC.Internal.Show.Show Text.Tabular.AsciiWide.Align
instance GHC.Internal.Show.Show Text.Tabular.AsciiWide.TableOpts

-- | Text formatting helpers, ported from String as needed. There may be
--   better alternatives out there.
module Hledger.Utils.Text
textCapitalise :: Text -> Text

-- | Remove all matching pairs of square brackets and parentheses from the
--   text.
textUnbracket :: Text -> Text

-- | Wrap a Text with the surrounding Text.
wrap :: Text -> Text -> Text -> Text

-- | Remove trailing newlines/carriage returns.
textChomp :: Text -> Text

-- | Wrap a string in double quotes, and -prefix any embedded single
--   quotes, if it contains whitespace and is not already single- or
--   double-quoted.
quoteIfSpaced :: Text -> Text
textQuoteIfNeeded :: Text -> Text
escapeDoubleQuotes :: Text -> Text
escapeBackslash :: Text -> Text

-- | Strip one matching pair of single or double quotes on the ends of a
--   string.
stripquotes :: Text -> Text
textElideRight :: Int -> Text -> Text

-- | Clip and pad a string to a minimum & maximum width, andor
--   leftright justify it. Works on multi-line strings too (but will
--   rewrite non-unix line endings).
formatText :: Bool -> Maybe Int -> Maybe Int -> Text -> Text

-- | Join several multi-line strings as side-by-side rectangular strings of
--   the same height, top-padded. Treats wide characters as double width.
textConcatTopPadded :: [Text] -> Text

-- | Join several multi-line strings as side-by-side rectangular strings of
--   the same height, bottom-padded. Treats wide characters as double
--   width.
textConcatBottomPadded :: [Text] -> Text

-- | General-purpose wide-char-aware single-line text layout function. It
--   can left- or right-pad a short string to a minimum width. It can left-
--   or right-clip a long string to a maximum width, optionally inserting
--   an ellipsis (the third argument). It clips and pads on the right when
--   the fourth argument is true, otherwise on the left. It treats wide
--   characters as double width.
fitText :: Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text

-- | Add a prefix to each line of a string.
linesPrepend :: Text -> Text -> Text

-- | Add a prefix to the first line of a string, and a different prefix to
--   the remaining lines.
linesPrepend2 :: Text -> Text -> Text -> Text

-- | Join a list of Text Builders with a newline after each item.
unlinesB :: [Builder] -> Builder

-- | Helper for constructing Builders while keeping track of text width.
data WideBuilder
WideBuilder :: !Builder -> !Int -> WideBuilder
[wbBuilder] :: WideBuilder -> !Builder
[wbWidth] :: WideBuilder -> !Int

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a strict Text to a WideBuilder.
wbFromText :: Text -> WideBuilder

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Double-width-character-aware string truncation. Take as many
--   characters as possible from a string without exceeding the specified
--   width. Eg textTakeWidth 3 "りんご" = "り".
textTakeWidth :: Int -> Text -> Text

-- | Read a decimal number from a Text. Assumes the input consists only of
--   digit characters.
readDecimal :: Text -> Integer
tests_Text :: TestTree

-- | General and hledger-specific input/output-related helpers for
--   pretty-printing haskell values, error reporting, time, files, command
--   line parsing, terminals, pager output, ANSI colour/styles, etc.
module Hledger.Utils.IO

-- | Pretty show. An easier alias for pretty-simple's pShow. This will
--   probably show in colour if useColorOnStderrUnsafe is true.
pshow :: Show a => a -> String

-- | Monochrome version of pshow. This will never show in colour.
pshow' :: Show a => a -> String

-- | Pretty print a showable value. An easier alias for pretty-simple's
--   pPrint. This will print in colour if useColorOnStderrUnsafe is true.
pprint :: Show a => a -> IO ()

-- | Monochrome version of pprint. This will never print in colour.
pprint' :: Show a => a -> IO ()

-- | Call errorWithoutStackTrace, prepending a "Error:" label.
error' :: String -> a

-- | Like error', but add a hint about using -h.
usageError :: String -> a

-- | Show a warning message on stderr before returning the given value.
--   Like trace, but prepends a "Warning:" label, and does some ANSI
--   styling of the first line when allowed (using unsafe IO). Currently we
--   use this very sparingly in hledger; we prefer to either quietly work,
--   or loudly raise an error. Varying output can make scripting harder.
--   But on stderr, it shouldn't cause much hassle.
warn :: String -> a -> a

-- | Like warn, but take extra care to sequence properly in IO.
warnIO :: MonadIO m => String -> m ()

-- | Apply standard ANSI SGR formatting (red, bold) suitable for console
--   error text.
ansiFormatError :: String -> String

-- | Apply standard ANSI SGR formatting (yellow, bold) suitable for console
--   warning text.
ansiFormatWarning :: String -> String

-- | Print an error message to stderr, with a consistent "programname: "
--   prefix, and applying ANSI styling (bold bright red) to the first line
--   if that is supported and allowed.
printError :: String -> IO ()

-- | Print an error message with printError, then exit the program with a
--   non-zero exit code.
exitWithErrorMessage :: String -> IO ()

-- | This wraps a program's main routine so as to display more consistent,
--   useful, and GHC-version-independent error output when the program
--   exits because of certain common exceptions. It
--   
--   
--   
- disables SIGPIPE errors, which are usually harmless, caused when
--   our output is truncated in a piped command.
--   
- catches these common exceptions:
--   
--   
--   
--   
- UnicodeException, caused eg by text decoding errors in pure
--   code
--   
- IOException, caused by IO errors, including text decoding
--   errors during IO
--   
- ErrorCall - error / errorWithoutStackTrace
--   calls
--   
--   
--   
--   
- compensates for GHC output bugs:
--   
--   
--   
--   
- removes the trailing newlines added by some GHC 9.10.*
--   versions
--   
- removes "uncaught exception" output added by some GHC 9.12.*
--   versions
--   
- ensures a consistent "PROGNAME: " prefix
--   
--   
--   
--   
- applies bold bright red ANSI styling to the first line of error
--   output, if that is supported and allowed
--   
- for unicode exceptions and I/O exceptions which look like they
--   were unicode-related, it adds a message (in english) explaining the
--   problem and what to do.
--   
--   
--   Some exceptions this does not catch are ExitCode
--   (exitSuccessexitFailureexitWith) and UserInterrupt (control-C).
handleExit :: IO () -> IO ()
getCurrentLocalTime :: IO LocalTime
getCurrentZonedTime :: IO ZonedTime

-- | Like getHomeDirectory, but in case of IO error (home directory not
--   found, not understood, etc.), returns "".
getHomeSafe :: IO (Maybe FilePath)

-- | Like embedFile, but takes a path relative to the package directory.
embedFileRelative :: FilePath -> Q Exp

-- | Expand a single tilde (representing home directory) at the start of a
--   file path. ~username is not supported. This can raise an IO error.
expandHomePath :: FilePath -> IO FilePath

-- | Given a current directory, convert a possibly relative, possibly
--   tilde-prefixed file path to an absolute one. ~username is not
--   supported. If the file path is "-", it is left as-is. This can an
--   raise an IO error.
expandPath :: FilePath -> FilePath -> IO FilePath

-- | Like expandPath, but treats the expanded path as a glob, and
--   returns zero or more matched absolute file paths, alphabetically
--   sorted. Can raise an error. For a more elaborate glob expander, see
--   findMatchedFiles (used by the include directive).
expandGlob :: FilePath -> FilePath -> IO [FilePath]

-- | Like expandPath, but if the path contains glob metacharacters (* ? [
--   {), treats it as a glob pattern and expands it, returning the first
--   match. Raises an error if the glob pattern matches no files. If the
--   path contains no glob metacharacters, just expands ~ and returns the
--   path, even if the file doesn't exist yet. This is useful for options
--   like -f and LEDGER_FILE that should: - accept non-existent files (for
--   commands like add/import that create them) - expand glob patterns and
--   error if they don't match anything
expandPathOrGlob :: FilePath -> FilePath -> IO FilePath

-- | Given a list of existing file paths, sort them by modification time
--   (from oldest to newest).
sortByModTime :: [FilePath] -> IO [FilePath]

-- | Open a file for reading, using the standard System.IO.openFile. This
--   opens the handle in text mode, using the initial system locale's text
--   encoding.
openFileOrStdin :: String -> IO Handle

-- | Like readFilePortably, but read from standard input if the path is
--   "-".
readFileOrStdinPortably :: String -> IO Text

-- | Like readFileOrStdinPortably, but take an optional converter.
readFileOrStdinPortably' :: Maybe DynEncoding -> String -> IO Text

-- | Like readFilePortably, but read all of the file before proceeding.
readFileStrictly :: FilePath -> IO Text

-- | Read text from a file, converting any rn line endings to n,, using the
--   system locale's text encoding, ignoring any utf8 BOM prefix (as seen
--   in paypal's 2018 CSV, eg) if that encoding is utf8.
readFilePortably :: FilePath -> IO Text

-- | Read text from a handle, perhaps using a specified encoding from the
--   encoding package. Or if no encoding is specified, using the handle's
--   current encoding, changing it to UTF-8BOM if it was UTF-8, to ignore
--   any Byte Order Mark at the start. Also it converts Windows line
--   endings to newlines. If decoding fails, this throws an IOException (or
--   possibly a UnicodeException or something else from the encoding
--   package).
hGetContentsPortably :: Maybe DynEncoding -> Handle -> IO Text

-- | Create a handle from which the given text can be read. Its encoding
--   will be UTF-8.
textToHandle :: Text -> IO Handle

-- | The program's command line arguments. Uses unsafePerformIO; tends to
--   stick in GHCI until reloaded, and may or may not detect args provided
--   by a hledger config file.
progArgs :: [String]

-- | Given one or more long or short flag names, report whether this flag
--   is present in the command line. Concatenated short flags (-a -b
--   written as -ab) are not supported.
getFlag :: [String] -> IO Bool

-- | Given one or more long or short option names, read the rightmost value
--   of this option from the command line arguments. If the value is
--   missing raise an error. Concatenated short flags (-a -b written as
--   -ab) are not supported.
getOpt :: [String] -> IO (Maybe String)

-- | Parse yyesalways or nnonever to true or false, or return
--   an error message.
parseYN :: String -> Either String Bool

-- | Parse yyesalways or nnonever or a/auto to a YNA choice,
--   or return an error message.
parseYNA :: String -> Either String YNA
data YNA
Yes :: YNA
No :: YNA
Auto :: YNA

-- | An alternative to ansi-terminal's getTerminalSize, based on the more
--   robust-looking terminal-size package.
--   
--   Tries to get stdout's terminal's current height and width.
getTerminalHeightWidth :: IO (Maybe (Int, Int))
getTerminalHeight :: IO (Maybe Int)
getTerminalWidth :: IO (Maybe Int)

-- | Try to find a pager executable robustly, safely handling various error
--   conditions like an unset PATH var or the specified pager not being
--   found as an executable. The pager can be specified by a path or
--   program name in the PAGER environment variable. If that is unset or
--   has a problem, "less" is tried, then "more". If successful, the
--   pager's path or program name is returned.
findPager :: IO (Maybe String)

-- | Display the given text on the terminal, trying to use a pager ($PAGER,
--   less, or more) when appropriate (see maybePagerFor), otherwise
--   printing to standard output. Also, if the pager is less, we modify the
--   LESS environment variable (see lessVarValue) and check for problems
--   which could cause confusing output (see lessIsWorking).
runPager :: String -> IO ()

-- | Compute the LESS environment variable value that hledger will use for
--   the less pager. This used in runPager when invoking less, and also in
--   the setup command for display. It takes the current HLEDGER_LESS and
--   LESS env var values, and whether we are showing colour on stdout, and
--   returns the adjusted LESS value that should be used. Specifically:
--   
--   
--   
- If HLEDGER_LESS is defined, we use it in place of the LESS
--   environment variable.
--   
- Otherwise, if LESS is defined, append some preferred options
--   (lessOptions and maybe lessColourOptions) to it.
--   
- Otherwise, we set LESS to just use those preferred options.
--   
lessVarValue :: Maybe String -> Maybe String -> Bool -> String

-- | Test less, by running less --version and looking for a
--   nonzero exit, timeout, or stderr output. Uses the provided
--   environment, containing a LESS variable, if any. We do this because
--   various LESS settings can cause some less versions to fail or cause
--   confusing output without failing.
lessIsWorking :: Maybe [(String, String)] -> IO Bool

-- | Get the value of the rightmost --color or --colour option from the
--   program's command line arguments. Throws an error if the option's
--   value could not be parsed.
colorOption :: IO YNA

-- | Should ANSI color and styles be used for standard output ? Considers
--   useColorOnHandle stdout and hasOutputFile.
useColorOnStdout :: IO Bool

-- | Should ANSI color and styles be used for standard error output ?
--   Considers useColorOnHandle stderr; is not affected by an --output-file
--   option.
useColorOnStderr :: IO Bool

-- | Like useColorOnStdout, but using unsafePerformIO. Useful eg for
--   low-level debug code. Sticky in GHCI until reloaded, may not always be
--   affected by --color in a hledger config file, etc.
useColorOnStdoutUnsafe :: Bool

-- | Like useColorOnStdoutUnsafe, but for stderr.
useColorOnStderrUnsafe :: Bool

-- | Set various ANSI styles/colours in a string, only if
--   useColorOnStdoutUnsafe says we should.
bold' :: String -> String
faint' :: String -> String
black' :: String -> String
red' :: String -> String
green' :: String -> String
yellow' :: String -> String
blue' :: String -> String
magenta' :: String -> String
cyan' :: String -> String
white' :: String -> String
brightBlack' :: String -> String
brightRed' :: String -> String
brightGreen' :: String -> String
brightYellow' :: String -> String
brightBlue' :: String -> String
brightMagenta' :: String -> String
brightCyan' :: String -> String
brightWhite' :: String -> String
rgb' :: Float -> Float -> Float -> String -> String
sgrresetall :: String

-- | Wrap a string in ANSI codes to set and reset foreground colour.
--   ColorIntensity is Dull or Vivid (ie normal and
--   bold). Color is one of Black, Red, Green,
--   Yellow, Blue, Magenta, Cyan,
--   White. Eg: color Dull Red "text".
color :: ColorIntensity -> Color -> String -> String

-- | Wrap a string in ANSI codes to set and reset background colour.
bgColor :: ColorIntensity -> Color -> String -> String

-- | Wrap a WideBuilder in ANSI codes to set and reset foreground colour.
colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder

-- | Wrap a WideBuilder in ANSI codes to set and reset background colour.
bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder

-- | Detect whether the terminal currently has a light background colour,
--   if possible, using unsafePerformIO. If the terminal is transparent,
--   its apparent light/darkness may be different.
terminalIsLight :: Maybe Bool

-- | Detect the terminal's current background lightness (0..1), if
--   possible, using unsafePerformIO. If the terminal is transparent, its
--   apparent lightness may be different.
terminalLightness :: Maybe Float

-- | Detect the terminal's current foreground colour, if possible, using
--   unsafePerformIO.
terminalFgColor :: Maybe (RGB Float)

-- | Detect the terminal's current background colour, if possible, using
--   unsafePerformIO.
terminalBgColor :: Maybe (RGB Float)
instance GHC.Classes.Eq Hledger.Utils.IO.YNA
instance GHC.Internal.Show.Show Hledger.Utils.IO.YNA

-- | Here are debug tracing/logging helpers built on Debug.Trace, extracted
--   from the hledger project. Features:
--   
--   
--   
- they can be built in to your program permanently, and activated by
--   a --debug [LEVEL] option
--   
- they can optionally log to a file instead of stderr (for TUI
--   apps)
--   
- they can be used in IO, pure, or startup code
--   
- values are printed with a label, and pretty-printed (using
--   pretty-simple)
--   
- ANSI colour is used when appropriate.
--   
--   
--   Insert these dbg* helpers at points of interest in your code,
--   either temporarily while debugging, or permanently in production code,
--   and activate them with --debug [1-9] on the command line
--   (--debug with no value means level 1). For example, this
--   expression:
--   
--   
--   dbg4 "foo" foo
--   
--   
--   will pretty-print foo with a "foo:" label when it is evaluated, but
--   only if --debug's value is 4 or greater. In other words: use dbg1 for
--   the most useful debug output, dbg9 for the most specialised/verbose.
--   
--   They are intended to be easy to use and to find in your code, with a
--   consistent naming scheme:
--   
--   
--   dbg<LEVEL>Msg   STR    VAL  -- trace/log a string in pure code
--   dbg<LEVEL>MsgIO STR         -- trace/log a string in IO
--   
--   dbg<LEVEL>      STR    VAL  -- trace/log a showable value in pure code
--   dbg<LEVEL>IO    STR    VAL  -- trace/log a showable value in IO
--   
--   dbg<LEVEL>With  SHOWFN VAL  -- trace/log any value
--   
--   
--   Or if you prefer you can ignore the numbered variants and write an
--   extra argument:
--   
--   
--   dbgMsg   LEVEL  STR    VAL
--   dbgMsgIO LEVEL  STR
--   
--   dbg      LEVEL  STR    VAL
--   dbgIO    LEVEL  STR    VAL
--   
--   dbgWith  LEVEL  SHOWFN VAL
--   
--   
--   Haskell values will be pretty-printed by default, using pretty-simple.
--   
--   ANSI color will also be used if appropriate, respecting output
--   capabilities, NO_COLOR, and/or a --color [YNA] (or
--   --colour) command line option.
--   
--   These helpers normally print output on stderr, but can automatically
--   log to a file instead, which can be useful for TUI apps which are
--   redrawing the screen. To enable this logging mode, use
--   withProgName to add a ".log" suffix to the program name:
--   
--   
--   main = withProgName "PROGRAM.log" $ do ...
--   
--   
--   Now all dbg calls will log to PROGRAM.log in the current
--   directory.
--   
--   Logging, and reading the command line/program name/output context use
--   unsafePerformIO, so that these can be used anywhere, including early
--   in your program before command line parsing is complete. As a
--   consequence, if you are testing in GHCI and want to change the debug
--   level, you'll need to reload this module.
--   
--   The dbg function name clashes with the one in
--   Text.Megaparsec.Debug, unfortunately; sorry about that. If you are
--   also using that, use qualified imports, or our dbg_ alias, to
--   avoid the clash.
--   
--   The meaning of debug levels is up to you. Eg hledger uses them as
--   follows:
--   
--   
--   Debug level:  What to show:
--   ------------  ---------------------------------------------------------
--   0             normal program output only
--   1             useful warnings, most common troubleshooting info
--   2             common troubleshooting info, more detail
--   3             report options selection
--   4             report generation
--   5             report generation, more detail
--   6             input file reading
--   7             input file reading, more detail
--   8             command line parsing
--   9             any other rarely needed / more in-depth info
--   
--   
--   It's not yet possible to select debug output by topic; that would be
--   useful.
module Hledger.Utils.Debug

-- | The program's debug output verbosity, from 0 to 9. The default is 0
--   meaning no debug output. This can be overridden by running the program
--   with a --debug [1-9] command line option; a --debug flag with no value
--   means 1. Uses unsafePerformIO to read the command line. When running
--   in GHCI, changing this requires reloading this module.
debugLevel :: Int

-- | Trace or log a string if the program debug level is at or above the
--   specified level, then return the second argument.
dbgMsg :: Int -> String -> a -> a
dbg0Msg :: String -> a -> a
dbg1Msg :: String -> a -> a
dbg2Msg :: String -> a -> a
dbg3Msg :: String -> a -> a
dbg4Msg :: String -> a -> a
dbg5Msg :: String -> a -> a
dbg6Msg :: String -> a -> a
dbg7Msg :: String -> a -> a
dbg8Msg :: String -> a -> a
dbg9Msg :: String -> a -> a

-- | Like dbgMsg, but sequences properly in IO.
dbgMsgIO :: MonadIO m => Int -> String -> m ()
dbg0MsgIO :: MonadIO m => String -> m ()
dbg1MsgIO :: MonadIO m => String -> m ()
dbg2MsgIO :: MonadIO m => String -> m ()
dbg3MsgIO :: MonadIO m => String -> m ()
dbg4MsgIO :: MonadIO m => String -> m ()
dbg5MsgIO :: MonadIO m => String -> m ()
dbg6MsgIO :: MonadIO m => String -> m ()
dbg7MsgIO :: MonadIO m => String -> m ()
dbg8MsgIO :: MonadIO m => String -> m ()
dbg9MsgIO :: MonadIO m => String -> m ()

-- | Trace or log a label and showable value, pretty-printed, if the
--   program debug level is at or above the specified level; then return
--   the value.
dbg :: Show a => Int -> String -> a -> a

-- | Alias for dbg, can be used to avoid namespace clashes.
dbg_ :: Show a => Int -> String -> a -> a
dbg0 :: Show a => String -> a -> a
dbg1 :: Show a => String -> a -> a
dbg2 :: Show a => String -> a -> a
dbg3 :: Show a => String -> a -> a
dbg4 :: Show a => String -> a -> a
dbg5 :: Show a => String -> a -> a
dbg6 :: Show a => String -> a -> a
dbg7 :: Show a => String -> a -> a
dbg8 :: Show a => String -> a -> a
dbg9 :: Show a => String -> a -> a

-- | Like dbg, but sequences properly in IO.
dbgIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
dbg0IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg1IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg2IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg3IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg4IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg5IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg6IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg7IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg8IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg9IO :: (MonadIO m, Show a) => String -> a -> m ()

-- | Like dbg, but with a custom show function.
dbgWith :: Int -> (a -> String) -> a -> a
dbg0With :: (a -> String) -> a -> a
dbg1With :: (a -> String) -> a -> a
dbg2With :: (a -> String) -> a -> a
dbg3With :: (a -> String) -> a -> a
dbg4With :: (a -> String) -> a -> a
dbg5With :: (a -> String) -> a -> a
dbg6With :: (a -> String) -> a -> a
dbg7With :: (a -> String) -> a -> a
dbg8With :: (a -> String) -> a -> a
dbg9With :: (a -> String) -> a -> a

-- | Helper for producing debug messages: concatenates a name (eg a
--   function name), short description of the value being logged, and
--   string representation of the value.
--   
--   Eg: let lbl = lbl_ "print", dbg1With (lbl "part 1".show)
--   ....
lbl_ :: String -> String -> String -> String

-- | The progam name, with any ".log" suffix removed.
progName :: String

-- | Is the hledger-lib package built with ghc-debug support ?
ghcDebugSupportedInLib :: Bool

-- | Whether ghc-debug support is included in this build, and if so, how it
--   will behave. When hledger is built with the ghcdebug cabal
--   flag (off by default, because of extra deps), it can listen (on unix
--   ?) for connections from ghc-debug clients like ghc-debug-brick, for
--   pausing/resuming the program and inspecting memory usage and profile
--   information.
--   
--   With a ghc-debug-supporting build, ghc-debug can be enabled by running
--   hledger with a negative --debug level. There are three different
--   modes: --debug=-1 - run normally (can be paused/resumed by a ghc-debug
--   client), --debug=-2 - pause and await client commands at program start
--   (not useful currently), --debug=-3 - pause and await client commands
--   at program end.
data GhcDebugMode
GDNotSupported :: GhcDebugMode
GDDisabled :: GhcDebugMode
GDNoPause :: GhcDebugMode
GDPauseAtStart :: GhcDebugMode
GDPauseAtEnd :: GhcDebugMode

-- | Should the program open a socket allowing control by ghc-debug-brick
--   or similar ghc-debug client ? See GhcDebugMode.
ghcDebugMode :: GhcDebugMode

-- | When ghc-debug support has been built into the program and enabled at
--   runtime with --debug=-N, this calls ghc-debug's withGhcDebug;
--   otherwise it's a no-op.
withGhcDebug' :: a -> a

-- | When ghc-debug support has been built into the program, this calls
--   ghc-debug's pause, otherwise it's a no-op.
ghcDebugPause' :: IO ()

-- | The trace function outputs the trace message given as its first
--   argument, before returning the second argument as its result.
--   
--   For example, this returns the value of f x and outputs the
--   message to stderr. Depending on your terminal (settings), they may or
--   may not be mixed.
--   
--   
--   >>> let x = 123; f = show
--   
--   >>> trace ("calling f with x = " ++ show x) (f x)
--   calling f with x = 123
--   "123"
--   
--   
--   The trace function should only be used for debugging, or
--   for monitoring execution. The function is not referentially
--   transparent: its type indicates that it is a pure function but it has
--   the side effect of outputting the trace message.
trace :: String -> a -> a

-- | The traceIO function outputs the trace message from the IO
--   monad. This sequences the output with respect to other IO actions.
traceIO :: String -> IO ()

-- | Like traceShow but returns the shown value instead of a third
--   value.
--   
--   
--   >>> traceShowId (1+2+3, "hello" ++ "world")
--   (6,"helloworld")
--   (6,"helloworld")
--   
traceShowId :: Show a => a -> a
instance GHC.Classes.Eq Hledger.Utils.Debug.GhcDebugMode
instance GHC.Classes.Ord Hledger.Utils.Debug.GhcDebugMode
instance GHC.Internal.Show.Show Hledger.Utils.Debug.GhcDebugMode

module Hledger.Utils.Parse

-- | A parser of string to some type.
type SimpleStringParser a = Parsec HledgerParseErrorData String a

-- | A parser of strict text to some type.
type SimpleTextParser = Parsec HledgerParseErrorData Text

-- | A parser of text that runs in some monad.
type TextParser (m :: Type -> Type) a = ParsecT HledgerParseErrorData Text m a

-- | The data type SourcePos represents source positions. It
--   contains the name of the source file, a line number, and a column
--   number. Source line and column positions change intensively during
--   parsing, so we need to make them strict to avoid memory leaks.
data SourcePos
SourcePos :: FilePath -> !Pos -> !Pos -> SourcePos

-- | Name of source file
[sourceName] :: SourcePos -> FilePath

-- | Line number
[sourceLine] :: SourcePos -> !Pos

-- | Column number
[sourceColumn] :: SourcePos -> !Pos

-- | Construction of Pos from Int. The function throws
--   InvalidPosException when given a non-positive argument.
mkPos :: Int -> Pos

-- | Extract Int from Pos.
unPos :: Pos -> Int

-- | Construct initial position (line 1, column 1) given name of source
--   file.
initialPos :: FilePath -> SourcePos

-- | Pretty-print a SourcePos.
sourcePosPretty :: SourcePos -> String

-- | Render a pair of source positions in human-readable form, only
--   displaying the range of lines.
sourcePosPairPretty :: (SourcePos, SourcePos) -> String

-- | Backtracking choice, use this when alternatives share a prefix.
--   Consumes no input if all choices fail.
choice' :: forall (m :: Type -> Type) a. [TextParser m a] -> TextParser m a

-- | Backtracking choice, use this when alternatives share a prefix.
--   Consumes no input if all choices fail.
choiceInState :: forall s (m :: Type -> Type) a. [StateT s (ParsecT HledgerParseErrorData Text m) a] -> StateT s (ParsecT HledgerParseErrorData Text m) a
surroundedBy :: Applicative m => m openclose -> m a -> m a
parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a

-- | Run a text parser in the identity monad. See also: parseWithState.
runTextParser :: TextParser Identity a -> Text -> Either HledgerParseErrors a

-- | Run a text parser in the identity monad. See also: parseWithState.
rtp :: TextParser Identity a -> Text -> Either HledgerParseErrors a
parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a

-- | Run a stateful parser with some initial state on a text. See also:
--   runTextParser, runJournalParser.
parseWithState :: Monad m => st -> StateT st (ParsecT HledgerParseErrorData Text m) a -> Text -> m (Either HledgerParseErrors a)
parseWithState' :: Stream s => st -> StateT st (ParsecT e s Identity) a -> s -> Either (ParseErrorBundle s e) a
fromparse :: (Show t, Show (Token t), Show e) => Either (ParseErrorBundle t e) a -> a
parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a
showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String
nonspace :: forall (m :: Type -> Type). TextParser m Char
isNewline :: Char -> Bool
isNonNewlineSpace :: Char -> Bool
restofline :: forall (m :: Type -> Type). TextParser m String
eolof :: forall (m :: Type -> Type). TextParser m ()
spacenonewline :: forall s (m :: Type -> Type). (Stream s, Char ~ Token s) => ParsecT HledgerParseErrorData s m Char
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces' :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool

-- | Trace to stderr or log to debug log the provided label (if non-null)
--   and current parser state (position and next input), if the global
--   debug level is at or above the specified level. See also:
--   Hledger.Utils.Debug, megaparsec's dbg. Uses unsafePerformIO. XXX Can
--   be hard to make this evaluate.
dbgparse :: forall (m :: Type -> Type). Int -> String -> TextParser m ()

-- | Custom error data for hledger parsers. Specialised for a Text
--   parse stream. ReparseableTextParseErrorData ?
data HledgerParseErrorData

-- | A specialised version of ParseErrorBundle: a non-empty collection of
--   hledger parse errors, equipped with PosState to help pretty-print
--   them. Specialised for a Text parse stream.
type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData

-- | Fail at a specific source position, given by the raw offset from the
--   start of the input stream (the number of tokens processed at that
--   point).
parseErrorAt :: Int -> String -> HledgerParseErrorData

-- | Fail at a specific source interval, given by the raw offsets of its
--   endpoints from the start of the input stream (the numbers of tokens
--   processed at those points).
--   
--   Note that care must be taken to ensure that the specified interval
--   does not span multiple lines of the input source. This will not be
--   checked.
parseErrorAtRegion :: Int -> Int -> String -> HledgerParseErrorData

-- | A fragment of source suitable for "re-parsing". The purpose of this
--   data type is to preserve the content and source position of the
--   excerpt so that parse errors raised during "re-parsing" may properly
--   reference the original source.
data SourceExcerpt

-- | Get the raw text of a source excerpt.
getExcerptText :: SourceExcerpt -> Text

-- | 'excerpt_ p' applies the given parser p and extracts the
--   portion of the source consumed by p, along with the source
--   position of this portion. This is the only way to create a source
--   excerpt suitable for "re-parsing" by reparseExcerpt.
excerpt_ :: MonadParsec HledgerParseErrorData Text m => m a -> m SourceExcerpt

-- | 'reparseExcerpt s p' "re-parses" the source excerpt s using
--   the parser p. Parse errors raised by p will be
--   re-thrown at the source position of the source excerpt.
--   
--   In order for the correct source file to be displayed when re-throwing
--   parse errors, we must ensure that the source file during the use of
--   'reparseExcerpt s p' is the same as that during the use of
--   excerpt_ that generated the source excerpt s. However,
--   we can usually expect this condition to be satisfied because, at the
--   time of writing, the only changes of source file in the codebase take
--   place through include files, and the parser for include files neither
--   accepts nor returns SourceExcerpts.
reparseExcerpt :: forall (m :: Type -> Type) a. Monad m => SourceExcerpt -> ParsecT HledgerParseErrorData Text m a -> ParsecT HledgerParseErrorData Text m a

-- | Pretty-print our custom parse errors. It is necessary to use this
--   instead of errorBundlePretty when custom parse errors are
--   thrown.
--   
--   This function intercepts our custom parse errors and applies final
--   adjustments (finalizeCustomError) before passing them to
--   errorBundlePretty. These adjustments are part of the
--   implementation of the behaviour of our custom parse errors.
--   
--   Note: We must ensure that the offset of the PosState of the
--   provided ParseErrorBundle is no larger than the offset
--   specified by a ErrorFailAt constructor. This is guaranteed if
--   this offset is set to 0 (that is, the beginning of the source file),
--   which is the case for ParseErrorBundles returned from
--   runParserT.
customErrorBundlePretty :: HledgerParseErrors -> String
type FinalParseError = FinalParseError' HledgerParseErrorData

-- | A type representing "final" parse errors that cannot be backtracked
--   from and are guaranteed to halt parsing. The anti-backtracking
--   behaviour is implemented by an ExceptT layer in the parser's
--   monad stack, using this type as the ExceptT error type.
--   
--   We have three goals for this type: (1) it should be possible to
--   convert any parse error into a "final" parse error, (2) it should be
--   possible to take a parse error thrown from an include file and
--   re-throw it in the context of the parent file, and (3) the
--   pretty-printing of "final" parse errors should be consistent with that
--   of ordinary parse errors, but should also report the stack of parent
--   files when errors are thrown from included files.
--   
--   In order to pretty-print a "final" parse error (goal 3), it must be
--   bundled with include filepaths and its full source text. When a
--   "final" parse error is thrown from within a parser, we do not have
--   access to the full source, so we must hold the parse error
--   (FinalParseError) until it can be combined with the full source
--   (and any parent file paths) by the parser's caller
--   (FinalParseErrorBundle).
data FinalParseError' e
type FinalParseErrorBundle = FinalParseErrorBundle' HledgerParseErrorData

-- | A type bundling a ParseError with its full source text,
--   filepath, and stack of include files. Suitable for pretty-printing.
--   
--   Megaparsec's ParseErrorBundle type already bundles a parse
--   error with its full source text and filepath, so we just add a stack
--   of include files.
data FinalParseErrorBundle' e

-- | Convert a "regular" parse error into a "final" parse error.
finalError :: ParseError Text e -> FinalParseError' e

-- | Like megaparsec's fancyFailure, but as a "final" parse error.
finalFancyFailure :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => Set (ErrorFancy e) -> m a

-- | Like fail, but as a "final" parse error.
finalFail :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => String -> m a

-- | Like megaparsec's customFailure, but as a "final" parse error.
finalCustomFailure :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => e -> m a

-- | Pretty-print a "final" parse error: print the stack of include files,
--   then apply the pretty-printer for parse error bundles. Note that
--   attachSource must be used on a "final" parse error before it
--   can be pretty-printed.
finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String

-- | Attach a filepath and source text to a "final" parse error so that it
--   can be pretty-printed. You must ensure that you provide the
--   appropriate source text and filepath.
attachSource :: FilePath -> Text -> FinalParseError' e -> FinalParseErrorBundle' e

-- | Parse an include file with the given parser and initial state,
--   discarding the resulting state, and re-throwing any parse errors as
--   final parse errors with the file's info attached.
parseIncludeFile :: forall (m :: Type -> Type) st a. Monad m => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a -> st -> FilePath -> Text -> StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a
instance GHC.Classes.Eq Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Internal.Base.Monoid (Hledger.Utils.Parse.FinalParseError' e)
instance GHC.Classes.Ord Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Classes.Ord (Text.Megaparsec.Error.ParseError Data.Text.Internal.Text Hledger.Utils.Parse.HledgerParseErrorData)
instance GHC.Internal.Base.Semigroup (Hledger.Utils.Parse.FinalParseError' e)
instance Text.Megaparsec.Error.ShowErrorComponent Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (Hledger.Utils.Parse.FinalParseError' e)
instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (Hledger.Utils.Parse.FinalParseErrorBundle' e)
instance GHC.Internal.Show.Show Hledger.Utils.Parse.HledgerParseErrorData

module Hledger.Utils.Test

-- | Timeout to be applied to individual tests.
data Timeout

-- | String is the original representation of the timeout (such as
--   "0.5m"), so that we can print it back. Integer is the
--   number of microseconds.
Timeout :: Integer -> String -> Timeout
NoTimeout :: Timeout

-- | The after combinator declares dependencies between tests.
--   
--   If a TestTree is wrapped in after, the tests in this
--   tree will not run until certain other tests («dependencies») have
--   finished. These dependencies are specified using an AWK pattern (see
--   the «Patterns» section in the README).
--   
--   Moreover, if the DependencyType argument is set to
--   AllSucceed and at least one dependency has failed, this test
--   tree will not run at all.
--   
--   Tasty does not check that the pattern matches any tests (let alone the
--   correct set of tests), so it is on you to supply the right pattern.
--   
--   
Examples
--   
--   The following test will be executed only after all tests that contain
--   Foo anywhere in their path finish.
--   
--   
--   after AllFinish "Foo" $
--      
--   
--   
--   testCase "A test that depends on Foo.Bar" $ ... 
--   
--   Note, however, that our test also happens to contain Foo as
--   part of its name, so it also matches the pattern and becomes a
--   dependency of itself. This will result in a DependencyLoop
--   exception. To avoid this, either change the test name so that it
--   doesn't mention Foo or make the pattern more specific.
--   
--   You can use AWK patterns, for instance, to specify the full path to
--   the dependency.
--   
--   
--   after AllFinish "$0 == \"Tests.Foo.Bar\"" $
--      
--   
--   
--   testCase "A test that depends on Foo.Bar" $ ... 
--   
--   Or only specify the dependency's own name, ignoring the group names:
--   
--   
--   after AllFinish "$NF == \"Bar\"" $
--      
--   
--   
--   testCase "A test that depends on Foo.Bar" $ ... 
after :: DependencyType -> String -> TestTree -> TestTree

-- | Customize the test tree based on the run-time options.
askOption :: IsOption v => (v -> TestTree) -> TestTree

-- | Locally set the option value for the given test subtree.
localOption :: IsOption v => v -> TestTree -> TestTree

-- | List of the default ingredients. This is what defaultMain uses.
--   
--   At the moment it consists of listingTests and
--   consoleTestReporter.
defaultIngredients :: [Ingredient]

-- | A shortcut for creating Timeout values.
mkTimeout :: Integer -> Timeout

-- | The main data structure defining a test suite.
--   
--   It consists of individual test cases and properties, organized in
--   named groups which form a tree-like hierarchy.
--   
--   There is no generic way to create a test case. Instead, every test
--   provider (tasty-hunit, tasty-smallcheck etc.) provides a function to
--   turn a test case into a TestTree.
--   
--   Groups can be created using testGroup.
data TestTree

-- | These are the two ways in which one test may depend on the others.
--   
--   This is the same distinction as the hard vs soft dependencies in
--   TestNG.
data DependencyType

-- | The current test tree will be executed after its dependencies finish,
--   and only if all of the dependencies succeed.
AllSucceed :: DependencyType

-- | The current test tree will be executed after its dependencies finish,
--   regardless of whether they succeed or not.
AllFinish :: DependencyType

-- | The name of a test or a group of tests.
type TestName = String

-- | Create a named group of test cases or other groups. Tests are executed
--   in parallel. For sequential execution, see sequentialTestGroup.
testGroup :: TestName -> [TestTree] -> TestTree

-- | Create a named group of test cases or other groups. Tests are executed
--   in order. For parallel execution, see testGroup.
sequentialTestGroup :: TestName -> DependencyType -> [TestTree] -> TestTree

-- | Like after, but accepts the pattern as a syntax tree instead of
--   a string. Useful for generating a test tree programmatically.
--   
--   
Examples
--   
--   Only match on the test's own name, ignoring the group names:
--   
--   
--   after_ AllFinish (EQ (Field NF) (StringLit "Bar")) $
--      
--   
--   
--   testCase "A test that depends on Foo.Bar" $ ... 
after_ :: DependencyType -> Expr -> TestTree -> TestTree

-- | This ingredient doesn't do anything apart from registering additional
--   options.
--   
--   The option values can be accessed using askOption.
includingOptions :: [OptionDescription] -> Ingredient

-- | Parse the command line arguments and run the tests using the provided
--   ingredient list.
--   
--   When the tests finish, this function calls exitWith with the
--   exit code that indicates whether any tests have failed. See
--   defaultMain for details.
defaultMainWithIngredients :: [Ingredient] -> TestTree -> IO ()

-- | Locally adjust the option value for the given test subtree.
adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree

-- | Acquire the resource to run this test (sub)tree and release it
--   afterwards.
withResource :: IO a -> (a -> IO ()) -> (IO a -> TestTree) -> TestTree

-- | Assert any Left value.
assertLeft :: (HasCallStack, Eq b, Show b) => Either a b -> Assertion

-- | Assert any Right value.
assertRight :: (HasCallStack, Eq a, Show a) => Either a b -> Assertion

-- | Assert that this stateful parser runnable in IO successfully parses
--   all of the given input text, showing the parse error if it fails.
--   Suitable for hledger's JournalParser parsers.
assertParse :: (HasCallStack, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> Assertion

-- | Assert a parser produces an expected value.
assertParseEq :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> a -> Assertion

-- | Like assertParseEq, but transform the parse result with the given
--   function before comparing it.
assertParseEqOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (a -> b) -> b -> Assertion

-- | Assert that this stateful parser runnable in IO fails to parse the
--   given input text, with a parse error containing the given string.
assertParseError :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> String -> Assertion
assertParseE :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> Assertion
assertParseEqE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> a -> Assertion
assertParseErrorE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> String -> Assertion

-- | Run a stateful parser in IO like assertParse, then assert that the
--   final state (the wrapped state, not megaparsec's internal state),
--   transformed by the given function, matches the given expected value.
assertParseStateOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (st -> b) -> b -> Assertion

-- | String formatting helpers, starting to get a bit out of control.
module Hledger.Utils.String

-- | Take elements from the end of a list.
takeEnd :: Int -> [a] -> [a]
capitalise :: String -> String
lowercase :: String -> String
uppercase :: String -> String
underline :: String -> String
stripbrackets :: String -> String

-- | Double-quote this string if it contains whitespace, single quotes or
--   double-quotes, escaping the quotes as needed.
quoteIfNeeded :: String -> String

-- | Single-quote this string if it contains whitespace or double-quotes.
--   Does not work for strings containing single quotes.
singleQuoteIfNeeded :: String -> String

-- | Try to single- and backslash-quote a string as needed to make it
--   usable as an argument on a (sh/bash) shell command line. At least,
--   well enough to handle common currency symbols, like $. Probably broken
--   in many ways.
--   
--   
--   >>> quoteForCommandLine "a"
--   "a"
--   
--   >>> quoteForCommandLine "\""
--   "'\"'"
--   
--   >>> quoteForCommandLine "$"
--   "'$'"
--   
quoteForCommandLine :: String -> String

-- | Quote-aware version of words - don't split on spaces which are inside
--   quotes. NB correctly handles "a'b" but not "'a'". Can raise
--   an error if parsing fails.
words' :: String -> [String]

-- | Strip ANSI escape sequences from a string.
--   
--   
--   >>> stripAnsi "\ESC[31m-1\ESC[m"
--   "-1"
--   
stripAnsi :: String -> String

-- | Remove leading and trailing whitespace.
strip :: String -> String

-- | Remove leading whitespace.
lstrip :: String -> String

-- | Remove trailing whitespace.
rstrip :: String -> String

-- | Strip the given starting and ending character from the start and end
--   of a string if both are present.
strip1Char :: Char -> Char -> String -> String

-- | Strip a run of zero or more characters matching the predicate from the
--   start and end of a string.
stripBy :: (Char -> Bool) -> String -> String

-- | Strip a single balanced enclosing pair of a character matching the
--   predicate from the start and end of a string.
strip1By :: (Char -> Bool) -> String -> String

-- | Remove all trailing newlines/carriage returns.
chomp :: String -> String

-- | Remove all trailing newline/carriage returns, leaving just one
--   trailing newline.
chomp1 :: String -> String

-- | Remove consecutive line breaks, replacing them with single space
singleline :: String -> String
elideLeft :: Int -> String -> String
elideRight :: Int -> String -> String

-- | Clip and pad a string to a minimum & maximum width, andor
--   leftright justify it. Works on multi-line strings too (but will
--   rewrite non-unix line endings).
formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String

-- | Returns width of a character in a monospace font: 0 for a combining
--   character, 1 for a regular character, 2 for an East Asian wide
--   character. Ambiguous characters are treated as width 1.
charWidth :: Char -> Int

-- | Alias for realLength.
strWidth :: String -> Int

-- | Like strWidth, but also strips ANSI escape sequences before
--   calculating the width.
--   
--   This is no longer used in code, as widths are calculated before adding
--   ANSI escape sequences, but is being kept around for now.
strWidthAnsi :: String -> Int

-- | Double-width-character-aware string truncation. Take as many
--   characters as possible from a string without exceeding the specified
--   width. Eg takeWidth 3 "りんご" = "り".
takeWidth :: Int -> String -> String

-- | Utilities used throughout hledger, or needed low in the module
--   hierarchy. These are the bottom of hledger's module graph.
module Hledger.Utils

-- | Apply a function the specified number of times, which should be > 0
--   (otherwise does nothing). Possibly uses O(n) stack ?
applyN :: Int -> (a -> a) -> a -> a

-- | Like mapM but uses sequence'.
mapM' :: Monad f => (a -> f b) -> [a] -> f [b]

-- | This is a version of sequence based on difference lists. It is
--   slightly faster but we mostly use it because it uses the heap instead
--   of the stack. This has the advantage that Neil Mitchell’s trick of
--   limiting the stack size to discover space leaks doesn’t show this as a
--   false positive.
sequence' :: Monad f => [f a] -> f [a]
curry2 :: ((a, b) -> c) -> a -> b -> c
uncurry2 :: (a -> b -> c) -> (a, b) -> c
curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e

-- | Division, returning 0 when the denominator is 0.
divideSafe :: (Eq a, Fractional a) => a -> a -> a

-- | Total version of maximum, for integral types, giving 0 for an empty
--   list.
maximum' :: Integral a => [a] -> a

-- | Strict version of maximum that doesn’t leak space
maximumStrict :: Ord a => [a] -> a

-- | Strict version of minimum that doesn’t leak space
minimumStrict :: Ord a => [a] -> a
splitAtElement :: Eq a => a -> [a] -> [[a]]

-- | Strict version of sum that doesn’t leak space
sumStrict :: Num a => [a] -> a

-- | Version of all that fails on an empty list.
all1 :: (a -> Bool) -> [a] -> Bool

-- | Take elements from a list until a predicate fails, and then keep the
--   first failing element as well.
takeUntilFails :: (a -> Bool) -> [a] -> [a]

-- | Take elements from a non-empty list until a predicate fails, and then
--   keep the first failing element as well.
takeUntilFailsNE :: (a -> Bool) -> NonEmpty a -> NonEmpty a

-- | Get the leaves of this tree as a list. The topmost node ("root" in
--   hledger account trees) is not counted as a leaf.
treeLeaves :: Tree a -> [a]
first3 :: (a, b, c) -> a
second3 :: (a, b, c) -> b
third3 :: (a, b, c) -> c
first4 :: (a, b, c, d) -> a
second4 :: (a, b, c, d) -> b
third4 :: (a, b, c, d) -> c
fourth4 :: (a, b, c, d) -> d
first5 :: (a, b, c, d, e) -> a
second5 :: (a, b, c, d, e) -> b
third5 :: (a, b, c, d, e) -> c
fourth5 :: (a, b, c, d, e) -> d
fifth5 :: (a, b, c, d, e) -> e
first6 :: (a, b, c, d, e, f) -> a
second6 :: (a, b, c, d, e, f) -> b
third6 :: (a, b, c, d, e, f) -> c
fourth6 :: (a, b, c, d, e, f) -> d
fifth6 :: (a, b, c, d, e, f) -> e
sixth6 :: (a, b, c, d, e, f) -> f

-- | Convert a list of strings to a multi-line multi-column list fitting
--   within the given width. Not wide character aware.
multicol :: Int -> [String] -> String

-- | Find the number of digits of an Int.
numDigitsInt :: Integral a => Int -> a

-- | Find the number of digits of an Integer. The integer should not have
--   more digits than an Int can count. This is probably inefficient.
numDigitsInteger :: Integer -> Int

-- | Make classy lenses for Hledger options fields. This is intended to be
--   used with BalancingOpts, InputOpt, ReportOpts, ReportSpec, and
--   CliOpts. When run on X, it will create a typeclass named HasX (except
--   for ReportOpts, which will be named HasReportOptsNoUpdate) containing
--   all the lenses for that type. If the field name starts with an
--   underscore, the lens name will be created by stripping the underscore
--   from the front on the name. If the field name ends with an underscore,
--   the field name ends with an underscore, the lens name will be mostly
--   created by stripping the underscore, but a few names for which this
--   would create too many conflicts instead have a second underscore
--   appended. ReportOpts fields for which updating them requires updating
--   the query in ReportSpec are instead names by dropping the trailing
--   underscore and appending NoUpdate to the name, e.g. querystring_ ->
--   querystringNoUpdate.
--   
--   There are a few reasons for the complicated rules. - We have some
--   legacy field names ending in an underscore (e.g. value_) which we want
--   to temporarily accommodate, before eventually switching to a more
--   modern style (e.g. _rsReportOpts) - Certain fields in ReportOpts need
--   to update the enclosing ReportSpec when they are updated, and it is a
--   common programming error to forget to do this. We append NoUpdate to
--   those lenses which will not update the enclosing field, and reserve
--   the shorter name for manually define lenses (or at least something
--   lens-like) which will update the ReportSpec. cf. the lengthy
--   discussion here and in surrounding comments:
--   https://github.com/simonmichael/hledger/pull/1545#issuecomment-881974554
makeHledgerClassyLenses :: Name -> DecsQ
tests_Utils :: TestTree

-- | CSV utilities.
module Hledger.Write.Csv
type CSV = [CsvRecord]
type CsvRecord = [CsvValue]
type CsvValue = Text
printCSV :: CSV -> Text
printTSV :: CSV -> Text
tests_CsvUtils :: TestTree

-- | hledger's cmdargs modes parse command-line arguments to an
--   intermediate format, RawOpts (an association list), rather than a
--   fixed ADT like CliOpts. This allows the modes and flags to be reused
--   more easily by hledger commands/scripts in this and other packages.
module Hledger.Data.RawOptions

-- | The result of running cmdargs: an association list of option names to
--   string values.
data RawOpts
mkRawOpts :: [(String, String)] -> RawOpts
overRawOpts :: ([(String, String)] -> [(String, String)]) -> RawOpts -> RawOpts
dropRawOpt :: String -> RawOpts -> RawOpts
setopt :: String -> String -> RawOpts -> RawOpts
setboolopt :: String -> RawOpts -> RawOpts
unsetboolopt :: String -> RawOpts -> RawOpts
appendopts :: [(String, String)] -> RawOpts -> RawOpts

-- | Is the named flag present ?
boolopt :: String -> RawOpts -> Bool

-- | Like boolopt, except if the flag is repeated on the command line it
--   toggles the value. An even number of repetitions is equivalent to
--   none.
toggleopt :: String -> RawOpts -> Bool

-- | From a list of RawOpts, get the last one (ie the right-most on the
--   command line) for which the given predicate returns a Just value.
--   Useful for exclusive choice flags like --daily|--weekly|--quarterly...
--   
--   
--   >>> import Safe (readMay)
--   
--   >>> choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])
--   Just "c"
--   
--   >>> choiceopt (const Nothing) (RawOpts [("a","")])
--   Nothing
--   
--   >>> choiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe Ordering
--   Just EQ
--   
choiceopt :: (String -> Maybe a) -> RawOpts -> Maybe a

-- | Collects processed and filtered list of options preserving their order
--   
--   
--   >>> collectopts (const Nothing) (RawOpts [("x","")])
--   []
--   
--   >>> collectopts Just (RawOpts [("a",""),("b","")])
--   [("a",""),("b","")]
--   
collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]
stringopt :: String -> RawOpts -> String
maybestringopt :: String -> RawOpts -> Maybe String
listofstringopt :: String -> RawOpts -> [String]

-- | Reads the named option's Int argument. If not present it will return
--   0. An argument that is too small or too large will raise an error.
intopt :: String -> RawOpts -> Int

-- | Reads the named option's natural-number argument. If not present it
--   will return 0. An argument that is negative or too large will raise an
--   error.
posintopt :: String -> RawOpts -> Int

-- | Reads the named option's Int argument, if it is present. An argument
--   that is too small or too large will raise an error.
maybeintopt :: String -> RawOpts -> Maybe Int

-- | Reads the named option's natural-number argument, if it is present. An
--   argument that is negative or too large will raise an error.
maybeposintopt :: String -> RawOpts -> Maybe Int
maybecharopt :: String -> RawOpts -> Maybe Char
maybeynopt :: String -> RawOpts -> Maybe Bool
maybeynaopt :: String -> RawOpts -> Maybe YNA
instance Data.Default.Internal.Default Hledger.Data.RawOptions.RawOpts
instance GHC.Internal.Show.Show Hledger.Data.RawOptions.RawOpts

-- | Date parsing and utilities for hledger.
--   
--   For date and time values, we use the standard Day and UTCTime types.
--   
--   A SmartDate is a date which may be partially-specified or
--   relative. Eg 2008/12/31, but also 2008/12, 12/31, tomorrow, last week,
--   next year, in 5 days, in -3 quarters. We represent these as a triple
--   of strings like ("2008","12",""), ("","","tomorrow"),
--   ("","last","week").
--   
--   A DateSpan is the span of time between two specific calendar
--   dates, or an open-ended span where one or both dates are unspecified.
--   (A date span with both ends unspecified matches all dates.)
--   
--   An Interval is ledger's "reporting interval" - weekly, monthly,
--   quarterly, etc.
--   
--   Period will probably replace DateSpan in due course.
module Hledger.Data.Dates
fromEFDay :: EFDay -> Day
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay

-- | Get the current local date.
getCurrentDay :: IO Day

-- | Get the current local month number.
getCurrentMonth :: IO Int

-- | Get the current local year.
getCurrentYear :: IO Integer
nulldate :: Day

-- | Does the span include the given date ?
spanContainsDate :: DateSpan -> Day -> Bool

-- | Does the period include the given date ? (Here to avoid import cycle).
periodContainsDate :: Period -> Day -> Bool

-- | A simple date parsing helper: parses these YMD date string formats:
--   `YYYY-MM-DD`, `YYYY<i>MM</i>DD`, DD or YYYYMMDD, where
--   the month and day each have two digits and the year has one or more.
--   
--   This is different from the Smart Dates of the CLI and period
--   expressions ("smartdate", below) and not quite the same as the Simple
--   Dates of the journal ("datep", in Hledger.Read.Common). It's mainly
--   for internal or interactive use, eg when debugging - but currently is
--   also used in a few user-facing places, such as: parsing --value's
--   argument, parsing .latest files, and parsing hledger's --version
--   output (which uses unseparated dates).
--   
--   Unseparated dates were added in 2025 for convenience. Note it means
--   many integers will now parse successfully.
--   
--   
--   >>> parsedate "2008/02/03"
--   Just 2008-02-03
--   
--   >>> parsedate "2008/02/03/"
--   Nothing
--   
--   >>> parsedate "2008/02/30"
--   Nothing
--   
--   >>> parsedate "2025-01-01"
--   Just 2025-01-01
--   
--   >>> parsedate "2025.01.01"
--   Just 2025-01-01
--   
--   >>> parsedate "20250101"
--   Just 2025-01-01
--   
--   >>> parsedate "00101"
--   Just 0000-01-01
--   
parsedate :: String -> Maybe Day
showDate :: Day -> Text
showEFDate :: EFDay -> Text

-- | Render a datespan as a display string, abbreviating into a compact
--   form if possible. Warning, hides whether dates are Exact or Flex.
showDateSpan :: DateSpan -> Text

-- | Show a DateSpan with its begin/end dates, exact or flex.
showDateSpanDebug :: DateSpan -> String

-- | Like showDateSpan, but show month spans as just the abbreviated month
--   name in the current locale.
showDateSpanAbbrev :: DateSpan -> Text
elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a
prevday :: Day -> Day

-- | Parse a period expression, specifying a date span and optionally a
--   reporting interval. Requires a reference "today" date for resolving
--   any relative start/end dates (only; it is not needed for parsing the
--   reporting interval).
--   
--   
--   >>> let p = parsePeriodExpr (fromGregorian 2008 11 26)
--   
--   >>> p "from Aug to Oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   >>> p "aug to oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   >>> p "2009q2"
--   Right (NoInterval,DateSpan 2009Q2)
--   
--   >>> p "Q3"
--   Right (NoInterval,DateSpan 2008Q3)
--   
--   >>> p "every 3 days in Aug"
--   Right (Days 3,DateSpan 2008-08)
--   
--   >>> p "daily from aug"
--   Right (Days 1,DateSpan 2008-08-01..)
--   
--   >>> p "every week to 2009"
--   Right (Weeks 1,DateSpan ..2008-12-31)
--   
--   >>> p "every 2nd day of month"
--   Right (MonthDay 2,DateSpan ..)
--   
--   >>> p "every 2nd day"
--   Right (MonthDay 2,DateSpan ..)
--   
--   >>> p "every 2nd day 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd day 2009-"
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 29th Nov"
--   Right (MonthAndDay 11 29,DateSpan ..)
--   
--   >>> p "every 29th nov ..2009"
--   Right (MonthAndDay 11 29,DateSpan ..2008-12-31)
--   
--   >>> p "every nov 29th"
--   Right (MonthAndDay 11 29,DateSpan ..)
--   
--   >>> p "every Nov 29th 2009.."
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   >>> p "every 11/29 from 2009"
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   >>> p "every 11/29 since 2009"
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd Thursday of month to 2009"
--   Right (NthWeekdayOfMonth 2 4,DateSpan ..2008-12-31)
--   
--   >>> p "every 1st monday of month to 2009"
--   Right (NthWeekdayOfMonth 1 1,DateSpan ..2008-12-31)
--   
--   >>> p "every tue"
--   Right (DaysOfWeek [2],DateSpan ..)
--   
--   >>> p "every 2nd day of week"
--   Right (DaysOfWeek [2],DateSpan ..)
--   
--   >>> p "every 2nd day of month"
--   Right (MonthDay 2,DateSpan ..)
--   
--   >>> p "every 2nd day"
--   Right (MonthDay 2,DateSpan ..)
--   
--   >>> p "every 2nd day 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd day of month 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan)

-- | Parse a period expression to an Interval and overall DateSpan using
--   the provided reference date, or return a parse error.
parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan)

-- | Like parsePeriodExpr, but call error' on failure.
parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan)
nulldatespan :: DateSpan

-- | An exact datespan of zero length, that matches no date.
emptydatespan :: DateSpan
datesepchar :: forall (m :: Type -> Type). TextParser m Char
datesepchars :: String
isDateSepChar :: Char -> Bool
spanStart :: DateSpan -> Maybe Day
spanEnd :: DateSpan -> Maybe Day
spanStartYear :: DateSpan -> Maybe Year
spanEndYear :: DateSpan -> Maybe Year

-- | Get the 0-2 years mentioned explicitly in a DateSpan.
spanYears :: DateSpan -> [Year]

-- | Get overall span enclosing multiple sequentially ordered spans. The
--   start and end date will be exact or flexible depending on the first
--   span's start date and last span's end date.
spansSpan :: [DateSpan] -> DateSpan

-- | Calculate the intersection of two datespans.
--   
--   For non-intersecting spans, gives an empty span beginning on the
--   second's start date: >>> DateSpan (Just $ Flex $
--   fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03)
--   spanIntersect DateSpan (Just $ Flex $ fromGregorian 2018 01 03)
--   (Just $ Flex $ fromGregorian 2018 01 05) DateSpan
--   2018-01-03..2018-01-02
spanIntersect :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the intersection of a number of datespans.
spansIntersect :: [DateSpan] -> DateSpan

-- | Fill any unspecified dates in the first span with the dates from the
--   second one (if specified there). Sort of a one-way spanIntersect. This
--   one can create an invalid span that'll always be empty.
--   
--   
--   >>> :{
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) Nothing
--    `spanDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2024-01-01
--   
--   
--   
--   >>> :{
--    DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
--    `spanDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2025-01-01..2024-01-01
--   
spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan

-- | A smarter version of spanDefaultsFrom that avoids creating invalid
--   spans ending before they begin. Kept separate for now to reduce risk.
--   
--   
--   >>> :{
--    DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
--    `spanValidDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2025-01-01..
--   
spanValidDefaultsFrom :: DateSpan -> DateSpan -> DateSpan

-- | Extend the definite start/end dates of the first span, if needed, to
--   include the definite start/end dates of the second span. Andor,
--   replace open startend dates in the first span with definite
--   start/end dates from the second. Unlike spanUnion, open start/end
--   dates in the second are ignored.
--   
--   
--   >>> ys2024 = fromGregorian 2024 01 01
--   
--   >>> ys2025 = fromGregorian 2025 01 01
--   
--   >>> to2024 = DateSpan Nothing               (Just $ Exact ys2024)
--   
--   >>> all2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
--   
--   >>> partof2024 = DateSpan (Just $ Exact $ fromGregorian 2024 03 01) (Just $ Exact $ fromGregorian 2024 09 01)
--   
--   >>> spanExtend to2024 all2024
--   DateSpan 2024
--   
--   >>> spanExtend all2024 to2024
--   DateSpan 2024
--   
--   >>> spanExtend partof2024 all2024
--   DateSpan 2024
--   
--   >>> spanExtend all2024 partof2024
--   DateSpan 2024
--   
spanExtend :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the union of two datespans. If either span is open-ended,
--   the union will be too.
--   
--   
--   >>> ys2024 = fromGregorian 2024 01 01
--   
--   >>> ys2025 = fromGregorian 2025 01 01
--   
--   >>> to2024 = DateSpan Nothing               (Just $ Exact ys2024)
--   
--   >>> in2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
--   
--   >>> spanUnion to2024 in2024
--   DateSpan ..2024-12-31
--   
--   >>> spanUnion in2024 to2024
--   DateSpan ..2024-12-31
--   
spanUnion :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the union of a number of datespans.
spansUnion :: [DateSpan] -> DateSpan

-- | Calculate the minimal DateSpan containing all of the given Days (in
--   the usual exclusive-end-date sense: beginning on the earliest, and
--   ending on the day after the latest).
daysSpan :: [Day] -> DateSpan

-- | Select the DateSpan containing a given Day, if any, from a given list
--   of DateSpans.
--   
--   If the DateSpans are non-overlapping, this returns the unique
--   containing DateSpan, if it exists. If the DateSpans are overlapping,
--   it will return the containing DateSpan with the latest start date, and
--   then latest end date.
latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan

-- | Parse a date in any of the formats allowed in Ledger's period
--   expressions, and some others. Assumes any text in the parse stream has
--   been lowercased. Returns a SmartDate, to be converted to a full date
--   later (see fixSmartDate).
--   
--   Examples:
--   
--   
--   2004                                        (start of year, which must have 4+ digits)
--   2004/10                                     (start of month, which must be 1-12)
--   2004/10/1                                   (exact date, day must be 1-31)
--   10/1                                        (month and day in current year)
--   21                                          (day in current month)
--   october, oct                                (start of month in current year)
--   yesterday, today, tomorrow                  (-1, 0, 1 days from today)
--   last/this/next day/week/month/quarter/year  (-1, 0, 1 periods from the current period)
--   last/this/next monday/mon                   (the previous or next named weekday; this=next)
--   last/next january/jan                       (previous or next start of named month; this disallowed to avoid confusion)
--   in n days/weeks/months/quarters/years       (n periods from the current period)
--   n days/weeks/months/quarters/years ago      (-n periods from the current period)
--   20181201                                    (8 digit YYYYMMDD with valid year month and day)
--   201812                                      (6 digit YYYYMM with valid year and month)
--   
--   
--   Note malformed digit sequences might give surprising results:
--   
--   
--   201813                                      (6 digits with an invalid month is parsed as start of 6-digit year)
--   20181301                                    (8 digits with an invalid month is parsed as start of 8-digit year)
--   20181232                                    (8 digits with an invalid day gives an error)
--   201801012                                   (9+ digits beginning with a valid YYYYMMDD gives an error)
--   
--   
--   Eg:
--   
--   YYYYMMDD is parsed as year-month-date if those parts are valid (>=4
--   digits, 1-12, and 1-31 respectively): >>> parsewith
--   (smartdate <* eof) "20181201" Right (SmartCompleteDate 2018-12-01)
--   
--   YYYYMM is parsed as year-month-01 if year and month are valid:
--   >>> parsewith (smartdate <* eof) "201804" Right
--   (SmartAssumeStart 2018 (Just 4))
--   
--   With an invalid month, it's parsed as a year: >>> parsewith
--   (smartdate <* eof) "201813" Right (SmartAssumeStart 201813 Nothing)
--   
--   A 9+ digit number beginning with valid YYYYMMDD gives an error:
--   >>> parsewith (smartdate <* eof) "201801012" Left (...)
--   
--   Big numbers not beginning with a valid YYYYMMDD are parsed as a year:
--   >>> parsewith (smartdate <* eof) "201813012" Right
--   (SmartAssumeStart 201813012 Nothing)
smartdate :: forall (m :: Type -> Type). TextParser m SmartDate

-- | Group elements based on where they fall in a list of DateSpans
--   without gaps. The precondition is not checked.
groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])]

-- | Convert a SmartDate to a specific date using the provided reference
--   date. This date will be exact or flexible depending on whether the day
--   was specified exactly. (Missing least-significant parts produces a
--   flex date.)
--   
--   
Examples:
--   
--   
--   >>> :set -XOverloadedStrings
--   
--   >>> let t = fixSmartDateStr (fromGregorian 2008 11 26)
--   
--   >>> t "0000-01-01"
--   "0000-01-01"
--   
--   >>> t "1999-12-02"
--   "1999-12-02"
--   
--   >>> t "1999.12.02"
--   "1999-12-02"
--   
--   >>> t "1999/3/2"
--   "1999-03-02"
--   
--   >>> t "19990302"
--   "1999-03-02"
--   
--   >>> t "2008/2"
--   "2008-02-01"
--   
--   >>> t "0020/2"
--   "0020-02-01"
--   
--   >>> t "1000"
--   "1000-01-01"
--   
--   >>> t "4/2"
--   "2008-04-02"
--   
--   >>> t "2"
--   "2008-11-02"
--   
--   >>> t "January"
--   "2008-01-01"
--   
--   >>> t "feb"
--   "2008-02-01"
--   
--   >>> t "today"
--   "2008-11-26"
--   
--   >>> t "yesterday"
--   "2008-11-25"
--   
--   >>> t "tomorrow"
--   "2008-11-27"
--   
--   >>> t "this day"
--   "2008-11-26"
--   
--   >>> t "last day"
--   "2008-11-25"
--   
--   >>> t "next day"
--   "2008-11-27"
--   
--   >>> t "this week"  -- last monday
--   "2008-11-24"
--   
--   >>> t "last week"  -- previous monday
--   "2008-11-17"
--   
--   >>> t "next week"  -- next monday
--   "2008-12-01"
--   
--   >>> t "this month"
--   "2008-11-01"
--   
--   >>> t "last month"
--   "2008-10-01"
--   
--   >>> t "next month"
--   "2008-12-01"
--   
--   >>> t "this quarter"
--   "2008-10-01"
--   
--   >>> t "last quarter"
--   "2008-07-01"
--   
--   >>> t "next quarter"
--   "2009-01-01"
--   
--   >>> t "this year"
--   "2008-01-01"
--   
--   >>> t "last year"
--   "2007-01-01"
--   
--   >>> t "next year"
--   "2009-01-01"
--   
--   
--   refdate is Wednesday, 2008-11-26 >>> t "last wednesday"
--   "2008-11-19" >>> t "this wednesday" "2008-12-03" >>>
--   t "next wednesday" "2008-12-03" >>> t "last january"
--   "2008-01-01" >>> t "this january" "2009-01-01" >>> t
--   "next january" "2009-01-01" >>> t "last november"
--   "2007-11-01" >>> t "this november" "2009-11-01" >>>
--   t "next november" "2009-11-01"
--   
--   
--   >>> t "in 5 days"
--   "2008-12-01"
--   
--   >>> t "in 7 months"
--   "2009-06-01"
--   
--   >>> t "in -2 weeks"
--   "2008-11-10"
--   
--   >>> t "1 quarter ago"
--   "2008-07-01"
--   
--   >>> t "1 week ahead"
--   "2008-12-01"
--   
fixSmartDate :: Day -> SmartDate -> EFDay

-- | Convert a smart date string to an explicit yyyy/mm/dd string using the
--   provided reference date, or raise an error.
fixSmartDateStr :: Day -> Text -> Text

-- | A safe version of fixSmartDateStr.
fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text
fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay

-- | Parse a year number from a Text, making sure that at least four digits
--   are used.
yearp :: forall (m :: Type -> Type). TextParser m Integer

-- | Count the days in a DateSpan, or if it is open-ended return Nothing.
daysInSpan :: DateSpan -> Maybe Integer
startofyear :: Day -> Day
startofquarter :: Day -> Day
startofmonth :: Day -> Day
startofweek :: Day -> Day
nextday :: Day -> Day
nextweek :: Day -> Day

-- | Find the next occurrence of the specified month and day of month, on
--   or after the given date. The month should be 1-12 and the day of month
--   should be 1-31, or an error will be raised.
--   
--   
--   >>> let wed22nd = fromGregorian 2017 11 22
--   
--   >>> nextmonthandday 11 21 wed22nd
--   2018-11-21
--   
--   >>> nextmonthandday 11 22 wed22nd
--   2017-11-22
--   
--   >>> nextmonthandday 11 23 wed22nd
--   2017-11-23
--   
nextmonthandday :: Month -> MonthDay -> Day -> Day

-- | Find the next occurrence of the specified day of month, on or after
--   the given date. The day of month should be 1-31, or an error will be
--   raised.
--   
--   
--   >>> let wed22nd = fromGregorian 2017 11 22
--   
--   >>> nextnthdayofmonth 21 wed22nd
--   2017-12-21
--   
--   >>> nextnthdayofmonth 22 wed22nd
--   2017-11-22
--   
--   >>> nextnthdayofmonth 23 wed22nd
--   2017-11-23
--   
nextnthdayofmonth :: MonthDay -> Day -> Day

-- | Find the previous occurrence of some nth weekday of a month, on or
--   before the given date d.
--   
--   
--   >>> let wed22nd = fromGregorian 2017 11 22
--   
--   >>> prevNthWeekdayOfMonth 4 3 wed22nd
--   2017-11-22
--   
--   >>> prevNthWeekdayOfMonth 5 2 wed22nd
--   2017-10-31
--   
prevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day

-- | For given date d find week-long interval that starts on nth day of
--   week and covers it.
--   
--   Examples: 2017-11-22 is Wed. Week-long intervals that cover it and
--   start on Mon, Tue or Wed will start in the same week. However
--   intervals that start on Thu or Fri should start in prev week:
--   >>> let wed22nd = fromGregorian 2017 11 22 >>>
--   nthdayofweekcontaining 1 wed22nd 2017-11-20 >>>
--   nthdayofweekcontaining 2 wed22nd 2017-11-21 >>>
--   nthdayofweekcontaining 3 wed22nd 2017-11-22 >>>
--   nthdayofweekcontaining 4 wed22nd 2017-11-16 >>>
--   nthdayofweekcontaining 5 wed22nd 2017-11-17
nthdayofweekcontaining :: WeekDay -> Day -> Day
addGregorianMonthsToMonthday :: MonthDay -> Integer -> Day -> Day

-- | Advance to the nth occurrence of the given weekday, on or after the
--   given date. Can call error.
advanceToNthWeekday :: Int -> WeekDay -> Day -> Day

-- | Find the next occurrence of some nth weekday of a month, on or after
--   the given date d.
--   
--   
--   >>> let wed22nd = fromGregorian 2017 11 22
--   
--   >>> nextNthWeekdayOfMonth 3 3 wed22nd  -- next third wednesday
--   2017-12-20
--   
--   >>> nextNthWeekdayOfMonth 4 3 wed22nd  -- next fourth wednesday
--   2017-11-22
--   
--   >>> nextNthWeekdayOfMonth 5 3 wed22nd  -- next fifth wednesday
--   2017-11-29
--   
nextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day

-- | Is this an empty span, ie closed with the end date on or before the
--   start date ?
isEmptySpan :: DateSpan -> Bool
instance GHC.Internal.Show.Show Hledger.Data.Types.DateSpan

-- | AccountNames are strings like assets:cash:petty, with
--   multiple components separated by :. From a set of these we
--   derive the account hierarchy.
module Hledger.Data.AccountName
accountLeafName :: AccountName -> Text
accountNameComponents :: AccountName -> [Text]

-- | Remove some number of account name components from the front of the
--   account name. If the special "unbudgeted" top-level account is
--   present, it is preserved and dropping affects the rest of the account
--   name.
accountNameDrop :: Int -> AccountName -> AccountName
accountNameFromComponents :: [Text] -> AccountName

-- | The level (depth) of an account name.
--   
--   
--   >>> accountNameLevel ""  -- special case
--   0
--   
--   >>> accountNameLevel "assets"
--   1
--   
--   >>> accountNameLevel "assets:cash"
--   2
--   
accountNameLevel :: AccountName -> Int

-- | Convert an account name to a regular expression matching it but not
--   its subaccounts.
accountNameToAccountOnlyRegex :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it but not
--   its subaccounts, case insensitively.
accountNameToAccountOnlyRegexCI :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it and its
--   subaccounts.
accountNameToAccountRegex :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it and its
--   subaccounts, case insensitively.
accountNameToAccountRegexCI :: AccountName -> Regexp

-- | Convert a list of account names to a tree, efficiently.
accountNameTreeFrom :: [AccountName] -> Tree AccountName

-- | Truncate all account name components but the last to two characters.
accountSummarisedName :: AccountName -> Text

-- | Try to guess an account's type from its name, matching common English
--   top-level account names.
accountNameInferType :: AccountName -> Maybe AccountType

-- | Like accountNameInferType, but exclude the provided types from the
--   guesses. Used eg to prevent "equity:conversion" being inferred as
--   Conversion when a different account has been declared with that type.
accountNameInferTypeExcept :: [AccountType] -> AccountName -> Maybe AccountType
accountNameType :: Map AccountName AccountType -> AccountName -> Maybe AccountType
defaultBaseConversionAccount :: IsString a => a

-- | Regular expressions matching common English top-level account names,
--   used as a fallback when account types are not declared.
assetAccountRegex :: Regexp
cashAccountRegex :: Regexp
liabilityAccountRegex :: Regexp
equityAccountRegex :: Regexp
conversionAccountRegex :: Regexp
revenueAccountRegex :: Regexp
gainAccountRegex :: Regexp
expenseAccountRegex :: Regexp
acctsep :: Text
acctsepchar :: Char

-- | Clip an account name to a given DepthSpec, first checking
--   whether it matches any of the regular expressions controlling depth.
--   If so, clip to the depth of the most specific of those matches, i.e.
--   the one which starts matching the latest as you progress up the
--   parents of the account. Otherwise clip to the flat depth provided, or
--   return the full name if Nothing.
clipAccountName :: DepthSpec -> AccountName -> AccountName

-- | As clipAccountName, but return ... if asked to clip to
--   depth 0.
clipOrEllipsifyAccountName :: DepthSpec -> AccountName -> AccountName

-- | Calculate the depth to which an account name should be clipped for a
--   given DepthSpec.
--   
--   First checking whether the account name matches any of the regular
--   expressions controlling depth. If so, clip to the depth of the most
--   specific of those matches, i.e. the one which starts matching the
--   latest as you progress up the parents of the account. Otherwise clip
--   to the flat depth provided, or return the full name if Nothing.
getAccountNameClippedDepth :: DepthSpec -> AccountName -> Maybe Int

-- | Elide an account name to fit in the specified width. From the ledger
--   2.6 news:
--   
--   
--   What Ledger now does is that if an account name is too long, it will
--   start abbreviating the first parts of the account name down to two
--   letters in length.  If this results in a string that is still too
--   long, the front will be elided -- not the end.  For example:
--   
--     Expenses:Cash           ; OK, not too long
--     Ex:Wednesday:Cash       ; Expenses was abbreviated to fit
--     Ex:We:Afternoon:Cash    ; Expenses and Wednesday abbreviated
--     ; Expenses:Wednesday:Afternoon:Lunch:Snack:Candy:Chocolate:Cash
--     ..:Af:Lu:Sn:Ca:Ch:Cash  ; Abbreviated and elided!
--   
elideAccountName :: Int -> AccountName -> AccountName

-- | Escape an AccountName for use within a regular expression.
--   >>> putStr . T.unpack $ escapeName "First?!#$*?$(*) !^#*?
--   %)*!#" First?!#$*?$<math> !^#*? %)*!#
escapeName :: AccountName -> Text

-- | "a:b:c" -> ["a","a:b","a:b:c"]
expandAccountName :: AccountName -> [AccountName]

-- | Sorted unique account names implied by these account names, ie these
--   plus all their parent accounts up to the root. Eg: ["a:b:c","d:e"]
--   -> ["a","a:b","a:b:c","d","d:e"]
expandAccountNames :: [AccountName] -> [AccountName]

-- | Is the first account a parent or other ancestor of (and not the same
--   as) the second ?
isAccountNamePrefixOf :: AccountName -> AccountName -> Bool
isSubAccountNameOf :: AccountName -> AccountName -> Bool
parentAccountName :: AccountName -> AccountName
parentAccountNames :: AccountName -> [AccountName]

-- | From a list of account names, select those which are direct
--   subaccounts of the given account name.
subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName]

-- | 
--   
- "a:b:c","d:e" -> ["a","d"]
--   
topAccountNames :: [AccountName] -> [AccountName]

-- | "a:b:c" -> "a"
topAccountName :: AccountName -> AccountName

-- | A top-level account prefixed to some accounts in budget reports.
--   Defined here so it can be ignored by accountNameDrop.
unbudgetedAccountName :: Text
accountNamePostingType :: AccountName -> PostingType
accountNameWithoutPostingType :: AccountName -> AccountName
accountNameWithPostingType :: PostingType -> AccountName -> AccountName

-- | Prefix one account name to another, preserving posting type indicators
--   like concatAccountNames.
joinAccountNames :: AccountName -> AccountName -> AccountName

-- | Join account names into one. If any of them has () or [] posting type
--   indicators, these (the first type encountered) will also be applied to
--   the resulting account name.
concatAccountNames :: [AccountName] -> AccountName

-- | Rewrite an account name using all matching aliases from the given
--   list, in sequence. Each alias sees the result of applying the previous
--   aliases. Or, return any error arising from a bad regular expression in
--   the aliases.
accountNameApplyAliases :: [AccountAlias] -> AccountName -> Either RegexError AccountName

-- | Memoising version of accountNameApplyAliases, maybe overkill.
accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> Either RegexError AccountName
tests_AccountName :: TestTree

-- | Parse format strings provided by --format, with awareness of hledger's
--   report item fields. The formats are used by report-specific renderers
--   like renderBalanceReportItem.
module Hledger.Data.StringFormat

-- | Parse a string format specification, or return a parse error.
parseStringFormat :: Text -> Either String StringFormat
defaultStringFormatStyle :: [StringFormatComponent] -> StringFormat

-- | A format specification/template to use when rendering a report line
--   item as text.
--   
--   A format is a sequence of components; each is either a literal string,
--   or a hledger report item field with specified width and justification
--   whose value will be interpolated at render time.
--   
--   A component's value may be a multi-line string (or a multi-commodity
--   amount), in which case the final string will be either single-line or
--   a top or bottom-aligned multi-line string depending on the
--   StringFormat variant used.
--   
--   Currently this is only used in the balance command's single-column
--   mode, which provides a limited StringFormat renderer.
data StringFormat

-- | multi-line values will be rendered on one line, comma-separated
OneLine :: [StringFormatComponent] -> StringFormat

-- | values will be top-aligned (and bottom-padded to the same height)
TopAligned :: [StringFormatComponent] -> StringFormat

-- | values will be bottom-aligned (and top-padded)
BottomAligned :: [StringFormatComponent] -> StringFormat
data StringFormatComponent

-- | Literal text to be rendered as-is
FormatLiteral :: Text -> StringFormatComponent

-- | A data field to be formatted and interpolated. Parameters:
--   
--   
--   
- Left justify ? Right justified if false
--   
- Minimum width ? Will be space-padded if narrower than this
--   
- Maximum width ? Will be clipped if wider than this
--   
- Which of the standard hledger report item fields to
--   interpolate
--   
FormatField :: Bool -> Maybe Int -> Maybe Int -> ReportItemField -> StringFormatComponent

-- | An id identifying which report item field to interpolate. These are
--   drawn from several hledger report types, so are not all applicable for
--   a given report.
data ReportItemField

-- | A posting or balance report item's account name
AccountField :: ReportItemField

-- | A posting or register or entry report item's date
DefaultDateField :: ReportItemField

-- | A posting or register or entry report item's description
DescriptionField :: ReportItemField

-- | A balance or posting report item's balance or running total. Always
--   rendered right-justified.
TotalField :: ReportItemField

-- | A balance report item's indent level (which may be different from the
--   account name depth). Rendered as this number of spaces, multiplied by
--   the minimum width spec if any.
DepthSpacerField :: ReportItemField

-- | A report item's nth field. May be unimplemented.
FieldNo :: Int -> ReportItemField

-- | Default line format for balance report: "%20(total)
--   %2(depth_spacer)%-(account)"
defaultBalanceLineFormat :: StringFormat
tests_StringFormat :: TestTree
instance Data.Default.Internal.Default Hledger.Data.StringFormat.StringFormat
instance GHC.Classes.Eq Hledger.Data.StringFormat.ReportItemField
instance GHC.Classes.Eq Hledger.Data.StringFormat.StringFormat
instance GHC.Classes.Eq Hledger.Data.StringFormat.StringFormatComponent
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.ReportItemField
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.StringFormat
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.StringFormatComponent

-- | A simple Amount is some quantity of money, shares, or anything
--   else. It has a (possibly null) CommoditySymbol and a numeric
--   quantity:
--   
--   
--   $1
--   £-50
--   EUR 3.44
--   GOOG 500
--   1.5h
--   90 apples
--   0
--   
--   
--   It may also have an AmountCost, representing this amount's
--   per-unit or total cost in a different commodity. If present, this is
--   rendered like so:
--   
--   
--   EUR 2 @ $1.50  (unit cost)
--   EUR 2 @@ $3   (total cost)
--   
--   
--   A MixedAmount is zero or more simple amounts, so can represent
--   multiple commodities; this is the type most often used:
--   
--   
--   0
--   $50 + EUR 3
--   16h + $13.55 + AAPL 500 + 6 oranges
--   
--   
--   A mixed amount is always "normalised", it has no more than one amount
--   in each commodity and cost. When calling amounts it will have
--   no zero amounts, or just a single zero amount and no other amounts.
--   
--   Limited arithmetic with simple and mixed amounts is supported, best
--   used with similar amounts since it mostly ignores costss and commodity
--   exchange rates.
module Hledger.Data.Amount

-- | Show space-containing commodity symbols quoted, as they are in a
--   journal.
showCommoditySymbol :: Text -> Text
isNonsimpleCommodityChar :: Char -> Bool
quoteCommoditySymbolIfNeeded :: Text -> Text

-- | The empty simple amount - a zero with no commodity symbol or cost and
--   the default amount display style.
nullamt :: Amount

-- | A special amount used as a marker, meaning "no explicit amount
--   provided here, infer it when needed". It is nullamt with commodity
--   symbol AUTO.
missingamt :: Amount
num :: Quantity -> Amount
usd :: DecimalRaw Integer -> Amount
eur :: DecimalRaw Integer -> Amount
gbp :: DecimalRaw Integer -> Amount
per :: Quantity -> Amount
hrs :: Quantity -> Amount
at :: Amount -> Amount -> Amount
(@@) :: Amount -> Amount -> Amount

-- | Convert an amount to the specified commodity, ignoring and discarding
--   any costs and assuming an exchange rate of 1.
amountWithCommodity :: CommoditySymbol -> Amount -> Amount

-- | Convert a amount to its total cost in another commodity, using its
--   attached cost amount if it has one. Notes:
--   
--   
--   
- cost amounts must be MixedAmounts with exactly one component
--   Amount (or there will be a runtime error XXX)
--   
- cost amounts should be positive in the Journal (though this is
--   currently not enforced)
--   
amountCost :: Amount -> Amount

-- | Is this Amount (and its total cost, if it has one) exactly zero,
--   ignoring its display precision ?
amountIsZero :: Amount -> Bool

-- | Do this Amount and (and its total cost, if it has one) appear to be
--   zero when rendered with its display precision ? The display precision
--   should usually have a specific value here; if unset, it will be
--   treated like NaturalPrecision.
amountLooksZero :: Amount -> Bool

-- | Divide an amount's quantity (and total cost, if any) by some number.
divideAmount :: Quantity -> Amount -> Amount

-- | Multiply an amount's quantity (and its total cost, if it has one) by a
--   constant.
multiplyAmount :: Quantity -> Amount -> Amount

-- | Invert an amount (replace its quantity q with 1/q). The amount's
--   transacted price, if any, is not changed. An amount with zero quantity
--   is left unchanged.
invertAmount :: Amount -> Amount

-- | Default amount style
amountstyle :: AmountStyle

-- | Deprecated: please use styleAmounts instead
canonicaliseAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Deprecated: please use styleAmounts instead
styleAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Deprecated: please use styleAmounts instead
amountSetStyles :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Set this amount style's rounding strategy when it is being applied to
--   amounts.
amountStyleSetRounding :: Rounding -> AmountStyle -> AmountStyle

-- | Set these amount styles' rounding strategy when they are being applied
--   to amounts.
amountStylesSetRounding :: Rounding -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle

-- | Reset this amount's display style to the default.
amountUnstyled :: Amount -> Amount

-- | Given a list of amounts, in parse order (roughly speaking; see
--   journalStyleInfluencingAmounts), build a map from their commodity
--   names to standard commodity display formats. Can return an error
--   message eg if inconsistent number formats are found.
--   
--   Though, these amounts may have come from multiple files, so we
--   shouldn't assume they use consistent number formats. Currently we
--   don't enforce that even within a single file, and this function never
--   reports an error.
commodityStylesFromAmounts :: [Amount] -> Either String (Map CommoditySymbol AmountStyle)

-- | Get an amount and its attached cost amount if any. Returns one or two
--   amounts.
getAmounts :: Amount -> [Amount]

-- | Formatting options available when displaying Amounts and MixedAmounts.
--   Similar to AmountStyle but lower level, not attached to amounts
--   or commodities, and can override it in some ways. See also hledger
--   manual > "Amount formatting, parseability", which speaks of human,
--   hledger, and machine output.
data AmountFormat
AmountFormat :: Bool -> Bool -> Maybe [CommoditySymbol] -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> AmountFormat

-- | Whether to display commodity symbols.
[displayCommodity] :: AmountFormat -> Bool

-- | Whether to display commodity symbols for zero Amounts.
[displayZeroCommodity] :: AmountFormat -> Bool

-- | For a MixedAmount, an optional order in which to display the
--   commodities. Also, causes 0s to be generated for any commodities which
--   are not present (important for tabular reports).
[displayCommodityOrder] :: AmountFormat -> Maybe [CommoditySymbol]

-- | Whether to display digit group marks (eg thousands separators)
[displayDigitGroups] :: AmountFormat -> Bool

-- | Whether to add a trailing decimal mark when there are no decimal
--   digits and there are digit group marks, to disambiguate
[displayForceDecimalMark] :: AmountFormat -> Bool

-- | Whether to display on one line.
[displayOneLine] :: AmountFormat -> Bool

-- | Minimum width to pad to
[displayMinWidth] :: AmountFormat -> Maybe Int

-- | Maximum width to clip to
[displayMaxWidth] :: AmountFormat -> Maybe Int

-- | Whether to display Amounts' costs.
[displayCost] :: AmountFormat -> Bool

-- | Whether to display Amounts' cost basis (Ledger-style lot syntax).
[displayCostBasis] :: AmountFormat -> Bool

-- | Whether to ansi-colourise negative Amounts.
[displayColour] :: AmountFormat -> Bool

-- | Whether to enclose complex symbols in quotes (normally true)
[displayQuotes] :: AmountFormat -> Bool

-- | Display amounts without colour, and with various other defaults.
defaultFmt :: AmountFormat

-- | Like defaultFmt but show zero amounts with commodity symbol and
--   styling, like non-zero amounts.
fullZeroFmt :: AmountFormat

-- | Like defaultFmt but don't show costs or cost basis.
noCostFmt :: AmountFormat

-- | Like defaultFmt but display all amounts on one line.
oneLineFmt :: AmountFormat

-- | Like noCostFmt but display all amounts on one line.
oneLineNoCostFmt :: AmountFormat

-- | A (slightly more) machine-readable amount format; like
--   oneLineNoCostFmt but don't show digit group marks.
machineFmt :: AmountFormat

-- | Render an amount using its display style and the default amount
--   format. Zero-equivalent amounts are shown as just "0". The special
--   "missing" amount is shown as the empty string.
showAmount :: Amount -> String

-- | Like showAmount but uses the given amount format.
showAmountWith :: AmountFormat -> Amount -> String

-- | Render an amount using its display style and the given amount format,
--   as a builder for efficiency. (This can be converted to a Text with
--   wbToText or to a String with wbUnpack). The special "missing" amount
--   is displayed as the empty string.
showAmountB :: AmountFormat -> Amount -> WideBuilder
showAmountCost :: Amount -> String
showAmountCostB :: AmountFormat -> Amount -> WideBuilder

-- | Show an amount's cost basis as Ledger-style lot syntax: {LOTCOST}
--   LOTDATE.
showAmountCostBasis :: Amount -> String
showAmountCostBasisB :: AmountFormat -> Amount -> WideBuilder

-- | Colour version. For a negative amount, adds ANSI codes to change the
--   colour, currently to hard-coded red.
--   
--   
--   cshowAmount = wbUnpack . showAmountB def{displayColour=True}
--   
cshowAmount :: Amount -> String

-- | Like showAmount, but show a zero amount's commodity if it has one.
--   
--   
--   showAmountWithZeroCommodity = wbUnpack . showAmountB defaultFmt{displayZeryCommodity=True}
--   
showAmountWithZeroCommodity :: Amount -> String

-- | Get a string representation of an amount for debugging, appropriate to
--   the current debug level. 9 shows maximum detail.
showAmountDebug :: Amount -> String

-- | Get the string representation of an amount, without any @ cost.
--   
--   
--   showAmountWithoutCost = wbUnpack . showAmountB noCostFmt
--   
showAmountWithoutCost :: Amount -> String

-- | Set an amount's display precision.
amountSetPrecision :: AmountPrecision -> Amount -> Amount

-- | Ensure an amount's display precision is at least the given minimum
--   precision. Always sets an explicit Precision.
amountSetPrecisionMin :: Word8 -> Amount -> Amount

-- | Ensure an amount's display precision is at most the given maximum
--   precision. Always sets an explicit Precision.
amountSetPrecisionMax :: Word8 -> Amount -> Amount

-- | Set an amount's display precision, flipped.
withPrecision :: Amount -> AmountPrecision -> Amount

-- | Increase an amount's display precision, if needed, to enough decimal
--   places to show it exactly (showing all significant decimal digits,
--   without trailing zeros). If the amount's display precision is unset,
--   it will be treated as precision 0.
amountSetFullPrecision :: Amount -> Amount

-- | We often want to display "infinite decimal" amounts rounded to some
--   readable number of digits, while still displaying amounts with a large
--   but "non infinite" number of decimal digits (eg 10 or 100 or 200
--   digits) in full. This helper is like amountSetFullPrecision, but with
--   some refinements:
--   
--   
--   
- A maximum display precision can be specified, setting a hard upper
--   limit.
--   
- If no limit is specified, and the internal precision is the
--   maximum (255), indicating an infinite decimal, display precision is
--   set to a smaller default (8).
--   
--   
--   This function always sets an explicit display precision (ie, Precision
--   n).
amountSetFullPrecisionUpTo :: Maybe Word8 -> Amount -> Amount

-- | How many internal decimal digits are stored for this amount ?
amountInternalPrecision :: Amount -> Word8

-- | How many decimal digits will be displayed for this amount ?
amountDisplayPrecision :: Amount -> Word8

-- | The fallback display precision used when showing amounts representing
--   an infinite decimal.
defaultMaxPrecision :: Word8

-- | Set an amount's internal decimal precision as well as its display
--   precision. This rounds or pads its Decimal quantity to the specified
--   number of decimal places. Rounding is done with Data.Decimal's default
--   roundTo function: "If the value ends in 5 then it is rounded to the
--   nearest even value (Banker's Rounding)".
setAmountInternalPrecision :: Word8 -> Amount -> Amount

-- | setAmountInternalPrecision with arguments flipped.
withInternalPrecision :: Amount -> Word8 -> Amount

-- | Set (or clear) an amount's display decimal point.
setAmountDecimalPoint :: Maybe Char -> Amount -> Amount

-- | Set (or clear) an amount's display decimal point, flipped.
withDecimalPoint :: Amount -> Maybe Char -> Amount

-- | Strip all costs from an Amount
amountStripCost :: Amount -> Amount

-- | The empty mixed amount.
nullmixedamt :: MixedAmount

-- | A special mixed amount used as a marker, meaning "no explicit amount
--   provided here, infer it when needed".
missingmixedamt :: MixedAmount

-- | Does this MixedAmount include the "missing amount" marker ? Note:
--   currently does not test for equality with missingmixedamt, instead it
--   looks for missingamt among the Amounts. missingamt should always be
--   alone, but detect it even if not.
isMissingMixedAmount :: MixedAmount -> Bool

-- | Convert amounts in various commodities into a mixed amount.
mixed :: Foldable t => t Amount -> MixedAmount

-- | Create a MixedAmount from a single Amount.
mixedAmount :: Amount -> MixedAmount

-- | Add an Amount to a MixedAmount, normalising the result. Amounts with
--   different costs are kept separate.
maAddAmount :: MixedAmount -> Amount -> MixedAmount

-- | Add a collection of Amounts to a MixedAmount, normalising the result.
--   Amounts with different costs are kept separate.
maAddAmounts :: Foldable t => MixedAmount -> t Amount -> MixedAmount

-- | Get a mixed amount's component amounts, with some cleanups. The
--   following descriptions are old and possibly wrong:
--   
--   
--   
- amounts in the same commodity are combined unless they have
--   different costs or total costs
--   
- multiple zero amounts, all with the same non-null commodity, are
--   replaced by just the last of them, preserving the commodity and amount
--   style (all but the last zero amount are discarded)
--   
- multiple zero amounts with multiple commodities, or no
--   commodities, are replaced by one commodity-less zero amount
--   
- an empty amount list is replaced by one commodity-less zero
--   amount
--   
- the special "missing" mixed amount remains unchanged
--   
amounts :: MixedAmount -> [Amount]

-- | Get a mixed amount's component amounts without normalising zero and
--   missing amounts. This is used for JSON serialisation, so the order is
--   important. In particular, we want the Amounts given in the order of
--   the MixedAmountKeys, i.e. lexicographically first by commodity, then
--   by cost commodity, then by unit cost from most negative to most
--   positive.
amountsRaw :: MixedAmount -> [Amount]

-- | Get a mixed amount's component amounts, with some cleanups. This is a
--   new version of amounts, with updated descriptions and
--   optimised for print to show commodityful zeros.
--   
--   
--   
- If it contains the "missing amount" marker, only that is returned
--   (discarding any additional amounts).
--   
- Or if it contains any non-zero amounts, only those are returned
--   (discarding any zeroes).
--   
- Or if it contains any zero amounts (possibly more than one,
--   possibly in different commodities), all of those are returned.
--   
- Otherwise the null amount is returned.
--   
amountsPreservingZeros :: MixedAmount -> [Amount]

-- | Get this mixed amount's commodities as a set. Returns an empty set if
--   there are no amounts.
maCommodities :: MixedAmount -> Set CommoditySymbol

-- | Filter a mixed amount's component amounts by a predicate.
filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount

-- | Return an unnormalised MixedAmount containing just the amounts in the
--   requested commodity from the original mixed amount.
--   
--   The result will contain at least one Amount of the requested
--   commodity, even if the original mixed amount did not (with quantity
--   zero in that case, and this would be discarded when the mixed amount
--   is next normalised).
--   
--   The result can contain more than one Amount of the requested
--   commodity, eg because there were several with different costs, or
--   simply because the original mixed amount was was unnormalised.
filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount

-- | Apply a transform to a mixed amount's component Amounts.
mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount

-- | Unify a MixedAmount to a single commodity value if possible. This
--   consolidates amounts of the same commodity and discards zero amounts;
--   but this one insists on simplifying to a single commodity, and will
--   return Nothing if this is not possible.
unifyMixedAmount :: MixedAmount -> Maybe Amount

-- | Remove all costs from a MixedAmount.
mixedAmountStripCosts :: MixedAmount -> MixedAmount

-- | Convert all component amounts to cost where possible (see amountCost).
mixedAmountCost :: MixedAmount -> MixedAmount

-- | Negate mixed amount's quantities (and total costs, if any).
maNegate :: MixedAmount -> MixedAmount

-- | Sum two MixedAmount, keeping the cost of the first if any. Amounts
--   with different costs are kept separate (since 2021).
maPlus :: MixedAmount -> MixedAmount -> MixedAmount

-- | Subtract a MixedAmount from another. Amounts with different costs are
--   kept separate.
maMinus :: MixedAmount -> MixedAmount -> MixedAmount

-- | Sum a collection of MixedAmounts. Amounts with different costs are
--   kept separate.
maSum :: Foldable t => t MixedAmount -> MixedAmount

-- | Divide a mixed amount's quantities (and total costs, if any) by a
--   constant.
divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount

-- | Multiply a mixed amount's quantities (and total costs, if any) by a
--   constant.
multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount

-- | Calculate the average of some mixed amounts.
averageMixedAmounts :: Foldable f => f MixedAmount -> MixedAmount

-- | Calculate the sum and average of some mixed amounts.
sumAndAverageMixedAmounts :: Foldable f => f MixedAmount -> (MixedAmount, MixedAmount)

-- | Is this amount negative ? The cost is ignored.
isNegativeAmount :: Amount -> Bool

-- | Is this mixed amount negative, if we can tell that unambiguously? Ie
--   when normalised, are all individual commodity amounts negative ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool

-- | Is this mixed amount exactly zero, ignoring its display precision? See
--   amountIsZero.
mixedAmountIsZero :: MixedAmount -> Bool

-- | Is this mixed amount exactly zero, ignoring its display precision?
--   
--   A convenient alias for mixedAmountIsZero.
maIsZero :: MixedAmount -> Bool

-- | Is this mixed amount non-zero, ignoring its display precision?
--   
--   A convenient alias for not . mixedAmountIsZero.
maIsNonZero :: MixedAmount -> Bool

-- | Does this mixed amount appear to be zero when rendered with its
--   display precision? See amountLooksZero.
mixedAmountLooksZero :: MixedAmount -> Bool

-- | Deprecated: please use mixedAmountSetStyle False (or styleAmounts)
--   instead
canonicaliseMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Given a map of standard commodity display styles, find and apply the
--   appropriate style to each individual amount.

-- | Deprecated: please use styleAmounts instead
styleMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Deprecated: please use styleAmounts instead
mixedAmountSetStyles :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Reset each individual amount's display style to the default.
mixedAmountUnstyled :: MixedAmount -> MixedAmount

-- | Render a mixed amount using its amount display styles and the default
--   amount format, after normalising it (to at most one amount in each of
--   its commodities). See showMixedAmountB for special cases.
showMixedAmount :: MixedAmount -> String

-- | Like showMixedAmount but uses the given amount format. See
--   showMixedAmountB for special cases.
showMixedAmountWith :: AmountFormat -> MixedAmount -> String

-- | Get the one-line string representation of a mixed amount (also showing
--   any costs). See showMixedAmountB for special cases.
showMixedAmountOneLine :: MixedAmount -> String

-- | Get an unambiguous string representation of a mixed amount for
--   debugging.
showMixedAmountDebug :: MixedAmount -> String

-- | Get the string representation of a mixed amount, without showing any
--   costs. With a True argument, adds ANSI codes to show negative amounts
--   in red. See showMixedAmountB for special cases.
showMixedAmountWithoutCost :: Bool -> MixedAmount -> String

-- | Get the one-line string representation of a mixed amount, but without
--   any @ costs. With a True argument, adds ANSI codes to show negative
--   amounts in red. See showMixedAmountB for special cases.
showMixedAmountOneLineWithoutCost :: Bool -> MixedAmount -> String

-- | Like showMixedAmountOneLineWithoutCost, but show at most the given
--   width, with an elision indicator if there are more. With a True
--   argument, adds ANSI codes to show negative amounts in red. See
--   showMixedAmountB for special cases.
showMixedAmountElided :: Int -> Bool -> MixedAmount -> String

-- | Like showMixedAmount, but zero amounts are shown with their commodity
--   if they have one. See showMixedAmountB for special cases.
showMixedAmountWithZeroCommodity :: MixedAmount -> String

-- | Render a mixed amount using its amount display styles and the given
--   amount format, as a builder for efficiency. (This can be converted to
--   a Text with wbToText or to a String with wbUnpack).
--   
--   Warning: this (and its showMixedAmount aliases above) basically
--   assumes amounts have no costs. It can show misleading costs or not
--   show costs which are there.
--   
--   If a maximum width is given then:
--   
--   
--   
- If displayed on one line, it will display as many Amounts as can
--   fit in the given width, and further Amounts will be elided. There will
--   always be at least one amount displayed, even if this will exceed the
--   requested maximum width.
--   
- If displayed on multiple lines, any Amounts longer than the
--   maximum width will be elided.
--   
--   
--   Zero-equivalent amounts are shown as just "0".
--   
--   The special "missing" amount is shown as the empty string (?).
showMixedAmountB :: AmountFormat -> MixedAmount -> WideBuilder

-- | Helper for showMixedAmountB (and postingAsLines, ...) to show a list
--   of Amounts on multiple lines. This returns the list of WideBuilders:
--   one for each Amount, and padded/elided to the appropriate width. This
--   does not honour displayOneLine; all amounts will be displayed as if
--   displayOneLine were False.
showMixedAmountLinesB :: AmountFormat -> MixedAmount -> [WideBuilder]

-- | Like showMixedAmountLinesB but also returns the amounts
--   associated with each text builder.
showMixedAmountLinesPartsB :: AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Set the display precision in the amount's commodities.
mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount

-- | In each component amount, increase the display precision sufficiently
--   to render it exactly (showing all significant decimal digits).
mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount

-- | In each component amount, increase the display precision sufficiently
--   to render it exactly if possible, but not more than the given max
--   precision, and if no max precision is given and the amount has
--   infinite decimals, limit display precision to a hard-coded smaller
--   number (8). See amountSetFullPrecisionUpTo.
mixedAmountSetFullPrecisionUpTo :: Maybe Word8 -> MixedAmount -> MixedAmount

-- | In each component amount, ensure the display precision is at least the
--   given value. Makes all amounts have an explicit Precision.
mixedAmountSetPrecisionMin :: Word8 -> MixedAmount -> MixedAmount

-- | In each component amount, ensure the display precision is at most the
--   given value. Makes all amounts have an explicit Precision.
mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount
tests_Amount :: TestTree
instance Data.Default.Internal.Default Hledger.Data.Amount.AmountFormat
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (Hledger.Data.Types.Account a)
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Amount
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.BalanceData
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.MixedAmount
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Base.Monoid Hledger.Data.Types.MixedAmount
instance GHC.Internal.Num.Num Hledger.Data.Types.Amount
instance GHC.Internal.Num.Num Hledger.Data.Types.MixedAmount
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.MixedAmount
instance GHC.Internal.Show.Show Hledger.Data.Amount.AmountDisplay
instance GHC.Internal.Show.Show Hledger.Data.Amount.AmountFormat

-- | Rich data type to describe data in a table. This is the basis for ODS
--   and HTML export.
module Hledger.Write.Spreadsheet
data Type
TypeString :: Type
TypeInteger :: Type
TypeAmount :: !Amount -> Type
TypeMixedAmount :: Type
TypeDate :: Type
data Style
Body :: Emphasis -> Style
Head :: Style
data Emphasis
Item :: Emphasis
Total :: Emphasis
data Cell border text
Cell :: Type -> Border border -> Style -> Span -> Text -> Class -> text -> Cell border text
[cellType] :: Cell border text -> Type
[cellBorder] :: Cell border text -> Border border
[cellStyle] :: Cell border text -> Style
[cellSpan] :: Cell border text -> Span
[cellAnchor] :: Cell border text -> Text
[cellClass] :: Cell border text -> Class
[cellContent] :: Cell border text -> text
newtype Class
Class :: Text -> Class
textFromClass :: Class -> Text

-- | 
--   
- NoSpan means a single unmerged cell.
--   
- Covered is a cell if it is part of a horizontally or
--   vertically merged cell. We maintain these cells although they are
--   ignored in HTML output. In contrast to that, FODS can store covered
--   cells and allows to access the hidden cell content via formulas. CSV
--   does not support merged cells and thus simply writes the content of
--   covered cells. Maintaining Covered cells also simplifies
--   transposing.
--   
- SpanHorizontal n denotes the first cell in a row
--   that is part of a merged cell. The merged cell contains n
--   atomic cells, including the first one. That is SpanHorizontal
--   1 is actually like NoSpan. The content of this cell is
--   shown as content of the merged cell.
--   
- SpanVertical n starts a vertically merged
--   cell.
--   
--   
--   The writer functions expect consistent data, that is, Covered
--   cells must actually be part of a merged cell and merged cells must
--   only cover Covered cells.
data Span
NoSpan :: Span
Covered :: Span
SpanHorizontal :: Int -> Span
SpanVertical :: Int -> Span
data Border lines
Border :: lines -> lines -> lines -> lines -> Border lines
[borderLeft] :: Border lines -> lines
[borderRight] :: Border lines -> lines
[borderTop] :: Border lines -> lines
[borderBottom] :: Border lines -> lines
class Lines border
noLine :: Lines border => border

-- | The same as Tab.Properties, but has Eq and Ord
--   instances. We need those for storing NumLines in Sets.
data NumLines
NoLine :: NumLines
SingleLine :: NumLines
DoubleLine :: NumLines
noBorder :: Lines border => Border border
defaultCell :: Lines border => text -> Cell border text
headerCell :: Lines borders => Text -> Cell borders Text
emptyCell :: (Lines border, Monoid text) => Cell border text
transposeCell :: Cell border text -> Cell border text
transpose :: [[Cell border text]] -> [[Cell border text]]
horizontalSpan :: (Lines border, Monoid text) => [a] -> Cell border text -> [Cell border text]
addHeaderBorders :: [Cell () text] -> [Cell NumLines text]
addRowSpanHeader :: Cell border text -> [[Cell border text]] -> [[Cell border text]]
rawTableContent :: [[Cell border text]] -> [[text]]
cellFromMixedAmount :: Lines border => AmountFormat -> (Class, MixedAmount) -> Cell border WideBuilder
cellsFromMixedAmount :: Lines border => AmountFormat -> (Class, MixedAmount) -> [Cell border WideBuilder]
cellFromAmount :: Lines border => AmountFormat -> (Class, (wb, Amount)) -> Cell border wb
integerCell :: Lines border => Integer -> Cell border Text
instance GHC.Internal.Base.Applicative Hledger.Write.Spreadsheet.Border
instance GHC.Classes.Eq lines => GHC.Classes.Eq (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Classes.Eq Hledger.Write.Spreadsheet.Emphasis
instance GHC.Classes.Eq Hledger.Write.Spreadsheet.NumLines
instance GHC.Classes.Eq Hledger.Write.Spreadsheet.Span
instance GHC.Classes.Eq Hledger.Write.Spreadsheet.Style
instance GHC.Classes.Eq Hledger.Write.Spreadsheet.Type
instance GHC.Internal.Data.Foldable.Foldable Hledger.Write.Spreadsheet.Border
instance GHC.Internal.Base.Functor Hledger.Write.Spreadsheet.Border
instance GHC.Internal.Base.Functor (Hledger.Write.Spreadsheet.Cell border)
instance Hledger.Write.Spreadsheet.Lines Hledger.Write.Spreadsheet.NumLines
instance Hledger.Write.Spreadsheet.Lines ()
instance GHC.Classes.Ord lines => GHC.Classes.Ord (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Classes.Ord Hledger.Write.Spreadsheet.Emphasis
instance GHC.Classes.Ord Hledger.Write.Spreadsheet.NumLines
instance GHC.Classes.Ord Hledger.Write.Spreadsheet.Style
instance GHC.Classes.Ord Hledger.Write.Spreadsheet.Type
instance GHC.Internal.Show.Show lines => GHC.Internal.Show.Show (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Emphasis
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.NumLines
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Style
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Type

-- | Export table data as OpenDocument Spreadsheet
--   https://docs.oasis-open.org/office/OpenDocument/v1.3/. This
--   format supports character encodings, fixed header rows and columns,
--   number formatting, text styles, merged cells, formulas, hyperlinks.
--   Currently we support Flat ODS, a plain uncompressed XML format.
--   
--   This is derived from
--   https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs
module Hledger.Write.Ods
printFods :: TextEncoding -> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
instance GHC.Classes.Eq Hledger.Write.Ods.DataStyle
instance GHC.Classes.Ord Hledger.Write.Ods.DataStyle
instance GHC.Internal.Show.Show Hledger.Write.Ods.DataStyle

-- | Common definitions used by both Html.Blaze and Html.Lucid.
module Hledger.Write.Html.HtmlCommon
class Lines border => Lines border
borderLines :: Lines border => border -> [Text]
borderStyles :: Lines border => Cell border text -> [Text]
instance Hledger.Write.Html.HtmlCommon.Lines Hledger.Write.Spreadsheet.NumLines
instance Hledger.Write.Html.HtmlCommon.Lines ()

-- | HTML writing helpers using lucid.
module Hledger.Write.Html.Lucid
type Html = Html ()

-- | Convert to HTML, doing HTML escaping.
toHtml :: forall (m :: Type -> Type). (ToHtml a, Monad m) => a -> HtmlT m ()

-- | Export spreadsheet table data as HTML table. This is derived from
--   https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs
styledTableHtml :: Lines border => [[Cell border Html]] -> Html
formatRow :: Lines border => [Cell border Html] -> Html
formatCell :: Lines border => Cell border Html -> Html

-- | HTML writing helpers. This module would ideally hide the details of
--   which HTML library is used, but it doesn't yet.
--   
--   Currently hledger-web uses blaze-html, but hledger CLI reports use
--   lucid. lucid has a more usable API than blaze-html
--   (https:/chrisdone.composts/lucid). lucid2's is even better.
--   Unfortunately lucid* can not render multi-line or indented text. We
--   want this so that humans can read and troubleshoot our HTML output. So
--   a transition to blaze-html may be coming.
module Hledger.Write.Html

-- | Convert to HTML, doing HTML escaping.
toHtml :: forall (m :: Type -> Type). (ToHtml a, Monad m) => a -> HtmlT m ()
type Html = Html ()
formatRow :: Lines border => [Cell border Html] -> Html
htmlAsText :: Html -> Text
htmlAsLazyText :: Html -> Text

-- | Export spreadsheet table data as HTML table. This is derived from
--   https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs
styledTableHtml :: Lines border => [[Cell border Html]] -> Html
tests_Hledger_Write_Html :: TestTree

-- | HTML writing helpers using blaze-html.
module Hledger.Write.Html.Blaze

-- | Export spreadsheet table data as HTML table. This is derived from
--   https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs
styledTableHtml :: Lines border => [[Cell border Html]] -> Html
formatRow :: Lines border => [Cell border Html] -> Html
formatCell :: Lines border => Cell border Html -> Html

-- | Convert amounts to some related value in various ways. This involves
--   looking up historical market prices (exchange rates) between
--   commodities.
module Hledger.Data.Valuation

-- | Which operation to perform on conversion transactions. (There was also
--   an "infer equity postings" operation, but that is now done earlier, in
--   journal finalisation.)
data ConversionOp
NoConversionOp :: ConversionOp
ToCost :: ConversionOp

-- | What kind of value conversion should be done on amounts ? CLI:
--   --value=then|end|now|DATE[,COMM]
data ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at each posting's date
AtThen :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at period end(s)
AtEnd :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using current market
--   prices
AtNow :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   on some date
AtDate :: Day -> Maybe CommoditySymbol -> ValuationType

-- | A price oracle is a magic memoising function that efficiently looks up
--   market prices (exchange rates) from one commodity to another (or if
--   unspecified, to a default valuation commodity) on a given date.
type PriceOracle = (Day, CommoditySymbol, Maybe CommoditySymbol) -> Maybe (CommoditySymbol, Quantity)

-- | Generate a price oracle (memoising price lookup function) from a
--   journal's directive-declared and transaction-inferred market prices.
--   For best performance, generate this only once per journal, reusing it
--   across reports if there are more than one, as compoundBalanceCommand
--   does. The boolean argument is whether to infer market prices from
--   transactions or not.
journalPriceOracle :: Bool -> Journal -> PriceOracle

-- | Convert all component amounts to cost/selling price if requested, and
--   style them.
mixedAmountToCost :: Map CommoditySymbol AmountStyle -> ConversionOp -> MixedAmount -> MixedAmount

-- | Apply a specified valuation to this mixed amount, using the provided
--   price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
mixedAmountApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount

-- | Find the market value of each component amount in the given commodity,
--   or its default valuation commodity, at the given valuation date, using
--   the given market price oracle. When market prices available on that
--   date are not sufficient to calculate the value, amounts are left
--   unchanged.
mixedAmountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount

-- | Calculate the gain of each component amount, that is the difference
--   between the valued amount and the value of the cost basis (see
--   mixedAmountApplyValuation).
--   
--   If the commodity we are valuing in is not the same as the commodity of
--   the cost, this will value the cost at the same date as the primary
--   amount. This may not be what you want; for example you may want the
--   cost valued at the posting date. If so, let us know and we can change
--   this behaviour.
mixedAmountApplyGain :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount

-- | Calculate the gain of each component amount, that is the difference
--   between the valued amount and the value of the cost basis.
--   
--   If the commodity we are valuing in is not the same as the commodity of
--   the cost, this will value the cost at the same date as the primary
--   amount. This may not be what you want; for example you may want the
--   cost valued at the posting date. If so, let us know and we can change
--   this behaviour.
mixedAmountGainAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
marketPriceReverse :: MarketPrice -> MarketPrice
priceDirectiveToMarketPrice :: PriceDirective -> MarketPrice

-- | Infer a market price from the given amount and its cost (if any), and
--   make a corresponding price directive on the given date. The price's
--   display precision will be set to show all significant decimal digits;
--   or if they seem to be infinite, defaultPrecisionLimit.
amountPriceDirectiveFromCost :: Day -> Amount -> Maybe PriceDirective
valuationTypeValuationCommodity :: ValuationType -> Maybe CommoditySymbol
tests_Valuation :: TestTree
instance GHC.Classes.Eq Hledger.Data.Valuation.ConversionOp
instance GHC.Classes.Eq Hledger.Data.Valuation.ValuationType
instance GHC.Internal.Generics.Generic Hledger.Data.Valuation.PriceGraph
instance GHC.Internal.Show.Show Hledger.Data.Valuation.ConversionOp
instance GHC.Internal.Show.Show Hledger.Data.Valuation.PriceGraph
instance GHC.Internal.Show.Show Hledger.Data.Valuation.ValuationType

-- | A Posting represents a change (by some MixedAmount) of
--   the balance in some Account. Each Transaction contains
--   two or more postings which should add up to 0. Postings reference
--   their parent transaction, so we can look up the date or description
--   there.
module Hledger.Data.Posting
nullposting :: Posting
posting :: Posting

-- | Make a posting to an account.
post :: AccountName -> Amount -> Posting

-- | Make a virtual (unbalanced) posting to an account.
vpost :: AccountName -> Amount -> Posting

-- | Make a posting to an account, maybe with a balance assertion.
post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting

-- | Make a virtual (unbalanced) posting to an account, maybe with a
--   balance assertion.
vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
nullassertion :: BalanceAssertion

-- | Make a partial, exclusive balance assertion.
balassert :: Amount -> Maybe BalanceAssertion

-- | Make a total, exclusive balance assertion.
balassertTot :: Amount -> Maybe BalanceAssertion

-- | Make a partial, inclusive balance assertion.
balassertParInc :: Amount -> Maybe BalanceAssertion

-- | Make a total, inclusive balance assertion.
balassertTotInc :: Amount -> Maybe BalanceAssertion
originalPosting :: Posting -> Posting

-- | Get a posting's status. This is cleared or pending if those are
--   explicitly set on the posting, otherwise the status of its parent
--   transaction, or unmarked if there is no parent transaction. (Note the
--   ambiguity, unmarked can mean "posting and transaction are both
--   unmarked" or "posting is unmarked and don't know about the
--   transaction".
postingStatus :: Posting -> Status
isReal :: Posting -> Bool
isVirtual :: Posting -> Bool
isBalancedVirtual :: Posting -> Bool
isEmptyPosting :: Posting -> Bool
hasBalanceAssignment :: Posting -> Bool
hasAmount :: Posting -> Bool

-- | Tags for this posting including any inherited from its parent
--   transaction.
postingAllTags :: Posting -> [Tag]

-- | Tags for this transaction including any from its postings (which
--   includes any from the postings' accounts).
transactionAllTags :: Transaction -> [Tag]
relatedPostings :: Posting -> [Posting]

-- | Strip all prices from a Posting.
postingStripCosts :: Posting -> Posting

-- | Apply some account aliases to the posting's account name, as described
--   by accountNameApplyAliases. This can fail due to a bad replacement
--   pattern in a regular expression alias.
postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting

-- | Find and apply the appropriate display style to the posting amounts in
--   each commodity (see journalCommodityStyles). Main amount precisions
--   may be set or not according to the styles, but cost precisions are not
--   set.

-- | Deprecated: please use styleAmounts instead
postingApplyCommodityStyles :: Map CommoditySymbol AmountStyle -> Posting -> Posting

-- | Like postingApplyCommodityStyles, but neither main amount precisions
--   or cost precisions are set.

-- | Deprecated: please use styleAmounts instead
postingStyleAmounts :: Map CommoditySymbol AmountStyle -> Posting -> Posting

-- | Add tags to a posting, discarding any for which the posting already
--   has a value. Note this does not add tags to the posting's comment.
postingAddTags :: Posting -> [Tag] -> Posting

-- | Add the given hidden tag to a posting; and with a true argument, also
--   add the equivalent visible tag to the posting's tags and comment
--   fields. If the posting already has these tags (with any value), do
--   nothing.
postingAddHiddenAndMaybeVisibleTag :: Bool -> HiddenTag -> Posting -> Posting

-- | Get a posting's (primary) date - it's own primary date if specified,
--   otherwise the parent transaction's primary date, or the null date if
--   there is no parent transaction.
postingDate :: Posting -> Day

-- | Get a posting's secondary (secondary) date, which is the first of:
--   posting's secondary date, transaction's secondary date, posting's
--   primary date, transaction's primary date, or the null date if there is
--   no parent transaction.
postingDate2 :: Posting -> Day

-- | Get a posting's primary or secondary date, as specified.
postingDateOrDate2 :: WhichDate -> Posting -> Day

-- | Sorted unique account names referenced by these postings.
accountNamesFromPostings :: [Posting] -> [AccountName]

-- | Join two parts of a comment, eg a tag and another tag, or a tag and a
--   non-tag, on a single line. Interpolates a comma and space unless one
--   of the parts is empty.
commentJoin :: Text -> Text -> Text

-- | Add a tag to a comment, comma-separated from any prior content. A
--   space is inserted following the colon, before the value.
commentAddTag :: Text -> Tag -> Text

-- | Like commentAddTag, but omits the space after the colon.
commentAddTagUnspaced :: Text -> Tag -> Text

-- | Add a tag on its own line to a comment, preserving any prior content.
--   A space is inserted following the colon, before the value.
commentAddTagNextLine :: Text -> Tag -> Text

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
generatedTransactionTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
modifiedTransactionTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
generatedPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
costPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
conversionPostingTagName :: TagName

-- | Sum all amounts from a list of postings.
sumPostings :: [Posting] -> MixedAmount

-- | Negate the posting's main amount and balance assertion amount if any.
postingNegate :: Posting -> Posting

-- | Negate the posting's main amount but not the balance assertion amount.
postingNegateMainAmount :: Posting -> Posting
showPosting :: Posting -> String

-- | Render a posting, at the appropriate width for aligning with its
--   siblings if any. Used by the rewrite command.
showPostingLines :: Posting -> [Text]

-- | Render one posting, on one or more lines, suitable for print
--   output. Also returns the widths calculated for the account and amount
--   fields.
--   
--   There will be an indented account name, plus one or more of status
--   flag, posting amount, balance assertion, same-line comment, next-line
--   comments.
--   
--   If the posting's amount is implicit or if elideamount is true, no
--   amount is shown. If the posting's amount is explicit and
--   multi-commodity, multiple similar postings are shown, one for each
--   commodity, to help produce parseable journal syntax. Or if
--   onelineamounts is true, such amounts are shown on one line,
--   comma-separated (and the output will not be valid journal syntax).
--   
--   If an amount is zero, any commodity symbol attached to it is shown
--   (and the corresponding commodity display style is used).
--   
--   By default, 4 spaces (2 if there's a status flag) are shown between
--   account name and start of amount area, which is typically 12 chars
--   wide and contains a right-aligned amount (so 10-12 visible spaces
--   between account name and amount is typical). When given a list of
--   postings to be aligned with, the whitespace will be increased if
--   needed to match the posting with the longest account name. This is
--   used to align the amounts of a transaction's postings.
postingAsLines :: Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)

-- | Render a transaction's postings as indented lines, suitable for
--   print output.
--   
--   Normally these will be in valid journal syntax which hledger can
--   reparse (though they may include no-longer-valid balance assertions).
--   Explicit amounts are shown, implicit amounts are not.
--   
--   Postings with multicommodity explicit amounts are handled as follows:
--   if onelineamounts is true, these amounts are shown on one line,
--   comma-separated, and the output will not be valid journal syntax.
--   Otherwise, they are shown as several similar postings, one per
--   commodity. When the posting has a balance assertion, it is attached to
--   the last of these postings.
--   
--   Posting amounts will be aligned with each other, starting about 4
--   columns beyond the widest account name (see postingAsLines for
--   details). The postings will appear balanced (amounts summing to zero).
--   Amounts' display precisions, which may have been limited by commodity
--   directives, will be increased if necessary to ensure this.
postingsAsLines :: Bool -> [Posting] -> [Text]

-- | Prepend a suitable indent for a posting (or transaction/posting
--   comment) line.
postingIndent :: Text -> Text

-- | Show an account name, clipped to the given width if any, and
--   appropriately bracketed/parenthesised for the given posting type.
showAccountName :: Maybe Int -> PostingType -> AccountName -> Text

-- | Render a transaction or posting's comment as indented,
--   semicolon-prefixed comment lines. The first line (unless empty) will
--   have leading space, subsequent lines will have a larger indent.
renderCommentLines :: Text -> [Text]

-- | Render a balance assertion, as the =[=][*] symbol and expected amount.
showBalanceAssertion :: BalanceAssertion -> WideBuilder

-- | Apply a transform function to this posting's main amount (but not its
--   balance assertion amount).
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting

-- | Apply a specified valuation to this posting's amount, using the
--   provided price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
postingApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting

-- | Maybe convert this Postings amount to cost.
postingToCost :: ConversionOp -> Posting -> Maybe Posting

-- | Generate equity conversion postings corresponding to a
--   Posting's cost(s) (one pair of conversion postings per cost),
--   wherever they don't already exist.
postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]

-- | Make a market price equivalent to this posting's amount's unit price,
--   if any.
postingPriceDirectivesFromCost :: Posting -> [PriceDirective]

-- | Get the commodity symbols used in a posting's amounts (not including
--   costs).
postingCommodities :: Posting -> [CommoditySymbol]
tests_Posting :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.BalanceAssertion
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Posting

-- | A Transaction represents a movement of some commodity(ies)
--   between two or more accounts. It consists of multiple account
--   Postings which balance to zero, a date, and optional extras
--   like description, cleared status, and tags.
module Hledger.Data.Transaction
nulltransaction :: Transaction

-- | Make a simple transaction with the given date and postings.
transaction :: Day -> [Posting] -> Transaction

-- | Ensure a transaction's postings refer back to it, so that eg
--   relatedPostings works right.
txnTieKnot :: Transaction -> Transaction

-- | Ensure a transaction's postings do not refer back to it, so that eg
--   recursiveSize and GHCI's :sprint work right.
txnUntieKnot :: Transaction -> Transaction
hasRealPostings :: Transaction -> Bool
realPostings :: Transaction -> [Posting]
assignmentPostings :: Transaction -> [Posting]
virtualPostings :: Transaction -> [Posting]
balancedVirtualPostings :: Transaction -> [Posting]
transactionsPostings :: [Transaction] -> [Posting]

-- | Apply a transform function to this transaction's amounts.
transactionTransformPostings :: (Posting -> Posting) -> Transaction -> Transaction

-- | Apply a specified valuation to this transaction's amounts, using the
--   provided price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
transactionApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Transaction -> Transaction

-- | Maybe convert this Transactions amounts to cost.
transactionToCost :: ConversionOp -> Transaction -> Transaction

-- | For any costs in this Transaction which don't have associated
--   equity conversion postings, generate and add those.
transactionInferEquityPostings :: Bool -> AccountName -> Transaction -> Transaction

-- | Find, associate, and tag the corresponding equity conversion postings
--   and costful or potentially costful postings in this transaction. With
--   a true addcosts argument, also generate and add any equivalent costs
--   that are missing. The (previously detected) names of all equity
--   conversion accounts should be provided.
--   
--   For every pair of adjacent conversion postings, this first searches
--   for a posting with equivalent cost (1). If no such posting is found,
--   it then searches the costless postings, for one matching one of the
--   conversion amounts (2). If either of these found a candidate posting,
--   it is tagged with costPostingTagName. Then if in addcosts mode, if a
--   costless posting was found, a cost equivalent to the conversion
--   amounts is added to it.
--   
--   The name reflects the complexity of this and its helpers;
--   clarification is ongoing.
transactionTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> [AccountName] -> Transaction -> Either String Transaction

-- | Apply some account aliases to all posting account names in the
--   transaction, as described by accountNameApplyAliases. This can fail
--   due to a bad replacement pattern in a regular expression alias.
transactionApplyAliases :: [AccountAlias] -> Transaction -> Either RegexError Transaction

-- | Apply a transformation to a transaction's postings.
transactionMapPostings :: (Posting -> Posting) -> Transaction -> Transaction

-- | Apply a transformation to a transaction's posting amounts.
transactionMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Transaction -> Transaction

-- | All posting amounts from this transaction, in order.
transactionAmounts :: Transaction -> [MixedAmount]

-- | Get the canonical amount styles inferred from this transaction's
--   amounts.
transactionCommodityStyles :: Transaction -> Map CommoditySymbol AmountStyle

-- | Like transactionCommodityStyles, but attach a particular rounding
--   strategy to the styles, affecting how they will affect display
--   precisions when applied.
transactionCommodityStylesWith :: Rounding -> Transaction -> Map CommoditySymbol AmountStyle

-- | Flip the sign of this transaction's posting amounts (and balance
--   assertion amounts).
transactionNegate :: Transaction -> Transaction
partitionAndCheckConversionPostings :: Bool -> [AccountName] -> [IdxPosting] -> Either Text ([(IdxPosting, IdxPosting)], ([IdxPosting], [IdxPosting]))

-- | Add tags to a transaction, discarding any for which it already has a
--   value. Note this does not add tags to the transaction's comment.
transactionAddTags :: Transaction -> [Tag] -> Transaction

-- | Add the given hidden tag to a transaction; and with a true argument,
--   also add the equivalent visible tag to the transaction's tags and
--   comment fields. If the transaction already has these tags (with any
--   value), do nothing.
transactionAddHiddenAndMaybeVisibleTag :: Bool -> HiddenTag -> Transaction -> Transaction

-- | How to determine the precision used for checking that transactions are
--   balanced. See #2402.
data TransactionBalancingPrecision

-- | Legacy behaviour, as in hledger <1.50, included to ease upgrades.
--   use precision inferred from the whole journal, overridable by
--   commodity directive or -c. Display precision is also transaction
--   balancing precision; increasing it can break journal reading. Some
--   valid journals are rejected until commodity directives are added.
--   Small unbalanced remainders can be hidden, and in accounts that are
--   never reconciled, can accumulate over time.
TBPOld :: TransactionBalancingPrecision

-- | Simpler, more robust behaviour, as in Ledger: use precision inferred
--   from the transaction. Display precision and transaction balancing
--   precision are independent; display precision never affects journal
--   reading. Valid journals from ledger or beancount are accepted without
--   needing commodity directives. Every imbalance in a transaction is
--   visibly accounted for in that transaction's journal entry.
TBPExact :: TransactionBalancingPrecision

-- | Parse a transaction's description into payee and note (aka narration)
--   fields, assuming a convention of separating these with | (like
--   Beancount). Ie, everything up to the first | is the payee, everything
--   after it is the note. When there's no |, payee == note == description.
payeeAndNoteFromDescription :: Text -> (Text, Text)

-- | Like payeeAndNoteFromDescription, but if there's no | then payee is
--   empty.
payeeAndNoteFromDescription' :: Text -> (Text, Text)
transactionDate2 :: Transaction -> Day
transactionDateOrDate2 :: WhichDate -> Transaction -> Day
transactionPayee :: Transaction -> Text
transactionNote :: Transaction -> Text

-- | Render a journal transaction as text similar to the style of Ledger's
--   print command.
--   
--   Adapted from Ledger 2.x and 3.x standard format:
--   
--   
--   yyyy-mm-dd[ *][ CODE] description.........          [  ; comment...............]
--       account name 1.....................  ...$amount1[  ; comment...............]
--       account name 2.....................  ..$-amount1[  ; comment...............]
--   
--   pcodewidth    = no limit -- 10          -- mimicking ledger layout.
--   pdescwidth    = no limit -- 20          -- I don't remember what these mean,
--   pacctwidth    = 35 minimum, no maximum  -- they were important at the time.
--   pamtwidth     = 11
--   pcommentwidth = no limit -- 22
--   
--   
--   The output will be parseable journal syntax. To facilitate this,
--   postings with explicit multi-commodity amounts are displayed as
--   multiple similar postings, one per commodity. (Normally does not
--   happen with this function).
showTransaction :: Transaction -> Text

-- | Like showTransaction, but explicit multi-commodity amounts are shown
--   on one line, comma-separated. In this case the output will not be
--   parseable journal syntax.
showTransactionOneLineAmounts :: Transaction -> Text
showTransactionLineFirstPart :: Transaction -> Text

-- | The file path from which this transaction was parsed.
transactionFile :: Transaction -> FilePath
annotateErrorWithTransaction :: Transaction -> String -> String
tests_Transaction :: TestTree
instance GHC.Internal.Enum.Bounded Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Enum.Enum Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Classes.Eq Hledger.Data.Transaction.TransactionBalancingPrecision
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Transaction
instance GHC.Classes.Ord Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Read.Read Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Show.Show Hledger.Data.Transaction.TransactionBalancingPrecision

-- | Helpers for beancount output.
module Hledger.Write.Beancount

-- | Like showTransaction, but applies various adjustments to produce valid
--   Beancount journal data.
showTransactionBeancount :: Transaction -> Text

-- | Make a list of tags ready to be rendered as Beancount metadata: Encode
--   and lengthen names, encode values, and combine repeated tags into one.
--   Metadatas will be sorted by (encoded) name and then value.
tagsToBeancountMetadata :: [Tag] -> [BMetadata]

-- | Render a Beancount metadata as a metadata line (without the
--   indentation or newline). If a maximum name length is provided, space
--   will be left after the colon so that successive metadata values will
--   all start at the same column.
showBeancountMetadata :: Maybe Int -> BMetadata -> Text

-- | Convert a hledger account name to a valid Beancount account name. It
--   replaces spaces with dashes and other non-supported characters with
--   CHEXBYTES; prepends the letter A to any part which doesn't
--   begin with a letter or number; adds a second :A part if there is only
--   one part; and capitalises each part. It also checks that the first
--   part is one of the required english account names Assets, Liabilities,
--   Equity, Income, or Expenses, and if not raises an informative error.
--   Ref:
--   https://beancount.github.io/docs/beancount_language_syntax.html#accounts
accountNameToBeancount :: AccountName -> BeancountAccountName

-- | Convert a hledger commodity name to a valid Beancount commodity name.
--   That is: 2-24 uppercase letters  digits  apostrophe  period
--    underscore / dash, starting with a letter, and ending with a
--   letter or digit. Ref:
--   https://beancount.github.io/docs/beancount_language_syntax.html#commodities-currencies
--   So this: replaces common currency symbols with their ISO 4217 currency
--   codes, capitalises all letters, replaces spaces with dashes and other
--   invalid characters with CHEXBYTES, prepends a C if the first
--   character is not a letter, appends a C if the last character is not a
--   letter or digit, and disables hledger's enclosing double quotes.
--   
--   
--   >>> commodityToBeancount ""
--   "C"
--   
--   >>> commodityToBeancount "$"
--   "USD"
--   
--   >>> commodityToBeancount "Usd"
--   "USD"
--   
--   >>> commodityToBeancount "\"a1\""
--   "A1"
--   
--   >>> commodityToBeancount "\"A 1!\""
--   "A-1C21"
--   
commodityToBeancount :: CommoditySymbol -> BeancountCommoditySymbol
tests_WriteBeancount :: TestTree

-- | A general query system for matching things (accounts, postings,
--   transactions..) by various criteria, and a SimpleTextParser for query
--   expressions.
module Hledger.Query

-- | A query is a composition of search criteria, which can be used to
--   match postings, transactions, accounts and more.
data Query

-- | always match
Any :: Query

-- | never match data queries (in "standard" order, roughly as they appear
--   in a transaction)
None :: Query

-- | match primary dates in this date span
Date :: DateSpan -> Query

-- | match secondary dates in this date span
Date2 :: DateSpan -> Query

-- | match this txn/posting status
StatusQ :: Status -> Query

-- | match txn codes infix-matched by this regexp
Code :: Regexp -> Query

-- | match txn descriptions infix-matched by this regexp
Desc :: Regexp -> Query

-- | match if a tag's name, and optionally its value, is infix-matched by
--   the respective regexps
Tag :: Regexp -> Maybe Regexp -> Query

-- | match account names infix-matched by this regexp
Acct :: Regexp -> Query

-- | match accounts whose type is one of these (or with no types, any
--   account)
Type :: [AccountType] -> Query

-- | match if account depth is less than or equal to this value (or,
--   sometimes used as a display option)
Depth :: Int -> Query

-- | match if the account matches and account depth is less than or equal
--   to this value (usually used as a display option)
DepthAcct :: Regexp -> Int -> Query

-- | match postings with this "realness" value
Real :: Bool -> Query

-- | match if the amount's numeric quantity is less thangreater
--   thanequal to/unsignedly equal to some value
Amt :: OrdPlus -> Quantity -> Query

-- | match if the commodity symbol is fully-matched by this regexp compound
--   queries (expr:)
Sym :: Regexp -> Query

-- | negate this match
Not :: Query -> Query

-- | match if all of these match
And :: [Query] -> Query

-- | match if any of these match compound queries for transactions (any:,
--   all:) If used in a non transaction-matching context, these are
--   equivalent to And.
Or :: [Query] -> Query

-- | match if any one posting is matched by all of these
AnyPosting :: [Query] -> Query

-- | match if all of one or more postings are matched by all of these
AllPostings :: [Query] -> Query

-- | A query option changes a query's/report's behaviour and output in some
--   way.
data QueryOpt

-- | show an account register focussed on this account
QueryOptInAcctOnly :: AccountName -> QueryOpt

-- | as above but include sub-accounts in the account register
QueryOptInAcct :: AccountName -> QueryOpt

-- | report interval extracted from a date: query | QueryOptCostBasis -- ^
--   show amounts converted to cost where possible | QueryOptDate2 -- ^
--   show secondary dates instead of primary dates
QueryOptInterval :: Interval -> QueryOpt

-- | A more expressive Ord, used for amt: queries. The Abs* variants
--   compare with the absolute value of a number, ignoring sign.
data OrdPlus
Lt :: OrdPlus
LtEq :: OrdPlus
Gt :: OrdPlus
GtEq :: OrdPlus
Eq :: OrdPlus
AbsLt :: OrdPlus
AbsLtEq :: OrdPlus
AbsGt :: OrdPlus
AbsGtEq :: OrdPlus
AbsEq :: OrdPlus

-- | Construct a query for the payee: tag
payeeTag :: Maybe Text -> Either RegexError Query

-- | Construct a query for the note: tag
noteTag :: Maybe Text -> Either RegexError Query

-- | Construct a query for the generated-transaction: tag
generatedTransactionTag :: Query

-- | A version of parseQueryList which acts on a single Text of
--   space-separated terms.
--   
--   The usual shell quoting rules are assumed. When a pattern contains
--   whitespace, it (or the whole term including prefix) should be enclosed
--   in single or double quotes.
--   
--   A query term is either:
--   
--   
--   
- a search pattern, which matches on one or more fields,
--   eg:acct:REGEXP - match the account name with a regular expression
--   desc:REGEXP - match the transaction description date:PERIODEXP - match
--   the date with a period expression
--   
--   
--   The prefix indicates the field to match, or if there is no prefix
--   account name is assumed.
--   
--   
--   
- a query option, which modifies the reporting behaviour in some
--   way. There is currently one of these, which may appear only
--   once:inacct:FULLACCTNAME
--   
--   
--   Period expressions may contain relative dates, so a reference date is
--   required to fully parse these.
--   
--   
--   >>> parseQuery nulldate "expenses:dining out"
--   Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
--   
--   
--   
--   >>> parseQuery nulldate "\"expenses:dining out\""
--   Right (Acct (RegexpCI "expenses:dining out"),[])
--   
parseQuery :: Day -> Text -> Either String (Query, [QueryOpt])

-- | Convert a list of space-separated queries to a single query
--   
--   Multiple terms are combined as follows: 1. multiple account patterns
--   are OR'd together 2. multiple description patterns are OR'd together
--   3. multiple status patterns are OR'd together 4. then all terms are
--   AND'd together
parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt])

-- | Parse a single query term as either a query or a query option, or
--   return an error message if parsing fails.
parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt])

-- | Case-insensitively parse one single-letter code, or one long-form word
--   if permitted, to an account type. On failure, returns the unparseable
--   text.
parseAccountType :: Bool -> Text -> Either String AccountType
parseDepthSpec :: Text -> Either RegexError DepthSpec
simplifyQuery :: Query -> Query

-- | Remove query terms (or whole sub-expressions) from this query which do
--   not match the given predicate. XXX Semantics not completely clear.
--   Also calls simplifyQuery on the result.
filterQuery :: (Query -> Bool) -> Query -> Query

-- | Remove query terms (or whole sub-expressions) from this query which
--   match neither the given predicate nor that predicate negated (eg, if
--   predicate is queryIsAcct, this will keep both "acct:" and "not:acct:"
--   terms). Also calls simplifyQuery on the result. (Since 1.24.1, might
--   be merged into filterQuery in future.) XXX Semantics not completely
--   clear.
filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query

-- | Does this simple query predicate match any part of this possibly
--   compound query ?
matchesQuery :: (Query -> Bool) -> Query -> Bool

-- | Does this query match everything ?
queryIsNull :: Query -> Bool

-- | Is this a simple query of this type (date:) ? Does not match a
--   compound query involving andornot. Likewise for the following
--   functions.
queryIsDate :: Query -> Bool
queryIsDate2 :: Query -> Bool
queryIsDateOrDate2 :: Query -> Bool
queryIsStatus :: Query -> Bool
queryIsCode :: Query -> Bool
queryIsDesc :: Query -> Bool
queryIsTag :: Query -> Bool
queryIsAcct :: Query -> Bool
queryIsType :: Query -> Bool
queryIsDepth :: Query -> Bool
queryIsReal :: Query -> Bool
queryIsAmt :: Query -> Bool
queryIsSym :: Query -> Bool
queryIsAmtOrSym :: Query -> Bool

-- | Does this query specify a start date and nothing else (that would
--   filter postings prior to the date) ? When the flag is true, look for a
--   starting secondary date instead.
queryIsStartDateOnly :: Bool -> Query -> Bool

-- | Does this query involve a property of transactions (or their
--   postings), making it inapplicable to account declarations ?
queryIsTransactionRelated :: Query -> Bool

-- | What start date (or secondary date) does this query specify, if any ?
--   For OR expressions, use the earliest of the dates. NOT is ignored.
queryStartDate :: Bool -> Query -> Maybe Day

-- | What end date (or secondary date) does this query specify, if any ?
--   For OR expressions, use the latest of the dates. NOT is ignored.
queryEndDate :: Bool -> Query -> Maybe Day

-- | What date span (or with a true argument, what secondary date span)
--   does this query specify ? OR clauses specifying multiple spans return
--   their union (the span enclosing all of them). AND clauses specifying
--   multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan :: Bool -> Query -> DateSpan

-- | What date span does this query specify, treating primary and secondary
--   dates as equivalent ? OR clauses specifying multiple spans return
--   their union (the span enclosing all of them). AND clauses specifying
--   multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan' :: Query -> DateSpan

-- | The depth limit this query specifies, if it has one
queryDepth :: Query -> DepthSpec

-- | The account we are currently focussed on, if any, and whether
--   subaccounts are included. Just looks at the first query option.
inAccount :: [QueryOpt] -> Maybe (AccountName, Bool)

-- | A query for the account(s) we are currently focussed on, if any. Just
--   looks at the first query option.
inAccountQuery :: [QueryOpt] -> Maybe Query

-- | Does the match expression match this transaction ?
matchesTransaction :: Query -> Transaction -> Bool

-- | Like matchesTransaction, but if the journal's account types are
--   provided, any type: terms in the query must match at least one
--   posting's account type (and any negated type: terms must match none).
matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool

-- | Does the query match this transaction description ? Non-desc: query
--   terms are ignored (this might disrupt some boolean queries).
matchesDescription :: Query -> Text -> Bool

-- | Does the query match this transaction payee ? Tests desc: (and payee:
--   ?) terms, any other terms are ignored. XXX Currently an alias for
--   matchDescription. I'm not sure if more is needed, There's some
--   shenanigan with payee: and "payeeTag" to figure out.
matchesPayeeWIP :: Query -> Payee -> Bool

-- | Does the match expression match this posting ? When matching account
--   name, and the posting has been transformed in some way, we will match
--   either the original or transformed name.
matchesPosting :: Query -> Posting -> Bool

-- | Like matchesPosting, but if the posting's account's type is provided,
--   any type: terms in the query must match it (and any negated type:
--   terms must not match it).
matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool

-- | Does the query match this account name ? A matching in: clause is also
--   considered a match.
matchesAccount :: Query -> AccountName -> Bool

-- | Like matchesAccount, but with optional extra matching features:
--   
--   
--   
- If the account's type is provided, any type: terms in the query
--   must match it (and any negated type: terms must not match it).
--   
- If the account's tags are provided, any tag: terms must match at
--   least one of them (and any negated tag: terms must match none).
--   
matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool
matchesMixedAmount :: Query -> MixedAmount -> Bool

-- | Does the match expression match this (simple) amount ?
matchesAmount :: Query -> Amount -> Bool
matchesCommodity :: Query -> CommoditySymbol -> Bool

-- | Does the query match the name and optionally the value of this tag ?
--   Non-tag: query terms are ignored (this might disrupt some boolean
--   queries).
matchesTag :: Query -> Tag -> Bool

-- | Does the query match this market price ?
matchesPriceDirective :: Query -> PriceDirective -> Bool

-- | Quote-and-prefix-aware version of words - don't split on spaces which
--   are inside quotes, including quotes which may have one of the
--   specified prefixes in front, and maybe an additional not: prefix in
--   front of that.
words'' :: [Text] -> Text -> [Text]
queryprefixes :: [Text]
tests_Query :: TestTree
instance Data.Default.Internal.Default Hledger.Query.Query
instance GHC.Classes.Eq Hledger.Query.OrdPlus
instance GHC.Classes.Eq Hledger.Query.Query
instance GHC.Classes.Eq Hledger.Query.QueryOpt
instance GHC.Internal.Show.Show Hledger.Query.OrdPlus
instance GHC.Internal.Show.Show Hledger.Query.Query
instance GHC.Internal.Show.Show Hledger.Query.QueryOpt

-- | A TransactionModifier is a rule that modifies certain
--   Transactions, typically adding automated postings to them.
module Hledger.Data.TransactionModifier

-- | Apply all the given transaction modifiers, in turn, to each
--   transaction. Or if any of them fails to be parsed, return the first
--   error. A reference date is provided to help interpret relative dates
--   in transaction modifier queries.
modifyTransactions :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Map CommoditySymbol AmountStyle -> Day -> Bool -> [TransactionModifier] -> [Transaction] -> Either String [Transaction]

-- | A TimeclockEntry is a clock-in, clock-out, or other directive
--   in a timeclock file (see timeclock.el or the command-line version).
--   These can be converted to Transactions and queried like a
--   ledger.
module Hledger.Data.Timeclock

-- | Convert timeclock entries to journal transactions. This is the new,
--   default version added in hledger 1.43 and improved in 1.50. It allows
--   concurrent clocked-in sessions (though not with the same account
--   name), and clock-in/clock-out entries in any order.
--   
--   Entries are processed in parse order. Sessions crossing midnight are
--   split into days to give accurate per-day totals. At the end, any
--   sessions with no clockout get an implicit clockout with the provided
--   "now" time. If any entries cannot be paired as expected, an error is
--   raised.
timeclockToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]

-- | Convert timeclock entries to journal transactions. This is the old
--   version from hledger <1.43, now enabled by --old-timeclock. It
--   requires strictly alternating clock-in and clock-entries. It was
--   documented as allowing only one clocked-in session at a time, but in
--   fact it allows concurrent sessions, even with the same account name.
--   
--   Entries must be a strict alternation of in and out, beginning with in.
--   When there is no clockout, one is added with the provided current
--   time. Sessions crossing midnight are split into days to give accurate
--   per-day totals. If entries are not in the expected in/out order, an
--   error is raised.
timeclockToTransactionsOld :: LocalTime -> [TimeclockEntry] -> [Transaction]
tests_Timeclock :: TestTree
instance GHC.Internal.Read.Read Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Show.Show Hledger.Data.Timeclock.Session
instance GHC.Internal.Show.Show Hledger.Data.Timeclock.Sessions
instance GHC.Internal.Show.Show Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Show.Show Hledger.Data.Types.TimeclockEntry

-- | Data values for zero or more report periods, and for the pre-report
--   period. Report periods are assumed to be contiguous, and represented
--   only by start dates (as keys of an IntMap).
module Hledger.Data.PeriodData

-- | Construct a PeriodData from a historical data value and a list
--   of (period start, period data) pairs.
periodDataFromList :: a -> [(Day, a)] -> PeriodData a

-- | Convert PeriodData to a historical data value and a list of
--   (period start, period data) pairs.
periodDataToList :: PeriodData a -> (a, [(Day, a)])

-- | Get the data for the period containing the given Day, and that
--   period's start date. If the day is after the end of the last period,
--   it is assumed to be within the last period. If the day is before the
--   start of the first period (ie, in the historical period), return
--   Nothing.
lookupPeriodData :: Day -> PeriodData a -> Maybe (Day, a)

-- | Get the data for the period containing the given Day, and that
--   period's start date. If the day is after the end of the last period,
--   it is assumed to be within the last period. If the day is before the
--   start of the first period (ie, in the historical period), return the
--   data for the historical period and no start date.
lookupPeriodDataOrHistorical :: Day -> PeriodData a -> (Maybe Day, a)

-- | Set historical or period data in the appropriate location in a
--   PeriodData.
insertPeriodData :: Semigroup a => Maybe Day -> a -> PeriodData a -> PeriodData a

-- | Merge two PeriodData, using the given operation to combine
--   their data values.
--   
--   This will drop keys if they are not present in both PeriodData.
opPeriodData :: (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c

-- | Merge two PeriodData, using the given operations for combining
--   data that's only in the first, only in the second, or in both,
--   respectively.
mergePeriodData :: (a -> c) -> (b -> c) -> (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c

-- | Pad out the date map of a PeriodData so that every key from
--   another PeriodData is present.
padPeriodData :: a -> PeriodData b -> PeriodData a -> PeriodData a
tests_PeriodData :: TestTree
instance Data.Foldable1.Foldable1 Hledger.Data.Types.PeriodData
instance GHC.Internal.Data.Foldable.Foldable Hledger.Data.Types.PeriodData
instance GHC.Internal.Base.Monoid a => GHC.Internal.Base.Monoid (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Base.Semigroup a => GHC.Internal.Base.Semigroup (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Data.Traversable.Traversable Hledger.Data.Types.PeriodData

-- | A partition of time into contiguous spans, for defining reporting
--   periods.
module Hledger.Data.DayPartition

-- | A partition of time into one or more contiguous periods, plus a
--   historical period that precedes them. Note DayPartition does
--   not store per-period data - only the periods' start/end dates.
data DayPartition

-- | Construct a DayPartition from a non-empty list of period
--   boundary dates (start dates plus a final exclusive end date).
--   
--   
--   >>> boundariesToDayPartition (fromGregorian 2025 01 01 :| [fromGregorian 2025 02 01])
--   DayPartition {dayPartitionToPeriodData = PeriodData{ pdpre = 2024-12-31, pdperiods = fromList [(2025-01-01,2025-01-31)]}}
--   
boundariesToDayPartition :: NonEmpty Day -> DayPartition

-- | Construct a DayPartition from a list of period boundary dates
--   (start dates plus a final exclusive end date), if it's a non-empty
--   list.
boundariesToMaybeDayPartition :: [Day] -> Maybe DayPartition

-- | Convert DayPartition to a non-empty list of period start and
--   end dates (both inclusive). Each end date will be one day before the
--   next period's start date.
dayPartitionToNonEmpty :: DayPartition -> NonEmpty (Day, Day)

-- | Convert DayPartition to a list (which will always be non-empty)
--   of period start and end dates (both inclusive). Each end date will be
--   one day before the next period's start date.
dayPartitionToList :: DayPartition -> [(Day, Day)]

-- | Convert DayPartition to a list of DateSpans. Each span
--   will end one day before the next span begins (the span's exclusive end
--   date will be equal to the next span's start date).
dayPartitionToDateSpans :: DayPartition -> [DateSpan]
dayPartitionToPeriodData :: DayPartition -> PeriodData Day
maybeDayPartitionToDateSpans :: Maybe DayPartition -> [DateSpan]

-- | Return the union of two DayPartitions if that is a valid
--   DayPartition, or Nothing otherwise.
unionDayPartitions :: DayPartition -> DayPartition -> Maybe DayPartition

-- | Get this DayPartition's overall start date and end date (both
--   inclusive).
dayPartitionStartEnd :: DayPartition -> (Day, Day)

-- | Find the start and end dates of the period within a
--   DayPartition which contains a given day. If the day is after
--   the end of the last period, it is assumed to be within the last
--   period. If the day is before the start of the first period (ie, in the
--   historical period), only the historical period's end date is returned.
dayPartitionFind :: Day -> DayPartition -> (Maybe Day, Day)

-- | Split a DateSpan into a DayPartition consisting of
--   consecutive exact spans of the specified Interval, or Nothing
--   if the span is invalid. If no interval is specified, the original span
--   is returned. If the original span is the null date span, ie unbounded,
--   Nothing is returned. If the original span is empty, eg if the
--   end date is <= the start date, Nothing is returned.
--   
--   
Date adjustment
--   
--   Some intervals respect the "adjust" flag (years, quarters, months,
--   weeks, every Nth weekday of month seem to be the ones that need it).
--   This will move the start date earlier, if needed, to the previous
--   natural interval boundary (first of year, first of quarter, first of
--   month, monday, previous Nth weekday of month). Related: #1982 #2218
--   
--   The end date is always moved later if needed to the next natural
--   interval boundary, so that the last period is the same length as the
--   others.
--   
--   
Examples
--   
--   
--   >>> let t i y1 m1 d1 y2 m2 d2 = fmap dayPartitionToNonEmpty . splitSpan True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)
--   
--   >>> t NoInterval 2008 01 01 2009 01 01
--   Just ((2008-01-01,2008-12-31) :| [])
--   
--   >>> t (Quarters 1) 2008 01 01 2009 01 01
--   Just ((2008-01-01,2008-03-31) :| [(2008-04-01,2008-06-30),(2008-07-01,2008-09-30),(2008-10-01,2008-12-31)])
--   
--   >>> splitSpan True (Quarters 1) nulldatespan
--   Nothing
--   
--   >>> t (Days 1) 2008 01 01 2008 01 01  -- an empty datespan
--   Nothing
--   
--   >>> t (Quarters 1) 2008 01 01 2008 01 01
--   Nothing
--   
--   >>> t (Months 1) 2008 01 01 2008 04 01
--   Just ((2008-01-01,2008-01-31) :| [(2008-02-01,2008-02-29),(2008-03-01,2008-03-31)])
--   
--   >>> t (Months 2) 2008 01 01 2008 04 01
--   Just ((2008-01-01,2008-02-29) :| [(2008-03-01,2008-04-30)])
--   
--   >>> t (Weeks 1) 2008 01 01 2008 01 15
--   Just ((2007-12-31,2008-01-06) :| [(2008-01-07,2008-01-13),(2008-01-14,2008-01-20)])
--   
--   >>> t (Weeks 2) 2008 01 01 2008 01 15
--   Just ((2007-12-31,2008-01-13) :| [(2008-01-14,2008-01-27)])
--   
--   >>> t (MonthDay 2) 2008 01 01 2008 04 01
--   Just ((2008-01-02,2008-02-01) :| [(2008-02-02,2008-03-01),(2008-03-02,2008-04-01)])
--   
--   >>> t (NthWeekdayOfMonth 2 4) 2011 01 01 2011 02 15
--   Just ((2010-12-09,2011-01-12) :| [(2011-01-13,2011-02-09),(2011-02-10,2011-03-09)])
--   
--   >>> t (DaysOfWeek [2]) 2011 01 01 2011 01 15
--   Just ((2010-12-28,2011-01-03) :| [(2011-01-04,2011-01-10),(2011-01-11,2011-01-17)])
--   
--   >>> t (MonthAndDay 11 29) 2012 10 01 2013 10 15
--   Just ((2012-11-29,2013-11-28) :| [])
--   
splitSpan :: Bool -> Interval -> DateSpan -> Maybe DayPartition

-- | Get the natural start for the given interval that falls on or before
--   the given day, when applicable. Works for Weeks, Months, Quarters,
--   Years, eg.
intervalBoundaryBefore :: Interval -> Day -> Day
tests_DayPartition :: TestTree
instance GHC.Classes.Eq Hledger.Data.DayPartition.DayPartition
instance GHC.Classes.Ord Hledger.Data.DayPartition.DayPartition
instance GHC.Internal.Show.Show Hledger.Data.DayPartition.DayPartition

-- | A PeriodicTransaction is a rule describing recurring
--   transactions.
module Hledger.Data.PeriodicTransaction

-- | Generate transactions from PeriodicTransaction within a
--   DateSpan. This should be a closed span with both start and end
--   dates specified; an open ended span will generate no transactions.
--   
--   Note that new transactions require txnTieKnot post-processing.
--   The new transactions will have three tags added: - a
--   recur:PERIODICEXPR tag whose value is the generating periodic
--   expression - a generated-transaction: tag - a hidden
--   _generated-transaction: tag which does not appear in the comment.
--   
--   
--   >>> import Data.Time (fromGregorian)
--   
--   >>> _ptgen "monthly from 2017/1 to 2017/4"
--   2017-01-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a           $1.00
--   
--   2017-02-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a           $1.00
--   
--   2017-03-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "monthly from 2017/1 to 2017/5"
--   2017-01-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-02-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-03-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-04-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "every 2nd day of month from 2017/02 to 2017/04"
--   2017-02-02
--       ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--       a           $1.00
--   
--   2017-03-02
--       ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "every 30th day of month from 2017/1 to 2017/5"
--   2017-01-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-02-28
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-03-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a           $1.00
--   
--   2017-04-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"
--   2017-01-12
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a           $1.00
--   
--   2017-02-09
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a           $1.00
--   
--   2017-03-09
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "every nov 29th from 2017 to 2019"
--   2017-11-29
--       ; generated-transaction: ~ every nov 29th from 2017 to 2019
--       a           $1.00
--   
--   2018-11-29
--       ; generated-transaction: ~ every nov 29th from 2017 to 2019
--       a           $1.00
--   
--   
--   
--   >>> _ptgen "2017/1"
--   2017-01-01
--       ; generated-transaction: ~ 2017/1
--       a           $1.00
--   
--   
--   
--   >>> let reportperiod="daily from 2018/01/03" in let (i,s) = parsePeriodExpr' nulldate reportperiod in runPeriodicTransaction True (nullperiodictransaction{ptperiodexpr=reportperiod, ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1]}) (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03))
--   []
--   
--   
--   
--   >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 01 01) (Just $ Flex $ fromGregorian 2020 02 01))
--   
--   
--   
--   >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 02 01) (Just $ Flex $ fromGregorian 2020 03 01))
--   2020-02-01
--       ; generated-transaction: ~ every 3 months from 2019-05
--       a           $1.00
--   
--   
--   >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 05))
--   2018-01-01
--       ; generated-transaction: ~ every 3 days from 2018
--       a           $1.00
--   
--   2018-01-04
--       ; generated-transaction: ~ every 3 days from 2018
--       a           $1.00
--   
--   
--   >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 02) (Just $ Flex $ fromGregorian 2018 01 05))
--   2018-01-04
--       ; generated-transaction: ~ every 3 days from 2018
--       a           $1.00
--   
runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]

-- | Check that this date span begins at a boundary of this interval, or
--   return an explanatory error message including the provided period
--   expression (from which the span and interval are derived).
checkPeriodicTransactionStartDate :: Interval -> DateSpan -> Text -> Maybe String
instance GHC.Internal.Show.Show Hledger.Data.Types.PeriodicTransaction

module Hledger.Data.Json

-- | Show a JSON-convertible haskell value as pretty-printed JSON text.
toJsonText :: ToJSON a => a -> Text

-- | Write a JSON-convertible haskell value to a pretty-printed JSON file.
--   Eg: writeJsonFile "a.json" nulltransaction
writeJsonFile :: ToJSON a => FilePath -> a -> IO ()

-- | Read a JSON file and decode it to the target type, or raise an error
--   if we can't. Eg: readJsonFile "a.json" :: IO Transaction
readJsonFile :: FromJSON a => FilePath -> IO a
instance Data.Aeson.Types.FromJSON.FromJSON a => Data.Aeson.Types.FromJSON.FromJSON (Hledger.Data.Types.Account a)
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountCost
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.BalanceData
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.CostBasis
instance Data.Aeson.Types.FromJSON.FromJSON (Data.Decimal.DecimalRaw GHC.Num.Integer.Integer)
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.FromJSON.FromJSON a => Data.Aeson.Types.FromJSON.FromJSON (Hledger.Data.Types.PeriodData a)
instance Data.Aeson.Types.FromJSON.FromJSON Text.Megaparsec.Pos.Pos
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.PostingType
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Rounding
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.FromJSON.FromJSON Text.Megaparsec.Pos.SourcePos
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.ToJSON.ToJSONKey Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Data.Types.Account a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountAlias
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountCost
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.BalanceData
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Commodity
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.CostBasis
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DateSpan
instance (GHC.Internal.Real.Integral a, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Data.Decimal.DecimalRaw a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.EFDay
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Interval
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Journal
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Ledger
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PayeeDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Period
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Data.Types.PeriodData a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PeriodicTransaction
instance Data.Aeson.Types.ToJSON.ToJSON Text.Megaparsec.Pos.Pos
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PostingType
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PriceDirective
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Rounding
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.ToJSON.ToJSON Text.Megaparsec.Pos.SourcePos
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TMPostingRule
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TagDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TimeclockCode
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TimeclockEntry
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TransactionModifier

-- | 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).
module Hledger.Data.Journal

-- | A parser of text that runs in some monad, keeping a Journal as state.
type JournalParser (m :: Type -> Type) a = StateT Journal ParsecT HledgerParseErrorData Text m a

-- | 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.
type ErroringJournalParser (m :: Type -> Type) a = StateT Journal ParsecT HledgerParseErrorData Text ExceptT FinalParseError m a
addPriceDirective :: PriceDirective -> Journal -> Journal
addTransactionModifier :: TransactionModifier -> Journal -> Journal
addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addTransaction :: Transaction -> Journal -> Journal
journalDbg :: Journal -> String

-- | 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.
journalInferMarketPricesFromTransactions :: Journal -> Journal

-- | 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. Can return an error message eg if
--   inconsistent number formats are found.
journalInferCommodityStyles :: Journal -> Either String Journal

-- | Apply this journal's commodity display styles to all of its 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. This can return
--   an error message eg if inconsistent number formats are found.
journalStyleAmounts :: Journal -> Either String Journal

-- | 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.
journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle

-- | Like journalCommodityStyles, but attach a particular rounding strategy
--   to the styles, affecting how they will affect display precisions when
--   applied.
journalCommodityStylesWith :: Rounding -> Journal -> Map CommoditySymbol AmountStyle

-- | Convert all this journal's amounts to cost using their attached
--   prices, if any.
journalToCost :: ConversionOp -> Journal -> Journal

-- | Add equity postings inferred from costs, where needed and possible.
--   See hledger manual > Cost reporting.
journalInferEquityFromCosts :: Bool -> Journal -> Journal

-- | 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.
journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either String Journal

-- | 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.
journalReverse :: Journal -> Journal

-- | Set this journal's last read time, ie when its files were last read.
journalSetLastReadTime :: POSIXTime -> Journal -> Journal

-- | Renumber all the account declarations. This is useful to call when
--   finalising or concatenating Journals, to give account declarations a
--   total order across files.
journalRenumberAccountDeclarations :: Journal -> Journal

-- | Apply the pivot transformation to all postings in a journal, replacing
--   their account name by their value for the given field or tag.
journalPivot :: Text -> Journal -> Journal

-- | To all postings in the journal, add any tags from their account
--   (including those inherited from parent accounts). If a tag already
--   exists on the posting, it is not changed (the account tag will be
--   ignored).
journalPostingsAddAccountTags :: Journal -> Journal

-- | 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.
journalPostingsKeepAccountTagsOnly :: Journal -> Journal

-- | To all postings in the journal, add any tags from their amount's
--   commodities. If a tag already exists on the posting, it is not changed
--   (the commodity tag will be ignored).
journalPostingsAddCommodityTags :: Journal -> Journal

-- | Keep only transactions matching the query expression.
filterJournalTransactions :: Query -> Journal -> Journal

-- | Keep only postings matching the query expression. This can leave
--   unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal

-- | Keep only postings which do not match the query expression, but for
--   which a related posting does. This can leave unbalanced transactions.
filterJournalRelatedPostings :: Query -> Journal -> Journal

-- | 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.
filterJournalAmounts :: Query -> Journal -> Journal

-- | 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.
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionPostings :: Query -> Transaction -> Transaction
filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction
filterTransactionRelatedPostings :: Query -> Transaction -> Transaction

-- | Filter out all parts of this posting's amount which do not match the
--   query, and remove the posting if this removes all amounts.
filterPostingAmount :: Query -> Posting -> Maybe Posting

-- | Apply a transformation to a journal's transactions.
journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal

-- | Apply a transformation to a journal's postings.
journalMapPostings :: (Posting -> Posting) -> Journal -> Journal

-- | Apply a transformation to a journal's posting amounts.
journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal

-- | Sorted unique account names posted to by this journal's transactions.
journalAccountNamesUsed :: Journal -> [AccountName]

-- | Sorted unique account names implied by this journal's transactions -
--   accounts posted to and all their implied parent accounts.
journalAccountNamesImplied :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives in this
--   journal.
journalAccountNamesDeclared :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives or posted
--   to by transactions in this journal.
journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives, or posted
--   to or implied as parents by transactions in this journal.
journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]

-- | Convenience/compatibility alias for
--   journalAccountNamesDeclaredOrImplied.
journalAccountNames :: Journal -> [AccountName]

-- | Sorted unique account names declared or implied in this journal which
--   have no children.
journalLeafAccountNames :: Journal -> [AccountName]
journalAccountNameTree :: Journal -> Tree AccountName

-- | Which tags have been declared explicitly for this account, if any ?
journalAccountTags :: Journal -> AccountName -> [Tag]

-- | Get any tags declared for this commodity.
journalCommodityTags :: Journal -> CommoditySymbol -> [Tag]

-- | Which tags are in effect for this account, including tags inherited
--   from parent accounts ?
journalInheritedAccountTags :: Journal -> AccountName -> [Tag]

-- | Sorted unique payees declared by payee directives in this journal.
journalPayeesDeclared :: Journal -> [Payee]

-- | Sorted unique payees used by transactions in this journal.
journalPayeesUsed :: Journal -> [Payee]

-- | Sorted unique payees used in transactions or declared by payee
--   directives in this journal.
journalPayeesDeclaredOrUsed :: Journal -> [Payee]

-- | Sorted unique tag names declared by tag directives in this journal.
journalTagsDeclared :: Journal -> [TagName]

-- | Sorted unique tag names used in this journal (in account directives,
--   transactions, postings..)
journalTagsUsed :: Journal -> [TagName]

-- | Sorted unique tag names used in transactions or declared by tag
--   directives in this journal.
journalTagsDeclaredOrUsed :: Journal -> [TagName]

-- | 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.)
journalAmounts :: Journal -> Set Amount

-- | All posting amounts from this journal, in order.
journalPostingAmounts :: Journal -> [MixedAmount]

-- | All raw amounts used in this journal's postings and costs, with
--   MixedAmounts flattened, in parse order.
journalPostingAndCostAmounts :: Journal -> [Amount]

-- | Sorted unique commodity symbols declared by commodity directives in
--   this journal.
journalCommoditiesDeclared :: Journal -> [CommoditySymbol]

-- | Sorted unique commodity symbols used anywhere in this journal,
--   including commodity directives, P directives, the last D directive,
--   posting amounts and cost amounts.
journalCommoditiesUsed :: Journal -> [CommoditySymbol]

-- | Sorted unique commodity symbols mentioned anywhere in this journal.
--   (Including commodity directives, P directives, the last D directive,
--   posting amounts and cost amounts.)
journalCommodities :: Journal -> Set CommoditySymbol

-- | Sorted unique commodity symbols mentioned in this journal's P
--   directives.
journalCommoditiesFromPriceDirectives :: Journal -> Set CommoditySymbol

-- | Sorted unique commodity symbols used in transactions, in either
--   posting or cost amounts.
journalCommoditiesFromTransactions :: Journal -> Set CommoditySymbol

-- | 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.
journalDateSpan :: Bool -> Journal -> DateSpan

-- | 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.
journalDateSpanBothDates :: Journal -> DateSpan

-- | The earliest of this journal's transaction and posting dates, or
--   Nothing if there are none.
journalStartDate :: Bool -> Journal -> Maybe Day

-- | The "exclusive end date" of this journal: the day following its latest
--   transaction or posting date, or Nothing if there are none.
journalEndDate :: Bool -> Journal -> Maybe Day

-- | The latest of this journal's transaction and posting dates, or Nothing
--   if there are none.
journalLastDay :: Bool -> Journal -> Maybe Day

-- | Unique transaction descriptions used in this journal.
journalDescriptions :: Journal -> [Text]
journalFilePath :: Journal -> FilePath
journalFilePaths :: Journal -> [FilePath]

-- | Get the transaction with this index (its 1-based position in the input
--   stream), if any.
journalTransactionAt :: Journal -> Integer -> Maybe Transaction

-- | Get the transaction that appeared immediately after this one in the
--   input stream, if any.
journalNextTransaction :: Journal -> Transaction -> Maybe Transaction

-- | Get the transaction that appeared immediately before this one in the
--   input stream, if any.
journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction

-- | All postings from this journal's transactions, in order.
journalPostings :: Journal -> [Posting]

-- | Show the journal posting amounts rendered, suitable for debug logging.
showJournalPostingAmountsDebug :: Journal -> String

-- | Find up to N most similar and most recent transactions matching the
--   given transaction description and query and exceeding the given
--   description similarity score (0 to 1, see compareDescriptions).
--   Returns transactions along with their age in days compared to the
--   latest transaction date, their description similarity score, and a
--   heuristically date-weighted variant of this that favours more recent
--   transactions.
journalTransactionsSimilarTo :: Journal -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, Age, SimilarityScore, Transaction)]
journalAccountType :: Journal -> AccountName -> Maybe AccountType

-- | Build a map of all known account types, explicitly declared or
--   inferred from the account's parent or name.
journalAccountTypes :: Journal -> Map AccountName AccountType

-- | Add a map of all known account types to the journal.
journalAddAccountTypes :: Journal -> Journal
defaultBaseConversionAccount :: IsString a => a

-- | The account name to use for conversion postings generated by
--   --infer-equity. This is the first account declared with type
--   V/Conversion, or otherwise the defaultBaseConversionAccount
--   (equity:conversion).
journalBaseConversionAccount :: Journal -> AccountName

-- | 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.
journalConversionAccounts :: Journal -> [AccountName]
nulljournal :: Journal

-- | 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.
journalConcat :: Journal -> Journal -> Journal

-- | Number (set the tindex field) this journal's transactions, counting
--   upward from 1.
journalNumberTransactions :: Journal -> Journal
journalNumberAndTieTransactions :: Journal -> Journal

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

-- | 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.
journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal

-- | 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.
journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal

-- | Debug log the ordering of a journal's account declarations (at debug
--   level 7+).
dbgJournalAcctDeclOrder :: String -> Journal -> Journal
samplejournal :: Journal
samplejournalMaybeExplicit :: Bool -> Journal
tests_Journal :: TestTree
instance Data.Default.Internal.Default Hledger.Data.Types.Journal
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.Journal
instance GHC.Internal.Show.Show Hledger.Data.Types.Journal

-- | Helpers for making error messages.
module Hledger.Data.Errors

-- | Given an account name and its account directive, and a problem tag
--   within the latter: render it as a megaparsec-style excerpt, showing
--   the original line number and marked column or region. Returns the file
--   path, line number, column(s) if known, and the rendered excerpt, or as
--   much of these as is possible. The returned columns will be accurate
--   for the rendered error message but not for the original journal data.
makeAccountTagErrorExcerpt :: (AccountName, AccountDeclarationInfo) -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Given a problem price directive, and maybe a function to calculate the
--   error region's column(s) (currently ignored): generate a
--   megaparsec-style error message with highlighted excerpt. Returns the
--   source file path, line number, column(s) if known, and the rendered
--   excerpt, or as much of these as possible. Columns will be accurate for
--   the rendered error message, not for the original journal entry.
makePriceDirectiveErrorExcerpt :: PriceDirective -> Maybe (PriceDirective -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Given a problem transaction and a function calculating the best
--   column(s) for marking the error region: render it as a
--   megaparsec-style excerpt, showing the original line number on the
--   transaction line, and a column(s) marker. Returns the file path, line
--   number, column(s) if known, and the rendered excerpt, or as much of
--   these as is possible. The returned columns will be accurate for the
--   rendered error message but not for the original journal data.
makeTransactionErrorExcerpt :: Transaction -> (Transaction -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Given a problem posting and a function calculating the best column(s)
--   for marking the error region: look up error info from the parent
--   transaction, and render the transaction as a megaparsec-style excerpt,
--   showing the original line number on the problem posting's line, and a
--   column indicator. Returns the file path, line number, column(s) if
--   known, and the rendered excerpt, or as much of these as is possible. A
--   limitation: columns will be accurate for the rendered error message
--   but not for the original journal data.
makePostingErrorExcerpt :: Posting -> (Posting -> Transaction -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | From the given posting, make an error excerpt showing the transaction
--   with this posting's account part highlighted.
makePostingAccountErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | From the given posting, make an error excerpt showing the transaction
--   with the balance assertion highlighted.
makeBalanceAssertionErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Find the 1-based index of the first posting in this transaction
--   satisfying the given predicate.
transactionFindPostingIndex :: (Posting -> Bool) -> Transaction -> Maybe Int

module Hledger.Data.JournalChecks.Uniqueleafnames

-- | Check that all the journal's postings are to accounts with a unique
--   leaf name. Otherwise, return an error message for the first offending
--   posting.
journalCheckUniqueleafnames :: Journal -> Either String ()

module Hledger.Data.JournalChecks.Ordereddates
journalCheckOrdereddates :: Journal -> Either String ()

-- | Functions for ensuring transactions and journals are balanced.
module Hledger.Data.Balancing
data BalancingOpts
BalancingOpts :: Bool -> Bool -> Maybe (Map CommoditySymbol AmountStyle) -> TransactionBalancingPrecision -> Map AccountName AccountType -> BalancingOpts

-- | should failing balance assertions be ignored ?
[ignore_assertions_] :: BalancingOpts -> Bool

-- | Are we permitted to infer missing costs to balance transactions ?
--   Distinct from InputOpts{infer_costs_}.
[infer_balancing_costs_] :: BalancingOpts -> Bool

-- | commodity display styles
[commodity_styles_] :: BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
[txn_balancing_] :: BalancingOpts -> TransactionBalancingPrecision

-- | account type map, passed through for any balancing helpers that need
--   it
[account_types_] :: BalancingOpts -> Map AccountName AccountType
class HasBalancingOpts c
balancingOpts :: HasBalancingOpts c => Lens' c BalancingOpts
account_types :: HasBalancingOpts c => Lens' c (Map AccountName AccountType)
commodity_styles :: HasBalancingOpts c => Lens' c (Maybe (Map CommoditySymbol AmountStyle))
ignore_assertions :: HasBalancingOpts c => Lens' c Bool
infer_balancing_costs :: HasBalancingOpts c => Lens' c Bool
txn_balancing :: HasBalancingOpts c => Lens' c TransactionBalancingPrecision
defbalancingopts :: BalancingOpts

-- | Legacy form of transactionCheckBalanced.
isTransactionBalanced :: BalancingOpts -> Transaction -> Bool

-- | Balance this isolated transaction, ensuring that its postings (and its
--   balanced virtual postings) sum to 0, by inferring a missing amount or
--   conversion price(s) if needed. Or if balancing is not possible,
--   because the amounts don't sum to 0 or because there's more than one
--   missing amount, return an error message.
--   
--   Note this is not as accurate as balanceTransactionInJournal,
--   which considers the whole journal when calculating balance assignments
--   and balance assertions.
balanceSingleTransaction :: BalancingOpts -> Transaction -> Either String Transaction

-- | Helper used by balanceSingleTransaction and
--   balanceTransactionWithBalanceAssignmentAndCheckAssertionsB; use one of
--   those instead. It also returns a list of accounts and amounts that
--   were inferred.
balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])

-- | Verify that any assertions in this transaction hold when included in
--   the larger journal.
transactionCheckAssertions :: BalancingOpts -> Journal -> Transaction -> Either String Transaction

-- | Infer any missing amounts and/or conversion costs (as needed to
--   balance transactions and satisfy balance assignments); and check that
--   all transactions are balanced; and (optional) check that all balance
--   assertions pass. Or, return an error message (just the first error
--   encountered).
--   
--   Assumes journalStyleAmounts has been called, since amount styles
--   affect transaction balancing.
--   
--   This does multiple things at once because amount inferring, balance
--   assignments, balance assertions and posting dates are interdependent.
journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal
tests_Balancing :: TestTree
instance GHC.Classes.Eq Hledger.Data.Balancing.BalancingOpts
instance Hledger.Data.Balancing.HasBalancingOpts Hledger.Data.Balancing.BalancingOpts
instance GHC.Classes.Ord Hledger.Data.Balancing.BalancingOpts
instance GHC.Internal.Show.Show Hledger.Data.Balancing.BalancingOpts

-- | Various options to use when reading journal files. Similar to
--   CliOptions.inputflags, simplifies the journal-reading functions.
module Hledger.Read.InputOptions
data InputOpts
InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> Bool -> DateSpan -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Day -> Bool -> InputOpts

-- | a file/storage format to try, unless overridden by a filename prefix.
--   Nothing means try all.
[mformat_] :: InputOpts -> Maybe StorageFormat

-- | a conversion rules file to use (when reading CSV)
[mrules_file_] :: InputOpts -> Maybe FilePath

-- | account name aliases to apply
[aliases_] :: InputOpts -> [String]

-- | do light obfuscation of the data ? Now corresponds to --obfuscate, not
--   the old --anon flag.
[anon_] :: InputOpts -> Bool

-- | read only new transactions since this file was last read ?
[new_] :: InputOpts -> Bool

-- | save latest new transactions state for next time ?
[new_save_] :: InputOpts -> Bool

-- | use the given field's value as the account name
[pivot_] :: InputOpts -> String

-- | span in which to generate forecast transactions
[forecast_] :: InputOpts -> Maybe DateSpan

-- | propagate commodity and account tags to postings ? Can be disabled
--   (for beancount export).
[auto_posting_tags_] :: InputOpts -> Bool

-- | add user-visible tags when generating/modifying transactions &
--   postings ?
[verbose_tags_] :: InputOpts -> Bool

-- | a dirty hack keeping the query dates in InputOpts. This rightfully
--   lives in ReportSpec, but is duplicated here.
[reportspan_] :: InputOpts -> DateSpan

-- | generate extra postings according to auto posting rules ?
[auto_] :: InputOpts -> Bool

-- | infer equity conversion postings from costs ?
[infer_equity_] :: InputOpts -> Bool

-- | infer costs from equity conversion postings ? distinct from
--   BalancingOpts{infer_balancing_costs_}
[infer_costs_] :: InputOpts -> Bool

-- | options for transaction balancing
[balancingopts_] :: InputOpts -> BalancingOpts

-- | do extra correctness checks ?
[strict_] :: InputOpts -> Bool

-- | internal flag: postpone checks, because we are processing multiple
--   files ?
[_defer] :: InputOpts -> Bool

-- | today's date, for use with forecast transactions XXX this duplicates
--   _rsDay, and should eventually be removed when it's not needed anymore.
[_ioDay] :: InputOpts -> Day

-- | parse with the old timeclock pairing rules?
[_oldtimeclock] :: InputOpts -> Bool
class HasInputOpts c
inputOpts :: HasInputOpts c => Lens' c InputOpts
aliases :: HasInputOpts c => Lens' c [String]
anon__ :: HasInputOpts c => Lens' c Bool
auto__ :: HasInputOpts c => Lens' c Bool
auto_posting_tags :: HasInputOpts c => Lens' c Bool
balancingopts :: HasInputOpts c => Lens' c BalancingOpts
defer :: HasInputOpts c => Lens' c Bool
forecast :: HasInputOpts c => Lens' c (Maybe DateSpan)
infer_costs :: HasInputOpts c => Lens' c Bool
infer_equity :: HasInputOpts c => Lens' c Bool
ioDay :: HasInputOpts c => Lens' c Day
mformat :: HasInputOpts c => Lens' c (Maybe StorageFormat)
mrules_file :: HasInputOpts c => Lens' c (Maybe FilePath)
new__ :: HasInputOpts c => Lens' c Bool
new_save :: HasInputOpts c => Lens' c Bool
oldtimeclock :: HasInputOpts c => Lens' c Bool
pivot :: HasInputOpts c => Lens' c String
reportspan :: HasInputOpts c => Lens' c DateSpan
strict :: HasInputOpts c => Lens' c Bool
verbose_tags :: HasInputOpts c => Lens' c Bool
definputopts :: InputOpts

-- | Get the Maybe the DateSpan to generate forecast options from. This
--   begins on: - the start date supplied to the `--forecast` argument, if
--   present - otherwise, the later of - the report start date if specified
--   with -b-pdate: - the day after the latest normal (non-periodic)
--   transaction in the journal, if any - otherwise today. It ends on: -
--   the end date supplied to the `--forecast` argument, if present -
--   otherwise the report end date if specified with -e-pdate: -
--   otherwise 180 days (6 months) from today.
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
instance GHC.Classes.Eq Hledger.Read.InputOptions.InputOpts
instance Hledger.Data.Balancing.HasBalancingOpts Hledger.Read.InputOptions.InputOpts
instance Hledger.Read.InputOptions.HasInputOpts Hledger.Read.InputOptions.InputOpts
instance GHC.Classes.Ord Hledger.Read.InputOptions.InputOpts
instance GHC.Internal.Show.Show Hledger.Read.InputOptions.InputOpts

-- | Various additional validation checks that can be performed on a
--   Journal. Some are called as part of reading a file in strict mode,
--   others can be called only via the check command.
module Hledger.Data.JournalChecks

-- | Run the extra -s/--strict checks on a journal, in order of priority,
--   returning the first error message if any of them fail.
journalStrictChecks :: Journal -> Either String ()

-- | Check that all the journal's postings are to accounts with account
--   directives, returning an error message otherwise.
journalCheckAccounts :: Journal -> Either String ()

-- | Check all balance assertions in the journal and return an error
--   message if any of them fail. (Technically, this also tries to balance
--   the journal and can return balancing failure errors; ensure the
--   journal is already balanced (with journalBalanceTransactions) to avoid
--   this.)
journalCheckBalanceAssertions :: Journal -> Either String ()

-- | Check that all the commodities used in this journal's postings and P
--   directives have been declared by commodity directives, returning an
--   error message otherwise.
journalCheckCommodities :: Journal -> Either String ()

-- | Check that all the journal's transactions have payees declared with
--   payee directives, returning an error message otherwise.
journalCheckPayees :: Journal -> Either String ()

-- | In each tranaction, check that any conversion postings occur in
--   adjacent pairs.
journalCheckPairedConversionPostings :: Journal -> Either String ()

-- | Check that accounts with balance assertions have no posting more than
--   maxlag days after their latest balance assertion.
journalCheckRecentAssertions :: Journal -> Either String ()

-- | Check that all the journal's tags (on accounts, transactions,
--   postings..) have been declared with tag directives, returning an error
--   message otherwise.
journalCheckTags :: Journal -> Either String ()

-- | A 'BalanceData is a data type tracking a number of postings,
--   exclusive, and inclusive balance for given date ranges.
module Hledger.Data.BalanceData

-- | Apply an operation to both MixedAmount in an
--   BalanceData.
mapBalanceData :: (MixedAmount -> MixedAmount) -> BalanceData -> BalanceData

-- | Merge two BalanceData, using the given operation to combine
--   their amounts.
opBalanceData :: (MixedAmount -> MixedAmount -> MixedAmount) -> BalanceData -> BalanceData -> BalanceData
tests_BalanceData :: TestTree
instance GHC.Internal.Base.Monoid Hledger.Data.Types.BalanceData
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.BalanceData
instance GHC.Internal.Show.Show Hledger.Data.Types.BalanceData

-- | An Account has a name, a list of subaccounts, an optional
--   parent account, and subaccounting-excluding and -including balances.
module Hledger.Data.Account
nullacct :: Account BalanceData

-- | Construct an 'Account" from an account name and balances. Other fields
--   are left blank.
accountFromBalances :: AccountName -> PeriodData a -> Account a

-- | Derive 1. an account tree and 2. each account's total exclusive and
--   inclusive changes associated with dates from a list of postings and a
--   function for associating a date to each posting (usually representing
--   the start dates of report subperiods). This is the core of the balance
--   command (and of *ledger). The accounts are returned as a tree.
accountFromPostings :: (Posting -> Maybe Day) -> [Posting] -> Account BalanceData

-- | Derive 1. an account tree and 2. each account's total exclusive and
--   inclusive changes associated with dates from a list of postings and a
--   function for associating a date to each posting (usually representing
--   the start dates of report subperiods). This is the core of the balance
--   command (and of *ledger). The accounts are returned as a list in
--   flattened tree order, and also reference each other as a tree. (The
--   first account is the root of the tree.)
accountsFromPostings :: (Posting -> Maybe Day) -> [Posting] -> [Account BalanceData]

-- | Convert a list of account names to a tree of Account objects, with
--   just the account names filled in and an empty balance. A single root
--   account with the given name is added.
accountTree :: Monoid a => AccountName -> [AccountName] -> Account a

-- | Convert a list of account names to a tree of Account objects, with
--   just the account names filled in. Each account is given the same
--   supplied balance. A single root account with the given name is added.
accountTreeFromBalanceAndNames :: AccountName -> PeriodData a -> [AccountName] -> Account a
showAccounts :: Show a => Account a -> String
showAccountsBoringFlag :: Account a -> String
printAccounts :: Show a => Account a -> IO ()

-- | Search an account list by name.
lookupAccount :: AccountName -> [Account a] -> Maybe (Account a)

-- | Get this account's parent accounts, from the nearest up to the root.
parentAccounts :: Account a -> [Account a]

-- | List the accounts at each level of the account tree.
accountsLevels :: Account a -> [[Account a]]

-- | Map a (non-tree-structure-modifying) function over this and sub
--   accounts.
mapAccounts :: (Account a -> Account a) -> Account a -> Account a

-- | Apply a function to all PeriodData within this and sub
--   accounts.
mapPeriodData :: (PeriodData a -> PeriodData a) -> Account a -> Account a

-- | Is the predicate true on any of this account or its subaccounts ?
anyAccounts :: (Account a -> Bool) -> Account a -> Bool

-- | Filter an account tree (to a list).
filterAccounts :: (Account a -> Bool) -> Account a -> [Account a]

-- | Recalculate all the subaccount-inclusive balances in this tree.
sumAccounts :: Account BalanceData -> Account BalanceData

-- | Remove all subaccounts below a certain depth.
clipAccounts :: Int -> Account a -> Account a

-- | Remove subaccounts below the specified depth, aggregating their
--   balance at the depth limit (accounts at the depth limit will have any
--   sub-balances merged into their exclusive balance). If the depth is
--   Nothing, return the original accounts
clipAccountsAndAggregate :: Monoid a => DepthSpec -> [Account a] -> [Account a]

-- | Remove all leaf accounts and subtrees matching a predicate.
pruneAccounts :: (Account a -> Bool) -> Account a -> Maybe (Account a)

-- | Flatten an account tree into a list, which is sometimes convenient.
--   Note since accounts link to their parents/subs, the tree's structure
--   remains intact and can still be used. It's a tree/list!
flattenAccounts :: Account a -> [Account a]

-- | Merge two account trees and their subaccounts.
--   
--   This assumes that the top-level Accounts have the same name.
mergeAccounts :: Account a -> Account b -> Account (These a b)

-- | Add extra info for this account derived from the Journal's account
--   directives, if any (comment, tags, declaration order..).
accountSetDeclarationInfo :: Journal -> Account a -> Account a

-- | Sort account names by the order in which they were declared in the
--   journal, at each level of the account tree (ie within each group of
--   siblings). Undeclared accounts are sorted last and alphabetically.
--   This is hledger's default sort for reports organised by account. The
--   account list is converted to a tree temporarily, adding any missing
--   parents; these can be kept (suitable for a tree-mode report) or
--   removed (suitable for a flat-mode report).
sortAccountNamesByDeclaration :: Journal -> Bool -> [AccountName] -> [AccountName]

-- | Sort each group of siblings in an account tree by declaration order,
--   then account name. So each group will contain first the declared
--   accounts, in the same order as their account directives were parsed,
--   and then the undeclared accounts, sorted by account name.
sortAccountTreeByDeclaration :: Account a -> Account a

-- | Sort each group of siblings in an account tree by projecting through a
--   provided function.
sortAccountTreeOn :: Ord b => (Account a -> b) -> Account a -> Account a
tests_Account :: TestTree
instance GHC.Classes.Eq (Hledger.Data.Types.Account a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Hledger.Data.Account.FastTree a)
instance GHC.Classes.Ord a => GHC.Classes.Ord (Hledger.Data.Account.FastTree a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Types.Account a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Account.FastTree a)

-- | A Ledger is derived from a Journal by applying a filter
--   specification to select Transactions and Postings of
--   interest. It contains the filtered journal and knows the resulting
--   chart of accounts, account balances, and postings in each account.
module Hledger.Data.Ledger
nullledger :: Ledger

-- | Filter a journal's transactions with the given query, then build a
--   Ledger, containing the journal plus the tree of all its
--   accounts with their subaccount-inclusive and subaccount-exclusive
--   balances. If the query includes a depth limit, the ledger's journal
--   will be depth limited, but the ledger's account tree will not.
ledgerFromJournal :: Query -> Journal -> Ledger

-- | List a ledger's account names.
ledgerAccountNames :: Ledger -> [AccountName]

-- | Get the named account from a ledger.
ledgerAccount :: Ledger -> AccountName -> Maybe (Account BalanceData)

-- | Get this ledger's root account, which is a dummy "root" account above
--   all others. This should always be first in the account list, if
--   somehow not this returns a null account.
ledgerRootAccount :: Ledger -> Account BalanceData

-- | List a ledger's top-level accounts (the ones below the root), in tree
--   order.
ledgerTopAccounts :: Ledger -> [Account BalanceData]

-- | List a ledger's bottom-level (subaccount-less) accounts, in tree
--   order.
ledgerLeafAccounts :: Ledger -> [Account BalanceData]

-- | List a ledger's postings, in the order parsed.
ledgerPostings :: Ledger -> [Posting]

-- | The (fully specified) date span containing all the ledger's (filtered)
--   transactions, or DateSpan Nothing Nothing if there are none.
ledgerDateSpan :: Ledger -> DateSpan

-- | All commodities used in this ledger.
ledgerCommodities :: Ledger -> [CommoditySymbol]
tests_Ledger :: TestTree
instance GHC.Internal.Show.Show Hledger.Data.Types.Ledger

-- | The Hledger.Data library allows parsing and querying of C++
--   ledger-style journal files. It generally provides a compatible subset
--   of C++ ledger's functionality. This package re-exports all the
--   Hledger.Data.* modules (except UTF8, which requires an explicit
--   import.)
module Hledger.Data
data Side
L :: Side
R :: Side
type Tag = (TagName, TagValue)
data AccountType
Asset :: AccountType
Liability :: AccountType
Equity :: AccountType
Revenue :: AccountType
Expense :: AccountType

-- | a subtype of Asset - liquid assets to show in cashflow report
Cash :: AccountType

-- | a subtype of Equity - account with which to balance commodity
--   conversions
Conversion :: AccountType

-- | a subtype of Revenue - realised capital gains/losses
Gain :: AccountType

-- | a subtype of Equity - accumulated unrealised capital gains/losses
--   (used by hledger 2)
UnrealisedGain :: AccountType

-- | One of the standard *-separated value file types known by hledger,
data SepFormat
Csv :: SepFormat
Tsv :: SepFormat
Ssv :: SepFormat

-- | The status of a transaction or posting, recorded with a status mark
--   (nothing, !, or *). What these mean is ultimately user defined.
data Status
Unmarked :: Status
Pending :: Status
Cleared :: Status
data Period
DayPeriod :: Day -> Period
WeekPeriod :: Day -> Period
MonthPeriod :: Year -> Month -> Period
QuarterPeriod :: Year -> Quarter -> Period
YearPeriod :: Year -> Period
PeriodBetween :: Day -> Day -> Period
PeriodFrom :: Day -> Period
PeriodTo :: Day -> Period
PeriodAll :: Period
data SmartInterval
Day :: SmartInterval
Week :: SmartInterval
Month :: SmartInterval
Quarter :: SmartInterval
Year :: SmartInterval

-- | Year of Common Era (when positive).
type Year = Integer
type YearDay = Int
type Month = Int
type MonthDay = Int
data Interval
NoInterval :: Interval
Days :: Int -> Interval
Weeks :: Int -> Interval
Months :: Int -> Interval
Quarters :: Int -> Interval
Years :: Int -> Interval
NthWeekdayOfMonth :: Int -> Int -> Interval
MonthDay :: Int -> Interval
MonthAndDay :: Int -> Int -> Interval
DaysOfWeek :: [Int] -> Interval
type Quarter = Int

-- | An account within a hierarchy, with references to its parent and
--   subaccounts if any, and with per-report-period data of type
--   a. Only the name is required; the other fields may or may not
--   be present.
data Account a
Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account a] -> Maybe (Account a) -> Bool -> PeriodData a -> Account a

-- | full name
[aname] :: Account a -> AccountName

-- | optional extra info from account directives relationships in the tree
[adeclarationinfo] :: Account a -> Maybe AccountDeclarationInfo

-- | subaccounts
[asubs] :: Account a -> [Account a]

-- | parent account
[aparent] :: Account a -> Maybe (Account a)

-- | used in some reports to indicate elidable accounts
[aboring] :: Account a -> Bool

-- | associated data per report period
[adata] :: Account a -> PeriodData a
type AccountName = Text
data Amount
Amount :: !CommoditySymbol -> !Quantity -> !AmountStyle -> !Maybe AmountCost -> !Maybe CostBasis -> Amount
[acommodity] :: Amount -> !CommoditySymbol
[aquantity] :: Amount -> !Quantity
[astyle] :: Amount -> !AmountStyle

-- | transacted exchange rate - the unit or total cost, in another
--   commodity, used for this amount within its transaction
[acost] :: Amount -> !Maybe AmountCost

-- | the cost basis of an investment lot represented by this amount. Or, a
--   matcher to select such a lot from the available lots.
[acostbasis] :: Amount -> !Maybe CostBasis

-- | Data that's useful in "balance" reports: subaccount-exclusive and
--   -inclusive amounts, typically representing either a balance change or
--   an end balance; and a count of postings.
data BalanceData
BalanceData :: MixedAmount -> MixedAmount -> Int -> BalanceData

-- | balance data excluding subaccounts
[bdexcludingsubs] :: BalanceData -> MixedAmount

-- | balance data including subaccounts
[bdincludingsubs] :: BalanceData -> MixedAmount

-- | the number of postings
[bdnumpostings] :: BalanceData -> Int

-- | A journal, containing general ledger transactions; also directives and
--   various other things. This is hledger's main data model.
--   
--   During parsing, it is used as the type alias ParsedJournal. The
--   jparse* fields are mainly used during parsing and included here for
--   convenience. The list fields described as "in parse order" are usually
--   reversed for efficiency during parsing. After parsing,
--   "journalFinalise" converts ParsedJournal to a finalised
--   Journal, which has all lists correctly ordered, and much data
--   inference and validation applied.
data Journal
Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> POSIXTime -> Journal

-- | the current default year, specified by the most recent Y directive (or
--   current date)
[jparsedefaultyear] :: Journal -> Maybe Year

-- | the current default commodity and its format, specified by the most
--   recent D directive
[jparsedefaultcommodity] :: Journal -> Maybe (CommoditySymbol, AmountStyle)

-- | the character to always parse as decimal point, if set by CsvReader's
--   decimal-mark (or a future journal directive)
[jparsedecimalmark] :: Journal -> Maybe DecimalMark

-- | the current stack of parent account names, specified by apply account
--   directives
[jparseparentaccounts] :: Journal -> [AccountName]

-- | the current account name aliases in effect, specified by alias
--   directives (& options ?) ,jparsetransactioncount :: Integer -- ^
--   the current count of transactions parsed so far (only journal format
--   txns, currently)
[jparsealiases] :: Journal -> [AccountAlias]

-- | timeclock sessions which have not been clocked out
[jparsetimeclockentries] :: Journal -> [TimeclockEntry]

-- | (absolute path, canonical path) of included files, most recent first
--   principal data
[jincludefilestack] :: Journal -> [(FilePath, FilePath)]

-- | Payees declared by payee directives, in parse order.
[jdeclaredpayees] :: Journal -> [(Payee, PayeeDeclarationInfo)]

-- | Tags declared by tag directives, in parse order.
[jdeclaredtags] :: Journal -> [(TagName, TagDeclarationInfo)]

-- | Accounts declared by account directives, in parse order.
[jdeclaredaccounts] :: Journal -> [(AccountName, AccountDeclarationInfo)]

-- | Accounts which were declared with tags, and those tags.
[jdeclaredaccounttags] :: Journal -> Map AccountName [Tag]

-- | Accounts which were declared with a type: tag, grouped by the type.
[jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName]

-- | All the account types known, from account declarations or account
--   names or parent accounts.
[jaccounttypes] :: Journal -> Map AccountName AccountType

-- | Commodities (and their display styles) declared by commodity
--   directives, in parse order.
[jdeclaredcommodities] :: Journal -> Map CommoditySymbol Commodity

-- | Commodities which were declared with tags, and those tags.
[jdeclaredcommoditytags] :: Journal -> Map CommoditySymbol [Tag]

-- | Commodity display styles inferred from amounts in the journal.
[jinferredcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | Commodity display styles declared by command line options (sometimes
--   augmented, see the import command).
[jglobalcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | P (market price) directives in the journal, in parse order.
[jpricedirectives] :: Journal -> [PriceDirective]

-- | Market prices inferred from transactions in the journal, in parse
--   order.
[jinferredmarketprices] :: Journal -> [MarketPrice]

-- | Auto posting rules declared in the journal.
[jtxnmodifiers] :: Journal -> [TransactionModifier]

-- | Periodic transaction rules declared in the journal.
[jperiodictxns] :: Journal -> [PeriodicTransaction]

-- | Transactions recorded in the journal. The important bit.
[jtxns] :: Journal -> [Transaction]

-- | any final trailing comments in the (main) journal file
[jfinalcommentlines] :: Journal -> Text

-- | the file path and raw text of the main and any included journal files.
--   The main file is first, followed by any included files in the order
--   encountered. TODO: FilePath is a sloppy type here, don't assume it's a
--   real file; values like "" or "-" can be seen
[jfiles] :: Journal -> [(FilePath, Text)]

-- | when this journal was last read from its file(s) NOTE: after adding
--   new fields, eg involving account names, consider updating the Anon
--   instance in Hleger.Cli.Anon
[jlastreadtime] :: Journal -> POSIXTime

-- | A Ledger has the journal it derives from, and the accounts derived
--   from that. Accounts are accessible both list-wise and tree-wise, since
--   each one knows its parent and subs; the first account is the root of
--   the tree and always exists.
data Ledger
Ledger :: Journal -> [Account BalanceData] -> Ledger
[ljournal] :: Ledger -> Journal
[laccounts] :: Ledger -> [Account BalanceData]

-- | A general container for storing data values associated with zero or
--   more contiguous report (sub)periods, and with the (open ended)
--   pre-report period. The report periods are typically all the same
--   length, but need not be.
--   
--   Report periods are represented only by their start dates, used as the
--   keys of a Map.
data PeriodData a
PeriodData :: a -> Map Day a -> PeriodData a

-- | data for the period before the report
[pdpre] :: PeriodData a -> a

-- | data for each period within the report
[pdperiods] :: PeriodData a -> Map Day a

-- | A periodic transaction rule, describing a transaction that recurs.
data PeriodicTransaction
PeriodicTransaction :: Text -> Interval -> DateSpan -> (SourcePos, SourcePos) -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> PeriodicTransaction

-- | the period expression as written
[ptperiodexpr] :: PeriodicTransaction -> Text

-- | the interval at which this transaction recurs
[ptinterval] :: PeriodicTransaction -> Interval

-- | the (possibly unbounded) period during which this transaction recurs.
--   Contains a whole number of intervals.
[ptspan] :: PeriodicTransaction -> DateSpan

-- | the file position where the period expression starts, and where the
--   last posting ends
[ptsourcepos] :: PeriodicTransaction -> (SourcePos, SourcePos)

-- | some of Transaction's fields
[ptstatus] :: PeriodicTransaction -> Status
[ptcode] :: PeriodicTransaction -> Text
[ptdescription] :: PeriodicTransaction -> Text
[ptcomment] :: PeriodicTransaction -> Text
[pttags] :: PeriodicTransaction -> [Tag]
[ptpostings] :: PeriodicTransaction -> [Posting]
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting

-- | this posting's date, if different from the transaction's
[pdate] :: Posting -> Maybe Day

-- | this posting's secondary date, if different from the transaction's
[pdate2] :: Posting -> Maybe Day
[pstatus] :: Posting -> Status
[paccount] :: Posting -> AccountName
[pamount] :: Posting -> MixedAmount

-- | this posting's comment lines, as a single non-indented multi-line
--   string
[pcomment] :: Posting -> Text
[ptype] :: Posting -> PostingType

-- | tag names and values, extracted from the posting comment and (after
--   finalisation) the posting account's directive if any
[ptags] :: Posting -> [Tag]

-- | an expected balance in the account after this posting, in a single
--   commodity, excluding subaccounts.
[pbalanceassertion] :: Posting -> Maybe BalanceAssertion

-- | this posting's parent transaction (co-recursive types). Tying this
--   knot gets tedious, Maybe makes it easier/optional.
[ptransaction] :: Posting -> Maybe Transaction

-- | When this posting has been transformed in some way (eg its amount or
--   cost was inferred, or the account name was changed by a pivot or
--   budget report), this references the original untransformed posting
--   (which will have Nothing in this field).
[poriginal] :: Posting -> Maybe Posting

-- | The id of a data format understood by hledger, eg journal or
--   csv. The --output-format option selects one of these for
--   output.
data StorageFormat
Rules :: StorageFormat
Journal' :: StorageFormat
Ledger' :: StorageFormat
Timeclock :: StorageFormat
Timedot :: StorageFormat
Sep :: SepFormat -> StorageFormat
data Transaction
Transaction :: Integer -> Text -> (SourcePos, SourcePos) -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Transaction

-- | this transaction's 1-based position in the transaction stream, or 0
--   when not available
[tindex] :: Transaction -> Integer

-- | any comment lines immediately preceding this transaction
[tprecedingcomment] :: Transaction -> Text

-- | the file position where the date starts, and where the last posting
--   ends
[tsourcepos] :: Transaction -> (SourcePos, SourcePos)
[tdate] :: Transaction -> Day
[tdate2] :: Transaction -> Maybe Day
[tstatus] :: Transaction -> Status
[tcode] :: Transaction -> Text
[tdescription] :: Transaction -> Text

-- | this transaction's comment lines, as a single non-indented multi-line
--   string
[tcomment] :: Transaction -> Text

-- | tag names and values, extracted from the comment
[ttags] :: Transaction -> [Tag]

-- | this transaction's postings
[tpostings] :: Transaction -> [Posting]

-- | A transaction modifier rule. This has a query which matches postings
--   in the journal, and a list of transformations to apply to those
--   postings or their transactions. Currently there is one kind of
--   transformation: the TMPostingRule, which adds a posting ("auto
--   posting") to the transaction, optionally setting its amount to the
--   matched posting's amount multiplied by a constant.
data TransactionModifier
TransactionModifier :: Text -> [TMPostingRule] -> TransactionModifier
[tmquerytxt] :: TransactionModifier -> Text
[tmpostingrules] :: TransactionModifier -> [TMPostingRule]
fromEFDay :: EFDay -> Day
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
type CommoditySymbol = Text

-- | The "display precision" for a hledger amount, by which we mean the
--   number of decimal digits to display to the right of the decimal mark.
data AmountPrecision

-- | show this many decimal digits (0..255)
Precision :: !Word8 -> AmountPrecision

-- | show all significant decimal digits stored internally
NaturalPrecision :: AmountPrecision

-- | Display styles for amounts - things which can be detected during
--   parsing, such as commodity side and spacing, digit group marks,
--   decimal mark, number of decimal digits etc. Every Amount has an
--   AmountStyle. After amounts are parsed from the input, for each
--   Commodity a standard style is inferred and then used when
--   displaying amounts in that commodity. Related to AmountFormat
--   but higher level.
--   
--   See also: - hledger manual > Commodity styles - hledger manual >
--   Amounts - hledger manual > Commodity display style
data AmountStyle
AmountStyle :: !Side -> !Bool -> !Maybe DigitGroupStyle -> !Maybe Char -> !AmountPrecision -> !Rounding -> AmountStyle

-- | show the symbol on the left or the right ?
[ascommodityside] :: AmountStyle -> !Side

-- | show a space between symbol and quantity ?
[ascommodityspaced] :: AmountStyle -> !Bool

-- | show the integer part with these digit group marks, or not
[asdigitgroups] :: AmountStyle -> !Maybe DigitGroupStyle

-- | show this character (should be . or ,) as decimal mark, or use the
--   default (.)
[asdecimalmark] :: AmountStyle -> !Maybe Char

-- | "display precision" - show this number of digits after the decimal
--   point
[asprecision] :: AmountStyle -> !AmountPrecision

-- | "rounding strategy" - kept here for convenience, for now: when
--   displaying an amount, it is ignored, but when applying this style to
--   another amount, it determines how hard we should try to adjust that
--   amount's display precision.
[asrounding] :: AmountStyle -> !Rounding
data MixedAmount

-- | A date which is either exact or flexible. Flexible dates are allowed
--   to be adjusted in certain situations.
data EFDay
Exact :: Day -> EFDay
Flex :: Day -> EFDay
type YearWeek = Int
type MonthWeek = Int
type WeekDay = Int

-- | A possibly incomplete year-month-day date provided by the user, to be
--   interpreted as either a date or a date span depending on context.
--   Missing parts "on the left" will be filled from the provided reference
--   date, e.g. if the year and month are missing, the reference date's
--   year and month are used. Missing parts "on the right" are assumed,
--   when interpreting as a date, to be 1, (e.g. if the year and month are
--   present but the day is missing, it means first day of that month); or
--   when interpreting as a date span, to be a wildcard (so it would mean
--   all days of that month). See the smartdate parser for more
--   examples.
--   
--   Or, one of the standard periods and a numeric offset relative to the
--   reference date: (last|this|next) (day|week|month|quarter|year), where
--   "this" means the period containing the reference date.
--   
--   Or, (last|this|next) weekdayname, where "this" "next".
--   
--   Or, (last|this|next) monthname, where "this" means the previous 1st if
--   in that month, otherwise the start of the next occurrence of that
--   month.
data SmartDate
SmartCompleteDate :: Day -> SmartDate
SmartAssumeStart :: Year -> Maybe Month -> SmartDate
SmartFromReference :: Maybe Month -> MonthDay -> SmartDate
SmartMonth :: Month -> SmartDate
SmartRelative :: Integer -> SmartInterval -> SmartDate

-- | EQ will be treated like GT
SmartRelativeMonth :: Ordering -> Month -> SmartDate
SmartRelativeWeekDay :: Ordering -> WeekDay -> SmartDate
data WhichDate
PrimaryDate :: WhichDate
SecondaryDate :: WhichDate

-- | A possibly open-ended span of time, from an optional inclusive start
--   date to an optional exclusive end date. Each date can be either exact
--   or flexible. An "exact date span" is a Datepan with exact start and
--   end dates.
data DateSpan
DateSpan :: Maybe EFDay -> Maybe EFDay -> DateSpan
type Payee = Text
data DepthSpec
DepthSpec :: Maybe Int -> [(Regexp, Int)] -> DepthSpec
[dsFlatDepth] :: DepthSpec -> Maybe Int
[dsRegexpDepths] :: DepthSpec -> [(Regexp, Int)]
isBalanceSheetAccountType :: AccountType -> Bool
isIncomeStatementAccountType :: AccountType -> Bool

-- | Check whether the first argument is a subtype of the second: either
--   equal or one of the defined subtypes.
isAccountSubtypeOf :: AccountType -> AccountType -> Bool
data AccountAlias
BasicAlias :: AccountName -> AccountName -> AccountAlias
RegexAlias :: Regexp -> Replacement -> AccountAlias

-- | One of the decimal marks we support: either period or comma.
type DecimalMark = Char
isDecimalMark :: Char -> Bool

-- | The basic numeric type used in amounts.
type Quantity = Decimal

-- | An amount's per-unit or total cost/selling price in another commodity,
--   as recorded in the journal entry eg with  or @. Cost,
--   formerly AKA "transaction price". The amount is always positive.
data AmountCost
UnitCost :: !Amount -> AmountCost
TotalCost :: !Amount -> AmountCost

-- | A style for displaying digit groups in the integer part of a floating
--   point number. It consists of the character used to separate groups
--   (comma or period, whichever is not used as decimal point), and the
--   size of each group, starting with the one nearest the decimal point.
--   The last group size is assumed to repeat. Eg, comma between thousands
--   is DigitGroups ',' [3].
data DigitGroupStyle
DigitGroups :: !Char -> ![Word8] -> DigitGroupStyle

-- | "Rounding strategy" - how to apply an AmountStyle's display precision
--   to a posting amount (and its cost, if any). Mainly used to customise
--   print's output, with --round=none|soft|hard|all.
data Rounding

-- | keep display precisions unchanged in amt and cost
NoRounding :: Rounding

-- | do soft rounding of amt and cost amounts (show more or fewer decimal
--   zeros to approximate the target precision, but don't hide significant
--   digits)
SoftRounding :: Rounding

-- | do hard rounding of amt (use the exact target precision, possibly
--   hiding significant digits), and soft rounding of cost
HardRounding :: Rounding

-- | do hard rounding of amt and cost
AllRounding :: Rounding
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle

-- | any comment lines following the commodity directive
[ccomment] :: Commodity -> Text

-- | tags extracted from the comment, if any
[ctags] :: Commodity -> [Tag]

-- | The cost basis of an individual lot - some quantity of an asset
--   acquired at a given date and time. This can represent a definite cost
--   basis, which must have a cost and date; the label is optional. Or it
--   can represent a cost basis matcher for selecting lots. Note: cost is
--   always stored as a per-unit cost, even if the user specified total
--   cost with {{}}.
data CostBasis
CostBasis :: !Maybe Amount -> !Maybe Day -> !Maybe Text -> CostBasis

-- | nominal acquisition cost (per-unit)
[cbCost] :: CostBasis -> !Maybe Amount

-- | nominal acquisition date
[cbDate] :: CostBasis -> !Maybe Day

-- | a short label to ensure uniqueness, correct intra-day order, or
--   memorability, if needed
[cbLabel] :: CostBasis -> !Maybe Text

-- | Types with this class have one or more amounts, which can have display
--   styles applied to them.
class HasAmounts a
styleAmounts :: HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a

-- | Compare two MixedAmounts, substituting 0 for the quantity of any
--   missing commodities in either.
maCompare :: MixedAmount -> MixedAmount -> Ordering
pattern MixedAmountKeyNoCost :: () => !CommoditySymbol -> MixedAmountKey
pattern MixedAmountKeyTotalCost :: () => !CommoditySymbol -> !CommoditySymbol -> MixedAmountKey
pattern MixedAmountKeyUnitCost :: () => !CommoditySymbol -> !CommoditySymbol -> !Quantity -> MixedAmountKey
data PostingType
RegularPosting :: PostingType
VirtualPosting :: PostingType
BalancedVirtualPosting :: PostingType
type TagName = Text
type TagValue = Text
type HiddenTag = Tag
type DateTag = (TagName, Day)

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTag :: Tag -> HiddenTag

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTagName :: TagName -> TagName

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTag :: HiddenTag -> Tag

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTagName :: TagName -> TagName

-- | Does this tag name begin with the hidden tag prefix (_) ?
isHiddenTagName :: TagName -> Bool
nullsourcepos :: SourcePos
nullsourcepospair :: (SourcePos, SourcePos)

-- | A balance assertion is a declaration about an account's expected
--   balance at a certain point (posting date and parse order). They
--   provide additional error checking and readability to a journal file.
--   
--   A balance assignments is an instruction to hledger to adjust an
--   account's balance to a certain amount at a certain point.
--   
--   The BalanceAssertion type is used for representing both of
--   these.
--   
--   hledger supports multiple kinds of balance assertions/assignments,
--   which differ in whether they refer to a single commodity or all
--   commodities, and the (subaccount-)inclusive or exclusive account
--   balance.
data BalanceAssertion
BalanceAssertion :: Amount -> Bool -> Bool -> SourcePos -> BalanceAssertion

-- | the expected balance in a particular commodity
[baamount] :: BalanceAssertion -> Amount

-- | disallow additional non-asserted commodities ?
[batotal] :: BalanceAssertion -> Bool

-- | include subaccounts when calculating the actual balance ?
[bainclusive] :: BalanceAssertion -> Bool

-- | the assertion's file position, for error reporting
[baposition] :: BalanceAssertion -> SourcePos

-- | A transaction modifier transformation, which adds an extra posting to
--   the matched posting's transaction. Can be like a regular posting, or
--   can have the tmprIsMultiplier flag set, indicating that it's a
--   multiplier for the matched posting's amount.
data TMPostingRule
TMPostingRule :: Posting -> Bool -> TMPostingRule
[tmprPosting] :: TMPostingRule -> Posting
[tmprIsMultiplier] :: TMPostingRule -> Bool
nulltransactionmodifier :: TransactionModifier
nullperiodictransaction :: PeriodicTransaction
data TimeclockCode
SetBalance :: TimeclockCode
SetRequiredHours :: TimeclockCode
In :: TimeclockCode
Out :: TimeclockCode
FinalOut :: TimeclockCode
data TimeclockEntry
TimeclockEntry :: SourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> Text -> [Tag] -> TimeclockEntry
[tlsourcepos] :: TimeclockEntry -> SourcePos
[tlcode] :: TimeclockEntry -> TimeclockCode
[tldatetime] :: TimeclockEntry -> LocalTime
[tlaccount] :: TimeclockEntry -> AccountName
[tldescription] :: TimeclockEntry -> Text
[tlcomment] :: TimeclockEntry -> Text
[tltags] :: TimeclockEntry -> [Tag]

-- | A market price declaration made by the journal format's P directive.
--   It declares two things: a historical exchange rate between two
--   commodities, and an amount display style for the second commodity.
data PriceDirective
PriceDirective :: SourcePos -> Day -> CommoditySymbol -> Amount -> PriceDirective
[pdsourcepos] :: PriceDirective -> SourcePos
[pddate] :: PriceDirective -> Day
[pdcommodity] :: PriceDirective -> CommoditySymbol
[pdamount] :: PriceDirective -> Amount

-- | A historical market price (exchange rate) from one commodity to
--   another. A more concise form of a PriceDirective, without the amount
--   display info.
data MarketPrice
MarketPrice :: Day -> CommoditySymbol -> CommoditySymbol -> Quantity -> MarketPrice

-- | Date on which this price becomes effective.
[mpdate] :: MarketPrice -> Day

-- | The commodity being converted from.
[mpfrom] :: MarketPrice -> CommoditySymbol

-- | The commodity being converted to.
[mpto] :: MarketPrice -> CommoditySymbol

-- | One unit of the "from" commodity is worth this quantity of the "to"
--   commodity.
[mprate] :: MarketPrice -> Quantity
showMarketPrice :: MarketPrice -> String
showMarketPrices :: [MarketPrice] -> [Char]

-- | Extra information found in a payee directive.
data PayeeDeclarationInfo
PayeeDeclarationInfo :: Text -> [Tag] -> PayeeDeclarationInfo

-- | any comment lines following the payee directive
[pdicomment] :: PayeeDeclarationInfo -> Text

-- | tags extracted from the comment, if any
[pditags] :: PayeeDeclarationInfo -> [Tag]

-- | Extra information found in a tag directive.
newtype TagDeclarationInfo
TagDeclarationInfo :: Text -> TagDeclarationInfo

-- | any comment lines following the tag directive. No tags allowed here.
[tdicomment] :: TagDeclarationInfo -> Text

-- | Extra information about an account that can be derived from its
--   account directive (and the other account directives).
data AccountDeclarationInfo
AccountDeclarationInfo :: Text -> [Tag] -> Int -> SourcePos -> AccountDeclarationInfo

-- | any comment lines following an account directive for this account
[adicomment] :: AccountDeclarationInfo -> Text

-- | tags extracted from the account comment, if any
[aditags] :: AccountDeclarationInfo -> [Tag]

-- | the order in which this account was declared, relative to other
--   account declarations, during parsing (1..)
[adideclarationorder] :: AccountDeclarationInfo -> Int

-- | source file and position
[adisourcepos] :: AccountDeclarationInfo -> SourcePos

-- | A journal in the process of being parsed, not yet finalised. The data
--   is partial, and list fields are in reverse order.
type ParsedJournal = Journal
nullpayeedeclarationinfo :: PayeeDeclarationInfo
nulltagdeclarationinfo :: TagDeclarationInfo
nullaccountdeclarationinfo :: AccountDeclarationInfo

-- | Whether an account's balance is normally a positive number (in
--   accounting terms, a debit balance) or a negative number (credit
--   balance). Assets and expenses are normally positive (debit), while
--   liabilities, equity and income are normally negative (credit).
--   https://en.wikipedia.org/wiki/Normal_balance
data NormalSign
NormallyPositive :: NormalSign
NormallyNegative :: NormalSign
tests_Data :: TestTree

-- | Options common to most hledger reports.
module Hledger.Reports.ReportOptions

-- | Standard options for customising report filtering and output. Most of
--   these correspond to standard hledger command-line options or query
--   arguments, but not all. Some are used only by certain commands, as
--   noted below.
data ReportOpts
ReportOpts :: Period -> Interval -> [Status] -> Maybe ConversionOp -> Maybe ValuationType -> Bool -> DepthSpec -> Bool -> Bool -> Bool -> Bool -> StringFormat -> Maybe Text -> Bool -> [Text] -> Bool -> Bool -> SortSpec -> Bool -> BalanceCalculation -> BalanceAccumulation -> Maybe Text -> AccountListMode -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe NormalSign -> Bool -> Bool -> Layout -> ReportOpts
[period_] :: ReportOpts -> Period
[interval_] :: ReportOpts -> Interval

-- | Zero, one, or two statuses to be matched
[statuses_] :: ReportOpts -> [Status]

-- | Which operation should we apply to conversion transactions?
[conversionop_] :: ReportOpts -> Maybe ConversionOp

-- | What value should amounts be converted to ?
[value_] :: ReportOpts -> Maybe ValuationType

-- | Infer market prices from transactions ?
[infer_prices_] :: ReportOpts -> Bool
[depth_] :: ReportOpts -> DepthSpec
[date2_] :: ReportOpts -> Bool
[empty_] :: ReportOpts -> Bool
[no_elide_] :: ReportOpts -> Bool
[real_] :: ReportOpts -> Bool
[format_] :: ReportOpts -> StringFormat
[balance_base_url_] :: ReportOpts -> Maybe Text
[pretty_] :: ReportOpts -> Bool
[querystring_] :: ReportOpts -> [Text]
[average_] :: ReportOpts -> Bool
[related_] :: ReportOpts -> Bool
[sortspec_] :: ReportOpts -> SortSpec
[txn_dates_] :: ReportOpts -> Bool

-- | What to calculate in balance report cells
[balancecalc_] :: ReportOpts -> BalanceCalculation

-- | How to accumulate balance report values over time
[balanceaccum_] :: ReportOpts -> BalanceAccumulation

-- | A case-insensitive description substring to select periodic
--   transactions for budget reports. (Not a regexp, nor a full hledger
--   query, for now.)
[budgetpat_] :: ReportOpts -> Maybe Text
[accountlistmode_] :: ReportOpts -> AccountListMode
[drop_] :: ReportOpts -> Int

-- | Include accounts declared but not yet posted to ?
[declared_] :: ReportOpts -> Bool
[row_total_] :: ReportOpts -> Bool
[no_total_] :: ReportOpts -> Bool
[summary_only_] :: ReportOpts -> Bool

-- | Show costs for reports which normally don't show them ?
[show_costs_] :: ReportOpts -> Bool
[sort_amount_] :: ReportOpts -> Bool
[percent_] :: ReportOpts -> Bool

-- | Flip all amount signs in reports ?
[invert_] :: ReportOpts -> Bool

-- | This can be set when running balance reports on a set of accounts with
--   the same normal balance type (eg all assets, or all incomes). - It
--   helps --sort-amount know how to sort negative numbers (eg in the
--   income section of an income statement) - It helps compound balance
--   report commands (is, bs etc.) do sign normalisation, converting
--   normally negative subreports to normally positive for a more
--   conventional display.
[normalbalance_] :: ReportOpts -> Maybe NormalSign

-- | Whether to use ANSI color codes in text output. Influenced by the
--   --color/colour flag (cf CliOptions), whether stdout is an interactive
--   terminal, and the value of TERM and existence of NO_COLOR environment
--   variables.
[color_] :: ReportOpts -> Bool
[transpose_] :: ReportOpts -> Bool
[layout_] :: ReportOpts -> Layout

-- | Lenses for ReportOpts.
class HasReportOptsNoUpdate c
reportOptsNoUpdate :: HasReportOptsNoUpdate c => Lens' c ReportOpts
accountlistmode :: HasReportOptsNoUpdate c => Lens' c AccountListMode
average :: HasReportOptsNoUpdate c => Lens' c Bool
balance_base_url :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
balanceaccum :: HasReportOptsNoUpdate c => Lens' c BalanceAccumulation
balancecalc :: HasReportOptsNoUpdate c => Lens' c BalanceCalculation
budgetpat :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
color__ :: HasReportOptsNoUpdate c => Lens' c Bool
conversionop :: HasReportOptsNoUpdate c => Lens' c (Maybe ConversionOp)
date2NoUpdate :: HasReportOptsNoUpdate c => Lens' c Bool
declared :: HasReportOptsNoUpdate c => Lens' c Bool
depthNoUpdate :: HasReportOptsNoUpdate c => Lens' c DepthSpec
drop__ :: HasReportOptsNoUpdate c => Lens' c Int
empty__ :: HasReportOptsNoUpdate c => Lens' c Bool
format :: HasReportOptsNoUpdate c => Lens' c StringFormat
infer_prices :: HasReportOptsNoUpdate c => Lens' c Bool
interval :: HasReportOptsNoUpdate c => Lens' c Interval
invert :: HasReportOptsNoUpdate c => Lens' c Bool
layout :: HasReportOptsNoUpdate c => Lens' c Layout
no_elide :: HasReportOptsNoUpdate c => Lens' c Bool
no_total :: HasReportOptsNoUpdate c => Lens' c Bool
normalbalance :: HasReportOptsNoUpdate c => Lens' c (Maybe NormalSign)
percent :: HasReportOptsNoUpdate c => Lens' c Bool
periodNoUpdate :: HasReportOptsNoUpdate c => Lens' c Period
pretty :: HasReportOptsNoUpdate c => Lens' c Bool
querystringNoUpdate :: HasReportOptsNoUpdate c => Lens' c [Text]
realNoUpdate :: HasReportOptsNoUpdate c => Lens' c Bool
related :: HasReportOptsNoUpdate c => Lens' c Bool
row_total :: HasReportOptsNoUpdate c => Lens' c Bool
show_costs :: HasReportOptsNoUpdate c => Lens' c Bool
sort_amount :: HasReportOptsNoUpdate c => Lens' c Bool
sortspec :: HasReportOptsNoUpdate c => Lens' c SortSpec
statusesNoUpdate :: HasReportOptsNoUpdate c => Lens' c [Status]
summary_only :: HasReportOptsNoUpdate c => Lens' c Bool
transpose__ :: HasReportOptsNoUpdate c => Lens' c Bool
txn_dates :: HasReportOptsNoUpdate c => Lens' c Bool
value :: HasReportOptsNoUpdate c => Lens' c (Maybe ValuationType)

-- | Special lenses for ReportOpts which also update the Query and
--   QueryOpts in ReportSpec. Note that these are not true lenses, as they
--   have a further restriction on the functor. This will work as a normal
--   lens for all common uses, but since they don't obey the lens laws for
--   some fancy cases, they may fail in some exotic circumstances.
--   
--   Note that setEither/overEither should only be necessary with
--   querystring and reportOpts: the other lenses should never fail.
--   
--   
Examples:
--   
--   
--   >>> import Lens.Micro (set)
--   
--   >>> _rsQuery <$> setEither querystring ["assets"] defreportspec
--   Right (Acct (RegexpCI "assets"))
--   
--   >>> _rsQuery <$> setEither querystring ["(assets"] defreportspec
--   Left "This regular expression is invalid or unsupported, please correct it:\n(assets"
--   
--   >>> _rsQuery $ set querystring ["assets"] defreportspec
--   Acct (RegexpCI "assets")
--   
--   >>> _rsQuery $ set period (MonthPeriod 2021 08) defreportspec
--   Date DateSpan 2021-08
--   
--   
--   XXX testing error output isn't working since adding color to it: >
--   import System.Environment > setEnv NO_COLOR "1" >>
--   return (_rsQuery $ set querystring ["(assets"] defreportspec) ***
--   Exception: Error: Updating ReportSpec failed: try using overEither
--   instead of over or setEither instead of set
class HasReportOptsNoUpdate a => HasReportOpts a
reportOpts :: HasReportOpts a => ReportableLens' a ReportOpts
period :: HasReportOpts a => ReportableLens' a Period
statuses :: HasReportOpts a => ReportableLens' a [Status]
depth :: HasReportOpts a => ReportableLens' a DepthSpec
date2 :: HasReportOpts a => ReportableLens' a Bool
real :: HasReportOpts a => ReportableLens' a Bool
querystring :: HasReportOpts a => ReportableLens' a [Text]

-- | A fully-determined set of report parameters (report options with all
--   partial values made total, eg the begin and end dates are known,
--   avoiding date/regex errors; plus the reporting date), and the query
--   successfully calculated from them.
--   
--   If you change the report options or date in one of these, you should
--   use reportOptsToSpec to regenerate the whole thing, avoiding
--   inconsistency.
data ReportSpec
ReportSpec :: ReportOpts -> Day -> Query -> [QueryOpt] -> ReportSpec

-- | The underlying ReportOpts used to generate this ReportSpec
[_rsReportOpts] :: ReportSpec -> ReportOpts

-- | The Day this ReportSpec is generated for
[_rsDay] :: ReportSpec -> Day

-- | The generated Query for the given day
[_rsQuery] :: ReportSpec -> Query

-- | A list of QueryOpts for the given day
[_rsQueryOpts] :: ReportSpec -> [QueryOpt]
class HasReportSpec c
reportSpec :: HasReportSpec c => Lens' c ReportSpec
rsDay :: HasReportSpec c => Lens' c Day
rsQuery :: HasReportSpec c => Lens' c Query
rsQueryOpts :: HasReportSpec c => Lens' c [QueryOpt]
rsReportOpts :: HasReportSpec c => Lens' c ReportOpts
data SortField
AbsAmount' :: Bool -> SortField
Account' :: Bool -> SortField
Amount' :: Bool -> SortField
Date' :: Bool -> SortField
Description' :: Bool -> SortField
type SortSpec = [SortField]
sortKeysDescription :: [Char]

-- | Apply a function over a lens, but report on failure.
overEither :: ((a -> Either e b) -> s -> Either e t) -> (a -> b) -> s -> Either e t

-- | Set a field using a lens, but report on failure.
setEither :: ((a -> Either e b) -> s -> Either e t) -> b -> s -> Either e t

-- | What to calculate for each cell in a balance report. "Balance report
--   types -> Calculation type" in the hledger manual.
data BalanceCalculation

-- | Sum of posting amounts in the period.
CalcChange :: BalanceCalculation

-- | Sum of posting amounts and the goal for the period.
CalcBudget :: BalanceCalculation

-- | Change from previous period's historical end value to this period's
--   historical end value.
CalcValueChange :: BalanceCalculation

-- | Change from previous period's gain, i.e. valuation minus cost basis.
CalcGain :: BalanceCalculation

-- | Number of postings in the period.
CalcPostingsCount :: BalanceCalculation

-- | How to accumulate calculated values across periods (columns) in a
--   balance report. "Balance report types -> Accumulation type" in the
--   hledger manual.
data BalanceAccumulation

-- | No accumulation. Eg, shows the change of balance in each period.
PerPeriod :: BalanceAccumulation

-- | Accumulate changes across periods, starting from zero at report start.
Cumulative :: BalanceAccumulation

-- | Accumulate changes across periods, including any from before report
--   start. Eg, shows the historical end balance of each period.
Historical :: BalanceAccumulation

-- | Should accounts be displayed: in the command's default style,
--   hierarchically, or as a flat list ?
data AccountListMode
ALFlat :: AccountListMode
ALTree :: AccountListMode

-- | What kind of value conversion should be done on amounts ? CLI:
--   --value=then|end|now|DATE[,COMM]
data ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at each posting's date
AtThen :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at period end(s)
AtEnd :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using current market
--   prices
AtNow :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   on some date
AtDate :: Day -> Maybe CommoditySymbol -> ValuationType
data Layout
LayoutWide :: Maybe Int -> Layout
LayoutTall :: Layout
LayoutBare :: Layout
LayoutTidy :: Layout
defreportopts :: ReportOpts

-- | Generate a ReportOpts from raw command-line input, given a day and
--   whether to use ANSI colour/styles in standard output. This will fail
--   with a usage error if it is passed - an invalid --format argument, -
--   an invalid --value argument, - if --valuechange is called with a
--   valuation type other than -V/--value=end. - an invalid --pretty
--   argument,
rawOptsToReportOpts :: Day -> Bool -> RawOpts -> ReportOpts
defreportspec :: ReportSpec
defsortspec :: SortSpec

-- | Set the default ConversionOp.
setDefaultConversionOp :: ConversionOp -> ReportSpec -> ReportSpec

-- | Generate a ReportSpec from a set of ReportOpts on a given day.
reportOptsToSpec :: Day -> ReportOpts -> Either String ReportSpec

-- | Update the ReportOpts and the fields derived from it in a ReportSpec,
--   or return an error message if there is a problem such as missing or
--   unparseable options data. This is the safe way to change a ReportSpec,
--   ensuring that all fields (_rsQuery, _rsReportOpts, querystring_, etc.)
--   are in sync.
updateReportSpec :: ReportOpts -> ReportSpec -> Either String ReportSpec

-- | Like updateReportSpec, but takes a ReportOpts-modifying function.
updateReportSpecWith :: (ReportOpts -> ReportOpts) -> ReportSpec -> Either String ReportSpec

-- | Generate a ReportSpec from RawOpts and a provided day, or return an
--   error string if there are regular expression errors.
rawOptsToReportSpec :: Day -> Bool -> RawOpts -> Either String ReportSpec
balanceAccumulationOverride :: RawOpts -> Maybe BalanceAccumulation
flat_ :: ReportOpts -> Bool

-- | Legacy-compatible convenience aliases for accountlistmode_.
tree_ :: ReportOpts -> Bool

-- | Add/remove this status from the status list. Used by hledger-ui.
reportOptsToggleStatus :: Status -> ReportOpts -> ReportOpts

-- | Reduce a list of statuses to just one of each status, and if all
--   statuses are present return the empty list.
simplifyStatuses :: Ord a => [a] -> [a]

-- | Report which date we will report on based on --date2.
whichDate :: ReportOpts -> WhichDate

-- | Convert a Journal's amounts to cost and/or to value (see
--   journalApplyValuationFromOpts), and filter by the
--   ReportSpec Query.
--   
--   We make sure to first filter by amt: and cur: terms, then value the
--   Journal, then filter by the remaining terms.
journalValueAndFilterPostings :: ReportSpec -> Journal -> Journal

-- | Like journalValueAndFilterPostings, but takes a
--   PriceOracle as an argument.
journalValueAndFilterPostingsWith :: ReportSpec -> Journal -> PriceOracle -> Journal

-- | Convert this journal's postings' amounts to cost and/or to value, if
--   specified by options (-B--cost-V-X--value etc.). Strip
--   prices if not needed. This should be the main stop for performing
--   costing and valuation. The exception is whenever you need to perform
--   valuation _after_ summing up amounts, as in a historical balance
--   report with --value=end. valuationAfterSum will check for this
--   condition.
journalApplyValuationFromOpts :: ReportSpec -> Journal -> Journal

-- | Like journalApplyValuationFromOpts, but takes PriceOracle as an
--   argument.
journalApplyValuationFromOptsWith :: ReportSpec -> Journal -> PriceOracle -> Journal

-- | Select the Account valuation functions required for performing
--   valuation after summing amounts. Used in MultiBalanceReport to value
--   historical and similar reports.
mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle -> Day -> MixedAmount -> MixedAmount

-- | If the ReportOpts specify that we are performing valuation after
--   summing amounts, return Just of the commodity symbol we're converting
--   to, Just Nothing for the default, and otherwise return Nothing. Used
--   for example with historical reports with --value=end.
valuationAfterSum :: ReportOpts -> Maybe (Maybe CommoditySymbol)

-- | If the ReportOpts specify that we will need to consider historical
--   postings, either because this is a historical report, or because the
--   valuation strategy requires historical amounts.
requiresHistorical :: ReportOpts -> Bool

-- | Get the report interval, if any, specified by the last of -p/--period,
--   -D--daily, -W--weekly, -M/--monthly etc. options. An interval
--   from --period counts only if it is explicitly defined.
intervalFromRawOpts :: RawOpts -> Interval

-- | Convert report options to a query, ignoring any non-flag command line
--   arguments.
queryFromFlags :: ReportOpts -> Query

-- | Select the Transaction date accessor based on --date2.
transactionDateFn :: ReportOpts -> Transaction -> Day

-- | Select the Posting date accessor based on --date2.
postingDateFn :: ReportOpts -> Posting -> Day

-- | The effective report span is the start and end dates requested by
--   options or queries. If the start date is unspecified, the earliest
--   transaction or posting date is used. If the end date is unspecified,
--   the latest transaction or posting date (or non-future market price
--   date, when doing an end value report) is used. If none of these things
--   are present, the null date span is returned. The report sub-periods
--   caused by a report interval, if any, are also returned.
reportSpan :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)

-- | Like reportSpan, but considers both primary and secondary dates, not
--   just one or the other.
reportSpanBothDates :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)
reportStartDate :: Journal -> ReportSpec -> Maybe Day
reportEndDate :: Journal -> ReportSpec -> Maybe Day
reportPeriodStart :: ReportSpec -> Maybe Day
reportPeriodOrJournalStart :: ReportSpec -> Journal -> Maybe Day
reportPeriodLastDay :: ReportSpec -> Maybe Day
reportPeriodOrJournalLastDay :: ReportSpec -> Journal -> Maybe Day

-- | Make a name for the given period in a multiperiod report, given the
--   type of balance being reported and the full set of report periods.
--   This will be used as a column heading (or row heading, in a register
--   summary report). We try to pick a useful name as follows:
--   
--   
--   
- ending-balance reports: the period's end date
--   
- balance change reports where the periods are months and all in the
--   same year: the short month name in the current locale
--   
- all other balance change reports: a description of the datespan,
--   abbreviated to compact form if possible (see showDateSpan).
--   
reportPeriodName :: BalanceAccumulation -> [DateSpan] -> DateSpan -> Text
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.AccountListMode
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.BalanceAccumulation
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.BalanceCalculation
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.ReportOpts
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.ReportSpec
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.BalanceAccumulation
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.BalanceCalculation
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.Layout
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.SortField
instance Hledger.Reports.ReportOptions.HasReportOptsNoUpdate Hledger.Reports.ReportOptions.ReportOpts
instance Hledger.Reports.ReportOptions.HasReportOptsNoUpdate Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.HasReportOpts Hledger.Reports.ReportOptions.ReportOpts
instance Hledger.Reports.ReportOptions.HasReportOpts Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.HasReportSpec Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.Reportable (GHC.Internal.Data.Functor.Const.Const r) e
instance (e GHC.Types.~ a) => Hledger.Reports.ReportOptions.Reportable (GHC.Internal.Data.Either.Either a) e
instance Hledger.Reports.ReportOptions.Reportable GHC.Internal.Data.Functor.Identity.Identity e
instance Hledger.Reports.ReportOptions.Reportable GHC.Internal.Maybe.Maybe e
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.BalanceAccumulation
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.BalanceCalculation
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.Layout
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.ReportOpts
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.ReportSpec
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.SortField

-- | New common report types, used by the BudgetReport for now, perhaps all
--   reports later.
module Hledger.Reports.ReportTypes

-- | A periodic report is a generic tabular report, where each row
--   corresponds to some label (usually an account name) and each column to
--   a date period. The column periods are usually consecutive subperiods
--   formed by splitting the overall report period by some report interval
--   (daily, weekly, etc.). It has:
--   
--   
--   
- a list of each column's period (date span)
--   
- a list of rows, each containing:
--   
--   
--   
--   
- an account label
--   
- the account's depth
--   
- A list of amounts, one for each column. Depending on the value
--   type, these can represent balance changes, ending balances, budget
--   performance, etc. (for example, see BalanceAccumulation and
--   Hledger.Cli.Commands.Balance).
--   
- the total of the row's amounts for a periodic report, or zero for
--   cumulative/historical reports (since summing end balances generally
--   doesn't make sense).
--   
- the average of the row's amounts
--   
--   
--   
--   
- the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.
--   
data PeriodicReport a b
PeriodicReport :: [DateSpan] -> [PeriodicReportRow a b] -> PeriodicReportRow () b -> PeriodicReport a b
[prDates] :: PeriodicReport a b -> [DateSpan]
[prRows] :: PeriodicReport a b -> [PeriodicReportRow a b]
[prTotals] :: PeriodicReport a b -> PeriodicReportRow () b
data PeriodicReportRow a b
PeriodicReportRow :: a -> [b] -> b -> b -> PeriodicReportRow a b
[prrName] :: PeriodicReportRow a b -> a
[prrAmounts] :: PeriodicReportRow a b -> [b]
[prrTotal] :: PeriodicReportRow a b -> b
[prrAverage] :: PeriodicReportRow a b -> b
type Percentage = Decimal
type Change = MixedAmount
type Balance = MixedAmount
type Total = MixedAmount
type Average = MixedAmount

-- | Figure out the overall date span of a PeriodicReport
periodicReportSpan :: PeriodicReport a b -> DateSpan

-- | Map a function over the row names.
prMapName :: (a -> b) -> PeriodicReport a c -> PeriodicReport b c

-- | Map a function over the row names, possibly discarding some.
prMapMaybeName :: (a -> Maybe b) -> PeriodicReport a c -> PeriodicReport b c

-- | A compound balance report has:
--   
--   
--   
- an overall title
--   
- the period (date span) of each column
--   
- one or more named, normal-positive multi balance reports, with
--   columns corresponding to the above, and a flag indicating whether they
--   increased or decreased the overall totals
--   
- a list of overall totals for each column, and their grand total
--   and average
--   
--   
--   It is used in compound balance report commands like balancesheet,
--   cashflow and incomestatement.
data CompoundPeriodicReport a b
CompoundPeriodicReport :: Text -> [DateSpan] -> [(Text, PeriodicReport a b, Bool)] -> PeriodicReportRow () b -> CompoundPeriodicReport a b
[cbrTitle] :: CompoundPeriodicReport a b -> Text
[cbrDates] :: CompoundPeriodicReport a b -> [DateSpan]
[cbrSubreports] :: CompoundPeriodicReport a b -> [(Text, PeriodicReport a b, Bool)]
[cbrTotals] :: CompoundPeriodicReport a b -> PeriodicReportRow () b

-- | Description of one subreport within a compound balance report. Part of
--   a CompoundBalanceCommandSpec, but also used in hledger-lib.
data CBCSubreportSpec a
CBCSubreportSpec :: Text -> Query -> (ReportOpts -> ReportOpts) -> (PeriodicReport DisplayName MixedAmount -> PeriodicReport a MixedAmount) -> Bool -> CBCSubreportSpec a

-- | The title to use for the subreport
[cbcsubreporttitle] :: CBCSubreportSpec a -> Text

-- | The Query to use for the subreport
[cbcsubreportquery] :: CBCSubreportSpec a -> Query

-- | A function to transform the ReportOpts used to produce the subreport
[cbcsubreportoptions] :: CBCSubreportSpec a -> ReportOpts -> ReportOpts

-- | A function to transform the result of the subreport
[cbcsubreporttransform] :: CBCSubreportSpec a -> PeriodicReport DisplayName MixedAmount -> PeriodicReport a MixedAmount

-- | Whether the subreport and overall report total are of the same sign
--   (e.g. Assets are normally positive in a balance sheet report, as is
--   the overall total. Liabilities are normally of the opposite sign.)
[cbcsubreportincreasestotal] :: CBCSubreportSpec a -> Bool

-- | A full name, display name, and indent level for an account.
data DisplayName
DisplayName :: AccountName -> AccountName -> NumberOfIndents -> DisplayName
[displayFull] :: DisplayName -> AccountName
[displayName] :: DisplayName -> AccountName
[displayIndent] :: DisplayName -> NumberOfIndents

-- | Construct a display name for a list report, where full names are shown
--   unindented.
flatDisplayName :: AccountName -> DisplayName

-- | Construct a display name for a tree report, where leaf names (possibly
--   prefixed by boring parents) are shown indented).
treeDisplayName :: AccountName -> DisplayName
prrShowDebug :: PeriodicReportRow DisplayName MixedAmount -> String

-- | Get the full canonical account name from a PeriodicReportRow
--   containing a DisplayName.
prrFullName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the account display name from a PeriodicReportRow containing a
--   DisplayName.
prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the indent level from a PeriodicReportRow containing a
--   DisplayName.
prrIndent :: PeriodicReportRow DisplayName a -> Int

-- | Add two PeriodicReportRows, preserving the name of the first.
prrAdd :: Semigroup b => PeriodicReportRow a b -> PeriodicReportRow a b -> PeriodicReportRow a b
instance Data.Bifunctor.Bifunctor Hledger.Reports.ReportTypes.PeriodicReport
instance Data.Bifunctor.Bifunctor Hledger.Reports.ReportTypes.PeriodicReportRow
instance GHC.Classes.Eq Hledger.Reports.ReportTypes.DisplayName
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.CompoundPeriodicReport a)
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReport a)
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReportRow a)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Data.Text.Internal.Text, Hledger.Reports.ReportTypes.PeriodicReport a b, GHC.Types.Bool)
instance GHC.Classes.Ord Hledger.Reports.ReportTypes.DisplayName
instance GHC.Internal.Base.Semigroup b => GHC.Internal.Base.Semigroup (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance GHC.Internal.Show.Show Hledger.Reports.ReportTypes.DisplayName
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance (Data.Aeson.Types.ToJSON.ToJSON b, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Reports.ReportTypes.DisplayName
instance (Data.Aeson.Types.ToJSON.ToJSON a, Data.Aeson.Types.ToJSON.ToJSON b) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance (Data.Aeson.Types.ToJSON.ToJSON b, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReportRow a b)

-- | Postings report, used by the register command.
module Hledger.Reports.PostingsReport

-- | A postings report is a list of postings with a running total, and a
--   little extra transaction info to help with rendering. This is used eg
--   for the register command.
type PostingsReport = [PostingsReportItem]
type PostingsReportItem = (Maybe Day, Maybe Period, Maybe Text, Posting, MixedAmount)

-- | Select postings from the journal and add running balance and other
--   information to make a postings report. Used by eg hledger's register
--   command.
postingsReport :: ReportSpec -> Journal -> PostingsReport

-- | Generate one postings report line item, containing the posting, the
--   current running balance, and optionally the posting date and/or the
--   transaction description.
mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Period -> Posting -> MixedAmount -> PostingsReportItem
type SortSpec = [SortField]
defsortspec :: SortSpec
tests_PostingsReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.PostingsReport.PostingsReportItem

-- | Multi-column balance reports, used by the balance command.
module Hledger.Reports.MultiBalanceReport

-- | A multi balance report is a kind of periodic report, where the amounts
--   correspond to balance changes or ending balances in a given period. It
--   has:
--   
--   
--   
- a list of each column's period (date span)
--   
- a list of rows, each containing:
--   
--   
--   
--   
- the full account name, display name, and display depth
--   
- A list of amounts, one for each column.
--   
- the total of the row's amounts for a periodic report
--   
- the average of the row's amounts
--   
--   
--   
--   
- the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.
--   
type MultiBalanceReport = PeriodicReport DisplayName MixedAmount
type MultiBalanceReportRow = PeriodicReportRow DisplayName MixedAmount

-- | Generate a multicolumn balance report for the matched accounts,
--   showing the change of balance, accumulated balance, or historical
--   balance in each of the specified periods. If the normalbalance_ option
--   is set, it adjusts the sorting and sign of amounts (see ReportOpts and
--   CompoundBalanceCommand). hledger's most powerful and useful report,
--   used by the balance command (in multiperiod mode) and (via
--   compoundBalanceReport) by the bscfis commands.
multiBalanceReport :: ReportSpec -> Journal -> MultiBalanceReport

-- | A helper for multiBalanceReport. This one takes some extra arguments,
--   a PriceOracle to be used for looking up market prices, and a
--   set of AccountNames which should not be elided. Commands which
--   run multiple reports (bs etc.) can generate the price oracle just once
--   for efficiency, passing it to each report by calling this function
--   directly.
multiBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> MultiBalanceReport

-- | Generate a compound balance report from a list of CBCSubreportSpec.
--   This shares postings between the subreports.
compoundBalanceReport :: ReportSpec -> Journal -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount

-- | A helper for compoundBalanceReport, similar to multiBalanceReportWith.
compoundBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount

-- | Remove any date queries and insert queries from the report span. The
--   user's query expanded to the report span if there is one (otherwise
--   any date queries are left as-is, which handles the hledger-ui+future
--   txns case above).
makeReportQuery :: ReportSpec -> DateSpan -> ReportSpec

-- | Gather postings matching the query within the report period.
getPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting]

-- | Generate the Account for the requested multi-balance report
--   from a list of Postings.
generateMultiBalanceAccount :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> Account BalanceData

-- | Lay out a set of postings grouped by date span into a regular matrix
--   with rows given by AccountName and columns by DateSpan, then generate
--   a MultiBalanceReport from the columns.
generatePeriodicReport :: Show c => (forall a. () => ReportOpts -> (BalanceData -> MixedAmount) -> a -> Account b -> PeriodicReportRow a c) -> (b -> MixedAmount) -> (c -> MixedAmount) -> ReportOpts -> Maybe DayPartition -> Account b -> PeriodicReport DisplayName c

-- | Build a report row.
--   
--   Calculate the column totals. These are always the sum of column
--   amounts.
makePeriodicReportRow :: c -> (Map Day c -> (c, c)) -> ReportOpts -> (b -> c) -> a -> Account b -> PeriodicReportRow a c
tests_MultiBalanceReport :: TestTree

-- | Journal entries report, used by the print command.
module Hledger.Reports.EntriesReport

-- | A journal entries report is a list of whole transactions as originally
--   entered in the journal (mostly). This is used by eg hledger's print
--   command and hledger-web's journal entries view.
type EntriesReport = [EntriesReportItem]
type EntriesReportItem = Transaction

-- | Select transactions for an entries report.
entriesReport :: ReportSpec -> Journal -> EntriesReport
tests_EntriesReport :: TestTree

module Hledger.Reports.BudgetReport
type BudgetGoal = Change
type BudgetTotal = Total
type BudgetAverage = Average

-- | A budget report tracks expected and actual changes per account and
--   subperiod. Each table cell has an actual change amount and/or a budget
--   goal amount.
type BudgetCell = (Maybe Change, Maybe BudgetGoal)

-- | A row in a budget report table - account name and data cells.
type BudgetReportRow = PeriodicReportRow DisplayName BudgetCell

-- | A full budget report table.
type BudgetReport = PeriodicReport DisplayName BudgetCell

-- | Calculate per-account, per-period budget (balance change) goals from
--   all periodic transactions, calculate actual balance changes from the
--   regular transactions, and compare these to get a BudgetReport.
--   Unbudgeted accounts may be hidden or renamed (see
--   journalWithBudgetAccountNames).
budgetReport :: ReportSpec -> BalancingOpts -> DateSpan -> Journal -> BudgetReport
tests_BudgetReport :: TestTree

-- | Balance report, used by the balance command.
module Hledger.Reports.BalanceReport

-- | A simple balance report. It has:
--   
--   
--   
- a list of items, one per account, each containing:
--   
--   
--   
--   
- the full account name
--   
- the Ledger-style elided short account name (the leaf account name,
--   prefixed by any boring parents immediately above); or with --flat, the
--   full account name again
--   
- the number of indentation steps for rendering a Ledger-style
--   account tree, taking into account elided boring parents, --no-elide
--   and --flat
--   
- an amount
--   
--   
--   
--   
- the total of all amounts
--   
type BalanceReport = ([BalanceReportItem], MixedAmount)
type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount)

-- | Enabling this makes balance --flat --empty also show parent accounts
--   without postings, in addition to those with postings and a zero
--   balance. Disabling it shows only the latter. No longer supported, but
--   leave this here for a bit. flatShowsPostinglessAccounts = True
--   
--   Generate a simple balance report, containing the matched accounts and
--   their balances (change of balance) during the specified period. If the
--   normalbalance_ option is set, it adjusts the sorting and sign of
--   amounts (see ReportOpts and CompoundBalanceCommand).
balanceReport :: ReportSpec -> Journal -> BalanceReport

-- | When true (the default), this makes balance --flat reports and their
--   implementation clearer. Single/multi-col balance reports currently
--   aren't all correct if this is false.
flatShowsExclusiveBalance :: Bool
tests_BalanceReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.BalanceReport.BalanceReportItem

-- | An account-centric transactions report.
module Hledger.Reports.AccountTransactionsReport

-- | An account transactions report represents transactions affecting a
--   particular account (or possibly several accounts, but we don't use
--   that). It is used eg by hledger-ui's and hledger-web's register view,
--   and hledger's aregister report, where we want to show one row per
--   transaction, in the context of the current account. Report items
--   consist of:
--   
--   
--   
- the transaction, unmodified
--   
- the transaction as seen in the context of the current account and
--   query, which means:
--   
- the transaction date is set to the "transaction context date": the
--   earliest of the transaction date and any other posting dates of
--   postings to the current account (matched by the report query).
--   
- the transaction's postings are filtered, excluding any which are
--   not matched by the report query
--   
- a text description of the other account(s) posted to/from
--   
- a flag indicating whether there's more than one other account
--   involved
--   
- the total increase/decrease to the current account
--   
- the report transactions' running total after this transaction; or
--   if historical balance is requested (-H), the historical running total.
--   The historical running total includes transactions from before the
--   report start date if one is specified, filtered by the report query.
--   The historical running total may or may not be the account's
--   historical running balance, depending on the report query.
--   
--   
--   Items are sorted by transaction register date (the earliest date the
--   transaction posts to the current account), most recent first.
--   Reporting intervals are currently ignored.
type AccountTransactionsReport = [AccountTransactionsReportItem]
type AccountTransactionsReportItem = (Transaction, Transaction, Bool, [AccountName], MixedAmount, MixedAmount)
accountTransactionsReport :: ReportSpec -> Journal -> Query -> AccountTransactionsReport

-- | Generate transactions report items from a list of transactions, using
--   the provided user-specified report query, a query specifying which
--   account to use as the focus, a starting balance, 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 -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem]

-- | What date should be shown for a transaction in an account register
--   report ? This will be in context of a particular account (the "this
--   account" query) and any additional report query. It could be:
--   
--   
--   
- if postings are matched by both thisacctq and reportq, the
--   earliest of those matched postings' dates (or their secondary dates if
--   --date2 was used)
--   
- the transaction date, or its secondary date if --date2 was
--   used.
--   
transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day
triOrigTransaction :: (a, b, c, d, e, f) -> a
triDate :: (a, Transaction, c, d, e, f) -> Day
triAmount :: (a, b, c, d, e, f) -> e
triBalance :: (a, b, c, d, e, f) -> f
triCommodityAmount :: CommoditySymbol -> (a, b, c, d, MixedAmount, f) -> MixedAmount
triCommodityBalance :: CommoditySymbol -> (a, b, c, d, e, MixedAmount) -> MixedAmount

-- | Split an account transactions report whose items may involve several
--   commodities, into one or more single-commodity account transactions
--   reports.
accountTransactionsReportByCommodity :: AccountTransactionsReport -> [(CommoditySymbol, AccountTransactionsReport)]
tests_AccountTransactionsReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.AccountTransactionsReport.AccountTransactionsReportItem

-- | Generate several common kinds of report from a journal, as "*Report" -
--   simple intermediate data structures intended to be easily rendered as
--   text, html, json, csv etc. by hledger commands, hamlet templates,
--   javascript, or whatever.
module Hledger.Reports
tests_Reports :: TestTree

-- | File reading/parsing utilities used by multiple readers, and a good
--   amount of the parsers for journal format, to avoid import cycles when
--   JournalReader imports other readers.
--   
--   Some of these might belong in Hledger.Read.JournalReader or
--   Hledger.Read.
module Hledger.Read.Common

-- | A hledger journal reader is a storage format name, a list of file
--   extensions assumed to be in this format, and an IO action that reads
--   data in this format, returning a Journal.
--   
--   The journal parser used by the latter is also stored separately for
--   direct use by the journal reader's includedirectivep to parse included
--   files. The type variable m is needed for this parser. Lately it
--   requires an InputOpts, basically to support --old-timeclock.
data Reader (m :: Type -> Type)
Reader :: StorageFormat -> [String] -> (InputOpts -> FilePath -> Handle -> ExceptT String IO Journal) -> (MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal) -> Reader (m :: Type -> Type)
[rFormat] :: Reader (m :: Type -> Type) -> StorageFormat
[rExtensions] :: Reader (m :: Type -> Type) -> [String]
[rReadFn] :: Reader (m :: Type -> Type) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
[rParser] :: Reader (m :: Type -> Type) -> MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal

-- | A file path optionally prefixed by a reader name and colon (journal:,
--   csv:, timedot:, etc.). The file path part can also be - meaning
--   standard input.
type PrefixedFilePath = FilePath

-- | Is this the special file path meaning standard input ? (-, possibly
--   prefixed)
isStdin :: PrefixedFilePath -> Bool
data InputOpts
InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> Bool -> DateSpan -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Day -> Bool -> InputOpts

-- | a file/storage format to try, unless overridden by a filename prefix.
--   Nothing means try all.
[mformat_] :: InputOpts -> Maybe StorageFormat

-- | a conversion rules file to use (when reading CSV)
[mrules_file_] :: InputOpts -> Maybe FilePath

-- | account name aliases to apply
[aliases_] :: InputOpts -> [String]

-- | do light obfuscation of the data ? Now corresponds to --obfuscate, not
--   the old --anon flag.
[anon_] :: InputOpts -> Bool

-- | read only new transactions since this file was last read ?
[new_] :: InputOpts -> Bool

-- | save latest new transactions state for next time ?
[new_save_] :: InputOpts -> Bool

-- | use the given field's value as the account name
[pivot_] :: InputOpts -> String

-- | span in which to generate forecast transactions
[forecast_] :: InputOpts -> Maybe DateSpan

-- | propagate commodity and account tags to postings ? Can be disabled
--   (for beancount export).
[auto_posting_tags_] :: InputOpts -> Bool

-- | add user-visible tags when generating/modifying transactions &
--   postings ?
[verbose_tags_] :: InputOpts -> Bool

-- | a dirty hack keeping the query dates in InputOpts. This rightfully
--   lives in ReportSpec, but is duplicated here.
[reportspan_] :: InputOpts -> DateSpan

-- | generate extra postings according to auto posting rules ?
[auto_] :: InputOpts -> Bool

-- | infer equity conversion postings from costs ?
[infer_equity_] :: InputOpts -> Bool

-- | infer costs from equity conversion postings ? distinct from
--   BalancingOpts{infer_balancing_costs_}
[infer_costs_] :: InputOpts -> Bool

-- | options for transaction balancing
[balancingopts_] :: InputOpts -> BalancingOpts

-- | do extra correctness checks ?
[strict_] :: InputOpts -> Bool

-- | internal flag: postpone checks, because we are processing multiple
--   files ?
[_defer] :: InputOpts -> Bool

-- | today's date, for use with forecast transactions XXX this duplicates
--   _rsDay, and should eventually be removed when it's not needed anymore.
[_ioDay] :: InputOpts -> Day

-- | parse with the old timeclock pairing rules?
[_oldtimeclock] :: InputOpts -> Bool
class HasInputOpts c
inputOpts :: HasInputOpts c => Lens' c InputOpts
aliases :: HasInputOpts c => Lens' c [String]
anon__ :: HasInputOpts c => Lens' c Bool
auto__ :: HasInputOpts c => Lens' c Bool
auto_posting_tags :: HasInputOpts c => Lens' c Bool
balancingopts :: HasInputOpts c => Lens' c BalancingOpts
defer :: HasInputOpts c => Lens' c Bool
forecast :: HasInputOpts c => Lens' c (Maybe DateSpan)
infer_costs :: HasInputOpts c => Lens' c Bool
infer_equity :: HasInputOpts c => Lens' c Bool
ioDay :: HasInputOpts c => Lens' c Day
mformat :: HasInputOpts c => Lens' c (Maybe StorageFormat)
mrules_file :: HasInputOpts c => Lens' c (Maybe FilePath)
new__ :: HasInputOpts c => Lens' c Bool
new_save :: HasInputOpts c => Lens' c Bool
oldtimeclock :: HasInputOpts c => Lens' c Bool
pivot :: HasInputOpts c => Lens' c String
reportspan :: HasInputOpts c => Lens' c DateSpan
strict :: HasInputOpts c => Lens' c Bool
verbose_tags :: HasInputOpts c => Lens' c Bool
definputopts :: InputOpts

-- | Parse an InputOpts from a RawOpts and a provided date. This will fail
--   with a usage error if the forecast period expression cannot be parsed.
rawOptsToInputOpts :: Day -> Bool -> Bool -> RawOpts -> InputOpts
handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal

-- | Given a parser to ParsedJournal, input options, file path and content:
--   run the parser on the content, and finalise the result to get a
--   Journal; or throw an error.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal

-- | Given a parser to ParsedJournal, input options, file path and content:
--   run the parser on the content. This is all steps of
--   parseAndFinaliseJournal without the finalisation step, and is
--   used when you need to perform other actions before finalisatison, as
--   in parsing Timeclock and Timedot files.
initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal

-- | Post-process a Journal that has just been parsed or generated, in this
--   order:
--   
--   
--   
- add misc info (file path, read time)
--   
- reverse transactions into their original parse order
--   
- apply canonical commodity styles
--   
- propagate account tags to postings
--   
- maybe add forecast transactions
--   
- propagate account tags to postings (again to affect forecast
--   transactions)
--   
- maybe add auto postings
--   
- propagate account tags to postings (again to affect auto
--   postings)
--   
- evaluate balance assignments and balance each transaction
--   
- maybe check balance assertions
--   
- maybe infer costs from equity postings
--   
- maybe infer equity postings from costs
--   
- manye infer market prices from costs
--   
--   
--   One correctness check (parseable) has already passed when this
--   function is called. Up to four more are performed here:
--   
--   
--   
- ordereddates (when enabled)
--   
- assertions (when enabled)
--   
- autobalanced (and with --strict, balanced ?), in the
--   journalBalanceTransactions step.
--   
--   
--   Others (commodities, accounts..) are done later by
--   journalStrictChecks.
journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal

-- | Generate periodic transactions from all periodic transaction rules in
--   the journal. These transactions are added to the in-memory Journal
--   (but not the on-disk file).
--   
--   The start & end date for generated periodic transactions are
--   determined in a somewhat complicated way; see the hledger manual ->
--   Periodic transactions.
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal

-- | Apply any auto posting rules to generate extra postings on this
--   journal's transactions. With a true first argument, adds visible tags
--   to generated postings and modified transactions.
journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal
setYear :: forall (m :: Type -> Type). Year -> JournalParser m ()
getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year)
setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m ()
getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle))

-- | Get amount style associated with default currency.
--   
--   Returns AmountStyle used to defined by a latest default
--   commodity directive prior to current position within this file or its
--   parents.
getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle)

-- | Get the AmountStyle declared by the most recently parsed (in
--   the current or parent files, prior to the current position) commodity
--   directive for the given commodity, if any.
getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle)
addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m ()
addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m ()
pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m ()
popParentAccount :: forall (m :: Type -> Type). JournalParser m ()
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName
addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
getAccountAliases :: MonadState Journal m => m [AccountAlias]
clearAccountAliases :: MonadState Journal m => m ()
journalAddFile :: (FilePath, Text) -> Journal -> Journal
statusp :: forall (m :: Type -> Type). TextParser m Status
codep :: forall (m :: Type -> Type). TextParser m Text

-- | Parse possibly empty text until a semicolon or newline. Whitespace is
--   preserved (for now - perhaps helps preserve alignment of same-line
--   comments ?).
descriptionp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse a date in YYYY-MM-DD format. Slash (/) and period (.) are also
--   allowed as separators. The year may be omitted if a default year has
--   been set. Leading zeroes may be omitted.
datep :: forall (m :: Type -> Type). JournalParser m Day

-- | Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format. Slash
--   (/) and period (.) are also allowed as date separators. The year may
--   be omitted if a default year has been set. Seconds are optional. The
--   timezone is optional and ignored (the time is always interpreted as a
--   local time). Leading zeroes may be omitted (except in a timezone).
datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime
secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day

-- | Parse an account name plus one following space if present (see
--   accountnamep); then apply any parent account prefix and/or account
--   aliases currently in effect, in that order. Ie first add the parent
--   account prefix, then rewrite with aliases. This calls error if any
--   account alias with an invalid regular expression exists. The flag says
--   whether account names may include semicolons; currently account names
--   in journal format may, but account names in timeclock/timedot formats
--   may not.
modifiedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName

-- | Parse an account name, plus one following space if present. Account
--   names have one or more parts separated by the account separator
--   character, and are terminated by two or more spaces (or end of input).
--   Each part is at least one character long, may have single spaces
--   inside it, and starts with a non-whitespace. (We should have required
--   them to start with an alphanumeric, but didn't.) Note, this means
--   account names can contain all kinds of punctuation, including ; which
--   usually starts a following comment. Parent parsers usually remove the
--   following comment before using this parser.
accountnamep :: forall (m :: Type -> Type). TextParser m AccountName
accountnamenosemicolonp :: forall (m :: Type -> Type). TextParser m AccountName
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias

-- | Parse whitespace then an amount, or return the special "missing"
--   marker amount.
spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount

-- | Parse a single-commodity amount, applying the default commodity if
--   there is no commodity symbol; optionally followed by, in any order: a
--   Ledger-style cost, Ledger-style valuation expression, and/or
--   Ledger-style cost basis, which is one or more of lot cost, lot date,
--   and/or lot note (we loosely call this triple the lot's cost basis).
--   The cost basis makes it a lot rather than just an amount. Both cost
--   basis info and valuation expression are discarded for now. The main
--   amount's sign is significant; here are the possibilities and their
--   interpretation. Also imagine an optional VALUATIONEXPR added to any of
--   these (omitted for clarity): @
--   
--   AMT -- acquiring an amount AMT COST -- acquiring an amount at some
--   cost AMT COST COSTBASIS -- acquiring a lot at some cost, saving its
--   cost basis AMT COSTBASIS COST -- like the above AMT COSTBASIS -- like
--   the above with cost same as the cost basis
--   
--   
--   
- AMT -- releasing an amount
--   
- AMT SELLPRICE -- releasing an amount at some selling price
--   
- AMT SELLPRICE COSTBASISSEL -- releasing a lot at some selling
--   price, selecting it by its cost basis
--   
- AMT COSTBASISSEL SELLPRICE -- like the above
--   
- AMT COSTBASISSEL -- like the above with selling price same as the
--   selected lot's cost basis amount
--   
--   
--   COST/SELLPRICE can be  UNITAMT,  TOTALAMT, ()
--   UNITAMT, or (@@) TOTALAMT. The () are ignored. COSTBASIS is one or
--   more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order, with LOTCOST
--   defaulting to COST. COSTBASISSEL is one or more of {LOTCOST},
--   [LOTDATE], (LOTNOTE), in any order. {LOTCOST} can be {UNITAMT},
--   {{TOTALAMT}}, {=UNITAMT}, or {{=TOTALAMT}}. The = is ignored.
--   VALUATIONEXPR can be ((VALUE AMOUNT)) or ((VALUE FUNCTION)).
--   
--   @ Ledger amount syntax is really complex. Rule of thumb: curly braces,
--   parentheses, and/or square brackets in an amount means a Ledger-style
--   cost basis is involved.
--   
--   To parse an amount's numeric quantity we need to know which character
--   represents a decimal mark. We find it in one of three ways:
--   
--   
--   
- If a decimal mark has been set explicitly in the journal parse
--   state, we use that
--   
- Or if the journal has a commodity declaration for the amount's
--   commodity, we get the decimal mark from that
--   
- Otherwise we will parse any valid decimal mark appearing in the
--   number, as long as the number appears well formed. (This means we
--   handle files with any supported decimal mark without configuration,
--   but it also allows different decimal marks in different amounts, which
--   is a bit too loose. There's an open issue.)
--   
amountp :: forall (m :: Type -> Type). JournalParser m Amount
amountp' :: forall (m :: Type -> Type). Bool -> JournalParser m Amount
commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol

-- | Ledger-style cost notation:  UNITAMT,  TOTALAMT, ()
--   UNITAMT, or (@@) TOTALAMT. The () are ignored.
costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost
balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion
lotcostp :: forall (m :: Type -> Type). Quantity -> JournalParser m (Maybe Amount)

-- | Parse a string representation of a number for its value and display
--   attributes.
--   
--   Some international number formats are accepted, eg either period or
--   comma may be used for the decimal mark, and the other of these may be
--   used for separating digit groups in the integer part. See
--   http://en.wikipedia.org/wiki/Decimal_separator for more
--   examples.
--   
--   This returns: the parsed numeric value, the precision (number of
--   digits seen following the decimal mark), the decimal mark character
--   used if any, and the digit group style if any.
numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)

-- | Interpret a raw number as a decimal number.
--   
--   Returns: - the decimal number - the precision (number of digits after
--   the decimal point) - the decimal point character, if any - the digit
--   group style, if any (digit group character and sizes of digit groups)
fromRawNumber :: RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)

-- | Parse and interpret the structure of a number without external hints.
--   Numbers are digit strings, possibly separated into digit groups by one
--   of two types of separators. (1) Numbers may optionally have a decimal
--   mark, which may be either a period or comma. (2) Numbers may
--   optionally contain digit group marks, which must all be either a
--   period, a comma, or a space.
--   
--   It is our task to deduce the characters used as decimal mark and digit
--   group mark, based on the allowed syntax. For instance, we make use of
--   the fact that a decimal mark can occur at most once and must be to the
--   right of all digit group marks.
--   
--   
--   >>> parseTest rawnumberp "1,234,567.89"
--   Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
--   
--   >>> parseTest rawnumberp "1,000"
--   Left (AmbiguousNumber "1" ',' "000")
--   
--   >>> parseTest rawnumberp "1 000"
--   Right (WithSeparators ' ' ["1","000"] Nothing)
--   
rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber)

-- | Try to parse a single-commodity amount from a string
parseamount :: String -> Either HledgerParseErrors Amount

-- | Parse a single-commodity amount from a string, or get an error.
parseamount' :: String -> Amount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount' :: String -> MixedAmount

-- | Is this a character that, as the first non-whitespace on a line,
--   starts a comment line ?
isLineCommentStart :: Char -> Bool

-- | Is this a character that, appearing anywhere within a line, starts a
--   comment ?
isSameLineCommentStart :: Char -> Bool
multilinecommentp :: forall (m :: Type -> Type). TextParser m ()

-- | A blank or comment line in journal format: a line that's empty or
--   containing only whitespace or whose first non-whitespace character is
--   semicolon, hash, or star. See also emptyorcommentlinep2.
emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m ()

-- | A newer comment line parser. Parses a line which is empty, all blanks,
--   or whose first non-blank character is one of those provided. A final
--   newline is optional.
emptyorcommentlinep2 :: forall (m :: Type -> Type). [Char] -> TextParser m ()

-- | Parse a comment following a journal item, possibly continued on
--   multiple lines, and return the comment text.
--   
--   
--   >>> rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   >>> rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
--   Right "\n\n"
--   
followingcommentp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse a transaction comment and extract its tags.
--   
--   The first line of a transaction may be followed a 1-or-more-lines
--   comment, beginning with a semicolon possibly preceded by whitespace on
--   the current line, or with an indented semicolon on the next line.
--   Additional lines also must begin with an indented semicolon. See also
--   followingcommentpWith.
--   
--   200011 ; a transaction comment starting on the same line ... ;
--   extending to the next line account1 $1 account2
--   
--   Tags are name-value pairs.
--   
--   
--   >>> let getTags (_,tags) = tags
--   
--   >>> let parseTags = fmap getTags . rtp transactioncommentp
--   
--   
--   
--   >>> parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   
--   
--   A tag's name must be immediately followed by a colon, without
--   separating whitespace. The corresponding value consists of all the
--   text following the colon up until the next colon or newline, stripped
--   of leading and trailing whitespace.
transactioncommentp :: forall (m :: Type -> Type). TextParser m (Text, [Tag])
commentlinetagsp :: forall (m :: Type -> Type). TextParser m [Tag]

-- | Parse a posting comment and extract its tags and dates.
--   
--   Postings may be followed by comments, which begin with semicolons and
--   extend to the end of the line. Posting comments may span multiple
--   lines, but comment lines below the posting must be preceded by leading
--   whitespace.
--   
--   200011 account1 $1 ; a posting comment starting on the same
--   line ... ; extending to the next line
--   
--   account2 ; a posting comment beginning on the next line
--   
--   Tags are name-value pairs.
--   
--   
--   >>> let getTags (_,tags,_,_) = tags
--   
--   >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing)
--   
--   
--   
--   >>> parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   
--   
--   A tag's name must be immediately followed by a colon, without
--   separating whitespace. The corresponding value consists of all the
--   text following the colon up until the next colon or newline, stripped
--   of leading and trailing whitespace.
--   
--   Posting dates may be expressed with "date"/"date2" tags or with
--   bracketed date syntax. Posting dates will inherit their year from the
--   transaction date if the year is not specified. We throw parse errors
--   on invalid dates.
--   
--   
--   >>> let getDates (_,_,d1,d2) = (d1, d2)
--   
--   >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
--   
--   
--   
--   >>> parseDates "; date: 1/2, date2: 1999/12/31"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   
--   >>> parseDates "; [1/2=1999/12/31]"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   
--   
--   Example: tags, date tags, and bracketed dates >>> rtp
--   (postingcommentp (Just 2000)) "; a:b, date:34, [=56]" Right
--   ("a:b, date:34, [=56]n",[("a","b"),("date","3/4")],Just
--   2000-03-04,Just 2000-05-06)
--   
--   Example: extraction of dates from date tags ignores trailing text
--   >>> rtp (postingcommentp (Just 2000)) "; date:34=56"
--   Right ("date:34=56n",[("date","34=56")],Just
--   2000-03-04,Nothing)
postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)

-- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as "date"
--   and/or "date2" tags. Anything that looks like an attempt at this (a
--   square-bracketed sequence of 0123456789/-.= containing at least one
--   digit and one date separator) is also parsed, and will throw an
--   appropriate error.
--   
--   The dates are parsed in full here so that errors are reported in the
--   right position. A missing year in DATE can be inferred if a default
--   date is provided. A missing year in DATE2 will be inferred from DATE.
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
--   Right [("date",2016-01-02),("date2",2016-03-04)]
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"
--   Left ...not a bracketed date...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"
--   Left ...1:2:...This is not a valid date...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"
--   Left ...1:2:...This partial date can not be parsed because the current year is unknown...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
--   Left ...1:13:...expecting month or day...
--   
bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)]

-- | Parse a single line of possibly empty text enclosed in double quotes.
doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse possibly empty text, including whitespace, until a comment start
--   (semicolon) or newline.
noncommenttextp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty text, including whitespace, until a comment start
--   (semicolon) or newline.
noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, until a double space or newline.
singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, until a comment start (semicolon), double space, or
--   newline.
singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, where all characters satisfy the given predicate.
singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text

-- | Parse one non-newline whitespace character that is not followed by
--   another one.
singlespacep :: forall (m :: Type -> Type). TextParser m ()
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()

-- | Get the account name aliases from options, if any.
aliasesFromOpts :: InputOpts -> [AccountAlias]
tests_Common :: TestTree
instance GHC.Classes.Eq Hledger.Read.Common.AmbiguousNumber
instance GHC.Classes.Eq Hledger.Read.Common.DigitGrp
instance GHC.Classes.Eq Hledger.Read.Common.RawNumber
instance GHC.Internal.Base.Monoid Hledger.Read.Common.DigitGrp
instance GHC.Internal.Base.Semigroup Hledger.Read.Common.DigitGrp
instance GHC.Internal.Show.Show Hledger.Read.Common.AmbiguousNumber
instance GHC.Internal.Show.Show Hledger.Read.Common.DigitGrp
instance GHC.Internal.Show.Show Hledger.Read.Common.RawNumber
instance GHC.Internal.Show.Show (Hledger.Read.Common.Reader m)

-- | A reader for the "timedot" file format. Example:
--   
--   
--   ;DATE
--   ;ACCT  DOTS  # Each dot represents 15m, spaces are ignored
--   ;ACCT  8    # numbers with or without a following h represent hours
--   ;ACCT  5m   # numbers followed by m represent minutes
--   
--   ; on 2/1, 1h was spent on FOSS haskell work, 0.25h on research, etc.
--   2/1
--   fos.haskell   .... ..
--   biz.research  .
--   inc.client1   .... .... .... .... .... ....
--   
--   2/2
--   biz.research  .
--   inc.client1   .... .... ..
--   
module Hledger.Read.TimedotReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m
timedotfilep :: forall {m :: Type -> Type}. InputOpts -> JournalParser m ParsedJournal

-- | A reader for the timeclock file format.
--   
--   What exactly is this format ? It was introduced in timeclock.el
--   (http://www.emacswiki.org/emacs/TimeClock). The old
--   specification in timeclock.el 2.6 was:
--   
--   
--   A timeclock contains data in the form of a single entry per line.
--   Each entry has the form:
--   
--     CODE YYYYMMDD HH:MM:SS [COMMENT]
--   
--   CODE is one of: b, h, i, o or O.  COMMENT is optional when the code is
--   i, o or O.  The meanings of the codes are:
--   
--     b  Set the current time balance, or "time debt".  Useful when
--        archiving old log data, when a debt must be carried forward.
--        The COMMENT here is the number of seconds of debt.
--   
--     h  Set the required working time for the given day.  This must
--        be the first entry for that day.  The COMMENT in this case is
--        the number of hours in this workday.  Floating point amounts
--        are allowed.
--   
--     i  Clock in.  The COMMENT in this case should be the name of the
--        project worked on.
--   
--     o  Clock out.  COMMENT is unnecessary, but can be used to provide
--        a description of how the period went, for example.
--   
--     O  Final clock out.  Whatever project was being worked on, it is
--        now finished.  Useful for creating summary reports.
--   
--   
--   Ledger's timeclock format is different, and hledger's timeclock format
--   is different again. For example: in a clock-in entry, after the time,
--   
--   
--   
- timeclock.el's timeclock has 0-1 fields: [COMMENT]
--   
- Ledger's timeclock has 0-2 fields: [ACCOUNT[ PAYEE]]
--   
- hledger's timeclock has 1-3 fields: ACCOUNT[
--   DESCRIPTION[;COMMENT]]
--   
--   
--   hledger's timeclock format is:
--   
--   
--   # Comment lines like these, and blank lines, are ignored:
--   # comment line
--   ; comment line
--   * comment line
--   
--   # Lines beginning with b, h, or capital O are also ignored, for compatibility:
--   b SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   h SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   O SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   
--   # Lines beginning with i or o are are clock-in / clock-out entries:
--   i SIMPLEDATE HH:MM[:SS][+-ZZZZ] ACCOUNT[  DESCRIPTION][;COMMENT]]
--   o SIMPLEDATE HH:MM[:SS][+-ZZZZ][ ACCOUNT][;COMMENT]
--   
--   
--   The date is a hledger simple date (YYYY-MM-DD or similar). The
--   time parts must use two digits. The seconds are optional. A + or -
--   four-digit time zone is accepted for compatibility, but currently
--   ignored; times are always interpreted as a local time.
--   
--   In clock-in entries (i), the account name is required. A
--   transaction description, separated from the account name by 2+ spaces,
--   is optional. A transaction comment, beginning with `;`, is also
--   optional.
--   
--   In clock-out entries (o) have no description, but can have a
--   comment if you wish. A clock-in and clock-out pair form a
--   "transaction" posting some number of hours to an account - also known
--   as a session. Eg:
--   
--   ```timeclock i 20150330 09:00:00 session1 o 20150330
--   10:00:00 ```
--   
--   ```cli $ hledger -f a.timeclock print 2015-03-30 * 09:00-10:00
--   (session1) 1.00h ```
--   
--   Clock-ins and clock-outs are matched by their account/session name. If
--   a clock-outs does not specify a name, the most recent unclosed
--   clock-in is closed. Also, sessions spanning more than one day are
--   automatically split at day boundaries. Eg, the following time log:
--   
--   ```timeclock i 20150330 09:00:00 some account optional
--   description after 2 spaces ; optional comment, tags: o 20150330
--   09:20:00 i 20150331 22:21:45 another:account o 20150401
--   02:00:34 i 20150402 12:00:00 another:account ; this
--   demonstrates multple sessions being clocked in i 20150402
--   13:00:00 some account o 20150402 14:00:00 o 20150402
--   15:00:00 another:account ```
--   
--   generates these transactions:
--   
--   ```cli $ hledger -f t.timeclock print 2015-03-30 * optional
--   description after 2 spaces ; optional comment, tags: (some account)
--   0.33h
--   
--   2015-03-31 * 22:21-23:59 (another:account) 1.64h
--   
--   2015-04-01 * 00:00-02:00 (another:account) 2.01h
--   
--   2015-04-02 * 12:00-15:00 ; this demonstrates multiple sessions being
--   clocked in (another:account) 3.00h
--   
--   2015-04-02 * 13:00-14:00 (some account) 1.00h
--   
--   ```
module Hledger.Read.TimeclockReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m
timeclockfilep :: forall (m :: Type -> Type). MonadIO m => InputOpts -> JournalParser m ParsedJournal

-- | A reader for a CSV rules file. This reads the actual data from a file
--   specified by a source rule or from a similarly-named file in
--   the same directory.
--   
--   Most of the code for reading rules files and csv files is in this
--   module.
module Hledger.Read.RulesReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m

-- | Given a rules file path, what would be the corresponding data file ?
--   (Remove a .rules extension.)
dataFileFor :: FilePath -> Maybe FilePath

-- | Given a csv file path, what would be the corresponding rules file ?
--   (Add a .rules extension.)
rulesFileFor :: FilePath -> FilePath

-- | Return the given rules file path, or if none is given, the default
--   rules file for the given csv file; or if the csv file is "-", raise an
--   error.
getRulesFile :: FilePath -> Maybe FilePath -> FilePath

-- | An exception-throwing IO action that reads and validates the specified
--   CSV rules file (which may include other rules files).
readRules :: FilePath -> ExceptT String IO CsvRules

-- | Read the encoding specified by the encoding rule, if any. Or
--   throw an error if an unrecognised encoding is specified.
rulesEncoding :: CsvRules -> ExceptT String IO (Maybe DynEncoding)

-- | Read a Journal from the given CSV data (and filename, used for error
--   messages), or return an error. Proceed as follows:
--   
--   
--   
- Conversion rules are provided, or they are parsed from the
--   specified rules file, or from the default rules file for the CSV data
--   file. If rules parsing fails, or the required rules file does not
--   exist, throw an error.
--   
- Parse the CSV data using the rules, or throw an error.
--   
- Convert the CSV records to hledger transactions using the
--   rules.
--   
- Return the transactions as a Journal.
--   
readJournalFromCsv :: CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO Journal

-- | Detect from a balance assertion's syntax (=, ==, =*, ==*) whether it
--   is (a) total (multi-commodity) and (b) subaccount-inclusive. Returns
--   nothing if invalid syntax was provided.
parseBalanceAssertionType :: String -> Maybe (Bool, Bool)
tests_RulesReader :: TestTree
instance GHC.Classes.Eq Hledger.Read.RulesReader.ConditionalBlock
instance GHC.Classes.Eq Hledger.Read.RulesReader.CsvRules
instance GHC.Classes.Eq Hledger.Read.RulesReader.Matcher
instance GHC.Classes.Eq Hledger.Read.RulesReader.MatcherPrefix
instance Text.Megaparsec.Error.ShowErrorComponent GHC.Internal.Base.String
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.ConditionalBlock
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.CsvRules
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.Matcher
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.MatcherPrefix

-- | A reader for CSV (character-separated) data. This also reads a rules
--   file to help interpret the CSV data.
module Hledger.Read.CsvReader
reader :: forall (m :: Type -> Type). MonadIO m => SepFormat -> Reader m
tests_CsvReader :: TestTree

-- | A reader for hledger's journal file format
--   (http://hledger.org/hledger.html#the-journal-file). hledger's
--   journal format is a compatible subset of c++ ledger's
--   (http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format), so
--   this reader should handle many ledger files as well. Example:
--   
--   
--   2012/3/24 gift
--       expenses:gifts  $10
--       assets:cash
--   
--   
--   Journal format supports the include directive which can read files in
--   other formats, so the other file format readers need to be importable
--   and invocable here.
--   
--   Some important parts of journal parsing are therefore kept in
--   Hledger.Read.Common, to avoid import cycles.
module Hledger.Read.JournalReader

-- | 
--   findReader mformat mpath
--   
--   
--   Find the reader named by mformat, if provided. ("ssv" and
--   "tsv" are recognised as alternate names for the csv reader, which also
--   handles those formats.) Or, if a file path is provided, find the first
--   reader that handles its file extension, if any.
findReader :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | Separate a file path and its reader prefix, if any.
--   
--   
--   >>> splitReaderPrefix "csv:-"
--   (Just csv,"-")
--   
splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)
reader :: forall (m :: Type -> Type). MonadIO m => Reader m

-- | Given a parser to ParsedJournal, input options, file path and content:
--   run the parser on the content, and finalise the result to get a
--   Journal; or throw an error.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)

-- | Run a journal parser in some monad. See also: parseWithState.
rjp :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
runErroringJournalParser :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either HledgerParseErrors a))

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName

-- | A journal parser. Accumulates and returns a ParsedJournal,
--   which should be finalised/validated before use.
--   
--   
--   >>> rejp (journalp definputopts <* eof) "2015/1/1\n a  0\n"
--   Right (Right Journal (unknown) with 1 transactions, 1 accounts)
--   
journalp :: forall (m :: Type -> Type). MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal

-- | Parse any journal directive and update the parse state accordingly. Cf
--   http://hledger.org/hledger.html#directives,
--   http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives
directivep :: forall (m :: Type -> Type). MonadIO m => InputOpts -> ErroringJournalParser m ()
defaultyeardirectivep :: forall (m :: Type -> Type). JournalParser m ()
marketpricedirectivep :: forall (m :: Type -> Type). JournalParser m PriceDirective

-- | Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format. Slash
--   (/) and period (.) are also allowed as date separators. The year may
--   be omitted if a default year has been set. Seconds are optional. The
--   timezone is optional and ignored (the time is always interpreted as a
--   local time). Leading zeroes may be omitted (except in a timezone).
datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime

-- | Parse a date in YYYY-MM-DD format. Slash (/) and period (.) are also
--   allowed as separators. The year may be omitted if a default year has
--   been set. Leading zeroes may be omitted.
datep :: forall (m :: Type -> Type). JournalParser m Day

-- | Parse an account name plus one following space if present (see
--   accountnamep); then apply any parent account prefix and/or account
--   aliases currently in effect, in that order. Ie first add the parent
--   account prefix, then rewrite with aliases. This calls error if any
--   account alias with an invalid regular expression exists. The flag says
--   whether account names may include semicolons; currently account names
--   in journal format may, but account names in timeclock/timedot formats
--   may not.
modifiedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName
tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule
statusp :: forall (m :: Type -> Type). TextParser m Status

-- | A blank or comment line in journal format: a line that's empty or
--   containing only whitespace or whose first non-whitespace character is
--   semicolon, hash, or star. See also emptyorcommentlinep2.
emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m ()

-- | Parse a comment following a journal item, possibly continued on
--   multiple lines, and return the comment text.
--   
--   
--   >>> rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   >>> rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
--   Right "\n\n"
--   
followingcommentp :: forall (m :: Type -> Type). TextParser m Text
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias
tests_JournalReader :: TestTree

-- | This is the entry point to hledger's reading system, which can read
--   Journals from various data formats. Use this module if you want to
--   parse journal data or read journal files. Generally it should not be
--   necessary to import modules below this one.
--   
--   
Journal reading
--   
--   Reading an input file (in journal, csv, timedot, or timeclock
--   format..) involves these steps:
--   
--   
--   
- select an appropriate file format "reader" based on filename
--   extensionfile path prefixfunction parameter. A reader contains
--   a parser and a finaliser (usually journalFinalise).
--   
- run the parser to get a ParsedJournal (this may run additional
--   sub-parsers to parse included files)
--   
- run the finaliser to get a complete Journal, which passes standard
--   checks
--   
- if reading multiple files: merge the per-file Journals into one
--   overall Journal
--   
- if using -s/--strict: run additional strict checks
--   
- if running print --new: save .latest files for each input file.
--   (import also does this, as its final step.)
--   
--   
--   
Journal merging
--   
--   Journal implements the Semigroup class, so two Journals can be merged
--   into one Journal with j1 <> j2. This is implemented by
--   the journalConcat function, whose documentation explains what
--   merging Journals means exactly.
--   
--   
Journal finalising
--   
--   This is post-processing done after parsing an input file, such as
--   inferring missing information, normalising amount styles, checking for
--   errors and so on - a delicate and influential stage of data
--   processing. In hledger it is done by journalFinalise, which
--   converts a preliminary ParsedJournal to a validated, ready-to-use
--   Journal. This is called immediately after the parsing of each input
--   file. It is not called when Journals are merged.
--   
--   
Journal reading API
--   
--   There are three main Journal-reading functions:
--   
--   
--   
- readJournal to read from a Text value. Selects a reader and calls
--   its parser and finaliser, then does strict checking if needed.
--   
- readJournalFile to read one file, or stdin if the file path is
--   -. Uses the file path/file name to help select the reader,
--   calls readJournal, then writes .latest files if needed.
--   
- readJournalFiles to read multiple files. Calls readJournalFile for
--   each file (without strict checking or .latest file writing) then
--   merges the Journals into one, then does strict checking and .latest
--   file writing at the end if needed.
--   
--   
--   Each of these also has an easier variant with ' suffix, which uses
--   default options and has a simpler type signature.
--   
--   One more variant, readJournalFilesAndLatestDates, is like
--   readJournalFiles but exposing the latest transaction date (and how
--   many on the same day) seen for each file. This is used by the import
--   command.
module Hledger.Read

-- | Read the default journal file specified by the environment, with
--   default input options, or raise an error.
defaultJournal :: IO Journal

-- | Like defaultJournal, but return an error message instead of raising an
--   error.
defaultJournalSafely :: IO (Either String Journal)

-- | Like defaultJournal, but use the given input options.
defaultJournalWith :: InputOpts -> IO Journal

-- | Like defaultJournalWith, but return an error message instead of
--   raising an error.
defaultJournalWithSafely :: InputOpts -> IO (Either String Journal)

-- | Get the default journal file path - either $LEDGER_FILE or
--   $HOME/.hledger.journal file.
--   
--   This looks for the LEDGER_FILE environment variable, like Ledger. The
--   value should be a file path, possibly with ~ at the start meaning the
--   current user's home directory. Or the value can be a glob pattern
--   (containing *, ?, [ or {) ), in which case the first matching file
--   path is used. When it's a glob pattern that matches no existing files,
--   an error is raised.
--   
--   If LEDGER_FILE is unset or set to the empty string, this returns a
--   default file path: .hledger.journal in the user's home
--   directory, or if we can't find the user's home directory, in the
--   current directory.
--   
--   The referenced file can be nonexistent.
defaultJournalPath :: IO String

-- | Like defaultJournalPath, but return an error message instead of
--   raising an error.
defaultJournalPathSafely :: IO (Either String String)

-- | Like defaultJournalPath, but also checks that the file exists, and
--   raises an error if it doesn't.
defaultExistingJournalPath :: IO String

-- | Like defaultExistingJournalPath, but returns an error message instead
--   of raising an error.
defaultExistingJournalPathSafely :: IO (Either String String)

-- | If the specified journal file does not exist (and is not "-"), call
--   error with an informative message. (Using "journal file" generically
--   here; it could be in any of hledger's supported formats.)
requireJournalFileExists :: FilePath -> IO ()

-- | Ensure there is a journal file at the given path, creating an empty
--   one if needed. On Windows, also ensure that the path contains no
--   trailing dots which could cause data loss (see
--   isWindowsUnsafeDotPath).
ensureJournalFileExists :: FilePath -> IO ()
journalEnvVar :: String
journalDefaultFilename :: FilePath

-- | The inverse of ExceptT.
runExceptT :: ExceptT e m a -> m (Either e a)

-- | 
--   readJournal iopts mfile txt
--   
--   
--   Read a Journal from some handle, with strict checks if enabled, or
--   return an error message.
--   
--   The reader (data format) is chosen based on, in this order:
--   
--   
--   
- a reader name provided in iopts
--   
- a reader prefix in the mfile path
--   
- a file extension in mfile
--   
--   
--   If none of these is available, or if the reader name is unrecognised,
--   the journal reader is used.
--   
--   If a file path is not provided, "-" is assumed (and may appear in
--   error messages, files output etc, where it will be a slight
--   lie: it will mean "not from a file", not necessarily "from standard
--   input".
readJournal :: InputOpts -> Maybe FilePath -> Handle -> ExceptT String IO Journal

-- | Read a Journal from this file, or from stdin if the file path is -,
--   with strict checks if enabled, or return an error message. XXX or,
--   calls error if the file does not exist.
--   
--   (Note strict checks are disabled temporarily here when this is called
--   by readJournalFiles). The file path can have a READER: prefix.
--   
--   The reader (data format) to use is determined from (in priority
--   order): the mformat_ specified in the input options, if any;
--   the file path's READER: prefix, if any; a recognised file name
--   extension. if none of these identify a known reader, the journal
--   reader is used.
--   
--   The input options can also configure balance assertion checking,
--   automated posting generation, a rules file for converting CSV data,
--   etc.
--   
--   If using --new, and if latest-file writing is enabled in input
--   options, and not deferred by readJournalFiles, and after passing
--   strict checks if enabled, a .latest.FILE file will be created/updated
--   (for the main file only, not for included files), to remember the
--   latest transaction date processed.
readJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal

-- | Like readJournalFile, but if the file does not exist, returns an empty
--   journal with the file path set. This is useful for commands like add
--   and import that need to work with a potentially non-existent journal
--   file.
readPossibleJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal

-- | Like readJournalFiles, but if the first file does not exist, provides
--   an empty journal with that file path set. Other files must exist as
--   normal. This is useful for commands like add and import that write to
--   the first file, which might not exist yet, while also reading other
--   files for completions etc.
readPossibleJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal

-- | Read a Journal from each specified file path (using
--   readJournalFile) and combine them into one; or return the
--   first error message.
--   
--   Combining Journals means concatenating them, basically. The parse
--   state resets at the start of each file, which means that directives
--   & aliases do not affect subsequent sibling or parent files. They
--   do affect included child files though. Also the final parse state
--   saved in the Journal does span all files.
--   
--   Strict checks, if enabled, are temporarily deferred until all files
--   are read, to ensure they see the whole journal, and/or to avoid
--   redundant work. (Some checks, like assertions and ordereddates, might
--   still be doing redundant work ?)
--   
--   Writing .latest files, if enabled, is also deferred till the end, and
--   is done only if strict checks pass.
readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal
readJournalFilesAndLatestDates :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO (Journal, [LatestDatesForFile])

-- | An easy version of readJournal which assumes default options,
--   and fails in the IO monad.
readJournal' :: Handle -> IO Journal

-- | An even easier version of readJournal' which takes a Text
--   instead of a Handle.
readJournal'' :: Text -> IO Journal

-- | An easy version of readJournalFile which assumes default
--   options, and fails in the IO monad.
readJournalFile' :: PrefixedFilePath -> IO Journal

-- | An easy version of readJournalFiles' which assumes default
--   options, and fails in the IO monad.
readJournalFiles' :: [PrefixedFilePath] -> IO Journal

-- | Extract ExceptT to the IO monad, failing with an error message if
--   necessary.
orDieTrying :: MonadIO m => ExceptT String m a -> m a

-- | Save the given latest date(s) seen in the given data FILE, in a hidden
--   file named .latest.FILE, creating it if needed. Unless no latest dates
--   are provided, in which case do nothing.
saveLatestDates :: LatestDates -> FilePath -> IO ()

-- | Save each file's latest dates.
saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()

-- | Does any part of this path contain non-. characters and end with a . ?
--   Such paths are not safe to use on Windows (cf #1056).
isWindowsUnsafeDotPath :: FilePath -> Bool
tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule

-- | 
--   findReader mformat mpath
--   
--   
--   Find the reader named by mformat, if provided. ("ssv" and
--   "tsv" are recognised as alternate names for the csv reader, which also
--   handles those formats.) Or, if a file path is provided, find the first
--   reader that handles its file extension, if any.
findReader :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | Separate a file path and its reader prefix, if any.
--   
--   
--   >>> splitReaderPrefix "csv:-"
--   (Just csv,"-")
--   
splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)
tests_Read :: TestTree
instance GHC.Internal.Show.Show Hledger.Read.LatestDatesForFile

-- | This is the root of the hledger-lib package and the
--   Hledger.* module hierarchy. hledger-lib is the core engine
--   used by various hledger UIs and tools, providing the main data types,
--   file format parsers, reporting logic, and utilities.
--   
--   SPDX-License-Identifier: GPL-3.0-or-later Copyright (c) 2007-2025
--   (each year in this range) Simon Michael simon@joyful.com and
--   contributors.
--   
--   This program is free software: you can redistribute it and/or modify
--   it under the terms of the GNU General Public License as published by
--   the Free Software Foundation, either version 3 of the License, or (at
--   your option) any later version.
--   
--   This program is distributed in the hope that it will be useful, but
--   WITHOUT ANY WARRANTY; without even the implied warranty of
--   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
--   General Public License for more details. You should have received a
--   copy of the GNU General Public License along with this program. If
--   not, see https://www.gnu.org/licenses/.
module Hledger
tests_Hledger :: TestTree
