{-# LANGUAGE OverloadedStrings #-} module Controller.Payment ( getPaymentsAction , getMonthlyPaymentsAction , createPaymentAction , deletePaymentAction , getTotalPaymentsAction , getPaymentsCountAction ) where import Web.Scotty import Network.HTTP.Types.Status (ok200, badRequest400) import Database.Persist import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import qualified Data.Aeson.Types as Json import qualified Secure import Model.Database import Model.Payment import Model.Frequency import Model.Json.Number import qualified Model.Json.PaymentId as JP import Model.Message import Model.Message.Key (Key(PaymentNotDeleted)) import Json (jsonObject) getPaymentsAction :: Int -> Int -> ActionM () getPaymentsAction page perPage = Secure.loggedAction (\_ -> do (liftIO $ runDb (getPunctualPayments page perPage)) >>= json ) getMonthlyPaymentsAction :: ActionM () getMonthlyPaymentsAction = Secure.loggedAction (\user -> do (liftIO $ runDb (getUserMonthlyPayments (entityKey user))) >>= json ) createPaymentAction :: Text -> Int -> Frequency -> ActionM () createPaymentAction name cost frequency = Secure.loggedAction (\user -> do paymentId <- liftIO . runDb $ createPayment (entityKey user) name cost frequency json (JP.PaymentId paymentId) ) deletePaymentAction :: Text -> ActionM () deletePaymentAction paymentId = Secure.loggedAction (\user -> do deleted <- liftIO . runDb $ deleteOwnPayment user (textToKey paymentId) if deleted then status ok200 else do status badRequest400 jsonObject [("error", Json.String $ getMessage PaymentNotDeleted)] ) getTotalPaymentsAction :: ActionM () getTotalPaymentsAction = Secure.loggedAction (\_ -> do (liftIO . runDb $ getTotalPayments) >>= json ) getPaymentsCountAction :: ActionM () getPaymentsCountAction = Secure.loggedAction (\_ -> do Number <$> (liftIO . runDb $ getPaymentsCount) >>= json )