aboutsummaryrefslogtreecommitdiff
path: root/src/client/elm/Model/Payment.elm
blob: 27d5bedc68a3613d73a2154fc4680d88b0435969 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module Model.Payment
  ( perPage
  , Payments
  , Payment
  , PaymentId
  , Frequency(..)
  , paymentsDecoder
  , paymentIdDecoder
  , deletePayment
  , totalPayments
  , punctual
  , monthly
  ) where

import Date exposing (..)
import Json.Decode as Json exposing ((:=))

import Model.User exposing (UserId, userIdDecoder)
import Model.Date exposing (dateDecoder)

perPage : Int
perPage = 8

type alias Payments = List Payment

type alias Payment =
  { id : PaymentId
  , creation : Date
  , name : String
  , cost : Int
  , userId : UserId
  , frequency : Frequency
  }

type alias PaymentId = Int

type Frequency = Punctual | Monthly

paymentsDecoder : Json.Decoder Payments
paymentsDecoder = Json.list paymentDecoder

paymentDecoder : Json.Decoder Payment
paymentDecoder =
  Json.object6 Payment
    ("id" := paymentIdDecoder)
    ("creation" := dateDecoder)
    ("name" := Json.string)
    ("cost" := Json.int)
    ("userId" := userIdDecoder)
    ("frequency" := frequencyDecoder)

paymentIdDecoder : Json.Decoder PaymentId
paymentIdDecoder = Json.int

frequencyDecoder : Json.Decoder Frequency
frequencyDecoder =
  Json.customDecoder
    Json.string
    (\input -> case input of
      "Punctual" -> Ok Punctual
      "Monthly" -> Ok Monthly
      _ -> Err ("Could not deduce Punctual nor Monthly from " ++ input)
    )

deletePayment : PaymentId -> Payments -> Payments
deletePayment paymentId = List.filter (((/=) paymentId) << .id)

totalPayments : (Payment -> Bool) -> UserId -> Payments -> Int
totalPayments paymentFilter userId payments =
  payments
    |> List.filter (\payment ->
         paymentFilter payment
         && payment.userId == userId
         && payment.frequency == Punctual
       )
    |> List.map .cost
    |> List.sum

punctual : Payments -> Payments
punctual = List.filter ((==) Punctual << .frequency)

monthly : UserId -> Payments -> Payments
monthly userId = List.filter (\p -> p.frequency == Monthly && p.userId == userId)