Coverage for hledger_lots/hl.py: 93%
29 statements
« prev ^ index » next coverage.py v7.2.3, created at 2023-05-05 00:04 -0300
« prev ^ index » next coverage.py v7.2.3, created at 2023-05-05 00:04 -0300
1import json
2import subprocess
3import sys
4from typing import List, Optional, Tuple
6from .lib import AdjustedTxn, Txn, get_avg_fifo, get_files_comm, get_xirr
9def adjust_txn(txn: Txn) -> AdjustedTxn:
10 price = txn.price if txn.type == "UnitPrice" else txn.price / txn.qtty
12 result = AdjustedTxn(txn.date, price, txn.base_cur, txn.qtty, txn.acct)
13 return result
16def prices_items2txn(date: str, prices_items: dict, account: str) -> Txn:
17 price = prices_items["aprice"]["contents"]["aquantity"]["floatingPoint"]
18 base_cur = prices_items["aprice"]["contents"]["acommodity"]
19 qtty = prices_items["aquantity"]["floatingPoint"]
20 price_type = prices_items["aprice"]["tag"]
22 txn = Txn(date, price, base_cur, qtty, account, price_type)
23 return txn
26def hledger2txn(
27 file_path: Tuple[str, ...], cur: str, no_desc: Optional[str] = None
28) -> List[AdjustedTxn]:
29 files_comm = get_files_comm(file_path)
30 comm = ["hledger", *files_comm, "print", f"cur:{cur}", "--output-format=json"]
31 if no_desc:
32 comm.append(f"not:desc:{no_desc}")
34 hl_proc = subprocess.run(comm, stdin=sys.stdin, capture_output=True)
35 if hl_proc.returncode != 0:
36 raise ValueError(hl_proc.stderr.decode("utf8"))
38 hl_data = hl_proc.stdout.decode("utf8")
39 txns_list = json.loads(hl_data)
41 txns = [
42 prices_items2txn(txn["tdate"], prices_items, posting_items["paccount"])
43 for txn in txns_list
44 for posting_items in txn["tpostings"]
45 for prices_items in posting_items["pamount"]
46 if prices_items["acommodity"].upper() == cur.upper() and prices_items["aprice"]
47 ]
49 adjusted_txns = [adjust_txn(txn) for txn in txns]
50 return adjusted_txns