module Controller.Income ( list , create , edit , delete ) where import Control.Monad.IO.Class (liftIO) import Data.Validation (Validation (Failure, Success)) import qualified Network.HTTP.Types.Status as Status import Web.Scotty hiding (delete) import Common.Model (CreateIncomeForm (..), EditIncome (..), IncomeId, User (..)) import qualified Controller.Helper as ControllerHelper import Model.CreateIncome (CreateIncome (..)) import qualified Model.Query as Query import qualified Persistence.Income as IncomePersistence import qualified Secure import qualified Validation.Income as IncomeValidation list :: ActionM () list = Secure.loggedAction (\_ -> (liftIO . Query.run $ IncomePersistence.list) >>= json ) create :: CreateIncomeForm -> ActionM () create form = Secure.loggedAction (\user -> (liftIO . Query.run $ do case IncomeValidation.createIncome form of Success (CreateIncome amount date) -> do Right <$> (IncomePersistence.create (_user_id user) date amount) Failure validationError -> return $ Left validationError ) >>= ControllerHelper.jsonOrBadRequest ) edit :: EditIncome -> ActionM () edit (EditIncome incomeId date amount) = Secure.loggedAction (\user -> do updated <- liftIO . Query.run $ IncomePersistence.edit (_user_id user) incomeId date amount if updated then status Status.ok200 else status Status.badRequest400 ) delete :: IncomeId -> ActionM () delete incomeId = Secure.loggedAction (\user -> do _ <- liftIO . Query.run $ IncomePersistence.delete (_user_id user) incomeId status Status.ok200 )