blob: 233cafa0a94943ece63be4fb447ff3196d382191 (
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
|
module Model.Payment
( getPunctualPayments
, getUserMonthlyPayments
, getMonthlyPayments
, createPayment
, deleteOwnPayment
, getPaymentsCount
) where
import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.IO.Class (liftIO)
import Database.Persist
import qualified Database.Persist as P
import Database.Esqueleto
import qualified Database.Esqueleto as E
import Model.Database
import Model.Frequency
import qualified Model.Json.Payment as P
getPunctualPayments :: Int -> Int -> Persist [P.Payment]
getPunctualPayments page perPage = do
xs <- select $
from $ \(payment) -> do
where_ (isNothing (payment ^. PaymentDeletedAt))
where_ (payment ^. PaymentFrequency E.==. val Punctual)
orderBy [desc (payment ^. PaymentCreation)]
limit . fromIntegral $ perPage
offset . fromIntegral $ (page - 1) * perPage
return payment
return (map getJsonPayment xs)
getUserMonthlyPayments :: UserId -> Persist [P.Payment]
getUserMonthlyPayments userId =
filter ((==) userId . P.userId) . map getJsonPayment <$> getMonthlyPayments
getMonthlyPayments :: Persist [Entity Payment]
getMonthlyPayments =
select $
from $ \payment -> do
where_ (isNothing (payment ^. PaymentDeletedAt))
where_ (payment ^. PaymentFrequency E.==. val Monthly)
orderBy [desc (lower_ (payment ^. PaymentName))]
return payment
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
}
createPayment :: UserId -> Text -> Int -> Frequency -> Persist PaymentId
createPayment userId name cost frequency = do
now <- liftIO getCurrentTime
insert $ Payment userId now name cost Nothing frequency
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
P.update paymentId [PaymentDeletedAt P.=. Just now]
return True
else
return False
Nothing ->
return False
getPaymentsCount :: Persist Int
getPaymentsCount =
unValue . head <$>
(select $
from $ \payment -> do
where_ (isNothing (payment ^. PaymentDeletedAt))
where_ (payment ^. PaymentFrequency E.==. val Punctual)
return countRows) :: Persist Int
|