module MonthlyPaymentJob ( monthlyPaymentJobListener ) where import Data.Time.Clock import Data.Time.LocalTime import Data.Time.Calendar import Control.Concurrent (threadDelay) import Model.Database import Model.Payment (createPayment, getMonthlyPayments) import Model.JobKind import Model.Job import Model.Json.Payment as P import Model.Frequency monthlyPaymentJobListener :: IO () monthlyPaymentJobListener = do mbLastExecution <- runDb $ getLastExecution MonthlyPaymentJob runThisMonth <- case mbLastExecution of Just lastExecution -> belongToCurrentMonth lastExecution Nothing -> return False if not runThisMonth then runDb (monthlyJob >> actualizeLastExecution MonthlyPaymentJob) else return () sleepOneDay monthlyPaymentJobListener monthlyJob :: Persist () monthlyJob = do monthlyPayments <- getMonthlyPayments _ <- sequence $ map (\p -> createPayment (P.userId p) (P.name p) (P.cost p) Punctual) monthlyPayments return () 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 sleepOneDay :: IO () sleepOneDay = threadDelay (1000000 * 60 * 60 * 24)