Changeset - 3e21157f205b
[Not reviewed]
0 4 0
Brett Smith - 5 years ago 2019-07-29 16:37:42
brettcsmith@brettcsmith.org
ledger_entry: Support string tests in amount expressions.

This is useful for setting amounts based on imported strings like country,
Eventbrite ticket type, etc.
4 files changed with 46 insertions and 7 deletions:
0 comments (0 inline, 0 general)
README.rst
Show inline comments
...
 
@@ -39,13 +39,19 @@ Let's walk through this line by line.
 
Every setting in your configuration file has to be in a section.  ``[DEFAULT]`` is the default section, and import2ledger reads configuration settings from here if you don't specify another one.  This documentation explains how to use sections later.
 

	
 
``patreon income ledger entry =`` specifies which entry template this is.  Every template is found from a setting with a name in the pattern ``<SOURCE> <TYPE> ledger entry``.  The remaining lines are indented further than this name; this defines a multiline value.  Don't worry about the exact indentation of your template; import2ledger will indent its output nicely.
 

	
 
The first line of the template is a Ledger tag.  The program will leave all kinds of tags and Ledger comments alone, except to indent them nicely.
 

	
 
The next two lines split the money across accounts.  They follow almost the same format as they do in Ledger: there's an account named, followed by a tab or two or more spaces, and then an expression.  Each time import2ledger generates an entry, it will evaluate this expression using the data it imported to calculate the actual currency amount to write.  Your expression can use numbers, basic arithmetic operators (including parentheses for grouping), conditional expressions in the format ``TRUE_EXPR if CONDITION else FALSE_EXPR``, and imported data referred to as ``{variable_name}``.
 
The next two lines split the money across accounts.  They follow almost the same format as they do in Ledger: there's an account named, followed by a tab or two or more spaces, and then an expression.  Each time import2ledger generates an entry, it will evaluate this expression using the data it imported to calculate the actual currency amount to write.  Your expression can use:
 

	
 
* numbers and quoted strings
 
* imported data referred to as ``{variable_name}``
 
* basic arithmetic operators (including parentheses for grouping)
 
* the operators ``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=``, ``and``, ``or``, ``not``, and ``in``
 
* conditional expressions in the format ``TRUE_EXPR if CONDITION else FALSE_EXPR``
 

	
 
import2ledger uses decimal math to calculate each amount, and rounds to the number of digits appropriate for that currency.  If the amount of currency being imported doesn't split evenly, spare change will be allocated to the last split to keep the entry balanced on both sides.
 

	
 
Refer to the `Python documentation for INI file structure <https://docs.python.org/3/library/configparser.html#supported-ini-file-structure>`_ for full details of the syntax.  Note that import2ledger doesn't use ``;`` as a comment prefix, since that's the primary comment prefix in Ledger.
 

	
 
Template variables
import2ledger/hooks/ledger_entry.py
Show inline comments
...
 
@@ -51,13 +51,20 @@ class TokenTransformer:
 
    def transform(self):
 
        out_bytes = tokenize.untokenize(self)
 
        return out_bytes.decode(self.in_encoding)
 

	
 

	
 
class AmountTokenTransformer(TokenTransformer):
 
    SUPPORTED_NAMES = frozenset(['if', 'else'])
 
    SUPPORTED_NAMES = frozenset([
 
        'if',
 
        'else',
 
        'and',
 
        'or',
 
        'not',
 
        'in',
 
    ])
 
    SUPPORTED_OPS = frozenset([
 
        '(',
 
        ')',
 
        '+',
 
        '-',
 
        '*',
...
 
@@ -107,14 +114,19 @@ class AmountTokenTransformer(TokenTransformer):
 
            yield (tokenize.NAME, name_value)
 
        elif tvalue in self.SUPPORTED_OPS:
 
            yield from self._noop_transformer(ttype, tvalue)
 
        else:
 
            raise ValueError("unsupported operator {!r}".format(tvalue))
 

	
 
    transform_STRING = TokenTransformer._noop_transformer
 

	
 

	
 
class AccountSplitter:
 
    EVAL_GLOBALS = {
 
        'Decimal': decimal.Decimal,
 
    }
 
    TARGET_LINE_LEN = 78
 
    # -4 because that's how many spaces prefix an account line.
 
    TARGET_ACCTLINE_LEN = TARGET_LINE_LEN - 4
 

	
 
    def __init__(self, signed_currencies, signed_currency_fmt, unsigned_currency_fmt,
 
                 template_name):
...
 
@@ -163,19 +175,18 @@ class AccountSplitter:
 
            )
 
        else:
 
            account_name, start_amount = amounts[balance_index]
 
            amounts[balance_index] = (account_name, start_amount + remainder)
 

	
 
    def _build_amounts(self, template_vars):
 
        amount_vars = {k: v for k, v in template_vars.items() if isinstance(v, decimal.Decimal)}
 
        amount_vars['Decimal'] = decimal.Decimal
 
        try:
 
            amounts = [
 
                (account, self._currency_decimal(eval(amount_expr, amount_vars),
 
                                                 template_vars['currency']))
 
                for account, amount_expr in self.splits
 
                (account,
 
                 self._currency_decimal(eval(amount_expr, self.EVAL_GLOBALS, template_vars),
 
                                        template_vars['currency']),
 
                ) for account, amount_expr in self.splits
 
            ]
 
        except (ArithmeticError, NameError, TypeError, ValueError) as error:
 
            raise errors.UserInputConfigurationError(
 
                "{}: {}".format(type(error).__name__, error),
 
                "template {!r}".format(self.template_name)
 
            ) from error
tests/data/templates.ini
Show inline comments
...
 
@@ -50,12 +50,19 @@ template =
 
[Conditional]
 
template =
 
 Assets:Cash  {amount} - (6 if {amount} > 50 else 3)
 
 Expenses:Banking Fees  (6 if {amount} > 50 else 3)
 
 Income:Sales  -{amount}
 

	
 
[StringConditional]
 
template =
 
 Income:Sales  {true} and -1
 
 Income:Sales  {false} or -2
 
 Income:Sales  -3 if 'x' not in {false} else -{amount}
 
 Assets:Cash   {amount}
 

	
 
[NondecimalWord]
 
template =
 
 Income:Sales  -5
 
 Assets:Cash   foo
 

	
 
[NondecimalVariable]
tests/test_hook_ledger_entry.py
Show inline comments
...
 
@@ -196,12 +196,27 @@ def test_conditional(amount, expect_fee):
 
        "2015/03/14 Buyer",
 
        "  Assets:Cash  {:.02f} USD".format(expect_cash),
 
        "  Expenses:Banking Fees  {:.02f} USD".format(expect_fee),
 
        "  Income:Sales  -{} USD".format(amount_s),
 
    ]
 

	
 
def test_string_conditionals():
 
    render_vars = template_vars('MM', '6', other_vars={
 
        'false': '',
 
        'true': 'true',
 
    })
 
    lines = render_lines(render_vars, 'StringConditional')
 
    assert lines == [
 
        "",
 
        "2015/03/14 MM",
 
        "  Income:Sales  -1.00 USD",
 
        "  Income:Sales  -2.00 USD",
 
        "  Income:Sales  -3.00 USD",
 
        "  Assets:Cash  6.00 USD",
 
    ]
 

	
 
@pytest.mark.parametrize('amount_expr', [
 
    '',
 
    'name',
 
    '-',
 
    '()',
 
    '+()',
0 comments (0 inline, 0 general)