aboutsummaryrefslogtreecommitdiff
path: root/src/server/Model/Payment.hs
blob: 47397ff48a75fab14fb9313badc9f4b30e2f8056 (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
75
76
77
78
79
80
81
82
83
84
85
{-# LANGUAGE OverloadedStrings #-}

module Model.Payment
  ( getPayments
  , getMonthlyPayments
  , createPayment
  , deleteOwnPayment
  ) where

import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
import Data.Either (lefts)

import Control.Monad.IO.Class (liftIO)

import Database.Persist

import qualified Validation

import Model.Database
import Model.Frequency
import qualified Model.Json.Payment as P
import qualified Model.Message.Key as K

getPayments :: Persist [P.Payment]
getPayments =
  map getJsonPayment <$> selectList
    [ PaymentDeletedAt ==. Nothing ]
    [ Desc PaymentCreation ]

getMonthlyPayments :: Persist [Entity Payment]
getMonthlyPayments =
  selectList
    [ PaymentDeletedAt ==. Nothing
    , PaymentFrequency ==. Monthly
    ]
    [ Desc PaymentName ]

getJsonPayment :: Entity Payment -> P.Payment
getJsonPayment paymentEntity =
  let payment = entityVal paymentEntity
  in  P.Payment
        { P.id = entityKey paymentEntity
        , P.creation = paymentCreation payment
        , P.name = paymentName payment
        , P.cost = paymentCost payment
        , P.userId = paymentUserId payment
        , P.frequency = paymentFrequency payment
        }

createPayment :: UserId -> Text -> Text -> Frequency -> Persist (Either [(Text, K.Key)] PaymentId)
createPayment userId name cost frequency =
  case validatePayment name cost of
    Left err ->
      return . Left $ err
    Right (validatedName, validatedCost) -> do
      now <- liftIO getCurrentTime
      Right <$> insert (Payment userId now validatedName validatedCost Nothing frequency)

validatePayment :: Text -> Text -> Either [(Text, K.Key)] (Text, Int)
validatePayment name cost =
  let eitherName = Validation.nonEmpty K.CategoryRequired name
      eitherCost = Validation.nonEmpty K.CostRequired cost >>= Validation.number K.CostRequired (/= 0)
  in  case (eitherName, eitherCost) of
        (Right validatedName, Right validatedCost) ->
          Right (validatedName, validatedCost)
        _ ->
          let nameErrors = map (\x -> ("name", x)) $ lefts [eitherName]
              costErrors = map (\x -> ("cost", x)) $ lefts [eitherCost]
          in  Left (nameErrors ++ costErrors)

deleteOwnPayment :: Entity User -> PaymentId -> Persist Bool
deleteOwnPayment user paymentId = do
  mbPayment <- get paymentId
  case mbPayment of
    Just payment ->
      if paymentUserId payment == entityKey user
        then do
          now <- liftIO getCurrentTime
          update paymentId [PaymentDeletedAt =. Just now]
          return True
        else
          return False
    Nothing ->
      return False