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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
|
module Main exposing (main)
import Browser exposing (Document, UrlRequest(..))
import Browser.Navigation as Nav
import Html
exposing
( Attribute
, Html
, a
, button
, div
, hr
, input
, span
, table
, tbody
, td
, text
, th
, thead
, tr
)
import Html.Attributes
exposing
( class
, disabled
, href
, max
, min
, placeholder
, step
, style
, title
, type_
, value
)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode exposing (Decoder, field, float, int, list, map2, map3, map4)
import Json.Encode as Encode exposing (Value, object)
import Platform.Cmd exposing (batch)
import Round
import Set exposing (Set)
import Url exposing (Url)
import Url.Builder as UB
import Url.Parser as U exposing ((<?>))
import Url.Parser.Query as UQ
-- MAIN
main =
Browser.application
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
, onUrlRequest = SetUrl
, onUrlChange = ChangedUrl
}
-- MODEL
type alias Quota =
{ period : Int
, payed : Capital
, pending_principal : Float
}
quotaDecoder : Decoder Quota
quotaDecoder =
map3 Quota
(field "period" int)
(field "payed" capitalDecoder)
(field "pending_principal" float)
type alias Capital =
{ principal : Float
, interest : Float
}
capitalDecoder : Decoder Capital
capitalDecoder =
map2 Capital
(field "principal" float)
(field "interest" float)
type alias MortgageSim =
{ history : List Quota
, topay : Capital
, payed : Capital
, payed_amortized : Float
}
simDecoder : Decoder MortgageSim
simDecoder =
map4 MortgageSim
(field "history" (list quotaDecoder))
(field "topay" capitalDecoder)
(field "payed" capitalDecoder)
(field "payed_amortized" float)
type alias RawSpecs =
{ title : String
, totalValue : String
, initial : String
, financedRate : String
, i1 : String
, years : String
}
defaultRawSpecs : RawSpecs
defaultRawSpecs =
{ title = ""
, totalValue = "200000"
, initial = "40000"
, financedRate = "80"
, i1 = "1.621"
, years = "30"
}
rawSpecsParser : UQ.Parser RawSpecs
rawSpecsParser =
UQ.map6 RawSpecs
(UQ.map (Maybe.withDefault defaultRawSpecs.title) <| UQ.string "title")
(UQ.map (Maybe.withDefault defaultRawSpecs.totalValue) <| UQ.string "totalValue")
(UQ.map (Maybe.withDefault defaultRawSpecs.initial) <| UQ.string "initial")
(UQ.map (Maybe.withDefault defaultRawSpecs.financedRate) <| UQ.string "financedRate")
(UQ.map (Maybe.withDefault defaultRawSpecs.i1) <| UQ.string "i1")
(UQ.map (Maybe.withDefault defaultRawSpecs.years) <| UQ.string "years")
rawSpecsToURL : RawSpecs -> String
rawSpecsToURL { title, totalValue, initial, financedRate, i1, years } =
UB.toQuery <|
[ UB.string "title" title
, UB.string "totalValue" totalValue
, UB.string "initial" initial
, UB.string "financedRate" financedRate
, UB.string "i1" i1
, UB.string "years" years
]
type alias MortgageSpecs =
{ principal : Float
, i1 : Float
, years : Int
}
parseMortgageSpecs : RawSpecs -> Maybe MortgageSpecs
parseMortgageSpecs { totalValue, financedRate, i1, years } =
case
( List.map String.toFloat [ totalValue, i1 ]
, List.map String.toInt [ financedRate, years ]
)
of
( [ Just totalValueF, Just i1F ], [ Just rate, Just yearsI ] ) ->
Just { principal = totalValueF * toFloat rate / 100, i1 = i1F, years = yearsI }
_ ->
Nothing
mortgageSpecsToURL : MortgageSpecs -> String
mortgageSpecsToURL { principal, i1, years } =
UB.absolute [ "/api/simulate" ]
[ UB.string "principal" (String.fromFloat principal)
, UB.string "i1" (String.fromFloat (i1 / 100))
, UB.int "years" years
]
runMortgageSim : Model -> MortgageSpecs -> Cmd Msg
runMortgageSim m mortgageSpecs =
Http.get
{ url = mortgageSpecsToURL mortgageSpecs
, expect = Http.expectJson (GotMortgageSim m) simDecoder
}
type alias Model =
{ error : String
, navKey : Nav.Key
, rawSpecs : RawSpecs
, expandedYears : Set Int
, simulation : Maybe ( RawSpecs, MortgageSim )
}
type Route
= NotFound
| Root RawSpecs
routeQuery : Route -> RawSpecs
routeQuery route =
case route of
NotFound ->
defaultRawSpecs
Root query ->
query
routeParser : U.Parser (Route -> a) a
routeParser =
U.oneOf
[ U.map Root (U.top <?> rawSpecsParser)
]
toRoute : Url -> Route
toRoute url =
Maybe.withDefault NotFound (U.parse routeParser url)
init : () -> Url -> Nav.Key -> ( Model, Cmd Msg )
init () url navKey =
( { navKey = navKey
, error = ""
, rawSpecs = routeQuery (toRoute url)
, expandedYears = Set.empty
, simulation = Nothing
}
, Cmd.none
)
-- UPDATE
initialToRate : Float -> Int -> Float
initialToRate initial principal =
100 - (100 * initial / toFloat principal)
rateToInitial : Float -> Int -> Float
rateToInitial rate principal =
toFloat principal * ((100 - rate) / 100)
convertInitialRate : (Float -> Int -> Float) -> String -> String -> Maybe String
convertInitialRate convert val totalValue =
case ( String.toFloat val, String.toInt totalValue ) of
( Just x, Just totalValueF ) ->
Just <| String.fromFloat <| convert x totalValueF
_ ->
Nothing
errorToString : Http.Error -> String
errorToString error =
case error of
Http.BadUrl url ->
"The URL " ++ url ++ " was invalid"
Http.Timeout ->
"Unable to reach the server, try again"
Http.NetworkError ->
"Unable to reach the server, check your network connection"
Http.BadStatus 500 ->
"The server had a problem, try again later"
Http.BadStatus 400 ->
"Verify your information and try again"
Http.BadStatus _ ->
"Unknown error"
Http.BadBody errorMessage ->
errorMessage
type SpecField
= Title
| Principal
| Rate
| Initial
| I1
| Years
type Msg
= SetUrl UrlRequest
| ChangedUrl Url
| UpdateSpecs SpecField String
| RunMortgageSim MortgageSpecs
| GotMortgageSim Model (Result Http.Error MortgageSim)
| SetExpandedYears (Set Int)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg m =
let
_ =
Debug.log "UPDATE!" msg
in
case msg of
GotMortgageSim old_m (Ok msim) ->
( { m
| simulation =
Just ( old_m.rawSpecs, msim )
}
, Cmd.none
)
GotMortgageSim _ (Err err) ->
( { m | error = errorToString err }, Cmd.none )
RunMortgageSim specs ->
( m
, batch
[ runMortgageSim m specs
, Nav.pushUrl m.navKey (rawSpecsToURL m.rawSpecs)
]
)
SetUrl (Internal url) ->
( m, Nav.pushUrl m.navKey (Url.toString url) )
SetUrl (External url) ->
( m, Nav.load url )
ChangedUrl url ->
( m, Cmd.none )
UpdateSpecs field val ->
let
rawSpecs =
m.rawSpecs
newRawSpecs =
case field of
Title ->
{ rawSpecs | title = val }
Principal ->
{ rawSpecs
| totalValue = val
, initial =
Maybe.withDefault rawSpecs.initial <|
convertInitialRate rateToInitial rawSpecs.financedRate val
}
Rate ->
{ rawSpecs
| financedRate = val
, initial =
Maybe.withDefault rawSpecs.initial <|
convertInitialRate rateToInitial val rawSpecs.totalValue
}
Initial ->
{ rawSpecs
| initial = val
, financedRate =
Maybe.withDefault rawSpecs.financedRate <|
convertInitialRate initialToRate val rawSpecs.totalValue
}
I1 ->
{ rawSpecs | i1 = val }
Years ->
{ rawSpecs | years = val }
in
( { m | rawSpecs = newRawSpecs }, Cmd.none )
SetExpandedYears eyears ->
( { m | expandedYears = eyears }, Cmd.none )
-- VIEW (THEME)
butAttrs : List (Attribute Msg)
butAttrs =
[ class "px-3 rounded-md bg-lime-300 enabled:active:bg-lime-400 border border-lime-600 disabled:opacity-75" ]
clickableAttrs : Msg -> List (Attribute Msg)
clickableAttrs msg =
[ onClick msg, class "text-lime-600", style "cursor" "pointer" ]
-- VIEW
specsView : RawSpecs -> Html Msg
specsView rawSpecs =
let
{ title, totalValue, financedRate, initial, i1, years } =
rawSpecs
simButAttrs =
case parseMortgageSpecs rawSpecs of
Nothing ->
[ disabled True ]
Just specs ->
[ onClick (RunMortgageSim specs) ]
in
div []
[ div []
[ input
[ class "min-w-full mb-2 py-1 px-3 text-xl font-bold lime-100"
, placeholder "Title..."
, value title
, onInput (UpdateSpecs Title)
]
[]
]
, div [ class "flex my-1" ]
[ text "Property price: "
, input
[ type_ "range"
, class "accent-lime-400"
, Html.Attributes.min "0"
, Html.Attributes.max "1000000"
, step "5000"
, value totalValue
, onInput (UpdateSpecs Principal)
]
[]
, text totalValue
]
, div [ class "flex my-1" ]
[ div [ class "" ]
[ text "Initial contribution: "
, input
[ class "w-[100px] border border-lime-500 border-2 px-2 focus:outline focus:outline-lime-500"
, Html.Attributes.min "0"
, Html.Attributes.max totalValue
, value initial
, onInput (UpdateSpecs Initial)
]
[]
]
, div [ class "ml-4" ]
[ text " ("
, input
[ class "w-[55px] border border-lime-500 border-2 px-2 focus:outline focus:outline-lime-500"
, Html.Attributes.min "10"
, Html.Attributes.max "100"
, value financedRate
, onInput (UpdateSpecs Rate)
]
[]
, text "%)"
]
]
, div [ class "my-1" ]
[ text "Interest rate: "
, input
[ class "w-[80px] border border-lime-500 border-2 px-2 focus:outline focus:outline-lime-500"
, Html.Attributes.min "0"
, Html.Attributes.max "100"
, value i1
, onInput (UpdateSpecs I1)
]
[]
, text " % (nominal)"
]
, div [ class "flex my-1 mb-2" ]
[ text "Years: "
, input
[ type_ "range"
, class "accent-lime-400"
, Html.Attributes.min "1"
, Html.Attributes.max "50"
, step "1"
, value years
, onInput (UpdateSpecs Years)
]
[]
, text years
]
, button (butAttrs ++ simButAttrs) [ text "Simulate" ]
]
historyView : Model -> List Quota -> Html Msg
historyView m quotas =
let
titles =
[ "Year", "Month", "Quota", "Pending" ]
head =
thead [ class "bg-lime-100" ] [ tr [] (List.map (\t -> th [ class "px-3 py-1 border border-gray-300" ] [ text t ]) titles) ]
in
div [ class "pt-4 flex flex-col items-center" ]
[ table [ class "border border-collapse bg-gray-50 border-gray-400" ]
[ head
, tbody []
(List.map (quotaView m)
quotas
)
]
]
capitalSumView : Capital -> Html Msg
capitalSumView { principal, interest } =
let
partsTitle =
String.concat
[ "Principal: "
, Round.round 2 principal
, "\nInterest: "
, Round.round 2 interest
, " ("
, Round.round 2 (100 * interest / (principal + interest))
, "% from total)"
]
in
span [ class "underline", title partsTitle ] [ text (Round.round 2 (principal + interest)) ]
periodToYear : Int -> Int
periodToYear period =
((period - 1) // 12) + 1
quotaView : Model -> Quota -> Html Msg
quotaView m { period, payed, pending_principal } =
let
year =
periodToYear period
yearExpanded =
Set.member year m.expandedYears
in
if modBy 12 (period - 1) == 0 then
tr []
(List.map (\t -> td [ class "px-3 py-1 border border-gray-300" ] [ t ])
[ div []
[ span
(clickableAttrs
(SetExpandedYears
((if yearExpanded then
Set.remove
else
Set.insert
)
year
m.expandedYears
)
)
)
[ text
(if yearExpanded then
"− "
else
"+ "
)
]
, text (String.fromInt year)
]
, text
(String.fromInt period)
, capitalSumView payed
, text (Round.round 2 pending_principal)
]
)
else if yearExpanded then
tr []
(List.map (\t -> td [ class "px-3 py-1 border border-gray-300" ] [ t ])
[ text ""
, text
(String.fromInt period)
, capitalSumView payed
, text (Round.round 2 pending_principal)
]
)
else
text ""
simView : Model -> ( RawSpecs, MortgageSim ) -> Html Msg
simView m ( rawSpecs, { history, topay, payed } ) =
let
initial =
Maybe.withDefault 0 <| String.toFloat rawSpecs.initial
total =
topay.principal + topay.interest + initial
in
div []
[ hr [ class "my-5" ] []
, div []
[ text "To pay: "
, text <| Round.round 2 total
, text " ("
, text <| Round.round 2 initial
, text " initial + "
, capitalSumView topay
, text " financed)"
]
-- , div [] [ text "payed: ", capitalSumView payed ]
, historyView m history
]
view : Model -> Document Msg
view m =
{ title = "Hiccup"
, body =
[ div [ class "flex flex-col max-w-lg mx-auto items-center mt-2 p-3 border-2 rounded-md border-gray-500 bg-gray-100" ]
[ div [ class "min-w-full" ]
[ specsView m.rawSpecs
, case m.simulation of
Nothing ->
text ""
Just sim ->
simView m sim
, text m.error
]
]
]
}
|