{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}

module Hledger.Cli.Commands.Import (
  importmode
 ,importcmd
)
where

import Control.Monad
import Data.List
import Data.Text.IO qualified as T
import System.Console.CmdArgs.Explicit
import Text.Printf

import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Commands.Add (journalAddTransaction, journalFileTextAfterAppends)
import Hledger.Cli.Utils (journalCheckChange)
import Hledger.Cli.Commands.Get (getcmd)
import Hledger.Cli.Commands.Print (layoutFlag, layoutFromRawOpts)
import System.Directory (doesDirectoryExist, listDirectory)
import System.IO (stderr)
import System.FilePath (takeDirectory, takeFileName, (</>))

importmode :: Mode RawOpts
importmode = FilePath
-> [Flag RawOpts]
-> [(FilePath, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Import.txt")
  [[FilePath] -> (RawOpts -> RawOpts) -> FilePath -> Flag RawOpts
forall a. [FilePath] -> (a -> a) -> FilePath -> Flag a
flagNone [FilePath
"get",FilePath
"g"] (FilePath -> RawOpts -> RawOpts
setboolopt FilePath
"get") FilePath
"fetch new data first by running the get command"
  ,[FilePath] -> (RawOpts -> RawOpts) -> FilePath -> Flag RawOpts
forall a. [FilePath] -> (a -> a) -> FilePath -> Flag a
flagNone [FilePath
"catchup"] (FilePath -> RawOpts -> RawOpts
setboolopt FilePath
"catchup") FilePath
"just mark all transactions as already imported"
  ,[FilePath] -> (RawOpts -> RawOpts) -> FilePath -> Flag RawOpts
forall a. [FilePath] -> (a -> a) -> FilePath -> Flag a
flagNone [FilePath
"dry-run"] (FilePath -> RawOpts -> RawOpts
setboolopt FilePath
"dry-run") FilePath
"just show the transactions to be imported"
  ,Flag RawOpts
layoutFlag
  ]
  [(FilePath, [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ FilePath -> Arg RawOpts
argsFlag FilePath
"[-f JOURNALFILE] [DATAFILES]")

importcmd :: CliOpts -> Journal -> IO ()
importcmd opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts,inputopts_ :: CliOpts -> InputOpts
inputopts_=InputOpts
iopts} Journal
j = do
  -- With -g/--get, run the get command first to fetch new data before importing.
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (FilePath -> RawOpts -> Bool
boolopt FilePath
"get" RawOpts
rawopts) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ CliOpts -> Journal -> IO ()
getcmd CliOpts
opts Journal
j
  -- XXX could be helpful to show the last-seen date, and number of old transactions, too
  let
    argfiles :: [FilePath]
argfiles = FilePath -> RawOpts -> [FilePath]
listofstringopt FilePath
"args" RawOpts
rawopts
    rulesdir :: FilePath
rulesdir = FilePath -> FilePath
takeDirectory (Journal -> FilePath
journalFilePath Journal
j) FilePath -> FilePath -> FilePath
</> FilePath
rulesDirName
    catchup :: Bool
catchup = FilePath -> RawOpts -> Bool
boolopt FilePath
"catchup" RawOpts
rawopts
    dryRun :: Bool
dryRun = FilePath -> RawOpts -> Bool
boolopt FilePath
"dry-run" RawOpts
rawopts
    postinglayout :: PostingLayout
postinglayout = RawOpts -> PostingLayout
layoutFromRawOpts RawOpts
rawopts
    combinedStyles :: Maybe (Map CommoditySymbol AmountStyle)
combinedStyles = 
      let
        maybeInputStyles :: Maybe (Map CommoditySymbol AmountStyle)
maybeInputStyles = BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_ (BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle))
-> (InputOpts -> BalancingOpts)
-> InputOpts
-> Maybe (Map CommoditySymbol AmountStyle)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InputOpts -> BalancingOpts
balancingopts_ (InputOpts -> Maybe (Map CommoditySymbol AmountStyle))
-> InputOpts -> Maybe (Map CommoditySymbol AmountStyle)
forall a b. (a -> b) -> a -> b
$ InputOpts
iopts
        inferredStyles :: Map CommoditySymbol AmountStyle
inferredStyles =  Journal -> Map CommoditySymbol AmountStyle
journalCommodityStyles Journal
j
      in
        case Maybe (Map CommoditySymbol AmountStyle)
maybeInputStyles of
          Maybe (Map CommoditySymbol AmountStyle)
Nothing -> Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
forall a. a -> Maybe a
Just Map CommoditySymbol AmountStyle
inferredStyles
          Just Map CommoditySymbol AmountStyle
inputStyles -> Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
forall a. a -> Maybe a
Just (Map CommoditySymbol AmountStyle
 -> Maybe (Map CommoditySymbol AmountStyle))
-> Map CommoditySymbol AmountStyle
-> Maybe (Map CommoditySymbol AmountStyle)
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle
inputStyles Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AmountStyle
forall a. Semigroup a => a -> a -> a
<> Map CommoditySymbol AmountStyle
inferredStyles

    -- Note: inputOptsSetJournalDir is needed here because this is a secondary
    -- read after the main journal has been loaded; without it the CSV rules
    -- reader would fall back to the rules file's directory for source/archive
    -- lookups instead of the main journal's data/ directory.
    iopts' :: InputOpts
iopts' = Journal -> InputOpts -> InputOpts
inputOptsSetJournalDir Journal
j (InputOpts -> InputOpts) -> InputOpts -> InputOpts
forall a b. (a -> b) -> a -> b
$ InputOpts
iopts{
      new_=True,  -- read only new transactions since last time
      new_save_=False,  -- defer saving .latest files until the end
      strict_=False,  -- defer strict checks until the end
      _importing=True,  -- let the CSV rules reader do its import-specific things (oldest source file, archiving)
      _dryrun=dryRun,   -- but with --dry-run, archive nothing, remove no data file, and run no data generating command
      balancingopts_=defbalancingopts{commodity_styles_= combinedStyles}  -- use amount styles from both when balancing txns
      }

  inputfiles <- case [FilePath]
argfiles of
    [] -> FilePath -> IO [FilePath]
discoverRulesFiles FilePath
rulesdir
    [FilePath]
fs -> [FilePath] -> IO [FilePath]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [FilePath]
fs
  let inputstr = FilePath -> [FilePath] -> FilePath
forall a. [a] -> [[a]] -> [a]
intercalate FilePath
", " ([FilePath] -> FilePath) -> [FilePath] -> FilePath
forall a b. (a -> b) -> a -> b
$ (FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (FilePath -> FilePath
quoteIfNeeded(FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
.FilePath -> FilePath
takeFileName) [FilePath]
inputfiles

  case inputfiles of
    [] -> FilePath -> IO ()
forall a. FilePath -> a
error' (FilePath -> IO ()) -> FilePath -> IO ()
forall a b. (a -> b) -> a -> b
$  -- PARTIAL:
      FilePath
"please specify one or more data files to import from,\n"
      FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
"or add .rules files in a rules/ directory next to the journal."
    [FilePath]
fs -> do
      enewjandlatestdatesforfiles <- ExceptT FilePath IO (Journal, [LatestDatesForFile])
-> IO (Either FilePath (Journal, [LatestDatesForFile]))
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT FilePath IO (Journal, [LatestDatesForFile])
 -> IO (Either FilePath (Journal, [LatestDatesForFile])))
-> ExceptT FilePath IO (Journal, [LatestDatesForFile])
-> IO (Either FilePath (Journal, [LatestDatesForFile]))
forall a b. (a -> b) -> a -> b
$ InputOpts
-> [FilePath]
-> ExceptT FilePath IO (Journal, [LatestDatesForFile])
readJournalFilesAndLatestDates InputOpts
iopts' [FilePath]
fs
      case enewjandlatestdatesforfiles of
        Left FilePath
err -> FilePath -> IO ()
forall a. FilePath -> a
error' FilePath
err
        Right (Journal
newj, [LatestDatesForFile]
latestdatesforfiles) ->
          case (Transaction -> Day) -> [Transaction] -> [Transaction]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Transaction -> Day
tdate ([Transaction] -> [Transaction]) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
newj of
            [] -> Handle -> FilePath -> FilePath -> IO ()
forall r. HPrintfType r => Handle -> FilePath -> r
hPrintf Handle
stderr FilePath
"no new transactions found in %s\n" FilePath
inputstr

            [Transaction]
newts | Bool
catchup ->
              if Bool
dryRun
                then Handle -> FilePath -> Int -> IO ()
forall r. HPrintfType r => Handle -> FilePath -> r
hPrintf Handle
stderr FilePath
"would skip %d new transactions (dry run)\n\n" ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
newts)
                else do
                  Handle -> FilePath -> FilePath -> Int -> IO ()
forall r. HPrintfType r => Handle -> FilePath -> r
hPrintf Handle
stderr FilePath
"marked %s as caught up, skipping %d transactions\n\n" FilePath
inputstr ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
newts)
                  [LatestDatesForFile] -> IO ()
saveLatestDatesForFiles [LatestDatesForFile]
latestdatesforfiles

            [Transaction]
newts -> do
              if Bool
dryRun
              then do
                -- show txns to be imported
                Handle -> FilePath -> Int -> FilePath -> IO ()
forall r. HPrintfType r => Handle -> FilePath -> r
hPrintf Handle
stderr FilePath
"would import %d new transactions from %s:\n\n" ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
newts) FilePath
inputstr
                (Transaction -> IO ()) -> [Transaction] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (CommoditySymbol -> IO ()
T.putStr (CommoditySymbol -> IO ())
-> (Transaction -> CommoditySymbol) -> Transaction -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PostingLayout -> Transaction -> CommoditySymbol
showTransactionWithLayout PostingLayout
postinglayout) [Transaction]
newts

                -- then check that the journal would be readable with them added
                IO ()
