Files @ 21bea11beb53
Branch filter:

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

Brett Smith
meta_paypal_id: Start validator. RT#10260.
"""meta_paypal_id - Validate paypal-id 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 MetaPayPalID(core._PostingHook):
    METADATA_KEY = 'paypal-id'
    HOOK_GROUPS = frozenset(['metadata', METADATA_KEY])
    TXN_ID_RE = re.compile(r'^[A-Z0-9]{17}$')
    INVOICE_ID_RE = re.compile(r'^INV2(?:-[A-Z0-9]{4}){4}$')

    def _run_on_post(self, txn: Transaction, post: data.Posting) -> bool:
        if post.account.is_under('Assets:PayPal'):
            return True
        elif post.account.is_under('Assets:Receivable'):
            return self.METADATA_KEY in post.meta
        else:
            return False

    def post_run(self, txn: Transaction, post: data.Posting) -> errormod.Iter:
        if post.account.is_under('Assets:Receivable'):
            regexp = self.INVOICE_ID_RE
        else:
            regexp = self.TXN_ID_RE
        value = post.meta.get(self.METADATA_KEY)
        try:
            # A bad argument type is okay because we catch the TypeError.
            match = regexp.match(value)  # type:ignore[arg-type]
        except TypeError:
            match = None
        if match is None:
            yield errormod.InvalidMetadataError(txn, self.METADATA_KEY, value, post)