module Model.Income ( getJsonIncome , getIncomes , create , editOwn , deleteOwn ) where import Data.Time.Clock (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 getJsonIncome :: Entity Income -> Json.Income getJsonIncome incomeEntity = Json.Income (entityKey incomeEntity) (incomeUserId income) (incomeDate income) (incomeAmount income) where income = entityVal incomeEntity getIncomes :: Persist [Entity Income] getIncomes = selectList [IncomeDeletedAt ==. Nothing] [] 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