aboutsummaryrefslogtreecommitdiff
path: root/src/client/Model/PaymentCategory.elm
blob: a4fceb1fff7116798671dfb90f17fa1f3c32349b (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
module Model.PaymentCategory exposing
  ( PaymentCategories
  , paymentCategoriesDecoder
  , search
  , groupPaymentsByCategory
  , isCategoryUnused
  , save
  )

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

import Model.Category exposing (CategoryId, categoryIdDecoder)
import Model.Payment exposing (Payments)
import Utils.Json as Json
import Utils.List as List
import Utils.Search as Search

type alias PaymentCategories = List PaymentCategory

type alias PaymentCategory =
  { name : String
  , category : CategoryId
  }

paymentCategoriesDecoder : Decoder PaymentCategories
paymentCategoriesDecoder =
  Decode.list <| Decode.map2 PaymentCategory
    (Decode.field "name" Decode.string)
    (Decode.field "category" categoryIdDecoder)

groupPaymentsByCategory : PaymentCategories -> Payments -> List (CategoryId, Payments)
groupPaymentsByCategory paymentCategories payments =
  payments
    |> List.groupBy (\payment ->
         search payment.name paymentCategories
           |> Maybe.withDefault -1
       )
    |> List.filterMap (\(category, payments) ->
         case category of
           -1 -> Nothing
           _ -> Just (category, payments)
       )

search : String -> PaymentCategories -> Maybe CategoryId
search paymentName paymentCategories =
  paymentCategories
    |> List.find (\pc -> Search.format pc.name == Search.format paymentName)
    |> Maybe.map .category

isCategoryUnused : CategoryId -> PaymentCategories -> Bool
isCategoryUnused category paymentCategories =
  paymentCategories
    |> List.find ((==) category << .category)
    |> Maybe.isNothing

save : String -> CategoryId -> PaymentCategories -> PaymentCategories
save name category paymentCategories =
  { name = name, category = category } :: List.filter (\pc -> not <| Search.format pc.name == Search.format name) paymentCategories