aboutsummaryrefslogtreecommitdiff
path: root/src/client/elm/LoggedIn/Home/Account/Model.elm
blob: d8bf748e7b3fffe312830af452007f72fff8c652 (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 LoggedIn.Home.Account.Model
  ( Model
  , IncomeEdition
  , init
  , initIncomeEdition
  , getCurrentIncome
  , validateIncome
  ) where

import Result as Result exposing (Result(..))
import Dict
import String

import Utils.Dict exposing (mapValues)

import Model.Translations exposing (..)
import Model.Income exposing (..)
import Model.User exposing (UserId)

type alias Model =
  { me : UserId
  , incomes : Incomes
  , visibleDetail : Bool
  , incomeEdition : Maybe IncomeEdition
  }

init : UserId -> Incomes -> Model
init me incomes =
  { me = me
  , incomes = incomes
  , visibleDetail = False
  , incomeEdition = Nothing
  }

getCurrentIncome : Model -> Maybe Int
getCurrentIncome account =
  account.incomes
    |> Dict.filter (\_ income -> income.userId == account.me)
    |> Dict.values
    |> List.sortBy .creation
    |> List.reverse
    |> List.head
    |> Maybe.map .amount

type alias IncomeEdition =
  { income : String
  , error : Maybe String
  }

initIncomeEdition : Int -> IncomeEdition
initIncomeEdition income =
  { income = toString income
  , error = Nothing
  }

validateIncome : String -> Translations -> Result String Int
validateIncome amount translations =
  case String.toInt amount of
    Ok number ->
      if number > 0
        then Ok number
        else Err <| getMessage "IncomeMustBePositiveNumber" translations
    Err _ ->
      Err <| getMessage "IncomeRequired" translations