{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-|

The @.latest@ mechanism: a per-input-file record of the latest transaction
date(s) seen on the previous read, used by @hledger import@ (and any reader
called with @new_=True@) to filter out already-seen transactions.

For an input file @F@, the latest dates are kept in a @.latest.F@ hidden file
in @F@'s directory. They are written after a successful import and read on the
next one. The CSV rules reader's @archive@ rule also consults these to decide
whether a fresh archive is warranted.

These helpers live in their own module so both the high-level reader
('Hledger.Read') and the low-level CSV rules reader ('Hledger.Read.RulesReader')
can use them without a module-graph cycle.

-}

module Hledger.Read.LatestDates (
  LatestDates,
  LatestDatesForFile(..),
  latestDates,
  latestDatesFileFor,
  previousLatestDates,
  saveLatestDates,
  saveLatestDatesForFiles,
  journalFilterSinceLatestDates,
) where

import Control.Monad (forM, when)
import Data.List (group, sort, sortBy)
import Data.Maybe (catMaybes)
import Data.Ord (comparing)
import Data.Text qualified as T
import Data.Text.IO qualified as T
import Data.Time (Day)
import Safe (headDef)
import System.Directory (doesFileExist)
import System.FilePath (splitFileName, (</>), (<.>))
import Text.Printf (printf)

import Hledger.Data.Dates (parsedate, showDate)
import Hledger.Data.Types (Journal(..), Transaction(..))
import Hledger.Utils (error', readFileStrictly)

-- | One or more dates of the same kind, eg the latest transaction date(s) read from a file.
type LatestDates = [Day]

-- | The path of an input file, and its current 'LatestDates'.
data LatestDatesForFile = LatestDatesForFile FilePath LatestDates
  deriving Int -> LatestDatesForFile -> String -> String
[LatestDatesForFile] -> String -> String
LatestDatesForFile -> String
(Int -> LatestDatesForFile -> String -> String)
-> (LatestDatesForFile -> String)
-> ([LatestDatesForFile] -> String -> String)
-> Show LatestDatesForFile
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> LatestDatesForFile -> String -> String
showsPrec :: Int -> LatestDatesForFile -> String -> String
$cshow :: LatestDatesForFile -> String
show :: LatestDatesForFile -> String
$cshowList :: [LatestDatesForFile] -> String -> String
showList :: [LatestDatesForFile] -> String -> String
Show

-- | Get all instances of the latest date in an unsorted list of dates.
-- Ie, if the latest date appears once, return it in a one-element list,
-- if it appears three times (anywhere), return three of it.
latestDates :: [Day] -> LatestDates
latestDates :: LatestDates -> LatestDates
latestDates = {-# HLINT ignore "Avoid reverse" #-}
  LatestDates -> [LatestDates] -> LatestDates
forall a. a -> [a] -> a
headDef [] ([LatestDates] -> LatestDates)
-> (LatestDates -> [LatestDates]) -> LatestDates -> LatestDates
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [LatestDates] -> [LatestDates]
forall a. Int -> [a] -> [a]
take Int
1 ([LatestDates] -> [LatestDates])
-> (LatestDates -> [LatestDates]) -> LatestDates -> [LatestDates]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LatestDates -> [LatestDates]
forall a. Eq a => [a] -> [[a]]
group (LatestDates -> [LatestDates])
-> (LatestDates -> LatestDates) -> LatestDates -> [LatestDates]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LatestDates -> LatestDates
forall a. [a] -> [a]
reverse (LatestDates -> LatestDates)
-> (LatestDates -> LatestDates) -> LatestDates -> LatestDates
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LatestDates -> LatestDates
forall a. Ord a => [a] -> [a]
sort

-- | Where to save latest transaction dates for the given file path: @.latest.FILE@
-- in @FILE@'s directory.
latestDatesFileFor :: FilePath -> FilePath
latestDatesFileFor :: String -> String
latestDatesFileFor String
f = String
dir String -> String -> String
</> String
".latest" String -> String -> String
<.> String
fname
  where
    (String
dir, String
fname) = String -> (String, String)
splitFileName String
f

-- | 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 ()
saveLatestDates :: LatestDates -> String -> IO ()
saveLatestDates LatestDates
dates String
f = Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ LatestDates -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null LatestDates
dates) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
  String -> Text -> IO ()
T.writeFile (String -> String
latestDatesFileFor String
f) (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Day -> Text) -> LatestDates -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Day -> Text
showDate LatestDates
dates

-- | Save each file's latest dates.
saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()
saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()
saveLatestDatesForFiles = (LatestDatesForFile -> IO ()) -> [LatestDatesForFile] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\(LatestDatesForFile String
f LatestDates
ds) -> LatestDates -> String -> IO ()
saveLatestDates LatestDates
ds String
f)

