{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-|

A 'PeriodicTransaction' is a rule describing recurring transactions.

-}
module Hledger.Data.PeriodicTransaction (
    runPeriodicTransaction
  , checkPeriodicTransactionStartDate
)
where

import Data.Function ((&))
import Data.Maybe (isNothing)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Printf

import Hledger.Data.Types
import Hledger.Data.Dates
import Hledger.Data.Amount
import Hledger.Data.Posting (post, commentAddTagNextLine)
import Hledger.Data.Transaction

-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import Hledger.Data.Posting
-- >>> import Hledger.Data.Journal

-- doctest helper, too much hassle to define in the comment
-- XXX duplicates some logic in periodictransactionp
_ptgen :: String -> IO ()
_ptgen String
str = do
  let
    t :: AccountName
t = String -> AccountName
T.pack String
str
    (Interval
i,DateSpan
s) = Day -> AccountName -> (Interval, DateSpan)
parsePeriodExpr' Day
nulldate AccountName
t
  forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (AccountName -> IO ()
T.putStr forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> AccountName
showTransaction) forall a b. (a -> b) -> a -> b
$
    Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
runPeriodicTransaction Bool
True
      PeriodicTransaction
nullperiodictransaction{ ptperiodexpr :: AccountName
ptperiodexpr=AccountName
t , ptspan :: DateSpan
ptspan=DateSpan
s, ptinterval :: Interval
ptinterval=Interval
i, ptpostings :: [Posting]
ptpostings=[AccountName
"a" AccountName -> Amount -> Posting
`post` DecimalRaw Integer -> Amount
usd DecimalRaw Integer
1] }
      DateSpan
nulldatespan

_ptgenspan :: String -> DateSpan -> IO ()
_ptgenspan String
str DateSpan
spn = do
  let
    t :: AccountName
t = String -> AccountName
T.pack String
str
    (Interval
i,DateSpan
s) = Day -> AccountName -> (Interval, DateSpan)
parsePeriodExpr' Day
nulldate AccountName
t
  forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (AccountName -> IO ()
T.putStr forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> AccountName
showTransaction) forall a b. (a -> b) -> a -> b
$
    Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
runPeriodicTransaction Bool
True
      PeriodicTransaction
nullperiodictransaction{ ptperiodexpr :: AccountName
ptperiodexpr=AccountName
t , ptspan :: DateSpan
ptspan=DateSpan
s, ptinterval :: Interval
ptinterval=Interval
i, ptpostings :: [Posting]
ptpostings=[AccountName
"a" AccountName -> Amount -> Posting
`post` DecimalRaw Integer -> Amount
usd DecimalRaw Integer
1] }
      DateSpan
spn

--deriving instance Show PeriodicTransaction
-- for better pretty-printing:
instance Show PeriodicTransaction where
  show :: PeriodicTransaction -> String
show PeriodicTransaction{[Tag]
[Posting]
(SourcePos, SourcePos)
AccountName
Status
Interval
DateSpan
pttags :: PeriodicTransaction -> [Tag]
ptcomment :: PeriodicTransaction -> AccountName
ptdescription :: PeriodicTransaction -> AccountName
ptcode :: PeriodicTransaction -> AccountName
ptstatus :: PeriodicTransaction -> Status
ptsourcepos :: PeriodicTransaction -> (SourcePos, SourcePos)
ptpostings :: [Posting]
pttags :: [Tag]
ptcomment :: AccountName
ptdescription :: AccountName
ptcode :: AccountName
ptstatus :: Status
ptsourcepos :: (SourcePos, SourcePos)
ptspan :: DateSpan
ptinterval :: Interval
ptperiodexpr :: AccountName
ptpostings :: PeriodicTransaction -> [Posting]
ptinterval :: PeriodicTransaction -> Interval
ptspan :: PeriodicTransaction -> DateSpan
ptperiodexpr :: PeriodicTransaction -> AccountName
..} =
    forall r. PrintfType r => String -> r
printf String
"PeriodicTransactionPP {%s, %s, %s, %s, %s, %s, %s, %s, %s, %s}"
      -- Warning, be careful to keep these synced ^ v
      (String
"ptperiodexpr=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show AccountName
ptperiodexpr)
      (String
"ptinterval=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show Interval
ptinterval)
      (String
"ptspan=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show (forall a. Show a => a -> String
show DateSpan
ptspan))
      (String
"ptsourcepos=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show (SourcePos, SourcePos)
ptsourcepos)
      (String
"ptstatus=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show (forall a. Show a => a -> String
show Status
ptstatus))
      (String
"ptcode=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show AccountName
ptcode)
      (String
"ptdescription=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show AccountName
ptdescription)
      (String
"ptcomment=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show AccountName
ptcomment)
      (String
"pttags=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show [Tag]
pttags)
      (String
"ptpostings=" forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show [Posting]
ptpostings)

