generated from felixm/defaultpy
Implement new mapping format
This commit is contained in:
@@ -3,11 +3,11 @@ import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from toldg.models import Config, Transaction
|
||||
from toldg.models import Config, Mapping, Transaction
|
||||
|
||||
|
||||
def get_files(directory: Path, ending="") -> List[Path]:
|
||||
@@ -64,46 +64,33 @@ def write_meta(config: Config):
|
||||
f.write("\n")
|
||||
f.write('option "operating_currency" "USD"\n\n')
|
||||
|
||||
# Commodity section is not required for beancount
|
||||
# for commodity in config.commodities:
|
||||
# f.write(f"commodity {commodity}\n")
|
||||
# f.write("\n")
|
||||
|
||||
|
||||
def write_mappings(transactions: List[Transaction], mappings_file: Path):
|
||||
"""Write transactions to the mappings file."""
|
||||
mappings = {}
|
||||
for t in transactions:
|
||||
try:
|
||||
mappings[t.account2.strip()].append(t.row)
|
||||
except KeyError:
|
||||
mappings[t.account2.strip()] = [t.row]
|
||||
mapping = Mapping(
|
||||
**{
|
||||
"account2": t.account2.strip(),
|
||||
}
|
||||
)
|
||||
if t.narration:
|
||||
mapping.narration = t.narration
|
||||
if t.payee:
|
||||
mapping.payee = t.payee
|
||||
mappings[t.row] = mapping.dict()
|
||||
|
||||
with open(mappings_file, "w") as f:
|
||||
json.dump({k: sorted(v) for k, v in sorted(mappings.items())}, f, indent=4)
|
||||
json.dump(mappings, f, indent=4)
|
||||
|
||||
|
||||
def read_mappings(mappings_file: Path) -> Dict[str, str]:
|
||||
def read_mappings(mappings_file: Path) -> Dict[str, Mapping]:
|
||||
"""Read mappings from file."""
|
||||
with open(mappings_file, "r") as f:
|
||||
account2_to_rows = json.load(f)
|
||||
return {
|
||||
row: category for category, rows in account2_to_rows.items() for row in rows
|
||||
}
|
||||
|
||||
|
||||
def read_descriptions(descriptions_file: Path) -> Dict[str, str]:
|
||||
"""I am basic so the description file is currently a double row based
|
||||
format where the first row matches the CSV row and the second one is the
|
||||
description."""
|
||||
descriptions = {}
|
||||
current_row = None
|
||||
with open(descriptions_file, "r") as f:
|
||||
for line in f.readlines():
|
||||
if current_row is None:
|
||||
current_row = line.rstrip("\n")
|
||||
else:
|
||||
descriptions[current_row] = line.rstrip("\n")
|
||||
current_row = None
|
||||
return descriptions
|
||||
data = json.load(f)
|
||||
for key, value in data.items():
|
||||
data[key] = Mapping(**value)
|
||||
return data
|
||||
|
||||
|
||||
def remove_if_exists(output_file: Path):
|
||||
|
||||
Reference in New Issue
Block a user