diff options
Diffstat (limited to 'src/server/Model')
-rw-r--r-- | src/server/Model/Database.hs | 2 | ||||
-rw-r--r-- | src/server/Model/Json/TotalPayment.hs | 18 | ||||
-rw-r--r-- | src/server/Model/Payment.hs | 20 |
3 files changed, 39 insertions, 1 deletions
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) |