{-|

Various options to use when reading journal files.
Similar to CliOptions.inputflags, simplifies the journal-reading functions.

-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Read.InputOptions (
-- * Types and helpers for input options
  InputOpts(..)
, HasInputOpts(..)
, definputopts
, fileOverride
, inputOptsSetJournalDir
, forecastPeriod
) where

import Control.Applicative ((<|>))
import Data.Map qualified as M
import Data.Text (Text)
import Data.Time (Day, addDays)
import System.Directory (canonicalizePath)
import System.FilePath (takeDirectory)

import Hledger.Data.Types
import Hledger.Data.Journal (journalEndDate, journalFilePath)
import Hledger.Data.Dates (nulldate, nulldatespan)
import Hledger.Data.Balancing (BalancingOpts(..), HasBalancingOpts(..), defbalancingopts)
import Hledger.Utils (dbg2, makeHledgerClassyLenses)

data InputOpts = InputOpts {
     -- files_             :: [FilePath]
     InputOpts -> Maybe StorageFormat
mformat_           :: Maybe StorageFormat  -- ^ a file/storage format to try, unless overridden
                                                --   by a filename prefix. Nothing means try all.
    ,InputOpts -> Maybe FilePath
mrules_file_       :: Maybe FilePath       -- ^ a conversion rules file to use (when reading CSV)
    ,InputOpts -> [FilePath]
aliases_           :: [String]             -- ^ account name aliases to apply
    ,InputOpts -> Bool
anon_              :: Bool                 -- ^ do light obfuscation of the data ? Now corresponds to --obfuscate, not the old --anon flag.
    ,InputOpts -> Bool
new_               :: Bool                 -- ^ read only new transactions since this file was last read ?
    ,InputOpts -> Bool
new_save_          :: Bool                 -- ^ save latest new transactions state for next time ?
    ,InputOpts -> FilePath
pivot_             :: String               -- ^ use the given field's value as the account name
    ,InputOpts -> Maybe DateSpan
forecast_          :: Maybe DateSpan       -- ^ span in which to generate forecast transactions
    ,InputOpts -> Bool
verbose_tags_      :: Bool                 -- ^ add user-visible tags when generating/modifying transactions & postings ?
    ,InputOpts -> DateSpan
reportspan_        :: DateSpan             -- ^ a dirty hack keeping the query dates in InputOpts. This rightfully lives in ReportSpec, but is duplicated here.
    ,InputOpts -> Bool
auto_              :: Bool                 -- ^ generate extra postings according to auto posting rules ?
    ,InputOpts -> Bool
infer_equity_      :: Bool                 -- ^ infer equity conversion postings from costs ?
    ,InputOpts -> Bool
infer_costs_       :: Bool                 -- ^ infer costs from equity conversion postings ? distinct from BalancingOpts{infer_balancing_costs_}
    ,InputOpts -> Bool
ignore_lots_       :: Bool                 -- ^ skip lot tracking and its checks, silencing lot errors ? (basic lot inference still runs, leniently, so lot entries balance)
    ,InputOpts -> BalancingOpts
balancingopts_     :: BalancingOpts        -- ^ options for transaction balancing
    ,InputOpts -> Bool
strict_            :: Bool                 -- ^ do extra correctness checks ?
    ,InputOpts -> Bool
_defer             :: Bool                 -- ^ internal flag: postpone checks, because we are processing multiple files ?
    ,InputOpts -> Bool
_importing         :: Bool                 -- ^ internal flag: is this the @import@ command reading its data files ?
                                                --   Enables the CSV rules reader's import-specific behaviour: preferring the
                                                --   oldest file matched by a @source@ glob, and honouring the @archive@ rule.
                                                --   Set by 'importcmd'; other reads should leave it off.
    ,InputOpts -> Bool
_dryrun            :: Bool                 -- ^ internal flag: is this a @import --dry-run@ command ?
                                                --   If set, the CSV rules reader will never archive or remove a data file.
    ,InputOpts -> Bool
_scanfiles         :: Bool                 -- ^ internal flag: are we just finding the files read (for the files command) ?
                                                --   If set, files are parsed only to find the files they include or use:
                                                --   data is not converted or finalised (balanced, checked), source commands are not run,
                                                --   and an included file which is missing (or a glob matching nothing) is recorded, not an error.
    ,InputOpts -> Bool
_forecastOnlyForDisplay :: Bool        -- ^ internal flag: are forecast transactions being generated only so they can be shown on request
                                                --   (as hledger-ui always does), not because the user asked for them with --forecast ?
                                                --   If so, assert rules ignore them, so they pass or fail as they do without --forecast.
    ,InputOpts -> Day
_ioDay             :: Day                  -- ^ today's date, for use with forecast transactions  XXX this duplicates _rsDay, and should eventually be removed when it's not needed anymore.
    ,InputOpts -> Bool
_oldtimeclock      :: Bool                 -- ^ parse with the old timeclock pairing rules?
    ,InputOpts -> Maybe FilePath
_journaldir        :: Maybe FilePath       -- ^ The main journal file's directory. Used eg by the CSV rules reader to locate the
                                                --   journal's @data/@ directory. Set by the CLI entry points 'withJournal',
                                                --   'withPossibleJournal', and 'journalReload'.
                                                --   If you do a further 'readJournalFile' / 'readJournalFiles' call after a
                                                --   journal has been loaded (eg as @import@ does), apply 'inputOptsSetJournalDir'
                                                --   to its 'InputOpts' so the CSV rules reader can find the right @data/@.
                                                --   Otherwise, the CSV rules reader falls back to the rules file's own directory.
    ,InputOpts -> Map FilePath Text
_fileoverrides     :: M.Map FilePath Text  -- ^ internal: replacement content for some files, keyed by canonical path
                                                --   (see 'canonicalizePath'), with \n line endings. When the reader would read
                                                --   one of these files (as a journal file or an included file), it reads this text
                                                --   instead, and the file need not exist. Used to check a change to a file before
                                                --   writing it (see @journalCheckChange@ in hledger's Hledger.Cli.Utils).
 } deriving (InputOpts -> InputOpts -> Bool
(InputOpts -> InputOpts -> Bool)
-> (InputOpts -> InputOpts -> Bool) -> Eq InputOpts
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: InputOpts -> InputOpts -> Bool
== :: InputOpts -> InputOpts -> Bool
$c/= :: InputOpts -> InputOpts -> Bool
/= :: InputOpts -> InputOpts -> Bool
Eq, Eq InputOpts
Eq InputOpts =>
(InputOpts -> InputOpts -> Ordering)
-> (InputOpts -> InputOpts -> Bool)
-> (InputOpts -> InputOpts -> Bool)
-> (InputOpts -> InputOpts -> Bool)
-> (InputOpts -> InputOpts -> Bool)
-> (InputOpts -> InputOpts -> InputOpts)
-> (InputOpts -> InputOpts -> InputOpts)
-> Ord InputOpts
InputOpts -> InputOpts -> Bool
InputOpts -> InputOpts -> Ordering
InputOpts -> InputOpts -> InputOpts
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: InputOpts -> InputOpts -> Ordering
compare :: InputOpts -> InputOpts -> Ordering
$c< :: InputOpts -> InputOpts -> Bool
< :: InputOpts -> InputOpts -> Bool
$c<= :: InputOpts -> InputOpts -> Bool
<= :: InputOpts -> InputOpts -> Bool
$c> :: InputOpts -> InputOpts -> Bool
> :: InputOpts -> InputOpts -> Bool
$c>= :: InputOpts -> InputOpts -> Bool
>= :: InputOpts -> InputOpts -> Bool
$cmax :: InputOpts -> InputOpts -> InputOpts
max :: InputOpts -> InputOpts -> InputOpts
$cmin :: InputOpts -> InputOpts -> InputOpts
min :: InputOpts -> InputOpts -> InputOpts
Ord, Int -> InputOpts -> ShowS
[InputOpts] -> ShowS
InputOpts -> FilePath
(Int -> InputOpts -> ShowS)
-> (InputOpts -> FilePath)
-> ([InputOpts] -> ShowS)
-> Show InputOpts
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> InputOpts -> ShowS
showsPrec :: Int -> InputOpts -> ShowS
$cshow :: InputOpts -> FilePath
show :: InputOpts -> FilePath
$cshowList :: [InputOpts] -> ShowS
showList :: [InputOpts] -> ShowS
Show)

definputopts :: InputOpts
definputopts :: InputOpts
definputopts = InputOpts
    { mformat_ :: Maybe StorageFormat
mformat_           = Maybe StorageFormat
forall a. Maybe a
Nothing
    , mrules_file_ :: Maybe FilePath
mrules_file_       = Maybe FilePath
forall a. Maybe a
Nothing
    , aliases_ :: [FilePath]
aliases_           = []
    , anon_ :: Bool
anon_              = Bool
False
    , new_ :: Bool
new_               = Bool
False
    , new_save_ :: Bool
new_save_          = Bool
True
    , pivot_ :: FilePath
pivot_             = FilePath
""
    , forecast_ :: Maybe DateSpan
forecast_          = Maybe DateSpan
forall a. Maybe a
Nothing
    , verbose_tags_ :: Bool
verbose_tags_      = Bool
False
    , reportspan_ :: DateSpan
reportspan_        = DateSpan
nulldatespan
    , auto_ :: Bool
auto_              = Bool
False
    , infer_equity_ :: Bool
infer_equity_      = Bool
False
    , infer_costs_ :: Bool
infer_costs_       = Bool
False
    , ignore_lots_ :: Bool
ignore_lots_       = Bool
False
    , balancingopts_ :: BalancingOpts
balancingopts_     = BalancingOpts
defbalancingopts
    , strict_ :: Bool
strict_            = Bool
False
    , _defer :: Bool
_defer             = Bool
False
    , _importing :: Bool
_importing         = Bool
False
    , _dryrun :: Bool
_dryrun            = Bool
False
    , _scanfiles :: Bool
_scanfiles         = Bool
False
    , _forecastOnlyForDisplay :: Bool
_forecastOnlyForDisplay = Bool
False
    , _ioDay :: Day
_ioDay             = Day
nulldate
    , _oldtimeclock :: Bool
_oldtimeclock      = Bool
False
    , _journaldir :: Maybe FilePath
_journaldir        = Maybe FilePath
forall a. Maybe a
Nothing
    , _fileoverrides :: Map FilePath Text
_fileoverrides     = Map FilePath Text
forall k a. Map k a
M.empty
    }

-- | The replacement content for this file in the input options' '_fileoverrides', if any.
-- Standard input ("-") is never overridden. Paths are compared canonically,
-- which is skipped when there are no overrides (the usual case).
fileOverride :: InputOpts -> FilePath -> IO (Maybe Text)
fileOverride :: InputOpts -> FilePath -> IO (Maybe Text)
fileOverride InputOpts{_fileoverrides :: InputOpts -> Map FilePath Text
_fileoverrides=Map FilePath Text
os} FilePath
f
  | Map FilePath Text -> Bool
forall k a. Map k a -> Bool
M.null Map FilePath Text
os Bool -> Bool -> Bool
|| FilePath
f FilePath -> FilePath -> Bool
forall a. Eq a => a -> a -> Bool
== FilePath
"-" = Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Text
forall a. Maybe a
Nothing
  | Bool
otherwise = (FilePath -> Map FilePath Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
`M.lookup` Map FilePath Text
os) (FilePath -> Maybe Text) -> IO FilePath -> IO (Maybe Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO FilePath
canonicalizePath FilePath
f

-- | Set 'InputOpts._journaldir' from a parsed 'Journal' (using @takeDirectory . journalFilePath@).
--
-- Use this when you want to do a further @readJournalFile@ / @readJournalFiles@ call
-- after a journal has been loaded — eg the @hledger import@ command reads the user's rules
-- files in a second pass — so the CSV rules reader can find the journal's @data/@ directory
-- for @source@ lookups and @archive@ saves. Otherwise it will fall back to using the rules
-- file's own directory, which is no longer the preferred place.
--
-- Usage:
--
-- @
-- iopts' = inputOptsSetJournalDir j $ iopts { ...other tweaks... }
-- @
inputOptsSetJournalDir :: Journal -> InputOpts -> InputOpts
inputOptsSetJournalDir :: Journal -> InputOpts -> InputOpts
inputOptsSetJournalDir Journal
j InputOpts
iopts = InputOpts
iopts{_journaldir = Just (takeDirectory (journalFilePath j))}

-- | 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/-p/date:
--   - 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/-p/date:
-- - otherwise 180 days (6 months) from today.
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
forecastPeriod InputOpts
iopts Journal
j = do
    DateSpan requestedStart requestedEnd <- InputOpts -> Maybe DateSpan
forecast_ InputOpts
iopts
    let forecastStart = EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
requestedStart Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe Day -> Maybe Day -> Maybe Day
forall a. Ord a => a -> a -> a
max Maybe Day
mjournalend (EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
reportStart) Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Day -> Maybe Day
forall a. a -> Maybe a
Just (InputOpts -> Day
_ioDay InputOpts
iopts)
        forecastEnd   = EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
requestedEnd Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> EFDay -> Day
fromEFDay (EFDay -> Day) -> Maybe EFDay -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EFDay
reportEnd Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (Day -> Maybe Day
forall a. a -> Maybe a
Just (Day -> Maybe Day) -> Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Integer -> Day -> Day
addDays Integer
180 (Day -> Day) -> Day -> Day
forall a b. (a -> b) -> a -> b
$ InputOpts -> Day
_ioDay InputOpts
iopts)
        mjournalend   = FilePath -> Maybe Day -> Maybe Day
forall a. Show a => FilePath -> a -> a
dbg2 FilePath
"journalEndDate" (Maybe Day -> Maybe Day) -> Maybe Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Bool -> Journal -> Maybe Day
journalEndDate Bool
False Journal
j  -- ignore secondary dates
        DateSpan reportStart reportEnd = reportspan_ iopts
    return . dbg2 "forecastspan" $ DateSpan (Exact <$> forecastStart) (Exact <$> forecastEnd)

-- ** Lenses

makeHledgerClassyLenses ''InputOpts

instance HasBalancingOpts InputOpts where
    balancingOpts :: Lens' InputOpts BalancingOpts
balancingOpts = (BalancingOpts -> f BalancingOpts) -> InputOpts -> f InputOpts
forall c. HasInputOpts c => Lens' c BalancingOpts
Lens' InputOpts BalancingOpts
balancingopts