module CQRSExample.Json ( qProjectListJson , qTaskListJson , qTimesheetJson ) where import Control.Monad (liftM) import Data.Aeson (ToJSON, Value, toJSON) import Data.CQRS.GUID (GUID, hexEncode) import Data.List (groupBy) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Time.Calendar (Day) import Database.HDBC (IConnection) import CQRSExample.Aggregates (UserId) import qualified CQRSExample.Duration as D import CQRSExample.Query -- Instances. instance ToJSON Day where toJSON d = toJSON $ show d -- Generate a list of JSONable values. qListToJson :: (IConnection c, ToJSON b) => (c -> IO [a]) -> (a -> b) -> c -> IO [b] qListToJson lister f conn = liftM (map f) $ lister conn -- JSON queries. qProjectListJson :: (IConnection c) => c -> IO [Map Text Text] qProjectListJson = (qListToJson qProjectList (\(g,pn,psd) -> M.fromList [ (T.pack "id" , TE.decodeUtf8 $ hexEncode g) , (T.pack "name" , pn) , (T.pack "short_desc", psd) ])) qTaskListJson :: (IConnection c) => UserId -> Maybe GUID -> c -> IO [Map Text Value] qTaskListJson userId mProjectId = (qListToJson (qTaskList userId mProjectId) (\(g,tsd,starred) -> M.fromList [ (T.pack "id" , toJSON $ TE.decodeUtf8 $ hexEncode g) , (T.pack "short_description", toJSON $ tsd) , (T.pack "starred" , toJSON $ starred) ])) qTimesheetJson :: (IConnection c) => Day -> Day -> UserId -> c -> IO [Map Text Value] qTimesheetJson fromDate toDate userId connection = do -- Generate the time sheet data. timeSheet <- fmap g $ qTimeSheet fromDate toDate userId connection -- Generate the JSON data. return $ map (\entries -> case entries of [] -> M.fromList [] ((tid,tsd,_,_):_) -> M.fromList [ (T.pack "task_id", toJSON $ hexEncode tid) , (T.pack "task_short_description", toJSON tsd) , (T.pack "timeSheet", toJSON $ map (\(_,_,day,total) -> M.fromList [ (T.pack "date", toJSON $ day) , (T.pack "total", toJSON $ D.toMinutes total) ] ) entries) ]) timeSheet where g = groupBy (\(tid1,_,_,_) (tid2,_,_,_) -> (tid1==tid2))