Files
ledgerai/src/toldg/write.py

62 lines
1.9 KiB
Python

from pathlib import Path
from typing import List
from toldg.models import Config, Transaction
from toldg.utils import category_to_bean
BEANCOUNT_TRANSACTION_TEMPLATE = """
{t.date} * {description}{tags}
{account2:<40} {t.debit:<6} {t.currency}
{account1:<40} {t.credit:<6} {t.currency}
source_file: "{t.csv_file}"
source_index: {t.index}
source_row: "{t.row}"
"""
def format(t):
t.date = t.date.replace("/", "-")
tags = ""
description = None
if t.mapping:
m = t.mapping
t.account2 = m.account2
if m.narration and m.payee:
# A transaction may have an optional “payee” and/or a “narration.”
description = f'"{m.payee}" "{m.narration}"'
elif m.narration:
# If you place a single string on a transaction line, it becomes its narration:
description = f'"{m.narration}"'
elif m.payee:
# If you want to set just a payee, put an empty narration string:
description = f'"{m.payee}" ""'
if m.tags:
tags = " #" + " #".join(m.tags)
if description is None:
description = f'"{t.description}"'
if not t.debit.startswith("-"):
t.debit = " " + t.debit
if not t.credit.startswith("-"):
t.credit = " " + t.credit
if t.currency == "EUR":
t.debit = t.debit.replace(".", "|").replace(",", ".").replace("|", ",")
t.credit = t.credit.replace(".", "|").replace(",", ".").replace("|", ",")
return BEANCOUNT_TRANSACTION_TEMPLATE.format(
t=t,
description=description,
tags=tags,
account1=category_to_bean(t.account1),
account2=category_to_bean(t.account2),
)
def render_to_file(transactions: List[Transaction], config: Config):
content = "".join(format(t) for t in transactions)
with open(config.output_file, "a") as f:
f.write(content)