-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModel.elm
73 lines (55 loc) · 1.66 KB
/
Model.elm
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
65
66
67
68
69
70
71
72
73
module Model (..) where
import Dict exposing (Dict)
import Amount exposing (Amount, Currency(..))
import Account exposing (Account)
type AccountId
= AccountId String
type alias Transaction =
{ amount : Amount
, source : AccountId
, target : AccountId
}
type alias Model =
{ accounts : Dict String Account }
accountBalance : AccountId -> Model -> Maybe Amount
accountBalance (AccountId accountId) { accounts } =
Dict.get accountId accounts
|> Maybe.map .balance
init : Model
init =
{ accounts =
Dict.empty
|> Dict.insert "checking" (Account (Amount 0 USD_Cents) "Checking")
|> Dict.insert "expenses" (Account (Amount 0 USD_Cents) "Expenses")
|> Dict.insert "income" (Account (Amount 0 USD_Cents) "Income")
}
update : Transaction -> Model -> Result String Model
update tx model =
let
(AccountId sourceId) =
tx.source
(AccountId targetId) =
tx.target
newSource : Result String Account
newSource =
Dict.get sourceId model.accounts
|> Result.fromMaybe "source account doesn't exist"
|> (flip Result.andThen) (Account.subtract tx.amount)
newTarget =
Dict.get targetId model.accounts
|> Result.fromMaybe "target account doesn't exist"
|> (flip Result.andThen) (Account.add tx.amount)
in
case ( newSource, newTarget ) of
( Ok newSource', Ok newTarget' ) ->
{ model
| accounts =
model.accounts
|> Dict.insert sourceId newSource'
|> Dict.insert targetId newTarget'
}
|> Ok
( Err message, _ ) ->
Err message
( _, Err message ) ->
Err message