aboutsummaryrefslogtreecommitdiff
path: root/src/server/Controller/Payment.hs
blob: ec241f78125278b7780ecb71a85470042e26601a (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{-# LANGUAGE OverloadedStrings #-}

module Controller.Payment
  ( getPayments
  , getMonthlyPayments
  , createPayment
  , deletePayment
  , getPaymentsCount
  ) 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.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Aeson.Types as Json

import qualified Secure

import Json (jsonObject)

import Model.Database
import qualified Model.Payment as P
import Model.Frequency
import Model.Json.Number
import Model.Message.Key (Key(PaymentNotDeleted))

getPayments :: ActionM ()
getPayments =
  Secure.loggedAction (\_ -> do
    (liftIO $ runDb P.getPunctualPayments) >>= json
  )

getMonthlyPayments :: ActionM ()
getMonthlyPayments =
  Secure.loggedAction (\user -> do
    (liftIO $ runDb (P.getUserMonthlyPayments (entityKey user))) >>= json
  )

createPayment :: Text -> Text -> Frequency -> ActionM ()
createPayment name cost frequency =
  Secure.loggedAction (\user -> do
    creationResult <- liftIO . runDb $ P.createPayment (entityKey user) name cost frequency
    case creationResult of
      Left errors -> do
        status badRequest400
        jsonObject . map (\(a, b) -> (a, Json.String . T.pack . show $ b)) $ errors
      Right paymentId ->
        jsonObject [("id", Json.Number . fromIntegral . keyToInt64 $ paymentId)]
  )

deletePayment :: Text -> ActionM ()
deletePayment paymentId =
  Secure.loggedAction (\user -> do
    deleted <- liftIO . runDb $ P.deleteOwnPayment user (textToKey paymentId)
    if deleted
      then
        status ok200
      else do
        status badRequest400
        text . TL.pack . show $ PaymentNotDeleted
  )

getPaymentsCount :: ActionM ()
getPaymentsCount =
  Secure.loggedAction (\_ -> do
    Number <$> (liftIO . runDb $ P.getPaymentsCount) >>= json
  )