summaryrefslogtreecommitdiff
path: root/bragi/bar.hs
blob: 61d241191124e086a024701a6b501a764712f911 (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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#! /usr/bin/env nix-shell
#! nix-shell -i runghc -p "haskellPackages.ghcWithPackages (p: with p; [ yesod persistent-postgresql ])"


{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE ViewPatterns               #-}
{-# LANGUAGE TupleSections              #-}
{-# LANGUAGE ApplicativeDo              #-}
  

import Yesod
import Database.Persist.Postgresql
  
import Control.Monad.Logger (runStderrLoggingT)
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Trans.Maybe

import Data.Time.Clock
import Data.Time.Calendar
import Data.Time.Format

import Data.Text (Text)
import qualified Data.Text as Text

import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as Map

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

import Data.Aeson
import Data.Traversable
import Data.Maybe
import Data.Bool
import Data.String (IsString(..))
import Data.Unique
import Data.List (sortOn)
import Data.Ord


share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Item
    kind Text
    bought Day Maybe
    expires Day Maybe
    opened Day Maybe
    deriving Show Eq
|]

instance Ord Item where
  x `compare` y = mconcat
                  [ (isNothing $ itemOpened x) `compare` (isNothing $ itemOpened y)
                  , itemOpened x `compare` itemOpened y
                  , itemExpires x `compare` itemExpires x
                  , itemKind x `compare` itemKind x
                  , itemBought x `compare` itemBought x
                  ]

instance ToJSON Item where
  toJSON Item{..} = object $
    [ "kind" .= itemKind
    ] ++ maybe [] (\x -> ["bought" .= x]) itemBought
    ++ maybe [] (\x -> ["expires" .= x]) itemExpires
    ++ maybe [] (\x -> ["opened" .= x]) itemOpened

instance FromJSON Item where
  parseJSON = withObject "Item" $ \obj -> do
    itemKind <- obj .: "kind"
    itemBought <- obj .:? "bought"
    itemExpires <- obj .:? "expires"
    itemOpened <- obj .:? "opened"
    return Item{..}
  
instance ToJSON (Entity Item) where
  toJSON = entityIdToJSON

instance FromJSON (Entity Item) where
  parseJSON = entityIdFromJSON

data ItemDiff = DiffKind Text
              | DiffBought (Maybe Day)
              | DiffExpires (Maybe Day)
              | DiffOpened (Maybe Day)

newtype ItemDiffs = ItemDiffs [ItemDiff]

instance FromJSON ItemDiffs where
  parseJSON = withObject "ItemDiff" $ \obj -> fmap ItemDiffs . execWriterT $ do
    tell =<< maybe [] (pure . DiffKind) <$> lift (obj .:? "kind")
    tell =<< maybe [] (pure . DiffBought) <$> lift (obj .:! "bought")
    tell =<< maybe [] (pure . DiffExpires) <$> lift (obj .:! "expires")
    tell =<< maybe [] (pure . DiffOpened) <$> lift (obj .:! "opened")

toUpdate :: ItemDiffs -> [Update Item]
toUpdate (ItemDiffs ds) = do
  x <- ds
  return $ case x of
    DiffKind t -> ItemKind =. t
    DiffBought d -> ItemBought =. d
    DiffExpires d -> ItemExpires =. d
    DiffOpened d -> ItemOpened =. d

  
data BarInventory = BarInventory
  { sqlPool :: ConnectionPool
  }

mkYesod "BarInventory" [parseRoutes|
/ InventoryR GET PUT POST
/#ItemId ItemR GET PUT PATCH DELETE
/#ItemId/open OpenItemR POST
/#ItemId/update UpdateItemR POST GET
/#ItemId/delete DeleteItemR POST
|]

instance Yesod BarInventory where
  approot = guessApproot

instance RenderMessage BarInventory FormMessage where
  renderMessage _ _ = defaultFormMessage

instance YesodPersist BarInventory where
  type YesodPersistBackend BarInventory = SqlBackend

  runDB action = runSqlPool action . sqlPool =<< getYesod


data ViewState = ViewState
  { errs :: [Text]
  , insertForm :: Maybe Widget
  , insertEncoding :: Maybe Enctype
  , stock :: [Entity Item]
  , updateItem :: Maybe ItemId
  , updateForm :: Maybe Widget
  , updateEncoding :: Maybe Enctype
  }



main = runStderrLoggingT . withPostgresqlPool "user=bar dbname=bar" 5 . runReaderT $ do
  sqlPool <- ask
  mapM_ ($(logWarnS) "DB") =<< runSqlPool (runMigrationSilent migrateAll) sqlPool
  liftIO . warpEnv $ BarInventory{..}


itemFragment itemId = "item" <> show (fromSqlKey itemId)
  
itemForm :: Maybe Item -> Html -> MForm Handler (FormResult Item, Widget)
itemForm proto identView = do
  today <- utctDay <$> liftIO getCurrentTime
  
  (kindRes, kindView) <- mreq textField "" $ itemKind <$> proto
  (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
        return Item{..}

  return . (itemRes, ) $ do
    toWidget
      [cassius|
              label.checkbox
                input
                  vertical-align: middle
                span
                  vertical-align: middle
              |]
    -- addScriptRemote "https://cdn.jsdelivr.net/webshim/1.16.0/extras/modernizr-custom.js"
    addScriptRemote "https://cdn.jsdelivr.net/webshim/1.16.0/polyfiller.js"
    addScriptRemote "https://cdn.jsdelivr.net/jquery/3.1.1/jquery.js"
    toWidget
      [julius|
             webshims.setOptions("forms-ext", {
               "widgets": {
                 "classes": "hide-dropdownbtn"
               }
             });
             webshims.activeLang("en-GB");
             webshims.polyfill("forms forms-ext");
             |]
    [whamlet|
            #{identView}
            <div .td>^{fvInput kindView}
            <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}
                |]



getInventoryR, postInventoryR :: Handler TypedContent
postInventoryR = getInventoryR
getInventoryR = do
  ((insertResult, (Just -> insertForm)), (Just -> insertEncoding)) <- runFormPost $ itemForm Nothing

  errs <- case insertResult of 
    FormSuccess newItem -> [] <$ runDB (insert newItem)
    FormFailure errors -> return errors
    _ -> return []

  (sortOn entityVal -> stock) <- runDB $ selectList [] []

  selectRep $ do
    provideJson (stock :: [Entity Item])
    provideRep $ mainView ViewState
      { updateItem = Nothing
      , updateForm = Nothing
      , updateEncoding = Nothing
      , ..
      }

postUpdateItemR, getUpdateItemR :: ItemId -> Handler TypedContent
postUpdateItemR = getUpdateItemR
getUpdateItemR updateItem = do
  Just entity <- fmap (Entity updateItem) <$> runDB (get updateItem)
  
  ((updateResult, (Just -> updateForm)), (Just -> updateEncoding)) <- runFormPost . itemForm . Just $ entityVal entity

  errs <- case updateResult of 
    FormSuccess Item{..} -> [] <$ runDB (update updateItem [ ItemKind =. itemKind
                                                           , ItemBought =. itemBought
                                                           , ItemExpires =. itemExpires
                                                           , ItemOpened =. itemOpened
                                                           ])
    FormFailure errors -> return errors
    _ -> return []

  selectRep $ do
    provideRep $ case updateResult of
      FormSuccess _ -> redirect $ InventoryR :#: itemFragment updateItem :: Handler Html
      _ -> do
        (sortOn entityVal -> stock) <- runDB $ selectList [] []
        mainView ViewState
          { insertForm = Nothing
          , insertEncoding = Nothing
          , updateItem = Just updateItem
          , ..
          }
    provideJson ()

mainView :: ViewState -> Handler Html
mainView ViewState{..} = defaultLayout $ do 
    let
      dayFormat = formatTime defaultTimeLocale "%e. %b %y"
              
    setTitle "Bar Inventory"
    toWidget
      [cassius|
              .table
                display: table
              .table div
                vertical-align: middle
              .td
                display: table-cell
                text-align: center
                padding: 0.25em
              .tr
                display: table-row
              .tc
                display: table-caption
                padding: 0.25em
              .th
                display: table-cell
                font-variant: small-caps
                font-weight: bold
                text-align: center
                padding: 0.25em
              .kind
                display: table-cell
                text-align: left
                padding: 0.25em
              .table .table .td, .table .table .tc, .table .table .th, .table .table .kind
                padding: 0
              .error
                background-color: #fdd
                text-align: center
                color: #c00
                list-style-type: none
              button
                width: 6em
                display:inline-text
              .day hr
                width: 2em
                border: 1px solid #ddd
                border-style: solid none solid none
              .sepBelow > div, .sepAbove > div
                border: 2px none #ddd
              .sepBelow > div
                border-bottom-style: solid
              .sepAbove > div
                border-top-style: solid
              .color:nth-child(even)
                background-color: #f0f0f0
              .color:nth-child(odd)
                background-color: #fff
              body > div
                margin: 0 auto
              .table > h1
                display: table-caption
              h1
                font-size: 1.5em
                font-weight: bold
                font-variant: small-caps
                text-align: center
                margin:0 0 .5em 0
              |]
    toWidget
      [whamlet|
              <div .table>
                <h1>
                  Inventory
                $if not $ null errs
                  <ul .tc .error .sepBelow>
                  $forall e <- errs
                    <li>#{e}
                <div .tr .sepBelow>
                  <div .th>Description
                  <div .th>Bought
                  <div .th>Expires
                  <div .th>Opened
                  <div .th>Actions
                $maybe insertEncoding <- insertEncoding
                  $maybe insertForm <- insertForm
                    <form .tr .sepBelow action=@{InventoryR} method=post enctype=#{insertEncoding}>
                      ^{insertForm}
                      <div .td>
                        <button type=submit>
                          Insert
                $forall e@(Entity itemId Item{..}) <- stock
                  $with idN <- fromSqlKey itemId
                    $if and [ Just itemId == updateItem, isJust updateEncoding, isJust updateForm ]
                      $maybe updateEncoding <- updateEncoding
                        $maybe updateForm <- updateForm
                          <form .tr .color action=@{UpdateItemR itemId}##{itemFragment itemId} method=post enctype=#{updateEncoding} ##{itemFragment itemId}>
                            ^{updateForm}
                            <div .td>
                              <button type=submit>
                                Save Changes
                    $else
                      <div .tr .color ##{itemFragment itemId}>
                        <div .kind>#{itemKind}
                        <div .td .day>
                          $maybe bought <- itemBought
                            #{dayFormat bought}
                          $nothing
                            <hr>
                        <div .td .day>
                          $maybe expires <- itemExpires
                            #{dayFormat expires}
                          $nothing
                            <hr>
                        <div .td .day>
                          $maybe opened <- itemOpened
                            #{dayFormat opened}
                          $nothing
                            <form method=post action=@{OpenItemR itemId}>
                              <button type=submit>
                                Open
                        <div .td>
                          <form method=get action=@{UpdateItemR itemId}##{itemFragment itemId}>
                            <button type=submit>
                              Alter
                          <form method=post action=@{DeleteItemR itemId}>
                            <button type=submit>
                              Delete
              |]

putInventoryR :: Handler Value
putInventoryR = returnJson =<< runDB . insertEntity =<< (requireCheckJsonBody :: Handler Item)

getItemR :: ItemId -> Handler TypedContent
getItemR itemId = do
  let getEntity id = fmap (Entity id) <$> get id

  eLookup <- runDB $ getEntity itemId

  case eLookup of
    Nothing -> notFound
    Just entity -> do
      
      selectRep $ do
        provideJson entity

patchItemR :: ItemId -> Handler Value
patchItemR itemId = do
  diffs <- (requireCheckJsonBody :: Handler ItemDiffs)
  returnJson . Entity itemId =<< runDB (updateGet itemId $ toUpdate diffs)

putItemR :: ItemId -> Handler Value
putItemR itemId = do
  Item{..} <- requireCheckJsonBody
  returnJson . Entity itemId =<< runDB
    (updateGet itemId [ ItemKind =. itemKind
                      , ItemBought =. itemBought
                      , ItemExpires =. itemExpires
                      , ItemOpened =. itemOpened
                      ])

deleteItemR :: ItemId -> Handler ()
deleteItemR = runDB . delete

postDeleteItemR :: ItemId -> Handler TypedContent
postDeleteItemR itemId = do
  runDB $ delete itemId
  selectRep $ do
    provideJson ()
    provideRep (redirect $ InventoryR :: Handler Html)

postOpenItemR :: ItemId -> Handler TypedContent
postOpenItemR itemId = do
  today <- utctDay <$> liftIO getCurrentTime
  result <- fmap (Entity itemId) . runDB $ updateGet itemId [ ItemOpened =. Just today
                                                            ]
  selectRep $ do
    provideJson result
    provideRep (redirect $ InventoryR :#: itemFragment itemId :: Handler Html)