ledger_entry: Support string tests in amount expressions.

This is useful for setting amounts based on imported strings like country,
Eventbrite ticket type, etc.
This commit is contained in:
Brett Smith 2019-07-29 12:37:42 -04:00
parent 4009c626d4
commit 3e21157f20
4 changed files with 46 additions and 7 deletions

View file

@ -42,7 +42,13 @@ Every setting in your configuration file has to be in a section. ``[DEFAULT]``
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 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. 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.

View file

@ -54,7 +54,14 @@ class TokenTransformer:
class AmountTokenTransformer(TokenTransformer): class AmountTokenTransformer(TokenTransformer):
SUPPORTED_NAMES = frozenset(['if', 'else']) SUPPORTED_NAMES = frozenset([
'if',
'else',
'and',
'or',
'not',
'in',
])
SUPPORTED_OPS = frozenset([ SUPPORTED_OPS = frozenset([
'(', '(',
')', ')',
@ -110,8 +117,13 @@ class AmountTokenTransformer(TokenTransformer):
else: else:
raise ValueError("unsupported operator {!r}".format(tvalue)) raise ValueError("unsupported operator {!r}".format(tvalue))
transform_STRING = TokenTransformer._noop_transformer
class AccountSplitter: class AccountSplitter:
EVAL_GLOBALS = {
'Decimal': decimal.Decimal,
}
TARGET_LINE_LEN = 78 TARGET_LINE_LEN = 78
# -4 because that's how many spaces prefix an account line. # -4 because that's how many spaces prefix an account line.
TARGET_ACCTLINE_LEN = TARGET_LINE_LEN - 4 TARGET_ACCTLINE_LEN = TARGET_LINE_LEN - 4
@ -166,13 +178,12 @@ class AccountSplitter:
amounts[balance_index] = (account_name, start_amount + remainder) amounts[balance_index] = (account_name, start_amount + remainder)
def _build_amounts(self, template_vars): 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: try:
amounts = [ amounts = [
(account, self._currency_decimal(eval(amount_expr, amount_vars), (account,
template_vars['currency'])) self._currency_decimal(eval(amount_expr, self.EVAL_GLOBALS, template_vars),
for account, amount_expr in self.splits template_vars['currency']),
) for account, amount_expr in self.splits
] ]
except (ArithmeticError, NameError, TypeError, ValueError) as error: except (ArithmeticError, NameError, TypeError, ValueError) as error:
raise errors.UserInputConfigurationError( raise errors.UserInputConfigurationError(

View file

@ -53,6 +53,13 @@ template =
Expenses:Banking Fees (6 if {amount} > 50 else 3) Expenses:Banking Fees (6 if {amount} > 50 else 3)
Income:Sales -{amount} 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] [NondecimalWord]
template = template =
Income:Sales -5 Income:Sales -5

View file

@ -199,6 +199,21 @@ def test_conditional(amount, expect_fee):
" Income:Sales -{} USD".format(amount_s), " 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', [ @pytest.mark.parametrize('amount_expr', [
'', '',
'name', 'name',