Changeset - 7cd569be7b52
[Not reviewed]
0 3 0
Brett Smith - 4 years ago 2020-03-19 14:23:55
brettcsmith@brettcsmith.org
data.Account: Add is_income method.
3 files changed with 17 insertions and 1 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/data.py
Show inline comments
 
"""Enhanced Beancount data structures for Conservancy"""
 
# Copyright © 2020  Brett Smith
 
#
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU Affero General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
 

	
 
import collections.abc
 

	
 
from beancount.core import account as bc_account
 

	
 
from typing import (
 
    Iterable,
 
    Iterator,
 
    MutableMapping,
 
    Optional,
 
)
 

	
 
from .beancount_types import (
 
    MetaKey,
 
    MetaValue,
 
    Posting as BasePosting,
 
    Transaction,
 
)
 

	
 
class Account(str):
 
    SEP = bc_account.sep
 

	
 
    def is_income(self) -> bool:
 
        return self.is_under('Income:', 'UnearnedIncome:') is not None
 

	
 
    def is_real_asset(self) -> bool:
 
        return bool(
 
            self.is_under('Assets:')
 
            and not self.is_under('Assets:PrepaidExpenses')
 
            and not self.is_under('Assets:PrepaidVacation')
 
        )
 

	
 
    def is_under(self, *acct_seq: str) -> Optional[str]:
 
        for prefix in acct_seq:
 
            if self.startswith(prefix) and (
 
                prefix.endswith(self.SEP)
 
                or self == prefix
 
                or self[len(prefix)] == self.SEP
 
            ):
 
                return prefix
 
        return None
 

	
 

	
 
class PostingMeta(collections.abc.MutableMapping):
 
    def __init__(self,
 
                 txn: Transaction,
 
                 index: int,
 
                 post: Optional[BasePosting]=None,
 
    ) -> None:
 
        if post is None:
 
            post = txn.postings[index]
 
        self.txn = txn
 
        self.index = index
 
        self.post = post
 

	
 
    def __iter__(self) -> Iterator[MetaKey]:
 
        keys: Iterable[MetaKey]
 
        if self.post.meta is None:
 
            keys = self.txn.meta.keys()
 
        else:
 
            keys = frozenset(self.post.meta.keys()).union(self.txn.meta.keys())
 
        return iter(keys)
 

	
 
    def __len__(self) -> int:
 
        return sum(1 for _ in self)
 

	
 
    def __getitem__(self, key: MetaKey) -> MetaValue:
 
        if self.post.meta:
 
            try:
 
                return self.post.meta[key]
 
            except KeyError:
 
                pass
 
        return self.txn.meta[key]
 

	
 
    def __setitem__(self, key: MetaKey, value: MetaValue) -> None:
 
        if self.post.meta is None:
 
            self.post = self.post._replace(meta={key: value})
 
            self.txn.postings[self.index] = self.post
 
        else:
 
            self.post.meta[key] = value
 

	
 
    def __delitem__(self, key: MetaKey) -> None:
 
        if self.post.meta is None:
 
            raise KeyError(key)
 
        else:
 
            del self.post.meta[key]
 

	
 

	
 
class Posting(BasePosting):
 
    account: Account
 
    # mypy correctly complains that our MutableMapping is not compatible with
 
    # Beancount's meta type declaration of Optional[Dict]. IMO this is a case
 
    # of Beancount's type declaration being a smidge too specific: I think it
 
    # would be very unusual for code to actually require a dict over a more
 
    # generic mapping. If it did, this would work fine.
 
    meta: MutableMapping[MetaKey, MetaValue]  # type:ignore[assignment]
 

	
 

	
 
def iter_postings(txn: Transaction) -> Iterator[Posting]:
 
    for index, source in enumerate(txn.postings):
 
        yield Posting(
 
            Account(source.account),
 
            *source[1:5],
 
            # see rationale above about Posting.meta
 
            PostingMeta(txn, index, source), # type:ignore[arg-type]
 
        )
conservancy_beancount/plugin/meta_income_type.py
Show inline comments
 
"""meta_income_type - Validate income-type metadata"""
 
# Copyright © 2020  Brett Smith
 
#
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU Affero General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
 

	
 
from . import core
 
from .. import data
 
from .. import errors as errormod
 
from ..beancount_types import (
 
    MetaValueEnum,
 
    Transaction,
 
)
 

	
 
