diff options
Diffstat (limited to 'client/src/View/Payment/Reducer.hs')
-rw-r--r-- | client/src/View/Payment/Reducer.hs | 110 |
1 files changed, 110 insertions, 0 deletions
diff --git a/client/src/View/Payment/Reducer.hs b/client/src/View/Payment/Reducer.hs new file mode 100644 index 0000000..3fe59b2 --- /dev/null +++ b/client/src/View/Payment/Reducer.hs @@ -0,0 +1,110 @@ +module View.Payment.Reducer + ( perPage + , reducer + , In(..) + , Params(..) + ) where + +import Data.Text (Text) +import qualified Data.Text as T +import Data.Time (NominalDiffTime) +import Reflex.Dom (Dynamic, Event, MonadWidget) +import qualified Reflex.Dom as R + +import Common.Model (Frequency (..), PaymentPage) + +import Loadable (Loadable (..)) +import qualified Loadable as Loadable +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_search :: Event t Text + , _in_frequency :: Event t Frequency + , _in_addPayment :: Event t a + , _in_editPayment :: Event t b + , _in_deletePayment :: Event t c + } + +data Params = Params + { _params_page :: Int + , _params_search :: Text + , _params_frequency :: Frequency + } deriving (Show) + +initParams = Params 1 "" Punctual + +data Msg + = Page Int + | Search Text + | Frequency Common.Model.Frequency + | ResetSearch + deriving Show + +reducer :: forall t m a b c. MonadWidget t m => In t a b c -> m (Dynamic t (Loadable PaymentPage)) +reducer input = do + + postBuild <- R.getPostBuild + + debouncedSearch <- R.debounce (1 :: NominalDiffTime) (_in_search input) + + params <- R.foldDynMaybe + (\msg params -> case msg of + Page page -> + Just $ params { _params_page = page } + + Search "" -> + if _params_search params == "" then + Nothing + + else + Just $ initParams { _params_frequency = _params_frequency params } + + Search search -> + Just $ params { _params_search = search, _params_page = _params_page initParams } + + Frequency frequency -> + Just $ params { _params_frequency = frequency, _params_page = _params_page initParams } + + ResetSearch -> + Just $ initParams { _params_frequency = _params_frequency params } + ) + initParams + (R.leftmost + [ Page <$> _in_page input + , Search <$> debouncedSearch + , Frequency <$> _in_frequency input + , ResetSearch <$ _in_addPayment input + ]) + + let paramsEvent = + R.leftmost + [ initParams <$ postBuild + , R.updated params + , R.tag (R.current params) (_in_editPayment input) + , R.tag (R.current params) (_in_deletePayment input) + ] + + getResult <- AjaxUtil.get (pageUrl <$> paramsEvent) + + R.holdDyn + Loading + (R.leftmost + [ Loading <$ paramsEvent + , Loadable.fromEither <$> getResult + ]) + + where + pageUrl (Params page search frequency) = + "api/payments?page=" + <> (T.pack . show $ page) + <> "&perPage=" + <> (T.pack . show $ perPage) + <> "&search=" + <> search + <> "&frequency=" + <> (T.pack $ show frequency) |