aboutsummaryrefslogtreecommitdiff
path: root/client/src/View/Income/Reducer.hs
blob: 391890f6a2ac709302a69a5501762f08319f9d33 (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
module View.Income.Reducer
  ( perPage
  , reducer
  , In(..)
  ) where

import           Data.Text    (Text)
import qualified Data.Text    as T
import           Reflex.Dom   (Dynamic, Event, MonadWidget)
import qualified Reflex.Dom   as R

import           Common.Model (IncomePage)

import           Loadable     (Loadable2 (..))
import qualified Util.Ajax    as AjaxUtil
import qualified Util.Either  as EitherUtil

perPage :: Int
perPage = 7

data In t a b c = In
  { _in_page         :: Event t Int
  , _in_addIncome    :: Event t a
  , _in_editIncome   :: Event t b
  , _in_deleteIncome :: Event t c
  }

reducer :: forall t m a b c. MonadWidget t m => In t a b c -> m (Loadable2 t IncomePage)
reducer input = do

  postBuild <- R.getPostBuild

  currentPage <- R.holdDyn 1 (_in_page input)

  let loadPage =
        R.leftmost
          [ 1 <$ postBuild
          , _in_page input
          , 1 <$ _in_addIncome input
          , R.tag (R.current currentPage) (_in_editIncome input)
          , R.tag (R.current currentPage) (_in_deleteIncome input)
          ]

  getResult <- AjaxUtil.get $ fmap pageUrl loadPage

  isLoading <- R.holdDyn
    True
    (R.leftmost
      [ True <$ loadPage
      , False <$ getResult
      ])

  incomePage <- R.holdDyn
    Nothing
    (fmap EitherUtil.eitherToMaybe getResult)

  return $ Loadable2 isLoading incomePage

  where
    pageUrl p =
      "api/incomes?page="
      <> (T.pack . show $ p)
      <> "&perPage="
      <> (T.pack . show $ perPage)