module View.Income.Income ( init , view , In(..) ) where import Data.Aeson (FromJSON) import Prelude hiding (init) import Reflex.Dom (Dynamic, Event, MonadWidget) import qualified Reflex.Dom as R import Common.Model (Currency, Income (..), UserId) import Loadable (Loadable (..)) import qualified Loadable import qualified Util.Ajax as AjaxUtil import qualified View.Income.Header as Header import View.Income.Init (Init (..)) import qualified View.Income.Table as Table data In t = In { _in_currentUser :: UserId , _in_currency :: Currency , _in_init :: Dynamic t (Loadable Init) } init :: forall t m. MonadWidget t m => m (Dynamic t (Loadable Init)) init = do users <- AjaxUtil.getNow "api/users" incomes <- AjaxUtil.getNow "api/incomes" payments <- AjaxUtil.getNow "api/payments" return $ do us <- users is <- incomes ps <- payments return $ Init <$> us <*> is <*> ps view :: forall t m. MonadWidget t m => In t -> m () view input = do R.dyn . R.ffor (_in_init input) . Loadable.view $ \init -> R.elClass "main" "income" $ do rec let addIncome = R.leftmost [ Header._out_add header , Table._out_add table ] incomes <- reduceIncomes (_init_incomes init) addIncome (Table._out_delete table) header <- Header.view $ Header.In { Header._in_init = init , Header._in_currency = _in_currency input , Header._in_incomes = incomes } table <- Table.view $ Table.In { Table._in_currentUser = _in_currentUser input , Table._in_init = init , Table._in_currency = _in_currency input , Table._in_incomes = incomes } return () return () reduceIncomes :: forall t m. MonadWidget t m => [Income] -> Event t Income -- add income -> Event t Income -- delete income -> m (Dynamic t [Income]) reduceIncomes initIncomes add delete = R.foldDyn id initIncomes $ R.leftmost [ (:) <$> add , R.ffor delete (\p -> filter ((/= (_income_id p)) . _income_id)) ]