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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
|
module Main exposing (main)
import Browser exposing (Document, UrlRequest(..))
import Browser.Navigation as Nav
import Dict exposing (Dict)
import Html
exposing
( Attribute
, Html
, a
, button
, div
, hr
, input
, li
, p
, pre
, span
, table
, tbody
, td
, text
, th
, thead
, tr
, ul
)
import Html.Attributes
exposing
( class
, disabled
, max
, min
, placeholder
, step
, style
, title
, type_
, value
)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode as JD
import Json.Encode as JE
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
-- LOCALE
make_t : Language -> String -> String
make_t lang str =
case lang of
EN ->
str
ES ->
case str of
"Principal: " ->
"Capital: "
"Interest: " ->
"Interés: "
"% from total" ->
"% del total"
"Title..." ->
"Título..."
"Property price: " ->
"Precio del inmueble: "
"Initial contribution: " ->
"Contribución inicial: "
"Interest rate: " ->
"Tipo de interés: "
"Years: " ->
"Años: "
"VAT: " ->
"IVA/ITP: "
"Agent fee: " ->
"Honorarios agencia: "
"Simulate" ->
"Simular"
"Total to pay: " ->
"Total a pagar: "
"Total after early payments: " ->
"Total tras amortizaciones anticipadas: "
"Payed early: " ->
"Anticipado: "
"Saved: " ->
"Ahorro: "
"Initial payment: " ->
"Pago inicial: "
"Property: " ->
"Inmueble: "
"Financed (mortgage): " ->
"Financiado (hipoteca): "
"Year" ->
"Año"
"Month" ->
"Mes"
"Quota" ->
"Cuota"
"Pending" ->
"Pendiente"
"Updates" ->
"Actualizaciones"
_ ->
str
-- MAIN
main =
Browser.application
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
, onUrlRequest = SetUrl
, onUrlChange = ChangedUrl
}
-- MODEL
type alias Quota =
{ month : Int
, payed : Capital
, pending_principal : Float
}
quotaDecoder : JD.Decoder Quota
quotaDecoder =
JD.map3 Quota
(JD.field "period" JD.int)
(JD.field "payed" capitalDecoder)
(JD.field "pending_principal" JD.float)
type alias Capital =
{ principal : Float
, interest : Float
}
capitalDecoder : JD.Decoder Capital
capitalDecoder =
JD.map2 Capital
(JD.field "principal" JD.float)
(JD.field "interest" JD.float)
capitalSumView : Model -> Capital -> Html Msg
capitalSumView { t, settings } { principal, interest } =
let
partsTitle =
String.concat
[ t "Principal: "
, amountToString settings.currency principal
, "\n"
, t "Interest: "
, amountToString settings.currency interest
, " ("
, Round.round 2 (100 * interest / (principal + interest))
, t "% from total"
, ")"
]
in
amountView (titledAttrs partsTitle) settings.currency (principal + interest)
type alias MortgageSim =
{ updates : SimUpdates
, history : List Quota
, payed_noupdates : Capital
, payed_noprepays : Capital
, payed : Capital
, payed_amortized : Float
}
simDecoder : JD.Decoder MortgageSim
simDecoder =
JD.map6 MortgageSim
(JD.field "updates" simUpdatesDecoder)
(JD.field "history" (JD.list quotaDecoder))
(JD.field "payed_noupdates" capitalDecoder)
(JD.field "payed_noprepays" capitalDecoder)
(JD.field "payed" capitalDecoder)
(JD.field "payed_amortized" JD.float)
type alias RawSpecs =
{ title : String
, total : String
, initial : String
, rate : String
, i1 : String
, years : String
, vat : String
, fee : String
, updates : SimUpdates
}
defaultRawSpecs : RawSpecs
defaultRawSpecs =
{ title = ""
, total = "200000"
, initial = "40000"
, rate = "80"
, i1 = "1.621"
, years = "30"
, vat = "6"
, fee = "3"
, updates = defaultSimUpdates
}
rawSpecsParser : UQ.Parser RawSpecs
rawSpecsParser =
let
apply argParser funcParser =
UQ.map2 (<|) funcParser argParser
in
UQ.map RawSpecs
(UQ.map (Maybe.withDefault defaultRawSpecs.title) <| UQ.string "title")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.total) <| UQ.string "total")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.initial) <| UQ.string "initial")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.rate) <| UQ.string "rate")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.i1) <| UQ.string "i1")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.years) <| UQ.string "years")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.vat) <| UQ.string "vat")
|> apply (UQ.map (Maybe.withDefault defaultRawSpecs.fee) <| UQ.string "fee")
|> apply simUpdatesParser
rawSpecsToQS : RawSpecs -> List UB.QueryParameter
rawSpecsToQS { title, total, initial, rate, i1, years, vat, fee, updates } =
[ UB.string "title" title
, UB.string "total" total
, UB.string "initial" initial
, UB.string "rate" rate
, UB.string "i1" i1
, UB.string "years" years
, UB.string "vat" vat
, UB.string "fee" fee
]
++ simUpdatesToQS updates
modelToUrl : Model -> String
modelToUrl { settings, rawSpecs } =
UB.toQuery
(settingsToQS settings ++ rawSpecsToQS rawSpecs)
type SimUpdate
= Amortize Float
| SetI1 Float
simUpdateEncode : SimUpdate -> JE.Value
simUpdateEncode mupdate =
case mupdate of
Amortize f ->
JE.object [ ( "Amortize", JE.float f ) ]
SetI1 f ->
JE.object [ ( "SetI1", JE.float f ) ]
simUpdateDecoder : JD.Decoder SimUpdate
simUpdateDecoder =
JD.oneOf
[ JD.field "Amortize" <| JD.map Amortize JD.float
, JD.field "SetI1" <| JD.map SetI1 JD.float
]
simUpdateFlatten : List SimUpdate -> List SimUpdate
simUpdateFlatten us =
let
{ amortized, other } =
List.foldr
(\upd acc ->
case upd of
Amortize f ->
{ acc | amortized = acc.amortized + f }
SetI1 f ->
{ acc | other = upd :: acc.other }
)
{ amortized = 0, other = [] }
us
in
Amortize amortized :: other
type alias PeriodicUpdate =
{ period : Int
, from : Maybe Int
, to : Maybe Int
, upd : SimUpdate
}
periodicUpdateInMonth : Int -> PeriodicUpdate -> Bool
periodicUpdateInMonth month { period, from, to } =
let
base =
Maybe.withDefault 0 from
in
modBy period month == base && base <= month && Maybe.withDefault (month + 1) to > month
periodicUpdateEncode : PeriodicUpdate -> JE.Value
periodicUpdateEncode { period, from, to, upd } =
let
toJInt x =
case x of
Nothing ->
JE.null
Just val ->
JE.int val
in
JE.object
[ ( "period", JE.int period )
, ( "from", toJInt from )
, ( "to", toJInt to )
, ( "update", simUpdateEncode upd )
]
periodicUpdateDecoder : JD.Decoder PeriodicUpdate
periodicUpdateDecoder =
JD.map4 PeriodicUpdate
(JD.field "period" JD.int)
(JD.field "from" (JD.nullable JD.int))
(JD.field "to" (JD.nullable JD.int))
(JD.field "update" simUpdateDecoder)
type alias SimUpdates =
{ periodically : List PeriodicUpdate
, byMonth : List ( Int, SimUpdate )
}
defaultSimUpdates =
{ periodically = [], byMonth = [] }
simUpdatesParser : UQ.Parser SimUpdates
simUpdatesParser =
let
parseUpdate str =
String.dropLeft 1 str
|> String.toFloat
|> (case String.left 1 str of
"P" ->
Maybe.map Amortize
"I" ->
Maybe.map SetI1
_ ->
always Nothing
)
rawPeriodic str =
List.foldr
(\kv acc ->
case String.split "-" kv of
[ "p", v ] ->
{ acc | period = String.toInt v }
[ "f", v ] ->
{ acc | from = String.toInt v }
[ "t", v ] ->
{ acc | to = String.toInt v }
[ "u", v ] ->
{ acc | upd = parseUpdate v }
_ ->
acc
)
{ period = Nothing
, from = Nothing
, to = Nothing
, upd = Nothing
}
(String.split "," str)
parsePeriodic rp =
case ( rp.period, rp.upd ) of
( Just p, Just u ) ->
Just { period = p, from = rp.from, to = rp.to, upd = u }
_ ->
Nothing
parseByMonth str =
case String.split ":" str of
[ dr, ur ] ->
Maybe.map2 Tuple.pair (String.toInt dr) (parseUpdate ur)
_ ->
Nothing
in
UQ.map2 SimUpdates
(UQ.custom "u_period" (List.filterMap (parsePeriodic << rawPeriodic)))
(UQ.custom "u_bymon" (List.filterMap parseByMonth))
simUpdatesToQS : SimUpdates -> List UB.QueryParameter
simUpdatesToQS { periodically, byMonth } =
let
renderUpdate u =
case u of
Amortize f ->
"P" ++ Round.round 2 f
SetI1 f ->
"I" ++ Round.round 4 f
renderPeriod { period, from, to, upd } =
[ ( "p", Just (String.fromInt period) )
, ( "f", Maybe.map String.fromInt from )
, ( "t", Maybe.map String.fromInt to )
, ( "u", Just (renderUpdate upd) )
]
|> List.filterMap (\( k, vr ) -> Maybe.map (\v -> ( k, v )) vr)
|> List.map (\( k, v ) -> String.join "-" [ k, v ])
|> String.join ","
renderMonth ( m, u ) =
String.join ":" [ String.fromInt m, renderUpdate u ]
in
List.map (UB.string "u_period" << renderPeriod) periodically
++ List.map (UB.string "u_bymon" << renderMonth) byMonth
updatesInMonth : SimUpdates -> Int -> SimUpdates
updatesInMonth { periodically, byMonth } month =
let
newPeriodically =
List.filter (periodicUpdateInMonth month) periodically
newByMonth =
List.filter (\( m, updates ) -> m == month) byMonth
in
{ periodically = newPeriodically, byMonth = newByMonth }
simUpdatesEncode : SimUpdates -> JE.Value
simUpdatesEncode { periodically, byMonth } =
JE.object
[ ( "periodically", JE.list periodicUpdateEncode periodically )
, ( "by_month"
, JE.object <|
List.map (\( m, us ) -> ( String.fromInt m, simUpdateEncode us )) byMonth
)
]
simUpdatesDecoder : JD.Decoder SimUpdates
simUpdatesDecoder =
JD.map2 SimUpdates
(JD.field "periodically" (JD.list periodicUpdateDecoder))
(JD.field "by_month"
(JD.keyValuePairs simUpdateDecoder
|> JD.map
(\l ->
List.map (\( k, v ) -> ( Maybe.withDefault 0 (String.toInt k), v )) l
)
)
)
type alias SimSpecs =
{ principal : Float
, i1 : Float
, years : Int
, updates : SimUpdates
}
parseSimSpecs : RawSpecs -> Maybe SimSpecs
parseSimSpecs { total, rate, i1, years, updates } =
case
( List.map String.toFloat [ total, i1 ]
, List.map String.toInt [ rate, years ]
)
of
( [ Just totalValueF, Just i1F ], [ Just rateI, Just yearsI ] ) ->
Just
{ principal = totalValueF * toFloat rateI / 100
, i1 = i1F
, years = yearsI
, updates = updates
}
_ ->
Nothing
simSpecsEncode : SimSpecs -> JE.Value
simSpecsEncode { principal, i1, years, updates } =
JE.object
[ ( "principal", JE.float principal )
, ( "i1", JE.float <| i1 / 100 )
, ( "years", JE.int years )
, ( "updates", simUpdatesEncode updates )
]
runSim : Model -> SimSpecs -> Cmd Msg
runSim m simSpecs =
Http.post
{ url = UB.absolute [ "api", "simulate" ] []
, body = Http.jsonBody <| simSpecsEncode simSpecs
, expect = Http.expectJson (GotSim m) simDecoder
}
type Language
= ES
| EN
langToString : Language -> String
langToString lang =
case lang of
ES ->
"ES"
EN ->
"EN"
langFromString : String -> Language
langFromString lang =
case lang of
"ES" ->
ES
_ ->
EN
type Currency
= USD
| EUR
currencyToString : Currency -> String
currencyToString curr =
case curr of
EUR ->
"EUR"
USD ->
"USD"
currencyFromString : String -> Currency
currencyFromString curr =
case curr of
"EUR" ->
EUR
_ ->
USD
currencySymbol : Currency -> String
currencySymbol curr =
case curr of
EUR ->
"€"
USD ->
"$"
currencySep : Currency -> { thousands : Char, decimal : Char }
currencySep curr =
case curr of
EUR ->
{ thousands = '.', decimal = ',' }
USD ->
{ thousands = ',', decimal = '.' }
type CurrencyOrder
= Prefix
| Postfix
currencyOrder : Currency -> CurrencyOrder
currencyOrder curr =
case curr of
EUR ->
Postfix
USD ->
Prefix
type alias Settings =
{ lang : Language
, currency : Currency
}
defaultSettings : Settings
defaultSettings =
{ lang = ES
, currency = EUR
}
settingsParser : UQ.Parser Settings
settingsParser =
UQ.map2 Settings
(UQ.map (Maybe.withDefault defaultSettings.lang << Maybe.map langFromString) <| UQ.string "lang")
(UQ.map (Maybe.withDefault defaultSettings.currency << Maybe.map currencyFromString) <| UQ.string "currency")
settingsToQS : Settings -> List UB.QueryParameter
settingsToQS { lang, currency } =
[ UB.string "lang" (langToString lang)
, UB.string "currency" (currencyToString currency)
]
type alias Model =
{ settings : Settings
, navKey : Nav.Key
, error : String
, rawSpecs : RawSpecs
, expandedYears : Set Int
, simulation : Maybe ( RawSpecs, MortgageSim )
, t : String -> String
}
type Route
= NotFound
| Root ( Settings, RawSpecs )
routeQuery : Route -> ( Settings, RawSpecs )
routeQuery route =
case route of
NotFound ->
( defaultSettings, defaultRawSpecs )
Root query ->
query
routeParser : U.Parser (Route -> a) a
routeParser =
U.oneOf
[ U.map Root (U.top <?> UQ.map2 Tuple.pair settingsParser rawSpecsParser)
]
toRoute : Url -> Route
toRoute url =
Maybe.withDefault NotFound (U.parse routeParser url)
init : () -> Url -> Nav.Key -> ( Model, Cmd Msg )
init () url navKey =
let
( settings, rawSpecs ) =
routeQuery (toRoute url)
in
( { settings = settings
, navKey = navKey
, error = ""
, rawSpecs = rawSpecs
, expandedYears = Set.empty
, simulation = Nothing
, t = make_t settings.lang
}
, 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 total =
case ( String.toFloat val, String.toInt total ) 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
| TotalValue
| Rate
| Initial
| I1
| Years
| VAT
| Fee
type SettingsChange
= ToggleLang
| ToggleCurrency
type Msg
= SetUrl UrlRequest
| ChangedUrl Url
| UpdateSpecs SpecField String
| UpdateSettings SettingsChange
| RunSim SimSpecs
| GotSim 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
GotSim old_m (Ok msim) ->
( { m
| simulation =
Just ( old_m.rawSpecs, msim )
}
, Cmd.none
)
GotSim _ (Err err) ->
( { m | error = errorToString err }, Cmd.none )
RunSim specs ->
( m
, batch [ runSim m specs, Nav.pushUrl m.navKey (modelToUrl m) ]
)
SetUrl (Internal url) ->
( m, Nav.pushUrl m.navKey (Url.toString url) )
SetUrl (External url) ->
( m, Nav.load url )
ChangedUrl url ->
let
( settings, rawSpecs ) =
routeQuery (toRoute url)
in
( { m
| settings = settings
, rawSpecs = rawSpecs
, t = make_t settings.lang
}
, Cmd.none
)
UpdateSpecs field val ->
let
rawSpecs =
m.rawSpecs
newRawSpecs =
case field of
Title ->
{ rawSpecs | title = val }
TotalValue ->
{ rawSpecs
| total = val
, initial =
Maybe.withDefault rawSpecs.initial <|
convertInitialRate rateToInitial rawSpecs.rate val
}
Rate ->
{ rawSpecs
| rate = val
, initial =
Maybe.withDefault rawSpecs.initial <|
convertInitialRate rateToInitial val rawSpecs.total
}
Initial ->
{ rawSpecs
| initial = val
, rate =
Maybe.withDefault rawSpecs.rate <|
convertInitialRate initialToRate val rawSpecs.total
}
I1 ->
{ rawSpecs | i1 = val }
Years ->
{ rawSpecs | years = val }
VAT ->
{ rawSpecs | vat = val }
Fee ->
{ rawSpecs | fee = val }
in
( { m | rawSpecs = newRawSpecs }, Cmd.none )
SetExpandedYears eyears ->
( { m | expandedYears = eyears }, Cmd.none )
UpdateSettings change ->
let
settings =
m.settings
newSettings =
case change of
ToggleLang ->
{ settings
| lang =
case settings.lang of
EN ->
ES
ES ->
EN
}
ToggleCurrency ->
{ settings
| currency =
case settings.currency of
EUR ->
USD
USD ->
EUR
}
in
( m, Nav.pushUrl m.navKey (modelToUrl { m | settings = newSettings }) )
-- VIEW (THEME)
primaryButAttrs : List (Attribute Msg)
primaryButAttrs =
[ class "px-3 rounded-md bg-lime-300 enabled:active:bg-lime-400 border border-lime-600 disabled:opacity-75" ]
secondaryButAttrs : List (Attribute Msg)
secondaryButAttrs =
[ class "px-3 rounded-md text-gray-700 enabled:active:bg-lime-400 border border-2 border-gray-500 disabled:opacity-75" ]
clickableAttrs : Msg -> List (Attribute Msg)
clickableAttrs msg =
[ onClick msg, class "text-lime-600", style "cursor" "pointer" ]
txtInput : List (Attribute Msg) -> (String -> Msg) -> String -> Html Msg
txtInput attributes onInputMsg valueTxt =
input
([ class "border border-lime-500 border-2 px-2 focus:outline focus:outline-lime-500"
, onInput onInputMsg
, value valueTxt
]
++ attributes
)
[]
slider : List (Attribute Msg) -> (String -> Msg) -> String -> Html Msg
slider attributes onInputMsg valueTxt =
input
(attributes
++ [ type_ "range"
, class "mx-1 accent-lime-400"
, onInput onInputMsg
, value valueTxt
]
)
[]
-- VIEW
insertThousandsSep : Currency -> String -> String
insertThousandsSep currency str =
let
l =
List.reverse <| String.toList str
indexed =
List.map2 Tuple.pair (List.range 0 (String.length str)) l
withCommas =
List.concatMap
(\( i, c ) ->
if i > 0 && modBy 3 i == 0 then
[ (currencySep currency).thousands, c ]
else
[ c ]
)
indexed
in
String.fromList <| List.reverse withCommas
amountToString : Currency -> Float -> String
amountToString currency amount =
let
amountStr =
Round.round 2 amount
in
case String.split "." amountStr of
int :: float :: [] ->
let
strs =
[ insertThousandsSep currency int
, String.fromChar (currencySep currency).decimal
, float
]
in
String.join "" <|
case currencyOrder currency of
Prefix ->
[ currencySymbol currency ] ++ strs
Postfix ->
strs ++ [ currencySymbol currency ]
_ ->
amountStr
amountView : List (Attribute Msg) -> Currency -> Float -> Html Msg
amountView attrs currency amount =
let
amountStr =
Round.round 2 amount
in
span attrs <|
case String.split "." amountStr of
int :: float :: [] ->
let
floatPart =
case float of
"00" ->
[]
_ ->
[ text <| String.fromChar (currencySep currency).decimal
, span [ class "text-sm" ] [ text float ]
]
els =
[ text (insertThousandsSep currency int) ] ++ floatPart
in
case currencyOrder currency of
Prefix ->
[ text (currencySymbol currency) ] ++ els
Postfix ->
els ++ [ text (currencySymbol currency) ]
_ ->
[ text amountStr ]
titledAttrs : String -> List (Attribute Msg)
titledAttrs title_ =
[ class "underline", title title_ ]
specsView : Model -> Html Msg
specsView { t, settings, rawSpecs } =
let
{ title, total, rate, initial, i1, years, vat, fee } =
rawSpecs
simButAttrs =
case parseSimSpecs rawSpecs of
Nothing ->
[ disabled True ]
Just specs ->
[ onClick (RunSim specs) ]
in
div []
[ div []
[ input
[ class "min-w-full mb-2 py-1 px-3 text-xl font-bold"
, placeholder (t "Title...")
, value title
, onInput (UpdateSpecs Title)
]
[]
]
, div [ class "flex my-1" ]
[ text (t "Property price: ")
, slider [ Html.Attributes.min "50000", Html.Attributes.max "800000", step "5000" ]
(UpdateSpecs TotalValue)
total
, txtInput [ class "w-[100px]", Html.Attributes.min "0" ]
(UpdateSpecs TotalValue)
total
, text <| currencySymbol settings.currency
]
, div [ class "flex my-1" ]
[ div []
[ text (t "Initial contribution: ")
, txtInput [ class "w-[100px]", Html.Attributes.min "0", Html.Attributes.max total ]
(UpdateSpecs Initial)
initial
, text <| currencySymbol settings.currency
]
, div [ class "ml-4" ]
[ text " ("
, txtInput [ class "w-[55px]", Html.Attributes.min "10", Html.Attributes.max "100" ]
(UpdateSpecs Rate)
rate
, text "%)"
]
]
, div [ class "my-1" ]
[ text (t "Interest rate: ")
, txtInput [ class "w-[80px]", Html.Attributes.min "0", Html.Attributes.max "100" ]
(UpdateSpecs I1)
i1
, text " % (nominal)"
]
, div [ class "flex my-1" ]
[ text (t "Years: ")
, slider [ Html.Attributes.min "1", Html.Attributes.max "40", step "1" ]
(UpdateSpecs Years)
years
, text years
]
, div [ class "flex my-1" ]
[ div []
[ text (t "VAT: ")
, txtInput [ class "w-[55px] mx-1", Html.Attributes.min "0", Html.Attributes.max "50" ]
(UpdateSpecs VAT)
vat
, text "%"
]
, div [ class "ml-6" ]
[ text (t "Agent fee: ")
, txtInput [ class "w-[55px] mx-1", Html.Attributes.min "0", Html.Attributes.max "10" ]
(UpdateSpecs Fee)
fee
, text "%"
]
]
, div [ class "flex justify-between my-1 mt-2" ]
[ button (primaryButAttrs ++ simButAttrs) [ text (t "Simulate") ]
, div [ class "flex" ]
[ button (secondaryButAttrs ++ [ class "mr-1", onClick (UpdateSettings ToggleLang) ])
[ text <| langToString settings.lang ]
, button (secondaryButAttrs ++ [ class "mr-1", onClick (UpdateSettings ToggleCurrency) ])
[ text <| currencySymbol settings.currency ]
]
]
]
monthToYear : Int -> Int
monthToYear month =
((month - 1) // 12) + 1
simUpdateView : List (Attribute Msg) -> Model -> SimUpdate -> Html Msg
simUpdateView attrs m upd =
case upd of
Amortize f ->
p attrs [ text "+", amountView [] m.settings.currency f ]
SetI1 f ->
p attrs [ text <| String.fromFloat (f * 100), text "%" ]
quotaView : Model -> MortgageSim -> Quota -> Html Msg
quotaView m { updates } { month, payed, pending_principal } =
let
monthUpdates =
updatesInMonth updates month
year =
monthToYear month
monthInExpandedYear =
Set.member year m.expandedYears
( toggleYearIcon, newExpandedYears ) =
if monthInExpandedYear then
( "− ", Set.remove year m.expandedYears )
else
( "+ ", Set.insert year m.expandedYears )
( yearField, updatesField ) =
if modBy 12 (month - 1) == 0 then
( div []
[ span (clickableAttrs (SetExpandedYears newExpandedYears)) [ text toggleYearIcon ]
, text (String.fromInt year)
]
, text "..."
)
else
( text ""
, div []
(List.map (simUpdateView [ class "bg-lime-200" ] m << .upd) monthUpdates.periodically
++ (List.map (simUpdateView [ class "bg-lime-200" ] m) <|
List.map Tuple.second monthUpdates.byMonth
)
)
)
in
if modBy 12 (month - 1) == 0 || monthInExpandedYear then
tr []
(List.map (\t -> td [ class "px-3 py-1 border border-gray-300" ] [ t ])
[ yearField
, text (String.fromInt month)
, capitalSumView m payed
, amountView [] m.settings.currency pending_principal
, updatesField
]
)
else
text ""
mortgageView : Model -> MortgageSim -> Html Msg
mortgageView m sim =
let
titles =
[ "Year", "Month", "Quota", "Pending", "Updates" ]
head =
thead [ class "bg-lime-100" ]
[ tr []
(List.map
(\txt ->
th [ class "px-3 py-1 border border-gray-300" ]
[ text <| m.t txt ]
)
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 sim) sim.history)
]
]
simView : Model -> ( RawSpecs, MortgageSim ) -> Html Msg
simView m ( rawSpecs, sim ) =
let
currency =
m.settings.currency
t =
m.t
parseFloat =
Maybe.withDefault 0 << String.toFloat
total =
parseFloat rawSpecs.total
initial =
parseFloat rawSpecs.initial
vat =
total * parseFloat rawSpecs.vat / 100
fee =
total * parseFloat rawSpecs.fee / 100
overview title financed extraLis =
div [ class "my-2 p-1 border-2 rounded-md border-gray-400" ]
[ p [ class "text-lg" ]
[ text title
, amountView [ class "font-bold" ]
currency
(financed.principal
+ financed.interest
+ initial
+ vat
+ fee
)
]
, ul [ class "list-inside list-disc" ]
([ li []
[ text <| t "Initial payment: "
, amountView [] currency (initial + vat + fee)
]
, li []
[ text <| t "Financed (mortgage): "
, capitalSumView m financed
]
]
++ extraLis
)
]
in
div []
[ hr [ class "my-5" ] []
, p []
[ text <| t "Initial payment: "
, amountView [ class "font-bold" ] currency (initial + vat + fee)
]
, ul [ class "list-inside list-disc" ]
[ li []
[ text <| t "Property: "
, amountView [] currency initial
]
, li []
[ text <| t "Agent fee: "
, amountView [] currency fee
]
, li []
[ text <| t "VAT: "
, amountView [] currency vat
]
]
, overview (t "Total to pay: ") sim.payed_noprepays []
, if sim.payed_amortized > 0 then
overview (t "Total after early payments: ") sim.payed <|
[ li []
[ text <| t "Payed early: "
, amountView [] currency sim.payed_amortized
]
, li []
[ text <| t "Saved: "
, amountView [] currency (sim.payed_noprepays.interest - sim.payed.interest)
]
]
else
text ""
, mortgageView m sim
]
view : Model -> Document Msg
view m =
{ title = "Hiccup"
, body =
[ div [ class "flex flex-col max-w-xl 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
, case m.simulation of
Nothing ->
text ""
Just sim ->
simView m sim
, span [ class "text-rose-600" ] [ text m.error ]
]
]
]
}
|