checkImport

              else do
                -- first check that the journal would be readable with them added
                IO ()
checkImport

                -- then append the transactions to the main journal file.
                -- XXX This writes unix line endings (\n), some at least,
                -- even if the file uses dos line endings (\r\n), which could leave
                -- mixed line endings in the file. See also writeFileWithBackupIfChanged.
                (Journal -> Transaction -> IO Journal)
-> Journal -> [Transaction] -> IO ()
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m ()
foldM_ (Journal -> CliOpts -> Transaction -> IO Journal
`journalAddTransaction` CliOpts
opts) Journal
j [Transaction]
newts  -- gets forced somehow.. (how ?)

                Handle -> FilePath -> Int -> FilePath -> FilePath -> IO ()
forall r. HPrintfType r => Handle -> FilePath -> r
hPrintf Handle
stderr FilePath
"imported %d new transactions from %s to %s\n" ([Transaction] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Transaction]
newts) FilePath
inputstr (Journal -> FilePath
journalFilePath Journal
j)

                -- and if we got this far, update each file's .latest file
                [LatestDatesForFile] -> IO ()
saveLatestDatesForFiles [LatestDatesForFile]
latestdatesforfiles

              where
                -- Check that the journal would still be readable with the new transactions
                -- appended to the main file, as the next read would check it, with these options
                -- (balancing, balance assertions, lots, strict checks if enabled..). Or stop with its error.
                -- (journalAddTransaction appends them with appendToJournalFileOrStdout.)
                checkImport :: IO ()