class MetaIncomeType(core._NormalizePostingMetadataHook):
 
    VALUES_ENUM = core.MetadataEnum('income-type', {
 
        'Donations',
 
        'Payable-Derecognition',
 
        'RBI',
 
        'UBTI',
 
    })
 
    DEFAULT_VALUES = {
 
        'Income:Donations': 'Donations',
 
        'Income:Honoraria': 'RBI',
 
        'Income:Interest': 'RBI',
 
        'Income:Interest:Dividend': 'RBI',
 
        'Income:Royalties': 'RBI',
 
        'Income:Sales': 'RBI',
 
        'Income:SoftwareDevelopment': 'RBI',
 
        'Income:TrademarkLicensing': 'RBI',
 
        'UnearnedIncome:Conferences:Registrations': 'RBI',
 
        'UnearnedIncome:MatchPledges': 'Donations',
 
    }
 

	
 
    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
 
        return post.account.is_under('Income:', 'UnearnedIncome:') is not None
 
        return post.account.is_income()
 

	
 
    def _default_value(self, txn: Transaction, post: data.Posting) -> MetaValueEnum:
 
        try:
 
            return self.DEFAULT_VALUES[post.account]
 
        except KeyError:
 
            raise errormod.InvalidMetadataError(txn, post, self.METADATA_KEY) from None
tests/test_data_account.py
Show inline comments
 
"""Test Account class"""
 
# Copyright © 2020  Brett Smith
 
#
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU Affero General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
 

	
 
import pytest
 

	
 
from conservancy_beancount import data
 

	
 
@pytest.mark.parametrize('acct_name,under_arg,expected', [
 
    ('Expenses:Tax:Sales', 'Expenses:Tax:Sales:', False),
 
    ('Expenses:Tax:Sales', 'Expenses:Tax:Sales', True),
 
    ('Expenses:Tax:Sales', 'Expenses:Tax:', True),
 
    ('Expenses:Tax:Sales', 'Expenses:Tax', True),
 
    ('Expenses:Tax:Sales', 'Expenses:', True),
 
    ('Expenses:Tax:Sales', 'Expenses', True),
 
    ('Expenses:Tax:Sales', 'Expense', False),
 
    ('Expenses:Tax:Sales', 'Accrued:', False),
 
    ('Expenses:Tax:Sales', 'Accrued', False),
 
])
 
def test_is_under_one_arg(acct_name, under_arg, expected):
 
    expected = under_arg if expected else None
 
    assert data.Account(acct_name).is_under(under_arg) == expected
 

	
 
@pytest.mark.parametrize('acct_name,expected', [
 
    ('Income:Other', 'Income'),
 
    ('UnearnedIncome:Other', 'UnearnedIncome'),
 
    ('Accrued:AccountsPayable', None),
 
    ('Expenses:General', None),
 
])
 
def test_is_under_multi_arg(acct_name, expected):
 
    assert data.Account(acct_name).is_under('Income', 'UnearnedIncome') == expected
 
    if expected:
 
        expected += ':'
 
    assert data.Account(acct_name).is_under('Income:', 'UnearnedIncome:') == expected
 

	
 
@pytest.mark.parametrize('acct_name,expected', [
 
    ('Accrued:AccountsReceivable', False),
 
    ('Assets:Cash', False),
 
    ('Expenses:General', False),
 
    ('Income:Donations', True),
 
    ('Income:Sales', True),
 
    ('Income:Other', True),
 
    ('Liabilities:CreditCard', False),
 
    ('UnearnedIncome:MatchPledges', True),
 
])
 
def test_is_income(acct_name, expected):
 
    assert data.Account(acct_name).is_income() == expected
 

	
 
@pytest.mark.parametrize('acct_name,expected', [
 
    ('Accrued:AccountsPayable', False),
 
    ('Accrued:AccountsReceivable', False),
 
    ('Assets:Cash', True),
 
    ('Assets:Cash:EUR', True),
 
    ('Assets:PrepaidExpenses', False),
 
    ('Assets:PrepaidVacation', False),
 
    ('Assets:Bank:Checking', True),
 
    ('Expenses:General', False),
 
    ('Income:Donations', False),
 
])
 
def test_is_real_asset(acct_name, expected):
 
    assert data.Account(acct_name).is_real_asset() == expected
0 comments (0 inline, 0 general)