aboutsummaryrefslogtreecommitdiff
path: root/src/server/MonthlyPaymentJob.hs
blob: f9d89c0988d597a4f65e3f17656cfa2fcfa3a4e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module MonthlyPaymentJob
  ( monthlyPaymentJobListener
  ) where

import Data.Time.Clock
import Data.Time.LocalTime
import Data.Time.Calendar

import Control.Concurrent (threadDelay)

import Database.Persist (entityVal, insert)

import Model.Database
import Model.Payment (getMonthlyPayments)
import Model.JobKind
import Model.Job
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 <- map entityVal <$> getMonthlyPayments
  let punctualPayments = map (\p -> p { paymentFrequency = Punctual }) monthlyPayments
  sequence_ $ map insert punctualPayments

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)