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 -> []