| 1 |
{-# LANGUAGE FlexibleContexts #-} |
| 2 |
{-# LANGUAGE NamedFieldPuns #-} |
| 3 |
{-# LANGUAGE OverloadedStrings #-} |
| 4 |
{-# LANGUAGE QuasiQuotes #-} |
| 5 |
{-# LANGUAGE ScopedTypeVariables #-} |
| 6 |
|
| 7 |
module Hledger.Web.Handler.AddR |
| 8 |
( getAddR |
| 9 |
, postAddR |
| 10 |
, putAddR |
| 11 |
) where |
| 12 |
|
| 13 |
import Data.Aeson.Types (Result(..)) |
| 14 |
import Data.Text qualified as T |
| 15 |
import Network.HTTP.Types.Status (status400) |
| 16 |
import Text.Blaze.Html (preEscapedToHtml) |
| 17 |
import Yesod |
| 18 |
|
| 19 |
import Hledger |
| 20 |
import Hledger.Cli.Commands.Add (appendToJournalFileOrStdout, journalAddTransaction) |
| 21 |
import Hledger.Web.Import |
| 22 |
import Hledger.Web.WebOptions (WebOpts(..)) |
| 23 |
import Hledger.Web.Widget.AddForm (addForm) |
| 24 |
|
| 25 |
getAddR :: Handler () |
| 26 |
getAddR = do |
| 27 |
checkServerSideUiEnabled |
| 28 |
postAddR |
| 29 |
|
| 30 |
postAddR :: Handler () |
| 31 |
postAddR = do |
| 32 |
checkServerSideUiEnabled |
| 33 |
VD{j, today} <- getViewData |
| 34 |
require AddPermission |
| 35 |
|
| 36 |
((res, view), enctype) <- runFormPost $ addForm j today |
| 37 |
case res of |
| 38 |
FormSuccess (t,f) -> do |
| 39 |
let t' = txnTieKnot t |
| 40 |
liftIO $ do |
| 41 |
ensureJournalFileExists f |
| 42 |
appendToJournalFileOrStdout f (showTransaction t') |
| 43 |
setMessage "Transaction added." |
| 44 |
redirect JournalR |
| 45 |
FormMissing -> showForm view enctype |
| 46 |
FormFailure errs -> do |
| 47 |
mapM_ (setMessage . preEscapedToHtml . T.replace "\n" "<br>") errs |
| 48 |
showForm view enctype |
| 49 |
where |
| 50 |
showForm view enctype = |
| 51 |
sendResponse =<< defaultLayout [whamlet| |
| 52 |
<h2>Add transaction |
| 53 |
<div .row style="margin-top:1em"> |
| 54 |
<form#addform.form.col-xs-12.col-sm-11 method=post enctype=#{enctype}> |
| 55 |
^{view} |
| 56 |
|] |
| 57 |
|
| 58 |
-- Add a single new transaction, send as JSON via PUT, to the journal. |
| 59 |
-- The web form handler above should probably use PUT as well. |
| 60 |
putAddR :: Handler RepJson |
| 61 |
putAddR = do |
| 62 |
VD{j, opts} <- getViewData |
| 63 |
require AddPermission |
| 64 |
|
| 65 |
(r :: Result Transaction) <- parseCheckJsonBody |
| 66 |
case r of |
| 67 |
Error err -> sendStatusJSON status400 ("could not parse json: " ++ err ::String) |
| 68 |
Success t -> do |
| 69 |
void $ liftIO $ journalAddTransaction j (cliopts_ opts) t |
| 70 |
sendResponseCreated TransactionsR |