Files @ 90a58ef11258
Branch filter:

Location: NPO-Accounting/conservancy_beancount/conservancy_beancount/plugin/meta_entity.py

Brett Smith
meta_project: Not required on Equity accounts.
"""meta_entity - Validate entity 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/>.

import re

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

class MetaEntity(core.TransactionHook):
    METADATA_KEY = 'entity'
    HOOK_GROUPS = frozenset(['posting', 'metadata', METADATA_KEY])
    ENTITY_RE = re.compile(r'^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$')

    def run(self, txn: Transaction) -> errormod.Iter:
        txn_entity = txn.meta.get(self.METADATA_KEY)
        if txn_entity is None:
            txn_entity_ok = None
        elif isinstance(txn_entity, str):
            txn_entity_ok = bool(self.ENTITY_RE.match(txn_entity))
        else:
            txn_entity_ok = False
        if txn_entity_ok is False:
            yield errormod.InvalidMetadataError(txn, self.METADATA_KEY, txn_entity)
        for post in data.iter_postings(txn):
            if post.account.is_under('Assets', 'Equity', 'Liabilities'):
                continue
            entity = post.meta.get(self.METADATA_KEY)
            if entity is None:
                yield errormod.InvalidMetadataError(txn, self.METADATA_KEY, entity, post)
            elif entity is txn_entity:
                pass
            elif not self.ENTITY_RE.match(entity):
                yield errormod.InvalidMetadataError(txn, self.METADATA_KEY, entity, post)