summaryrefslogtreecommitdiff
path: root/Handler/Common.hs
blob: a1ae34bf8799bbf6f661d698a0adef2e42691f3f (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
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
{-# LANGUAGE ApplicativeDo #-}

module Handler.Common
  ( inventoryListing
  , itemForm
  , referenceListing
  , referenceForm
  , kinds
  , InventoryState(..)
  , ReferenceState(..)
  , FormState(..)
  , HasFormState(..)
  , stockSort, referenceSort
  ) where

import Import

import Data.Unique

import qualified Data.Text as Text

import Data.Set (Set)
import qualified Data.Set as Set

import Control.Lens

import Handler.Common.Types

import Text.Julius (RawJS(..))

dayFormat :: Day -> String
dayFormat = formatTime defaultTimeLocale "%e. %b %y"

itemForm :: Maybe Item -- ^ Update existing item or insert new?
         -> Html -> MForm Handler (FormResult (WithType Item), Widget)
itemForm proto identView = do
  today <- utctDay <$> liftIO getCurrentTime

  t <- lift . runDB $ maybe (return Nothing) (fmap (Just . kindType) . getType) proto
  
  let kt kWidget tWidget =
        [whamlet|
                <div .td>^{kWidget}
                <div .td>^{tWidget}
                |]
  ((kindRes, typeRes), typedKindWidget) <- typedKindField kt ((itemKind <$> proto), t)
  (boughtRes, boughtWidget) <- dayForm (maybe (Just $ Just today) Just $ fmap itemBought proto) "Unknown"
  (expiresRes, expiresWidget) <- dayForm (fmap itemExpires proto) "Never"
  (openedRes, openedWidget) <- dayForm (fmap itemOpened proto) "Never"

  let itemRes = do
        itemKind <- kindRes
        itemBought <- boughtRes
        itemExpires <- expiresRes
        itemOpened <- openedRes
        t <- typeRes
        return $ Item{ itemNormKind = normalizeKind itemKind, ..} `WithType` t

  return . (itemRes, ) $
    [whamlet|
            $newline never
            #{identView}
            ^{typedKindWidget}
            <div .td>^{boughtWidget}
            <div .td>^{expiresWidget}
            <div .td>^{openedWidget}
            |]
  where
    dayForm :: Maybe (Maybe Day) -> String -> MForm Handler (FormResult (Maybe Day), Widget)
    dayForm proto label = do
      today <- utctDay <$> liftIO getCurrentTime

      checkboxId <- ("check" <>) . show . hashUnique <$> liftIO newUnique
      
      (fmap (fromMaybe False) -> isNothingRes, isNothingView) <-
        mopt checkBoxField ("" { fsId = Just $ Text.pack checkboxId }) . Just . Just . fromMaybe True $ fmap isNothing proto
      (dayRes, dayView) <-
        mreq dayField "" . Just . fromMaybe today $ join proto

      let res = (bool Just (const Nothing) <$> isNothingRes) <*> dayRes
      return . (res, ) $ do
        [whamlet|
                $newline never
                <div .table>
                  <div .tr>
                    <label for=#{checkboxId} .checkbox .td>
                      ^{fvInput isNothingView}
                      <span>
                        #{label}
                  <div .tr>
                    <div .td .dayInput>^{fvInput dayView}
                |]

inventoryListing :: InventoryState -> Widget
inventoryListing InventoryState{ invFormState = formState, ..} = $(widgetFile "inventoryListing")

referenceForm :: Maybe Reference -- ^ Update existing item or insert new?
              -> Html -> MForm Handler (FormResult (WithType Reference), Widget)
referenceForm proto identView = do
  t <- lift . runDB $ maybe (return Nothing) (fmap (Just . kindType) . getType) proto
  
  let kt kWidget tWidget =
        [whamlet|
                <div .td>^{kWidget}
                <div .td>^{tWidget}
                |]

  ((kindRes, typeRes), typedKindWidget) <- typedKindField kt ((referenceKind <$> proto), t)

  let referenceRes = do
        referenceKind <- kindRes
        t <- typeRes
        return $ Reference{ referenceNormKind = normalizeKind referenceKind, .. } `WithType` t

  return . (referenceRes, ) $
    [whamlet|
            $newline never
            #{identView}
            ^{typedKindWidget}
            |]

referenceListing :: ReferenceState -> Widget
referenceListing ReferenceState{ refFormState = formState, ..} = $(widgetFile "referenceListing")

typedKindField :: (Widget -> Widget -> Widget) -- ^ `\kindWidget typeWidget -> _`
               -> (Maybe Text, Maybe Text) -- ^ `(kindProto, typeProto)`
               -> MForm Handler ((FormResult Text, FormResult Text), Widget) -- ^ `((kindRes, typeRes), typedKindWidget)`
typedKindField collate (kindProto, typeProto) = do
  tOptionId <- ("options" <>) . tshow . hashUnique <$> liftIO newUnique
  let
    tAttrs = [ ("list", tOptionId)
             , ("autocomplete", "off")
             ]
  kOptionId <- ("options" <>) . tshow . hashUnique <$> liftIO newUnique

  let
    kAttrs = [ ("list", kOptionId)
             , ("autocomplete", "off")
             ]

  (kindRes, kindView) <- mreq textField ("" { fsAttrs = kAttrs }) kindProto
  (typeRes, typeView) <- mreq textField ("" { fsAttrs = tAttrs }) typeProto

  kOptions <- lift kinds
  (Set.fromList . map (kindType . entityVal) -> tOptions) <- lift . runDB $ selectList [] []

  return . ((kindRes, typeRes), ) $ do
    toWidget $
      [julius|
             $(function () {
               $("##{rawJS $ fvId kindView}").change(function () {
                 $.ajax({
                   url: '@{TypeR}',
                   type: 'GET',
                   contentType: 'application/json',
                   data: {
                     kind: $(this).val()
                   },
                   success: function (answer) {
                     $("##{rawJS $ fvId typeView}").val(answer);
                    typeChanged = false;
                    }
                 });
               }) ;
             });
             |]
    let
      kindWidget =
        [whamlet|
                $newline never
                ^{fvInput kindView}
                <datalist ##{kOptionId}>
                  $forall opt <- kOptions
                    <option value=#{opt}>
                |]
      typeWidget =
        [whamlet|
                $newline never
                ^{fvInput typeView}
                <datalist ##{tOptionId}>
                  $forall opt <- tOptions
                    <option value=#{opt}>
                |]
    collate kindWidget typeWidget

kinds :: Handler (Set Text)
kinds = do
  stock <- runDB $ selectList [] []
  reference <- runDB $ selectList [] []

  return . Set.fromList $ concat
    [ [ itemKind | Entity _ Item{..} <- stock ]
    , [ referenceKind | Entity _ Reference{..} <- reference ]
    ]

type Sort a = a -> a

stockSort :: Sort [WithType (Entity Item)]
stockSort = concat . map (sortOn $ entityVal . typedVal) . sortGroups . group
  where
    group = groupBy ((==) `on` valType) . sortOn valType
    sortGroups = sortOn (fmap minimum . fromNullable . map (entityVal . typedVal))

referenceSort :: Sort [WithType (Entity Reference)]
referenceSort = sortBy referenceOrdering
  where
    referenceOrdering (Entity _ refA `WithType` refAType) (Entity _ refB `WithType` refBType) = compare refAType refBType <> compare refA refB