checkImport = do
                  let f :: FilePath
f = Journal -> FilePath
journalFilePath Journal
j
                  newtxt <- FilePath -> [CommoditySymbol] -> IO CommoditySymbol
journalFileTextAfterAppends FilePath
f ([CommoditySymbol] -> IO CommoditySymbol)
-> [CommoditySymbol] -> IO CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (Transaction -> CommoditySymbol)
-> [Transaction] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (PostingLayout -> Transaction -> CommoditySymbol
showTransactionWithLayout PostingLayout
postinglayout) [Transaction]
newts
                  runExceptT (journalCheckChange opts f newtxt) >>= either error' (const $ return ())

-- | List the .rules files in the given directory, in alphabetical order,
-- skipping files whose name begins with '.' (hidden) or '_'
-- (disabled, or shared rules included by others).
-- Returns an empty list if the directory does not exist.
discoverRulesFiles :: FilePath -> IO [FilePath]
discoverRulesFiles :: FilePath -> IO [FilePath]
discoverRulesFiles FilePath
dir = do
  exists <- FilePath -> IO Bool
doesDirectoryExist FilePath
dir
  if not exists
    then return []
    else do
      names <- listDirectory dir
      return $ sort [ dir </> n | n <- names
                                , ".rules" `isSuffixOf` n
                                , not (any (`isPrefixOf` n) [".", "_"]) ]