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 Model.Database import Model.Frequency import qualified Model.Json.Payment as P getPunctualPayments :: Persist [P.Payment] getPunctualPayments = map getJsonPayment <$> selectList [ PaymentDeletedAt P.==. Nothing , PaymentFrequency P.==. Punctual ] [ Desc PaymentCreation ] getUserMonthlyPayments :: UserId -> Persist [P.Payment] getUserMonthlyPayments userId = filter ((==) userId . P.userId) . map getJsonPayment <$> getMonthlyPayments getMonthlyPayments :: Persist [Entity Payment] getMonthlyPayments = selectList [ PaymentDeletedAt P.==. Nothing , PaymentFrequency P.==. Monthly ] [ Desc PaymentName ] 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 = count [ PaymentDeletedAt P.==. Nothing , PaymentFrequency P.==. Punctual ]