From 6b466f616035c2fc03359d182c074f096d6b7f17 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 29 Aug 2015 13:30:09 +0200 Subject: Showing exceeding payers --- src/server/Model/Database.hs | 2 +- src/server/Model/Json/TotalPayment.hs | 18 ++++++++++++++++++ src/server/Model/Payment.hs | 20 ++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/server/Model/Json/TotalPayment.hs (limited to 'src/server/Model') diff --git a/src/server/Model/Database.hs b/src/server/Model/Database.hs index 8715ca1..a6ce4f4 100644 --- a/src/server/Model/Database.hs +++ b/src/server/Model/Database.hs @@ -26,7 +26,7 @@ User creation UTCTime email Text name Text - EmailKey email + UniqEmail email UniqName name deriving Show Payment diff --git a/src/server/Model/Json/TotalPayment.hs b/src/server/Model/Json/TotalPayment.hs new file mode 100644 index 0000000..e386c79 --- /dev/null +++ b/src/server/Model/Json/TotalPayment.hs @@ -0,0 +1,18 @@ +{-# LANGUAGE DeriveGeneric #-} + +module Model.Json.TotalPayment + ( TotalPayment(..) + ) where + +import GHC.Generics + +import Data.Text (Text) +import Data.Aeson + +data TotalPayment = TotalPayment + { userName :: Text + , totalPayment :: Int + } deriving (Show, Generic) + +instance FromJSON TotalPayment +instance ToJSON TotalPayment diff --git a/src/server/Model/Payment.hs b/src/server/Model/Payment.hs index 51f09b9..300f6b8 100644 --- a/src/server/Model/Payment.hs +++ b/src/server/Model/Payment.hs @@ -3,11 +3,13 @@ module Model.Payment , createPayment , paymentKeyToText , deleteOwnPayment + , getTotalPayments ) where import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock (getCurrentTime) +import Data.Maybe (catMaybes) import Control.Monad.IO.Class (liftIO) @@ -18,6 +20,7 @@ import qualified Database.Esqueleto as E import Model.Database import qualified Model.Json.Payment as P +import qualified Model.Json.TotalPayment as TP getPayments :: Persist [P.Payment] getPayments = do @@ -62,3 +65,20 @@ deleteOwnPayment user paymentId = do return False Nothing -> return False + +getTotalPayments :: Persist [TP.TotalPayment] +getTotalPayments = do + values <- select $ + from $ \(payment `InnerJoin` user) -> do + on (payment ^. PaymentUserId E.==. user ^. UserId) + where_ (isNothing (payment ^. PaymentDeletedAt)) + groupBy (payment ^. PaymentUserId) + return (user ^. UserName, sum_ (payment ^. PaymentCost)) + return $ catMaybes . map (getTotalPayment . unValueTuple) $ values + +getTotalPayment :: (Text, Maybe Int) -> Maybe TP.TotalPayment +getTotalPayment (userName, Just cost) = Just (TP.TotalPayment userName cost) +getTotalPayment (_, Nothing) = Nothing + +unValueTuple :: (Value a, Value b) -> (a, b) +unValueTuple (Value a, Value b) = (a, b) -- cgit v1.2.3