aboutsummaryrefslogtreecommitdiff
path: root/src/server/Model/PaymentCategory.hs
blob: 7c504dc5b764a426d1e50041089b6d55bedeaeed (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{-# LANGUAGE OverloadedStrings #-}

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

import Data.Int (Int64)
import Data.Maybe (isJust, listToMaybe)
import Data.Text (Text)
import Data.Time (UTCTime)
import Data.Time.Clock (getCurrentTime)
import Database.SQLite.Simple (Only(Only), FromRow(fromRow))
import qualified Data.Text as T
import qualified Database.SQLite.Simple as SQLite

import Model.Category (CategoryId)
import Model.Query (Query(Query))
import qualified Utils.Text as T

type PaymentCategoryId = Int64

data PaymentCategory = PaymentCategory
  { id :: PaymentCategoryId
  , name :: Text
  , category :: CategoryId
  , createdAt :: UTCTime
  , editedAt :: Maybe UTCTime
  } deriving Show

instance FromRow PaymentCategory where
  fromRow = PaymentCategory <$>
    SQLite.field <*>
    SQLite.field <*>
    SQLite.field <*>
    SQLite.field <*>
    SQLite.field

list :: Query [PaymentCategory]
list = Query (\conn -> SQLite.query_ conn "SELECT * from payment_category")

listByCategory :: CategoryId -> Query [PaymentCategory]
listByCategory cat =
  Query (\conn ->
    SQLite.query conn "SELECT * FROM payment_category WHERE category = ?" (Only cat)
  )

save :: Text -> CategoryId -> Query ()
save newName categoryId =
  Query (\conn -> do
    now <- getCurrentTime
    mbPaymentCategory <- listToMaybe <$>
      (SQLite.query
        conn
        "SELECT * FROM payment_category WHERE name = ?"
        (Only (formatPaymentName newName)) :: IO [PaymentCategory])
    if isJust mbPaymentCategory
      then
        SQLite.execute
          conn
          "UPDATE payment_category SET category = ?, edited_at = ? WHERE name = ?"
          (categoryId, now, formatPaymentName newName)
      else do
        SQLite.execute
          conn
          "INSERT INTO payment_category (name, category, created_at) VALUES (?, ?, ?)"
          (formatPaymentName newName, categoryId, now)
  )
  where
    formatPaymentName :: Text -> Text
    formatPaymentName = T.unaccent . T.toLower