init
[tool/hledger.git] / hledger-print-csv.hs
1 #!/usr/bin/env runhaskell
2 {-|
3 hledger-print-csv [-f JOURNALFILE]
4
5 Print matched journal entries as CSV
6 Reads the default or specified journal.
7 |-}
8
9 import Hledger.Cli
10 import Text.CSV
11 import Data.Char (isSpace)
12 import Data.List (mapAccumL)
13
14 argsmode :: Mode RawOpts
15 argsmode = (defCommandMode ["print-csv"])
16 { modeHelp = "print matched journal entries as CSV"
17 , modeGroupFlags = Group
18 { groupNamed =
19 [ ("Input",inputflags)
20 , ("Reporting",reportflags)
21 , ("Misc",helpflags)
22 ]
23 , groupUnnamed = []
24 , groupHidden = []
25 }
26 }
27
28 chomp :: String -> String
29 chomp = reverse . dropWhile isSpace . reverse . dropWhile isSpace
30
31 postingToCSV :: Posting -> CSV
32 postingToCSV p =
33 map (\((Amount {aquantity=q,acommodity=c})) ->
34 let amount = show q in
35 let commodity = c in
36 let credit = if q < 0 then show $ negate q else "" in
37 let debit = if q > 0 then show q else "" in
38 account:amount:commodity:credit:debit:status:comment:[])
39 amounts
40 where
41 Mixed amounts = pamount p
42 status = if pstatus p then "*" else ""
43 account = showAccountName Nothing (ptype p) (paccount p)
44 comment = chomp $ pcomment p
45
46 postingsToCSV :: [Posting] -> CSV
47 postingsToCSV ps =
48 concatMap postingToCSV ps
49
50 transactionToCSV :: Integer -> Transaction -> CSV
51 transactionToCSV n t =
52 map (\p -> show n:date:date2:status:code:description:comment:p)
53 (postingsToCSV (tpostings t))
54 where
55 description = tdescription t
56 date = showDate (tdate t)
57 date2 = maybe "" showDate (tdate2 t)
58 status = if tstatus t then "*" else ""
59 code = tcode t
60 comment = chomp $ tcomment t
61
62 main :: IO ()
63 main = do
64 opts <- getCliOpts argsmode
65 withJournalDo opts $
66 \CliOpts{reportopts_=ropts} j -> do
67 d <- getCurrentDay
68 let ropts_ = ropts{flat_=True}
69 let q = queryFromOpts d ropts_
70 putStrLn $ printCSV $ concat $
71 ([["nth","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","status","posting-comment"]]:).snd $
72 mapAccumL (\n e -> (n + 1, transactionToCSV n e)) 0 $
73 entriesReport ropts_ q j