summaryrefslogtreecommitdiff
path: root/Handler/InventoryListing.hs
blob: c61c62b6b0680d8c431f35003233d7b20016e399 (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
module Handler.InventoryListing where

import Import
import Handler.Common

getInventoryListingR, postInventoryListingR :: Handler TypedContent
getInventoryListingR = postInventoryListingR
postInventoryListingR = do
  ((insertResult, fsInsertForm), fsInsertEncoding) <- runFormPost $ itemForm Nothing

  case insertResult of 
    FormSuccess (Item{..} `WithType` t) -> runDB $ do
      void $ upsertBy (UniqueKind itemNormKind) (Kind itemNormKind t) [ KindType =. t ]
      newItem <- insert Item{..}
      otherItems <- selectKeysList [ ItemNormKind ==. itemNormKind, ItemId !=. newItem ] []
      when (not $ null otherItems) . addMessage "insertAmbiguous" $
        [shamlet|
                $newline never
                There are other items of the same kind.
                <ul>
                  $forall other <- otherItems
                    <li .itemId>#{humanId other}
                |]
      addMessage "insertSuccess" [shamlet|
                                         $newline never
                                         Inserted new item as #
                                         <span .itemId>#{humanId newItem}
                                         |]
    FormFailure errors -> mapM_ (addMessage "formError" . toHtml) errors
    _ -> return ()

  (stockSort -> stock) <- runDB $ withTypes =<< selectList [] []

  selectRep $ do
    provideJson (stock :: [WithType (Entity Item)])
    provideRep . defaultLayout $ inventoryListing InventoryState
      { invFormState = Just InsertForm{..}
      , ..
      }

putInventoryListingR :: Handler Value
putInventoryListingR = do
  (Item{..} `WithType` t) <- requireCheckJsonBody
  returnJson <=< runDB $ do
    void $ upsertBy (UniqueKind itemNormKind) (Kind itemNormKind t) [ KindType =. t ]
    withType =<< insertEntity Item{..}