@@ -59,7 +59,21 @@ defmodule SimpleBank do
59
59
end
60
60
61
61
@ spec withdrawl ( pid ( ) , String . t ( ) , pos_integer ( ) ) :: { :ok , { pos_integer ( ) , pos_integer ( ) } } | { :error , reason }
62
- def withdrawl ( bank_pid , account_id , amount ) do
62
+ def withdrawl ( bank_pid , account_id , amount ) when is_integer ( amount ) and amount > 0 do
63
+ case get_account_by_id ( bank_pid , account_id ) do
64
+ nil -> { :error , :missing_account }
65
+ account ->
66
+ if account . balance < amount do
67
+ { :error , :insufficient_funds }
68
+ else
69
+ account = GenServer . call ( bank_pid , { :withdrawal , account , amount } )
70
+ { :ok , account . balance }
71
+ end
72
+ end
73
+ end
74
+
75
+ def withdrawl ( _bank_pid , _account_id , amount ) when is_integer ( amount ) and amount <= 0 do
76
+ { :error , :pos_integer_only }
63
77
end
64
78
65
79
def init ( initial_state ) do
@@ -90,10 +104,20 @@ defmodule SimpleBank do
90
104
{ :reply , account , new_state }
91
105
end
92
106
107
+ def handle_call ( { :withdrawal , account , amount } , _from , state ) do
108
+ account = do_withdrawal ( account , amount )
109
+ new_state = update_account_in_state ( account , state )
110
+ { :reply , account , new_state }
111
+ end
112
+
93
113
def do_deposit ( account , amount ) do
94
114
Map . put ( account , :balance , account . balance + amount )
95
115
end
96
116
117
+ def do_withdrawal ( account , amount ) do
118
+ Map . put ( account , :balance , account . balance - amount )
119
+ end
120
+
97
121
def update_account_in_state ( account , state ) do
98
122
accounts = Enum . reject ( state , fn a -> a . id == account . id end )
99
123
[ accounts | account ]
0 commit comments