-- A basic human-readable rendering.
--showPeriodicTransaction t = "~ " ++ T.unpack (ptperiodexpr t) ++ "\n" ++ unlines (map show (ptpostings t))

--nullperiodictransaction is defined in Types.hs

-- | 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
-- <BLANKLINE>
-- 2017-02-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
-- 2017-03-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "monthly from 2017/1 to 2017/5"
-- 2017-01-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-02-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-03-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-04-01
--     ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "every 2nd day of month from 2017/02 to 2017/04"
-- 2017-01-02
--     ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--     a           $1.00
-- <BLANKLINE>
-- 2017-02-02
--     ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--     a           $1.00
-- <BLANKLINE>
-- 2017-03-02
--     ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "every 30th day of month from 2017/1 to 2017/5"
-- 2016-12-30
--     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-01-30
--     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-02-28
--     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-03-30
--     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
-- 2017-04-30
--     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"
-- 2016-12-08
--     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
-- 2017-01-12
--     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
-- 2017-02-09
--     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
-- 2017-03-09
--     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "every nov 29th from 2017 to 2019"
-- 2016-11-29
--     ; generated-transaction: ~ every nov 29th from 2017 to 2019
--     a           $1.00
-- <BLANKLINE>
-- 2017-11-29
--     ; generated-transaction: ~ every nov 29th from 2017 to 2019
--     a           $1.00
-- <BLANKLINE>
-- 2018-11-29
--     ; generated-transaction: ~ every nov 29th from 2017 to 2019
--     a           $1.00
-- <BLANKLINE>
--
-- >>> _ptgen "2017/1"
-- 2017-01-01
--     ; generated-transaction: ~ 2017/1
--     a           $1.00
-- <BLANKLINE>
--
-- >>> 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
-- <BLANKLINE>
-- >>> _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
-- <BLANKLINE>
-- 2018-01-04
--     ; generated-transaction: ~ every 3 days from 2018
--     a           $1.00
-- <BLANKLINE>
-- >>> _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
-- <BLANKLINE>

runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
runPeriodicTransaction Bool
verbosetags PeriodicTransaction{[Tag]
[Posting]
(SourcePos, SourcePos)
AccountName
Status
Interval
DateSpan
ptpostings :: [Posting]
pttags :: [Tag]
ptcomment :: AccountName
ptdescription :: AccountName
ptcode :: AccountName
ptstatus :: Status
ptsourcepos :: (SourcePos, SourcePos)
ptspan :: DateSpan
ptinterval :: Interval
ptperiodexpr :: AccountName
pttags :: PeriodicTransaction -> [Tag]
ptcomment :: PeriodicTransaction -> AccountName
ptdescription :: PeriodicTransaction -> AccountName
ptcode :: PeriodicTransaction -> AccountName
ptstatus :: PeriodicTransaction -> Status
ptsourcepos :: PeriodicTransaction -> (SourcePos, SourcePos)
ptpostings :: PeriodicTransaction -> [Posting]
ptinterval :: PeriodicTransaction -> Interval
ptspan :: PeriodicTransaction -> DateSpan
ptperiodexpr :: PeriodicTransaction -> AccountName
..} DateSpan
requestedspan =
    [ Transaction
t{tdate :: Day
tdate=Day
d} | (DateSpan (Just EFDay
efd) Maybe EFDay
_) <- [DateSpan]
alltxnspans, let d :: Day
d = EFDay -> Day
fromEFDay EFDay
efd, DateSpan -> Day -> Bool
spanContainsDate DateSpan
requestedspan Day
d ]
  where
    t :: Transaction
