module MonthlyPaymentJob ( monthlyPaymentJobListener ) where import Control.Monad.IO.Class (liftIO) import Data.Time.Clock import Data.Time.LocalTime import Data.Time.Calendar import Database.Persist (entityVal, insert) import Job (jobListener) import Model.Database import Model.Payment (getMonthlyPayments) import Model.JobKind import Model.Frequency monthlyPaymentJobListener :: IO () monthlyPaymentJobListener = let lastExecutionTooOld = fmap not . belongToCurrentMonth runJob () = monthlyPaymentJob msDelay = 1000000 * 60 * 60 in jobListener MonthlyPaymentJob lastExecutionTooOld runJob msDelay belongToCurrentMonth :: UTCTime -> IO Bool belongToCurrentMonth time = do month <- getLocalMonth time actualMonth <- getCurrentTime >>= getLocalMonth return (month == actualMonth) getLocalMonth :: UTCTime -> IO Int getLocalMonth time = do timeZone <- getCurrentTimeZone let (_, month, _) = toGregorian . localDay $ utcToLocalTime timeZone time return month monthlyPaymentJob :: Persist () monthlyPaymentJob = do monthlyPayments <- map entityVal <$> getMonthlyPayments now <- liftIO $ getCurrentTime let punctualPayments = map (\p -> p { paymentFrequency = Punctual, paymentCreation = now }) monthlyPayments sequence_ $ map insert punctualPayments