aboutsummaryrefslogtreecommitdiff
path: root/src/server/Model/Payment.hs
blob: 0d5e188b2bf9df4388a6e2fc0fff5bd8629f2593 (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
86
87
88
{-# LANGUAGE OverloadedStrings #-}

module Model.Payment
  ( list
  , listMonthly
  , create
  , editOwn
  , deleteOwn
  ) where

import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
import Data.Time.Calendar (Day)

import Control.Monad.IO.Class (liftIO)

import Database.Persist

import Model.Database
import Model.Frequency
import qualified Model.Json.Payment as P

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

listMonthly :: Persist [Entity Payment]
listMonthly =
  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.date = paymentDate payment
        , P.name = paymentName payment
        , P.cost = paymentCost payment
        , P.userId = paymentUserId payment
        , P.frequency = paymentFrequency payment
        }

create :: UserId -> Text -> Int -> Day -> Frequency -> Persist PaymentId
create userId name cost date frequency = do
  now <- liftIO getCurrentTime
  insert (Payment userId name cost date frequency now Nothing Nothing)

editOwn :: UserId -> PaymentId -> Text -> Int -> Day -> Frequency -> Persist Bool
editOwn userId paymentId name cost date frequency = do
  mbPayment <- get paymentId
  case mbPayment of
    Just payment ->
      if paymentUserId payment == userId
        then do
          now <- liftIO getCurrentTime
          update paymentId
            [ PaymentEditedAt =. Just now
            , PaymentName =. name
            , PaymentCost =. cost
            , PaymentDate =. date
            , PaymentFrequency =. frequency
            ]
          return True
        else
          return False
    Nothing ->
      return False

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