summaryrefslogtreecommitdiff
path: root/Handler/Common.hs
blob: 88cbd8da2a247b8322b46454e3f4634b367d559f (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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
{-# LANGUAGE ApplicativeDo #-}

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

import Import hiding ((\\))

import qualified Data.Text as Text
import qualified Data.ByteString.Char8 as CBS

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

import Control.Lens

import Handler.Common.Types

import Text.Julius (RawJS(..))

import Database.Persist.Sql (fromSqlKey)
import qualified Web.Hashids as HID
import Data.List ((\\))

import Data.Monoid (First(..))

import Data.Time.Calendar

humanId :: ItemId -> Text
humanId = Text.pack . CBS.unpack . HID.encode ctx . fromIntegral . fromSqlKey
  where
    ctx = HID.createHashidsContext "ItemId" 3 $ (['0'..'9'] ++ ['a'..'z']) \\ ['0', 'l', 'v', '2']

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

data DayFormConfig = DayFormConfig
                     { dfNever :: Bool
                     , dfUnknown :: Bool
                     , dfKnown :: Bool
                     }

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 (Just . fromMaybe (DateKnown today) $ itemBought <$> proto) $ DayFormConfig False True True
  (expiresRes, expiresWidget) <- dayForm (itemExpires <$> proto) $ DayFormConfig True False True
  (openedRes, openedWidget) <- dayForm (itemOpened <$> proto) $ DayFormConfig True True True
  ((fmap $ fromMaybe False -> runningLowRes), runningLowWidget) <- mopt checkBoxField "" . Just . Just . fromMaybe False $ fmap itemRunningLow proto

  let itemRes = do
        itemKind <- kindRes
        itemBought <- boughtRes
        itemExpires <- expiresRes
        itemOpened <- openedRes
        itemRunningLow <- runningLowRes
        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}
            <div .td>
              <ul .status>
                <li>^{fvInput runningLowWidget}
                  <label for=#{fvId runningLowWidget}>
                    Running low
            |]
  where
    dayForm :: Maybe ItemDate -> DayFormConfig -> MForm Handler (FormResult ItemDate, Widget)
    dayForm proto DayFormConfig{..} = do
      today <- utctDay <$> liftIO getCurrentTime

      let mWhen = bool (Nothing <$) (fmap Just)

      neverBoxId <- newIdent
      unknownBoxId <- newIdent
      groupId <- newIdent
      
      dNever <- mWhen dfNever $
        mopt checkBoxField ("" { fsId = Just neverBoxId }) . Just . Just . fromMaybe True $ fmap isNever proto
      dUnknown <- mWhen dfUnknown $
        mopt checkBoxField ("" { fsId = Just unknownBoxId }) . Just . Just . fromMaybe False $ fmap isUnknown proto
      dDay <- mWhen dfKnown $
        mopt dayField "" . Just . Just $ case proto of
                             Just (DateKnown d) -> d
                             _                  -> today

      let res = resFromMaybe . fromMaybe FormMissing . fmap (fmap getFirst) $ mconcat
            [ fmap (fmap (First . bool Nothing (Just DateNever) . fromMaybe False) . fst) dNever
            , fmap (fmap (First . bool Nothing (Just DateUnknown) . fromMaybe False) . fst) dUnknown
            , fmap (fmap (First . fmap DateKnown) . fst) dDay
            ]
          resFromMaybe (FormSuccess Nothing) = FormFailure ["Missing required information"]
          resFromMaybe (FormSuccess (Just x)) = FormSuccess x
          resFromMaybe FormMissing = FormMissing
          resFromMaybe (FormFailure es) = FormFailure es
      return . (res, ) $ do
        toWidget $
          [julius|
                 $(function () {
                   var updateInput = function() {
                     $('##{rawJS groupId} :input').filter(':not(:checkbox)').prop("disabled", $('##{rawJS groupId} :checkbox').filter(':checked').length > 0);
                   };
                 
                   $('##{rawJS groupId} :checkbox').change(function() {
                     if (this.checked) {
                       $('##{rawJS groupId} :checkbox').not(this).prop('checked', false);
                     }
                     updateInput();
                   });

                   updateInput();
                 });
                 |]
        let width = length $ (filter id [ isJust dNever, isJust dUnknown ] :: [Bool])
        [whamlet|
                $newline never
                <table ##{groupId} .dayField>
                  <tr>
                    $maybe (_, isNeverView) <- dNever
                      <td>
                        <label for=#{neverBoxId} .checkbox>
                          ^{fvInput isNeverView}
                          <span>
                            Never
                    $maybe (_, isUnknownView) <- dUnknown
                      <td>
                        <label for=#{unknownBoxId} .checkbox>
                          ^{fvInput isUnknownView}
                          <span>
                            Unknown
                  $maybe (_, dayView) <- dDay
                    <tr>
                      <td .dayInput :width > 0:colspan=#{width}>
                        ^{fvInput dayView}
                |]

inventoryListing :: InventoryState -> Widget
inventoryListing InventoryState{ invFormState = formState, ..} = do
  today <- liftIO $ utctDay <$> getCurrentTime
  $(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 <- newIdent
  let
    tAttrs = [ ("list", tOptionId)
             , ("autocomplete", "off")
             ]
  kOptionId <- newIdent
  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;
                   }
                 });
               }) ;
             });
             |]
    toWidget $
      [cassius|
              ##{fvId kindView}
                width: 12em
              ##{fvId typeView}
                width: 8em
              |]
    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 :: [[a]] -> [a])
    [ [ itemKind | Entity _ Item{..} <- stock ]
    , [ referenceKind | Entity _ Reference{..} <- reference ]
    ]

type Sort a = a -> a

stockSort :: Sort [WithType (Entity Item)]
stockSort = concat . map sortInGroup . sortGroups . group
  where
    group = groupBy ((==) `on` valType) . sortOn valType
    sortGroups = sortOn (fmap minimum . fromNullable . map (entityVal . typedVal))
    sortInGroup = concat . map (sortOn $ entityVal . typedVal) . sortOn (fmap minimum . fromNullable . map (entityVal . typedVal)) . groupBy ((==) `on` (itemNormKind . entityVal . typedVal)) . sortOn (itemNormKind . 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