aboutsummaryrefslogtreecommitdiff
path: root/src/client/Model/Payers.elm
blob: 983e7b34a636d334cf132ecb7ecb294db3c5a5be (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
module Model.Payers
  ( Payers
  , ExceedingPayer
  , payersDecoder
  , updatePayers
  , getOrderedExceedingPayers
  ) where

import Json.Decode as Json exposing (..)
import Dict exposing (..)
import List
import Maybe

import Model.User exposing (UserId, userIdDecoder)

type alias Payers = Dict UserId Int

payersDecoder : Decoder Payers
payersDecoder = Json.map Dict.fromList (list payerDecoder)

payerDecoder : Decoder (UserId, Int)
payerDecoder =
  object2 (,)
    ("userId" := userIdDecoder)
    ("totalPayment" := int)

updatePayers : Payers -> UserId -> Int -> Payers
updatePayers payers userId amountDiff =
  Dict.update
    userId
    (\mbAmount ->
      case mbAmount of
        Just amount -> Just (amount + amountDiff)
        Nothing -> Nothing
    )
    payers

type alias ExceedingPayer =
  { userId : UserId
  , amount : Int
  }

getOrderedExceedingPayers : Payers -> List ExceedingPayer
getOrderedExceedingPayers payers =
  let orderedPayers =
        Dict.toList payers
          |> List.map (\(userId, amount) -> ExceedingPayer userId amount)
          |> List.sortBy .amount
      maybeMinAmount =
        List.head orderedPayers
          |> Maybe.map .amount
  in  case maybeMinAmount of
        Just minAmount ->
          orderedPayers
            |> List.map (\payer -> { payer | amount <- payer.amount - minAmount })
            |> List.filter (\payer -> payer.amount /= 0)
            |> List.reverse
        Nothing ->
          []