module Model.Income ( list , create , editOwn , deleteOwn , modifiedDuring ) where import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Calendar (Day) import Control.Monad.IO.Class (liftIO) import Database.Persist import Model.Database import qualified Model.Json.Income as Json list :: Persist [Json.Income] list = map getJsonIncome <$> selectList [IncomeDeletedAt ==. Nothing] [] getJsonIncome :: Entity Income -> Json.Income getJsonIncome incomeEntity = Json.Income (entityKey incomeEntity) (incomeUserId income) (incomeDate income) (incomeAmount income) where income = entityVal incomeEntity create :: UserId -> Day -> Int -> Persist IncomeId create userId date amount = do now <- liftIO getCurrentTime insert (Income userId date amount now Nothing Nothing) editOwn :: UserId -> IncomeId -> Day -> Int -> Persist Bool editOwn userId incomeId date amount = do mbIncome <- get incomeId case mbIncome of Just income -> if incomeUserId income == userId then do now <- liftIO getCurrentTime update incomeId [ IncomeEditedAt =. Just now , IncomeDate =. date , IncomeAmount =. amount ] return True else return False Nothing -> return False deleteOwn :: Entity User -> IncomeId -> Persist Bool deleteOwn user incomeId = do mbIncome <- get incomeId case mbIncome of Just income -> if incomeUserId income == entityKey user then do now <- liftIO getCurrentTime update incomeId [IncomeDeletedAt =. Just now] return True else return False Nothing -> return False modifiedDuring :: UTCTime -> UTCTime -> Persist [Income] modifiedDuring start end = map entityVal <$> selectList ( [IncomeCreatedAt >=. start, IncomeCreatedAt <. end] ||. [IncomeEditedAt >=. Just start, IncomeEditedAt <. Just end] ||. [IncomeDeletedAt >=. Just start, IncomeDeletedAt <. Just end] ) []