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