Debian Codegraph @

Hledger/Web/Widget/AddForm.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE GADTs #-}
4 {-# LANGUAGE OverloadedStrings #-}
5 {-# LANGUAGE QuasiQuotes #-}
6 {-# LANGUAGE RankNTypes #-}
7 {-# LANGUAGE TemplateHaskell #-}
8
9 module Hledger.Web.Widget.AddForm
10 ( addForm
11 , addModal
12 ) where
13
14 import Control.Monad.State.Strict (evalStateT)
15 #if MIN_VERSION_base64(1,0,0)
16 import Data.Base64.Types (extractBase64)
17 #endif
18 import Data.Bifunctor (first)
19 import Data.Foldable (toList)
20 import Data.List (dropWhileEnd, unfoldr)
21 import Data.Maybe (isJust, fromMaybe)
22 import Data.Set qualified as S
23 import Data.Text (Text)
24 import Data.Text.Encoding.Base64 (encodeBase64)
25 import Data.Text qualified as T
26 import Data.Time (Day)
27 import Text.Blaze.Internal (Markup, preEscapedText)
28 import Text.Megaparsec (bundleErrors, eof, parseErrorTextPretty, runParser)
29 import Yesod
30
31 import Hledger
32 import Hledger.Web.App (App, Handler, Widget)
33 import Hledger.Web.Settings (widgetFile)
34 import Data.Function ((&))
35 import Control.Arrow (right)
36
37 addModal :: Route App -> Journal -> Day -> Widget
38 addModal addR j today = do
39 (addView, addEnctype) <- handlerToWidget $ generateFormPost (addForm j today)
40 [whamlet|
41 <div .modal #addmodal tabindex="-1" role="dialog" aria-labelledby="addLabel" aria-hidden="true">
42 <div .modal-dialog .modal-lg>
43 <div .modal-content>
44 <div .modal-header>
45 <button type="button" .close data-dismiss="modal" aria-hidden="true">&times;
46 <h3 .modal-title #addLabel>Add a transaction
47 <div .modal-body>
48 <form#addform.form action=@{addR} method=POST enctype=#{addEnctype}>
49 ^{addView}
50 |]
51
52 addForm :: Journal -> Day -> Markup -> MForm Handler (FormResult (Transaction,FilePath), Widget)
53 addForm j today = identifyForm "add" $ \extra -> do
54 let -- bindings used in add-form.hamlet
55 descriptions = foldMap S.fromList [journalPayeesDeclaredOrUsed j, journalDescriptions j]
56 files = fst <$> jfiles j
57 deffile = journalFilePath j
58 (dateRes, dateView) <- mreq dateField dateSettings Nothing
59 (descRes, descView) <- mopt textField descSettings Nothing
60 (acctsRes, _) <- mreq listField acctSettings Nothing
61 (amtsRes, _) <- mreq listField amtSettings Nothing
62 (fileRes, fileView) <- mopt fileField' fileSettings Nothing
63 let
64 (postingsRes, displayRows) = validatePostings acctsRes amtsRes
65 formRes = validateTransaction deffile dateRes descRes postingsRes fileRes
66 return (formRes, $(widgetFile "add-form"))
67 where
68 -- custom fields
69 dateField = textField & checkMMap (pure . right fromEFDay . validateDate) (T.pack . show)
70 where
71 validateDate s =
72 first (const ("Invalid date format" :: Text)) $
73 fixSmartDateStrEither' today (T.strip s)
74 listField = Field
75 { fieldParse = const . pure . Right . Just . dropWhileEnd T.null
76 , fieldView = error' "listField should not be used for rendering" -- PARTIAL:
77 , fieldEnctype = UrlEncoded
78 }
79 fileField' :: Field Handler FilePath
80 fileField' = selectFieldList [(T.pack f, f) | f <- fs] & check validateFilepath
81 where
82 fs = journalFilePaths j
83 validateFilepath :: FilePath -> Either FormMessage FilePath
84 validateFilepath f
85 | f `elem` fs = Right f
86 | otherwise = Left $ MsgInputNotFound $ T.pack f
87 -- field settings
88 dateSettings = FieldSettings "date" Nothing Nothing (Just "date") [("class", "form-control input-lg"), ("placeholder", "Date")]
89 descSettings = FieldSettings "desc" Nothing Nothing (Just "description") [("class", "form-control input-lg typeahead"), ("placeholder", "Description"), ("size", "40")]
90 acctSettings = FieldSettings "account" Nothing Nothing (Just "account") []
91 amtSettings = FieldSettings "amount" Nothing Nothing (Just "amount") []
92 fileSettings = FieldSettings "file" Nothing Nothing (Just "file") [("class", "form-control input-lg")]
93
94 validateTransaction ::
95 FilePath -> FormResult Day -> FormResult (Maybe Text) -> FormResult [Posting] -> FormResult (Maybe FilePath)
96 -> FormResult (Transaction, FilePath)
97 validateTransaction deffile dateRes descRes postingsRes fileRes =
98 case makeTransaction <$> dateRes <*> descRes <*> postingsRes <*> fileRes of
99 FormSuccess (txn,f) -> case balanceSingleTransaction defbalancingopts txn of
100 Left e -> FormFailure [T.pack e]
101 Right txn' -> FormSuccess (txn',f)
102 x -> x
103 where
104 makeTransaction date mdesc postings mfile =
105 (nulltransaction {
106 tdate = date
107 ,tdescription = fromMaybe "" mdesc
108 ,tpostings = postings
109 ,tsourcepos = (initialPos f, initialPos f)
110 }, f)
111 where f = fromMaybe deffile mfile
112
113 -- | Parse a list of postings out of a list of accounts and a corresponding list
114 -- of amounts
115 validatePostings ::
116 FormResult [Text] -> FormResult [Text]
117 -> (FormResult [Posting], [(Int, (Text, Text, Maybe Text, Maybe Text))])
118 validatePostings acctsRes amtsRes = let
119
120 -- Zip accounts and amounts, fill in missing values and drop empty rows.
121 rows :: [(Text, Text)]
122 rows = filter (/= ("", "")) $ zipDefault "" (formSuccess [] acctsRes) (formSuccess [] amtsRes)
123
124 -- Parse values and check for incomplete rows with only an account or an amount.
125 -- The boolean in unfoldr state is for special handling of 'missingamt', where
126 -- one row may have only an account and not an amount.
127 postings :: [(Text, Text, Either (Maybe Text, Maybe Text) Posting)]
128 postings = unfoldr go (True, rows)
129 where
130 go (True, (x, ""):y:xs) = Just ((x, "", zipRow (checkAccount x) (Left "Missing amount")), (True, y:xs))
131 go (True, (x, ""):xs) = Just ((x, "", zipRow (checkAccount x) (Right missingamt)), (False, xs))
132 go (False, (x, ""):xs) = Just ((x, "", zipRow (checkAccount x) (Left "Missing amount")), (False, xs))
133 go (_, ("", y):xs) = Just (("", y, zipRow (Left "Missing account") (checkAmount y)), (False, xs))
134 go (_, (x, y):xs) = Just ((x, y, zipRow (checkAccount x) (checkAmount y)), (True, xs))
135 go (_, []) = Nothing
136
137 zipRow (Left e) (Left e') = Left (Just e, Just e')
138 zipRow (Left e) (Right _) = Left (Just e, Nothing)
139 zipRow (Right _) (Left e) = Left (Nothing, Just e)
140 zipRow (Right acct') (Right amt) = Right (nullposting {paccount = acct, ptype = atype, pamount = mixedAmount amt})
141 where
142 acct = accountNameWithoutPostingType acct'
143 atype = accountNamePostingType acct'
144
145 errorToFormMsg = first (("Invalid value: " <>) . T.pack .
146 foldl (\s a -> s <> parseErrorTextPretty a) "" .
147 bundleErrors)
148 checkAccount = errorToFormMsg . runParser (accountnamep <* eof) "" . T.strip
149 checkAmount = errorToFormMsg . runParser (evalStateT (amountp <* eof) nulljournal) "" . T.strip
150
151 -- Add errors to forms with zero rows if the form is not a FormMissing
152 result :: [(Text, Text, Either (Maybe Text, Maybe Text) Posting)]
153 result = case (acctsRes, amtsRes) of
154 (FormMissing, FormMissing) -> postings
155 _ -> case postings of
156 [] -> [ ("", "", Left (Just "Missing account", Just "Missing amount"))
157 , ("", "", Left (Just "Missing account", Nothing))
158 ]
159 xs -> xs
160
161 -- Prepare rows for rendering - resolve Eithers into error messages and pad to
162 -- at least four rows
163 display' = flip fmap result $ \(acc, amt, res) -> case res of
164 Left (mAccountErr, mAmountErr) -> (acc, amt, mAccountErr, mAmountErr)
165 Right _ -> (acc, amt, Nothing, Nothing)
166 display = display' ++ replicate (4 - length display') ("", "", Nothing, Nothing)
167
168 -- And finally prepare the final FormResult [Posting]
169 formResult = case traverse (\(_, _, x) -> x) result of
170 Left _ -> FormFailure ["Postings validation failed"]
171 Right xs -> FormSuccess xs
172
173 in (formResult, zip [(1 :: Int)..] display)
174
175 -- helper for add-form.hamlet
176 toBloodhoundJson :: [Text] -> Markup
177 toBloodhoundJson ts =
178 -- This used to work, but since 1.16, it seems like something changed.
179 -- toJSON ("a"::Text) gives String "a" instead of "a", etc.
180 -- preEscapedString . escapeJSSpecialChars . show . toJSON
181
182 preEscapedText $ T.concat [
183 "[",
184 T.intercalate "," $ map (
185 ("{\"value\":" <>).
186 (<> "}").
187 -- This will convert a value such as ``hledger!`` into
188 -- ``atob("aGxlZGdlciE=")``. When this gets evaluated on the client,
189 -- the resulting string is ``hledger!`` again. The same data is
190 -- passed, but the user-controlled bit of that string can only use
191 -- characters [a-zA-Z0-9+=/], making it impossible to break out of
192 -- string context.
193 b64wrap
194 ) ts,
195 "]"
196 ]
197 where
198 -- decodeBase64EncodedText is defined in add-form.hamlet
199 b64wrap = ("decodeBase64EncodedText(\""<>) . (<>"\")") .
200 #if MIN_VERSION_base64(1,0,0)
201 extractBase64 .
202 #endif
203 encodeBase64
204
205 zipDefault :: a -> [a] -> [a] -> [(a, a)]
206 zipDefault def (b:bs) (c:cs) = (b, c):(zipDefault def bs cs)
207 zipDefault def (b:bs) [] = (b, def):(zipDefault def bs [])
208 zipDefault def [] (c:cs) = (def, c):(zipDefault def [] cs)
209 zipDefault _ _ _ = []
210
211 formSuccess :: a -> FormResult a -> a
212 formSuccess def res = case res of
213 FormSuccess x -> x
214 _ -> def