From 3bfe0bdcb79b398a387e202c5150b5e6fd230d3a Mon Sep 17 00:00:00 2001 From: Gregor Kleen Date: Thu, 16 Mar 2017 01:19:07 +0100 Subject: More complicated date handling --- Model.hs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) (limited to 'Model.hs') diff --git a/Model.hs b/Model.hs index 90f5904..8778111 100644 --- a/Model.hs +++ b/Model.hs @@ -1,4 +1,5 @@ {-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE DeriveFunctor #-} module Model where @@ -18,6 +19,8 @@ import qualified Data.HashMap.Lazy as HashMap import Data.Aeson import Data.Aeson.Types (Parser, Value(..)) +import Model.Types + -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: @@ -68,32 +71,28 @@ withTypes vals = do instance Ord Item where x `compare` y = mconcat cmprs where - cmprs = [ itemOpened x `compareM` itemOpened y - , itemExpires x `compareM` itemExpires y + cmprs = [ itemOpened x `compare` itemOpened y + , itemExpires x `compare` itemExpires y , itemKind x `compare` itemKind y , itemBought x `compare` itemBought y ] - compareM (Just _) Nothing = LT - compareM Nothing (Just _) = GT - compareM (Just a) (Just b) = compare a b - compareM _ _ = EQ - instance ToJSON Item where toJSON Item{..} = object $ [ "kind" .= itemKind - ] ++ maybe [] (\x -> ["bought" .= x]) itemBought - ++ maybe [] (\x -> ["expires" .= x]) itemExpires - ++ maybe [] (\x -> ["opened" .= x]) itemOpened + , "bought" .= itemBought + , "expires" .= itemExpires + , "opened" .= itemOpened + ] instance FromJSON Item where parseJSON = withObject "Item" $ \obj -> do itemKind <- obj .: "kind" let itemNormKind = normalizeKind itemKind - itemBought <- obj .:? "bought" - itemExpires <- obj .:? "expires" - itemOpened <- obj .:? "opened" + itemBought <- maybe DateUnknown DateKnown <$> obj .:? "bought" + itemExpires <- maybe DateNever DateKnown <$> obj .:? "expires" + itemOpened <- obj .: "opened" return Item{..} instance ToJSON (Entity Item) where @@ -122,9 +121,9 @@ normalizeKind = Text.strip . Text.toCaseFold data ItemDiff = DiffKind Text | DiffType Text - | DiffBought (Maybe Day) - | DiffExpires (Maybe Day) - | DiffOpened (Maybe Day) + | DiffBought ItemDate + | DiffExpires ItemDate + | DiffOpened ItemDate newtype ItemDiffs = ItemDiffs [ItemDiff] @@ -149,7 +148,7 @@ toUpdate (ItemDiffs ds) = mconcat $ do DiffOpened d -> (, []) [ ItemOpened =. d ] data WithType a = WithType { typedVal :: a, valType :: Text } - deriving (Eq, Ord, Show) + deriving (Eq, Ord, Show, Functor) typeToJSON :: ToJSON a => Text -- ^ Key for value, if needed -- cgit v1.2.3