{-# 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.List.NonEmpty (NonEmpty) import Data.Semigroup hiding (First(..)) 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|
^{kWidget}
^{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}
^{boughtWidget}
^{expiresWidget}
^{openedWidget}
  • ^{fvInput runningLowWidget}