Ajout : doc/
[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 (\(a@(Amount {aquantity=q,acommodity=c})) ->
34 let a_ = a{acommodity=""} in
35 let amount = showAmount a_ in
36 let commodity = c in
37 let credit = if q < 0 then showAmount $ negate a_ else "" in
38 let debit = if q > 0 then showAmount a_ else "" in
39 account:amount:commodity:credit:debit:status:comment:[])
40 amounts
41 where
42 Mixed amounts = pamount p
43 status = if pstatus p then "*" else ""
44 account = showAccountName Nothing (ptype p) (paccount p)
45 comment = chomp $ pcomment p
46
47 postingsToCSV :: [Posting] -> CSV
48 postingsToCSV ps =
49 concatMap postingToCSV ps
50
51 transactionToCSV :: Integer -> Transaction -> CSV
52 transactionToCSV n t =
53 map (\p -> show n:date:date2:status:code:description:comment:p)
54 (postingsToCSV (tpostings t))
55 where
56 description = tdescription t
57 date = showDate (tdate t)
58 date2 = maybe "" showDate (tdate2 t)
59 status = if tstatus t then "*" else ""
60 code = tcode t
61 comment = chomp $ tcomment t
62
63 main :: IO ()
64 main = do
65 opts <- getCliOpts argsmode
66 withJournalDo opts $
67 \CliOpts{reportopts_=ropts} j -> do
68 d <- getCurrentDay
69 let ropts_ = ropts{flat_=True}
70 let q = queryFromOpts d ropts_
71 putStrLn $ printCSV $ concat $
72 ([["nth","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","status","posting-comment"]]:).snd $
73 mapAccumL (\n e -> (n + 1, transactionToCSV n e)) 0 $
74 entriesReport ropts_ q j