aboutsummaryrefslogtreecommitdiff
path: root/src/client/elm/LoggedIn/Home/AddPayment/Update.elm
blob: 7f5fb0afc9b00bce932c87c40f0dbaacb81b739b (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
module LoggedIn.Home.AddPayment.Update
  ( update
  , addPaymentError
  ) where

import Maybe
import Json.Decode as Json exposing ((:=))

import LoggedIn.Home.AddPayment.Action as AddPaymentAction
import LoggedIn.Home.AddPayment.Model as AddPaymentModel

import Model.Translations exposing (Translations, getMessage)
import Model.Payment exposing (Frequency(..))

update : AddPaymentAction.Action -> AddPaymentModel.Model -> AddPaymentModel.Model
update action addPayment =
  case action of

    AddPaymentAction.NoOp ->
      addPayment

    AddPaymentAction.Init frequency ->
      AddPaymentModel.init frequency

    AddPaymentAction.UpdateName name ->
      { addPayment | name = name }

    AddPaymentAction.UpdateCost cost ->
      { addPayment | cost = cost }

    AddPaymentAction.AddError nameError costError ->
      { addPayment
      | nameError = nameError
      , costError = costError
      , waitingServer = False
      }

    AddPaymentAction.ToggleFrequency ->
      { addPayment
      | frequency = if addPayment.frequency == Punctual then Monthly else Punctual
      }

    AddPaymentAction.WaitingServer ->
      { addPayment | waitingServer = True }

addPaymentError : Translations -> String -> Maybe AddPaymentAction.Action
addPaymentError translations jsonErr =
  let decoder =
        Json.object2 (,)
          (Json.maybe <| "name" := Json.string)
          (Json.maybe <| "cost" := Json.string)
  in  case Json.decodeString decoder jsonErr of
        Err _ ->
          Nothing
        Ok (mbNameKey, mbCostKey) ->
          Just <| AddPaymentAction.AddError
            (Maybe.map (flip getMessage translations) mbNameKey)
            (Maybe.map (flip getMessage translations) mbCostKey)