On the Ledger side, I've been using icsv2ledger[1] for many years. That
means I've a pretty rich mapping DB in the format of that tool.

[1]: https://github.com/quentinsf/icsv2ledger

When I started to play with bean-extract and the builtin CSV importer
(beancount.ingest.importers.csv), it occurred to me that it'd be nice to
have a categorizer for it that used the icsv2ledger mapping file as a
backend. Hence I wrote it, and you can find it attached to this mail.

Comments welcome.

In particular, this is my first attempt as using the internal Beancount
data structures, so I'd love to hear what I'm doing wrong.

Also, is the built-in CSV importer meant to be used this way
(sub-classing and all) or am I missing something?

Please let me knkow if this adapter is of interest to others than me. In
that case I can publish it on a more suitable place than this list.

Cheers
-- 
Stefano Zacchiroli . [email protected] . upsilon.cc/zack . . o . . . o . o
Computer Science Professor . CTO Software Heritage . . . . . o . . . o o
Former Debian Project Leader & OSI Board Director  . . . o o o . . . o .
« the first rule of tautology club is the first rule of tautology club »

-- 
You received this message because you are subscribed to the Google Groups 
"Beancount" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/beancount/20180423140752.GA23447%40upsilon.cc.
For more options, visit https://groups.google.com/d/optout.
"""categorizer for Beancount CSV importer based on icsv2ledger mapping DB

Given as input a mapping_file for `icsv2ledger
<https://github.com/quentinsf/icsv2ledger>`_, return a function from Beancount
transactions to Beancount transactions, suitable as categorizer argument for
Beancount built-in CSV importer
(:class:`beancount.ingest.importers.csv.Importer`).

This categorizer hence provides compatibility between icsv2ledger maintained
mapping DBs and Beancount importers, allowing to share mappings between the
Ledger and Beancount worlds.

"""
__copyright__ = "Copyright (C) 2018  Stefano Zacchiroli"
__license__ = "GPL-2.0-or-later"


import csv
import re

from beancount.core.data import Posting, Transaction


tag_kv_sep_RE = re.compile(r':\s*')


def read_mappings(mapping_file):
    """read a icsv2ledger mapping file and return a list of parsed mappings

    each parsed mapping is a dict with keys: "pattern" (a regexp),
    "description", "account", "metadata" (a list of key/value pairs), "tags"

    note that the order is significant: as per icsv2ledger semantics, the
    *last* match wins

    """
    mappings = []

    with open(mapping_file) as csvfile:
        reader = csv.reader(csvfile)
        for fields in reader:
            mapping = {}

            mapping['pattern'] = re.compile(fields[0].strip('/'))
            mapping['description'] = fields[1]
            mapping['account'] = fields[2]
            mapping['metadata'] = []
            mapping['tags'] = []
            for tag in fields[3:]:
                try:  # if it's a metadata entry, split key/value
                    k, v = tag_kv_sep_RE.split(tag)
                    mapping['metadata'].append((k, v))
                except ValueError:  # it's a tag, not a metadata entry
                    mapping['tags'].append(tag.strip(':'))

            mappings.append(mapping)

    return mappings


def categorize_txn(mappings, unknown_acct, txn):
    """categorize a transaction using icsv2ledger mappings

    find best (i.e., last) match and return a transaction which is a fresh copy
    of the input one, updated with all the info given in the matching mapping
    entry

    """
    assert txn.postings
    txn_amount = txn.postings[0].units

    matches = (m for m in reversed(mappings)  # look for best match
               if m['pattern'].search(txn.narration))

    new_txn = None
    try:  # match found: set narration, add metadata, tags, categorization leg
        mapping = next(matches)

        narration = mapping['description']

        meta = txn.meta
        meta.update(dict(mapping['metadata']))  # merge meta
        tags = txn.tags.union(set(mapping['tags']))  # merge tags

        new_posting = Posting(mapping['account'], -txn_amount,
                              None, None, None, None)
        postings = txn.postings + [new_posting]  # add category

        # make txn point to a new, updated transaction, and quit
        new_txn = Transaction(meta, txn.date, txn.flag,
                              txn.payee, narration,
                              tags, txn.links, postings)
    except StopIteration:  # no match: add "unkown account" leg
        new_posting = Posting(unknown_acct, -txn_amount,
                              None, None, None, None)
        postings = txn.postings + [new_posting]

        new_txn = Transaction(txn.meta, txn.date, txn.flag,
                              txn.payee, txn.narration,
                              txn.tags, txn.links, postings)

    return new_txn


def categorizer(mapping_file, unknown_acct='Expenses:Unknown'):
    """return a categorizer callable for
    :class:`beancount.ingest.importers.csv.Importer`

    Arguments:
      mapping_file(str): name of a icsv2ledger mapping file
      unknown_acct(str): account name to be used if no match is found

    """
    mappings = read_mappings(mapping_file)

    def f(txn):
        return categorize_txn(mappings, unknown_acct, txn)

    return f

Reply via email to