aboutsummaryrefslogtreecommitdiff
path: root/src/server/Model/Payer/Payment.hs
blob: 6efc38da458351fd12de785af0cd59be4f25cbaf (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
module Model.Payer.Payment
  ( getTotalPaymentsBefore
  , getTotalPaymentsAfter
  ) where

import Data.Time.Clock (UTCTime)
import Data.Maybe (catMaybes)

import Database.Persist
import Database.Esqueleto
import qualified Database.Esqueleto as E

import Model.Database
import Model.Frequency

getTotalPaymentsBefore :: UTCTime -> Persist [(UserId, Int)]
getTotalPaymentsBefore time =
  getTotalPayments (\p -> p ^. PaymentCreation E.<. val time)

getTotalPaymentsAfter :: UTCTime -> Persist [(UserId, Int)]
getTotalPaymentsAfter time =
  getTotalPayments (\p -> p ^. PaymentCreation E.>=. val time)

getTotalPayments :: (SqlExpr (Entity Payment) -> SqlExpr (Value Bool)) -> Persist [(UserId, Int)]
getTotalPayments paymentWhere = do
  values <- select $
            from $ \payment -> do
              where_ (isNothing (payment ^. PaymentDeletedAt))
              where_ (payment ^. PaymentFrequency E.==. val Punctual)
              where_ (paymentWhere payment)
              groupBy (payment ^. PaymentUserId)
              return (payment ^. PaymentUserId, sum_ (payment ^. PaymentCost))
  return $ catMaybes . map (unMaybe . unValueTuple) $ values

unValueTuple :: (Value a, Value b) -> (a, b)
unValueTuple (Value a, Value b) = (a, b)

unMaybe :: (a, Maybe b) -> Maybe (a, b)
unMaybe (a, Just b) = Just (a, b)
unMaybe _ = Nothing