t = Transaction
nulltransaction{
           tsourcepos :: (SourcePos, SourcePos)
tsourcepos   = (SourcePos, SourcePos)
ptsourcepos
          ,tstatus :: Status
tstatus      = Status
ptstatus
          ,tcode :: AccountName
tcode        = AccountName
ptcode
          ,tdescription :: AccountName
tdescription = AccountName
ptdescription
          ,tcomment :: AccountName
tcomment     = AccountName
ptcomment forall a b. a -> (a -> b) -> b
&
            (if Bool
verbosetags then (AccountName -> Tag -> AccountName
`commentAddTagNextLine` (AccountName
"generated-transaction",AccountName
period)) else forall a. a -> a
id)
          ,ttags :: [Tag]
ttags        = [Tag]
pttags forall a b. a -> (a -> b) -> b
&
            ((AccountName
"_generated-transaction",AccountName
period) forall a. a -> [a] -> [a]
:) forall a b. a -> (a -> b) -> b
&
            (if Bool
verbosetags then ((AccountName
"generated-transaction" ,AccountName
period) forall a. a -> [a] -> [a]
:) else forall a. a -> a
id)
          ,tpostings :: [Posting]
tpostings    = [Posting]
ptpostings
          }
    period :: AccountName
period = AccountName
"~ " forall a. Semigroup a => a -> a -> a
<> AccountName
ptperiodexpr
    -- All the date spans described by this periodic transaction rule.
    alltxnspans :: [DateSpan]
alltxnspans = Bool -> Interval -> DateSpan -> [DateSpan]
splitSpan Bool
adjust Interval
ptinterval DateSpan
span'
      where
        -- If the PT does not specify  start or end dates, we take them from the requestedspan.
        span' :: DateSpan
span' = DateSpan
ptspan DateSpan -> DateSpan -> DateSpan
`spanDefaultsFrom` DateSpan
requestedspan
        -- Unless the PT specified a start date explicitly, we will adjust the start date to the previous interval boundary.
        adjust :: Bool
adjust = forall a. Maybe a -> Bool
isNothing forall a b. (a -> b) -> a -> b
$ DateSpan -> Maybe Day
spanStart DateSpan
span'

-- | 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 -> T.Text -> Maybe String
checkPeriodicTransactionStartDate :: Interval -> DateSpan -> AccountName -> Maybe String
checkPeriodicTransactionStartDate Interval
i DateSpan
s AccountName
periodexpr =
  case (Interval
i, DateSpan -> Maybe Day
spanStart DateSpan
s) of
    (Weeks Int
_,    Just Day
d) -> Day -> SmartInterval -> Maybe String
checkStart Day
d SmartInterval
Week
    (Months Int
_,   Just Day
d) -> Day -> SmartInterval -> Maybe String
checkStart Day
d SmartInterval
Month
    (Quarters Int
_, Just Day
d) -> Day -> SmartInterval -> Maybe String
checkStart Day
d SmartInterval
Quarter
    (Years Int
_,    Just Day
d) -> Day -> SmartInterval -> Maybe String
checkStart Day
d SmartInterval
Year
    (Interval, Maybe Day)
_                    -> forall a. Maybe a
Nothing
    where
      checkStart :: Day -> SmartInterval -> Maybe String
checkStart Day
d SmartInterval
x =
        let firstDate :: Day
firstDate = EFDay -> Day
fromEFDay forall a b. (a -> b) -> a -> b
$ Day -> SmartDate -> EFDay
fixSmartDate Day
d forall a b. (a -> b) -> a -> b
$ Integer -> SmartInterval -> SmartDate
SmartRelative Integer
0 SmartInterval
x
        in
         if Day
d forall a. Eq a => a -> a -> Bool
== Day
firstDate
         then forall a. Maybe a
Nothing
         else forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$
          String
"Unable to generate transactions according to "forall a. [a] -> [a] -> [a]
++forall a. Show a => a -> String
show (AccountName -> String
T.unpack AccountName
periodexpr)
          forall a. [a] -> [a] -> [a]
++String
" because "forall a. [a] -> [a] -> [a]
++forall a. Show a => a -> String
show Day
dforall a. [a] -> [a] -> [a]
++String
" is not a first day of the "forall a. [a] -> [a] -> [a]
++forall a. Show a => a -> String
show SmartInterval
x

---- | What is the interval of this 'PeriodicTransaction's period expression, if it can be parsed ?
--periodTransactionInterval :: PeriodicTransaction -> Maybe Interval
--periodTransactionInterval pt =
--  let
--    expr = ptperiodexpr pt
--    err  = error' $ "Current date cannot be referenced in " ++ show (T.unpack expr)
--  in
--    case parsePeriodExpr err expr of
--      Left _      -> Nothing
--      Right (i,_) -> Just i