Files @ 13c316acf6e1
Branch filter:

Location: NPO-Accounting/import2ledger/import2ledger/importers/yourcause.py

Brett Smith
tests: More tests for positive results for last commit.
import decimal

try:
    import enum
except ImportError:
    import enum34 as enum

from . import _csv
from .. import strparse

ZERO_DECIMAL = decimal.Decimal(0)

class _DonorType(enum.Enum):
    Individual = 1
    Company = 2

    @classmethod
    def from_donation_type(cls, donation_type):
        if donation_type.startswith('Individual-'):
            return cls.Individual
        elif donation_type.startswith('Employer Match-'):
            return cls.Company
        else:
            raise ValueError("unknown donation type {!r}".format(donation_type))


class DonationsImporter(_csv.CSVImporterBase):
    ANONYMOUS = "Anonymous"
    DATE_FMT = '%m/%d/%Y %I:%M:%S %p'
    DONATION_TYPE_FIELD = 'Donation Type'
    ENTRY_SEED = {
        'currency': 'USD',
        'donor_amount': ZERO_DECIMAL,
        'match_amount': ZERO_DECIMAL,
    }
    DECIMAL_FIELDS = {
        'Local Currency Receipt Amount': 'original_amount',
        'Received Amount': 'received_amount',
        'Transaction Amount': 'amount',
    }
    NEEDED_FIELDS = frozenset([
        DONATION_TYPE_FIELD,
        'Donor First Name',
        'Donor Last Name',
        'Match Donor First Name',
        'Match Donor Last Name',
        *DECIMAL_FIELDS,
    ])
    COPIED_FIELDS = {
        'Company_Name': 'corporation',
        'Dedication Type': 'dedication_type',
        'Dedication': 'dedication',
        'Designation': 'designation',
        'Local Currency Type': 'original_currency',
        'Payment ID': 'payment_id',
        'Transaction_ID': 'transaction_id',
    }

    def _donor_name(self, row, *keys):
        names = [row[key] for key in keys]
        if any(s and s != self.ANONYMOUS for s in names):
            return ' '.join(names).strip()
        else:
            return self.ANONYMOUS

    def _read_row(self, row):
        donor_type = _DonorType.from_donation_type(row[self.DONATION_TYPE_FIELD])
        retval = {retkey: strparse.currency_decimal(row[rowkey])
                  for rowkey, retkey in self.DECIMAL_FIELDS.items()}
        retval['date'] = strparse.date(row['Donation_Date'], self.DATE_FMT)
        if donor_type is _DonorType.Individual:
            retval['donor'] = self._donor_name(row, 'Donor First Name', 'Donor Last Name')
            retval['donor_amount'] = retval['amount']
            retval['payee'] = retval['donor']
        else:
            retval['donor'] = self._donor_name(row, 'Match Donor First Name', 'Match Donor Last Name')
            retval['match_amount'] = retval['amount']
            retval['payee'] = row['Company_Name']
        return retval