-- | What were the latest transaction dates seen the last time this
-- journal file was read ? If there were multiple transactions on the
-- latest date, that number of dates is returned, otherwise just one.
-- Or none if no transactions were read, or if latest dates info is not
-- available for this file.
previousLatestDates :: FilePath -> IO LatestDates
previousLatestDates :: String -> IO LatestDates
previousLatestDates String
f = do
  let latestfile :: String
latestfile = String -> String
latestDatesFileFor String
f
  exists <- String -> IO Bool
doesFileExist String
latestfile
  t <- if exists then readFileStrictly latestfile else return T.empty
  let nls = [Int] -> [Text] -> [(Int, Text)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
1::Int ..] ([Text] -> [(Int, Text)]) -> [Text] -> [(Int, Text)]
forall a b. (a -> b) -> a -> b
$ Text -> [Text]
T.lines Text
t
  fmap catMaybes $ forM nls $ \(Int
n,Text
l) -> do
    let s :: String
s = Text -> String
T.unpack (Text -> String) -> Text -> String
forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip Text
l
    case (String
s, String -> Maybe Day
parsedate String
s) of
      (String
"", Maybe Day
_)       -> Maybe Day -> IO (Maybe Day)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Day
forall a. Maybe a
Nothing
      (String
_,  Maybe Day
Nothing) -> String -> IO (Maybe Day)
forall a. String -> a
error' (String -> String -> Int -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d: invalid date: \"%s\"" String
latestfile Int
n String
s)
      (String
_,  Just Day
d)  -> Maybe Day -> IO (Maybe Day)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Day -> IO (Maybe Day)) -> Maybe Day -> IO (Maybe Day)
forall a b. (a -> b) -> a -> b
$ Day -> Maybe Day
forall a. a -> Maybe a
Just Day
d

-- | Given zero or more latest dates (all the same, representing the
-- latest previously seen transaction date, and how many transactions
-- were seen on that date), remove transactions with earlier dates
-- from the journal, and the same number of transactions on the
-- latest date, if any, leaving only transactions that we can assume
-- are newer. Also returns the new latest dates of the new journal.
journalFilterSinceLatestDates :: LatestDates -> Journal -> (Journal, LatestDates)
journalFilterSinceLatestDates :: LatestDates -> Journal -> (Journal, LatestDates)
journalFilterSinceLatestDates [] Journal
j       = (Journal
j,  LatestDates -> LatestDates
latestDates (LatestDates -> LatestDates) -> LatestDates -> LatestDates
forall a b. (a -> b) -> a -> b
$ (Transaction -> Day) -> [Transaction] -> LatestDates
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Day
tdate ([Transaction] -> LatestDates) -> [Transaction] -> LatestDates
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j)
journalFilterSinceLatestDates ds :: LatestDates
ds@(Day
d:LatestDates
_) Journal
j = (Journal
j', LatestDates
ds')
  where
    samedateorlaterts :: [Transaction]
samedateorlaterts     = (Transaction -> Bool) -> [Transaction] -> [Transaction]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>= Day
d)(Day -> Bool) -> (Transaction -> Day) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Transaction -> Day
tdate) ([Transaction] -> [Transaction]) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j
    ([Transaction]
samedatets, [Transaction]
laterts) = (Transaction -> Bool)
-> [Transaction] -> ([Transaction], [Transaction])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span ((Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
== Day
d)(Day -> Bool) -> (Transaction -> Day) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Transaction -> Day
tdate) ([Transaction] -> ([Transaction], [Transaction]))
-> [Transaction] -> ([Transaction], [Transaction])
forall a b. (a -> b) -> a -> b
$ (Transaction -> Transaction -> Ordering)
-> [Transaction] -> [Transaction]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((Transaction -> Day) -> Transaction -> Transaction -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing Transaction -> Day
tdate) [Transaction]
samedateorlaterts
    newsamedatets :: [Transaction]
newsamedatets         = Int -> [Transaction] -> [Transaction]
forall a. Int -> [a] -> [a]
drop (LatestDates -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length LatestDates
ds) [Transaction]
samedatets
    j' :: Journal
j'                    = Journal
j{jtxns=newsamedatets++laterts}
    ds' :: LatestDates
ds'                   = LatestDates -> LatestDates
latestDates (LatestDates -> LatestDates) -> LatestDates -> LatestDates
forall a b. (a -> b) -> a -> b
$ (Transaction -> Day) -> [Transaction] -> LatestDates
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Day
tdate ([Transaction] -> LatestDates) -> [Transaction] -> LatestDates
forall a b. (a -> b) -> a -> b
$ [Transaction]
samedatets[Transaction] -> [Transaction] -> [Transaction]
forall a. [a] -> [a] -> [a]
++[Transaction]
laterts