aboutsummaryrefslogtreecommitdiff
path: root/src/server/Model/PaymentCategory.hs
blob: 3b0b858af04e17ee8c6ecfd27019b2bcc10c4353 (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
41
42
43
44
45
46
47
48
{-# LANGUAGE OverloadedStrings #-}

module Model.PaymentCategory
  ( list
  , listByCategory
  , save
  ) where

import Control.Monad.IO.Class (liftIO)
import Data.Maybe (isJust)

import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
import Database.Persist
import qualified Data.Text as T

import Model.Database
import qualified Model.Json.PaymentCategory as Json
import qualified Utils.Text as T

list :: Persist [Json.PaymentCategory]
list = map getJsonPaymentCategory <$> selectList [] []

listByCategory :: CategoryId -> Persist [Entity PaymentCategory]
listByCategory category = selectList [ PaymentCategoryCategory ==. category ] []

getJsonPaymentCategory :: Entity PaymentCategory -> Json.PaymentCategory
getJsonPaymentCategory entity =
  Json.PaymentCategory (paymentCategoryName pc) (paymentCategoryCategory pc)
  where pc = entityVal entity

save :: Text -> CategoryId -> Persist ()
save newName category = do
  now <- liftIO getCurrentTime
  mbPaymentCategory <- selectFirst [PaymentCategoryName ==. (formatPaymentName newName)] []
  if isJust mbPaymentCategory
    then
      updateWhere
        [ PaymentCategoryName ==. (formatPaymentName newName) ]
        [ PaymentCategoryCategory =. category
        , PaymentCategoryEditedAt =. Just now
        ]
    else do
      _ <- insert $ PaymentCategory (formatPaymentName newName) category now Nothing
      return ()

formatPaymentName :: Text -> Text
formatPaymentName = T.unaccent . T.toLower