converter.py 26.9 KB
Newer Older
1
# Copyright (c) 2013, 2014 Erik Hetzner
James Blachly's avatar
James Blachly committed
2
# Portions Copyright (c) 2016 James S Blachly, MD
Erik Hetzner's avatar
Erik Hetzner committed
3
#
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# This file is part of ledger-autosync
#
# ledger-autosync is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# ledger-autosync 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ledger-autosync. If not, see
# <http://www.gnu.org/licenses/>.

Erik Hetzner's avatar
Erik Hetzner committed
20

Erik Hetzner's avatar
Erik Hetzner committed
21
from decimal import Decimal
22
import re
23
from ofxparse.ofxparse import Transaction as OfxTransaction, InvestmentTransaction
24
from ledgerautosync import EmptyInstitutionException
25
import datetime
26
import hashlib
27

28
AUTOSYNC_INITIAL = "autosync_initial"
Erik Hetzner's avatar
Erik Hetzner committed
29
ALL_AUTOSYNC_INITIAL = "all.%s" % (AUTOSYNC_INITIAL)
30
UNKNOWN_BANK_ACCOUNT = "Assets:Unknown"
Erik Hetzner's avatar
Erik Hetzner committed
31

Erik Hetzner's avatar
Erik Hetzner committed
32

33 34 35 36 37 38 39 40 41 42
class EasyEquality(object):
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

Erik Hetzner's avatar
Erik Hetzner committed
43

James Blachly's avatar
James Blachly committed
44 45 46 47
class SecurityList(object):
    """
    The SecurityList represents the OFX <SECLIST>...</SECLIST>
    and holds securities present in the OFX records
48

James Blachly's avatar
James Blachly committed
49 50 51
    <SECINFO>...</SECINFO> as implemented by OFXparse only includes:
    {memo, name, ticker, uniqueid}
    Unfortunately does not provide uniqueid_type or currency
52

James Blachly's avatar
James Blachly committed
53 54 55
    It is iterable, and also provides lookup table (LUT) functionality
    provides __next__() for Py3
    """
Erik Hetzner's avatar
Erik Hetzner committed
56

57 58 59 60 61
    def __init__(self, ofx):
        securities = []
        if hasattr(ofx, 'security_list') and ofx.security_list is not None:
            securities = ofx.security_list

James Blachly's avatar
James Blachly committed
62 63
        self.cusip_lut = dict()
        self.ticker_lut = dict()
64

James Blachly's avatar
James Blachly committed
65 66
        self._iter = iter(securities)
        self.securities = securities
Erik Hetzner's avatar
Erik Hetzner committed
67 68
        if len(securities) == 0:
            return
69

James Blachly's avatar
James Blachly committed
70 71 72 73
        # index
        for sec in securities:
            # unfortunately OFXparse does not currently implement
            # security.uniqueid_type so I am presuming here
Erik Hetzner's avatar
Erik Hetzner committed
74 75 76 77
            if sec.uniqueid:
                self.cusip_lut[sec.uniqueid] = sec
            if sec.ticker:
                self.ticker_lut[sec.ticker] = sec
James Blachly's avatar
James Blachly committed
78 79 80 81
            # This indexing strategy (whereby I index the object instead of
            # the inverse value (e.g. ticker symbol) directly has a flaw
            # in that an OFX file could define a security list section and
            # list CUSIPs without ticker property, or the converse
82

James Blachly's avatar
James Blachly committed
83 84
    def __iter__(self):
        return self
85

86
    def __next__(self):
James Blachly's avatar
James Blachly committed
87
        return next(self._iter)
88

James Blachly's avatar
James Blachly committed
89 90 91 92 93 94 95 96
    def __len__(self):
        return len(self.securities)

    # one possibility is to just implement __getitem__(),
    # however since OFXparse does not implement securitylist.security.uniqueid_type
    # I'll have no idea if what I am seeing is a CUSISP
    # unless I look it up specifically as a CUSIP (and it exists)
    def find_cusip(self, cusip):
Erik Hetzner's avatar
Erik Hetzner committed
97 98 99 100
        if cusip in self.cusip_lut:
            return self.cusip_lut[cusip]
        else:
            return None
James Blachly's avatar
James Blachly committed
101 102

    def find_ticker(self, ticker):
Erik Hetzner's avatar
Erik Hetzner committed
103 104 105 106
        if ticker in self.ticker_lut:
            return self.ticker_lut[ticker]
        else:
            return None
James Blachly's avatar
James Blachly committed
107

108

109
class Transaction(object):
Erik Hetzner's avatar
Erik Hetzner committed
110 111 112 113 114 115 116 117
    def __init__(
            self,
            date,
            payee,
            postings,
            cleared=False,
            metadata={},
            aux_date=None):
118 119 120 121 122 123 124
        self.date = date
        self.aux_date = aux_date
        self.payee = payee
        self.postings = postings
        self.metadata = metadata
        self.cleared = cleared

125
    def format(self, indent=4, assertions=True):
126 127 128 129 130 131
        retval = ""
        cleared_str = " "
        if self.cleared:
            cleared_str = " * "
        aux_date_str = ""
        if self.aux_date is not None:
Erik Hetzner's avatar
Erik Hetzner committed
132 133 134
            aux_date_str = "=%s" % (self.aux_date.strftime("%Y/%m/%d"))
        retval += "%s%s%s%s\n" % (self.date.strftime("%Y/%m/%d"),
                                  aux_date_str, cleared_str, self.payee)
135 136
        for k in sorted(self.metadata.keys()):
            retval += "%s; %s: %s\n" % (" " * indent, k, self.metadata[k])
137
        for posting in self.postings:
138
            retval += posting.format(indent, assertions)
139 140
        return retval

Erik Hetzner's avatar
Erik Hetzner committed
141

Erik Hetzner's avatar
Erik Hetzner committed
142
class Posting(object):
Erik Hetzner's avatar
Erik Hetzner committed
143 144 145 146 147 148 149
    def __init__(
            self,
            account,
            amount,
            asserted=None,
            unit_price=None,
            metadata={}):
Erik Hetzner's avatar
Erik Hetzner committed
150 151 152 153
        self.account = account
        self.amount = amount
        self.asserted = asserted
        self.unit_price = unit_price
154
        self.metadata = metadata
Erik Hetzner's avatar
Erik Hetzner committed
155

156
    def format(self, indent=4, assertions=True):
Erik Hetzner's avatar
Erik Hetzner committed
157 158
        space_count = 65 - indent - \
            len(self.account) - len(self.amount.format())
Erik Hetzner's avatar
Erik Hetzner committed
159 160
        if space_count < 2:
            space_count = 2
Erik Hetzner's avatar
Erik Hetzner committed
161 162 163 164
        retval = "%s%s%s%s" % (" " * indent,
                               self.account,
                               " " * space_count,
                               self.amount.format())
165
        if assertions and self.asserted is not None:
Erik Hetzner's avatar
Erik Hetzner committed
166
            retval = "%s = %s" % (retval, self.asserted.format())
Erik Hetzner's avatar
Erik Hetzner committed
167
        if self.unit_price is not None:
Erik Hetzner's avatar
Erik Hetzner committed
168
            retval = "%s @ %s" % (retval, self.unit_price.format())
169
        retval += "\n"
170 171
        for k in sorted(self.metadata.keys()):
            retval += "%s; %s: %s\n" % (" " * indent, k, self.metadata[k])
172
        return retval
Erik Hetzner's avatar
Erik Hetzner committed
173

174 175 176 177 178 179
    def clone_inverted(self, account, asserted=None, metadata={}):
        return Posting(account,
                       self.amount.clone_inverted(),
                       asserted=asserted,
                       unit_price=self.unit_price,
                       metadata=metadata)
Erik Hetzner's avatar
Erik Hetzner committed
180

181
class Amount(EasyEquality):
Erik Hetzner's avatar
Erik Hetzner committed
182
    def __init__(self, number, currency, reverse=False, unlimited=False):
183
        self.number = Decimal(number)
Erik Hetzner's avatar
Erik Hetzner committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        self.reverse = reverse
        self.unlimited = unlimited
        self.currency = currency

    def format(self):
        # Commodities must be quoted in ledger if they have
        # whitespace or numerals.
        if re.search(r'[\s0-9]', self.currency):
            currency = "\"%s\"" % (self.currency)
        else:
            currency = self.currency
        if self.unlimited:
            number = str(abs(self.number))
        else:
            number = "%0.2f" % (abs(self.number))
        if self.number.is_signed() != self.reverse:
            prefix = "-"
        else:
            prefix = ""
        if len(currency) == 1:
            # $ comes before
            return "%s%s%s" % (prefix, currency, number)
        else:
            # USD comes after
            return "%s%s %s" % (prefix, number, currency)

210 211 212 213 214
    def clone_inverted(self):
        return Amount(self.number,
                      self.currency,
                      reverse=not(self.reverse),
                      unlimited=self.unlimited)
Erik Hetzner's avatar
Erik Hetzner committed
215

216
class Converter(object):
217 218 219 220 221
    @staticmethod
    def clean_id(id):
        return id.replace('/', '_').\
            replace('$', '_').\
            replace(' ', '_').\
222 223
            replace('@', '_').\
            replace('*', '_').\
224
            replace('+', '_').\
225 226
            replace('[', '_').\
            replace(']', '_')
227

Erik Hetzner's avatar
Erik Hetzner committed
228 229 230 231 232 233 234
    def __init__(
            self,
            ledger=None,
            unknownaccount=None,
            currency='$',
            indent=4,
            payee_format=None):
235 236 237
        self.lgr = ledger
        self.indent = indent
        self.unknownaccount = unknownaccount
238
        self.currency = currency.upper()
239
        self.payee_format = payee_format
240 241 242
        if self.currency == "USD":
            self.currency = "$"

243 244 245 246 247 248 249 250 251 252
    def mk_dynamic_account(self, payee, exclude):
        if self.lgr is None:
            return self.unknownaccount or 'Expenses:Misc'
        else:
            account = self.lgr.get_account_by_payee(payee, exclude)
            if account is None:
                return self.unknownaccount or 'Expenses:Misc'
            else:
                return account

253

254
class OfxConverter(Converter):
Erik Hetzner's avatar
Erik Hetzner committed
255 256 257 258 259 260 261 262 263 264 265 266 267
    def __init__(
            self,
            account,
            name,
            indent=4,
            ledger=None,
            fid=None,
            unknownaccount=None,
            payee_format=None,
            hardcodeaccount=None,
            shortenaccount=False,
            security_list=SecurityList(
            [])):
268
        super(OfxConverter, self).__init__(ledger=ledger,
269 270
                                           indent=indent,
                                           unknownaccount=unknownaccount,
271
                                           currency=account.statement.currency,
272
                                           payee_format=payee_format)
273
        self.real_acctid = account.account_id
274 275 276
        if hardcodeaccount is not None:
            self.acctid = hardcodeaccount
        elif shortenaccount:
277
            self.acctid = account.account_id[-4:]
278
        else:
279
            self.acctid = account.account_id
280
        self.payee_format = payee_format
281
        self.security_list = security_list
Erik Hetzner's avatar
Erik Hetzner committed
282

283 284 285
        if fid is not None:
            self.fid = fid
        else:
286
            if account.institution is None:
Erik Hetzner's avatar
Erik Hetzner committed
287 288
                raise EmptyInstitutionException(
                    "Institution provided by OFX is empty and no fid supplied!")
289
            else:
290
                self.fid = account.institution.fid
Erik Hetzner's avatar
Erik Hetzner committed
291
        self.name = name
Erik Hetzner's avatar
Erik Hetzner committed
292

Erik Hetzner's avatar
Erik Hetzner committed
293
    def mk_ofxid(self, txnid):
294 295
        if self.acctid != self.real_acctid:
            # Some banks insert the bank account number into the transaction ID
Erik Hetzner's avatar
Erik Hetzner committed
296 297
            # We will do this to properly hide the account number for privacy
            # reasons
298
            txnid = txnid.replace(self.real_acctid, self.acctid)
299
        return Converter.clean_id("%s.%s.%s" % (self.fid, self.acctid, txnid))
Erik Hetzner's avatar
Erik Hetzner committed
300

Erik Hetzner's avatar
Erik Hetzner committed
301
    def format_payee(self, txn):
302 303
        payee = ""
        if (hasattr(txn, 'payee') and txn.payee is not None):
Erik Hetzner's avatar
Erik Hetzner committed
304
            payee = txn.payee
305 306
        memo = ""
        if (hasattr(txn, 'memo') and txn.memo is not None):
Erik Hetzner's avatar
Erik Hetzner committed
307
            memo = txn.memo
308 309 310 311 312 313
        txntype = ""
        if (hasattr(txn, 'type') and txn.type is not None):
            txntype = txn.type
        tferaction = ""
        if (hasattr(txn, 'tferaction') and txn.tferaction is not None):
            tferaction = txn.tferaction.lower()
Erik Hetzner's avatar
Erik Hetzner committed
314

315
        if payee != "" and self.lgr is not None:
Scott Weldon's avatar
Scott Weldon committed
316 317
            payee = self.lgr.get_autosync_payee(payee, self.name)

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        payee_format = self.payee_format

        if payee_format is None:
            # Default when not provided
            payee_format = "{payee} {memo}"

            # Alternate for when payee and memo are blank, sometimes true for
            # investment accounts.
            if (payee == "") and (memo == ""):
                payee_format = "{account}: {txntype}"
                if tferaction != "":
                    payee_format += ": {tferaction}"

            # Sometimes memo/payee are simply longer versions of the other.
            if memo.startswith(payee):
                payee = ""
            if payee.startswith(memo):
                memo = ""

Erik Hetzner's avatar
Erik Hetzner committed
337 338 339 340 341 342
        return payee_format.format(
            payee=payee,
            memo=memo,
            txntype=txntype,
            account=self.name,
            tferaction=tferaction).strip()
Erik Hetzner's avatar
Erik Hetzner committed
343

344
    def format_balance(self, statement):
345 346
        # Get date. Ensure the date is a date-like object.
        if (hasattr(statement, 'balance_date') and
Erik Hetzner's avatar
Erik Hetzner committed
347
                hasattr(statement.balance_date, 'strftime')):
348
            date = statement.balance_date
349 350
        elif (hasattr(statement, 'end_date') and
              hasattr(statement.end_date, 'strftime')):
351
            date = statement.end_date
352
        else:
353
            return ""
354
        if (hasattr(statement, 'balance')):
355 356 357 358 359 360 361 362 363 364 365 366
            return Transaction(
                date=date,
                cleared=True,
                payee="--Autosync Balance Assertion",
                postings=[
                    Posting(
                        self.name,
                        Amount(Decimal("0"), currency=self.currency),
                        asserted=Amount(statement.balance, self.currency))
                ]).format(self.indent)
        else:
            return ""
367 368 369 370 371 372

    def format_initial_balance(self, statement):
        if (hasattr(statement, 'balance')):
            initbal = statement.balance
            for txn in statement.transactions:
                initbal -= txn.amount
373 374

            posting = Posting(
375
                        self.name,
Erik Hetzner's avatar
Erik Hetzner committed
376 377 378 379
                        Amount(
                            initbal,
                            currency=self.currency),
                        metadata={
380 381 382 383 384 385 386 387 388
                            "ofxid": self.mk_ofxid(AUTOSYNC_INITIAL)})

            return Transaction(
                date=statement.start_date,
                payee="--Autosync Initial Balance",
                cleared=True,
                postings=[
                    posting,
                    posting.clone_inverted("Assets:Equity").format(self.indent)],
Erik Hetzner's avatar
Erik Hetzner committed
389 390
            ).format(
                self.indent)
391 392
        else:
            return ""
Erik Hetzner's avatar
Erik Hetzner committed
393

394 395 396 397 398 399 400 401 402
    # Return the ticker symbol of the security with CUSIP, if it exists in the
    # security_list mapping. Otherwise, simply return the CUSIP.
    def maybe_get_ticker(self, cusip):
        security = self.security_list.find_cusip(cusip)
        if security is not None:
            return security.ticker
        else:
            return cusip

Erik Hetzner's avatar
Erik Hetzner committed
403
    def convert(self, txn):
404 405 406
        """
        Convert an OFX Transaction to a posting
        """
407

Erik Hetzner's avatar
Erik Hetzner committed
408
        ofxid = self.mk_ofxid(txn.id)
409 410
        metadata = {}
        posting_metadata = {"ofxid": ofxid}
James Blachly's avatar
James Blachly committed
411

412
        if isinstance(txn, OfxTransaction):
413 414 415
            posting = Posting(self.name,
                              Amount(txn.amount, self.currency),
                              metadata=posting_metadata)
416
            return Transaction(
417 418 419 420 421 422 423
                date=txn.date,
                payee=self.format_payee(txn),
                postings=[
                    posting,
                    posting.clone_inverted(
                        self.mk_dynamic_account(self.format_payee(txn),
                                                exclude=self.name))])
Erik Hetzner's avatar
Erik Hetzner committed
424
        elif isinstance(txn, InvestmentTransaction):
425 426
            acct1 = self.name
            acct2 = self.name
427 428 429 430

            posting1 = None
            posting2 = None

431
            security = self.maybe_get_ticker(txn.security)
Erik Hetzner's avatar
Erik Hetzner committed
432

Erik Hetzner's avatar
Erik Hetzner committed
433
            if isinstance(txn.type, str):
434 435 436
                # recent versions of ofxparse
                if re.match('^(buy|sell)', txn.type):
                    acct2 = self.unknownaccount or 'Assets:Unknown'
437 438
                elif txn.type == 'transfer':
                    acct2 = 'Transfer'
439 440 441 442
                elif txn.type == 'reinvest':
                    # reinvestment of income
                    # TODO: make this configurable
                    acct2 = 'Income:Interest'
443 444 445 446
                elif txn.type == 'income' and txn.income_type == 'DIV':
                    # Fidelity lists non-reinvested dividend income as
                    # type: income, income_type: DIV
                    # TODO: determine how dividend income is listed from other institutions
James Blachly's avatar
James Blachly committed
447
                    # income/DIV transactions do not involve buying or selling a security
Erik Hetzner's avatar
Erik Hetzner committed
448 449
                    # so their postings need special handling compared to
                    # others
Erik Hetzner's avatar
Erik Hetzner committed
450
                    metadata['dividend_from'] = security
451
                    acct2 = 'Income:Dividends'
452 453 454
                    posting1 = Posting(acct1,
                                       Amount(txn.total, self.currency),
                                       metadata=posting_metadata)
455
                    posting2 = posting1.clone_inverted(acct2)
456 457 458
                else:
                    # ???
                    pass
459
            else:
460 461 462 463 464 465 466 467 468 469
                # Old version of ofxparse
                if (txn.type in [0, 1, 3, 4]):
                    # buymf, sellmf, buystock, sellstock
                    acct2 = self.unknownaccount or 'Assets:Unknown'
                elif (txn.type == 2):
                    # reinvest
                    acct2 = 'Income:Interest'
                else:
                    # ???
                    pass
470

471
            aux_date = None
472 473
            if txn.settleDate is not None and \
               txn.settleDate != txn.tradeDate:
474
                aux_date = txn.settleDate
475

James Blachly's avatar
James Blachly committed
476 477
            # income/DIV already defined above;
            # this block defines all other posting types
478
            if posting1 is None and posting2 is None:
Erik Hetzner's avatar
Erik Hetzner committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
                posting1 = Posting(
                    acct1,
                    Amount(
                        txn.units,
                        security,
                        unlimited=True),
                    unit_price=Amount(
                        txn.unit_price,
                        self.currency,
                        unlimited=True),
                    metadata=posting_metadata)
                posting2 = Posting(
                    acct2,
                    Amount(
                        txn.units *
                        txn.unit_price,
                        self.currency,
                        reverse=True))
497 498 499 500
            else:
                # Previously defined if type:income income_type/DIV
                pass

501 502
            return Transaction(
                date=txn.tradeDate,
Erik Hetzner's avatar
Erik Hetzner committed
503
                aux_date=aux_date,
504
                payee=self.format_payee(txn),
505
                metadata=metadata,
Erik Hetzner's avatar
Erik Hetzner committed
506
                postings=[posting1, posting2]
Erik Hetzner's avatar
Erik Hetzner committed
507
            )
508 509 510 511 512

    def format_position(self, pos):
        if hasattr(pos, 'date') and hasattr(pos, 'security') and \
           hasattr(pos, 'unit_price'):
            dateStr = pos.date.strftime("%Y/%m/%d %H:%M:%S")
Erik Hetzner's avatar
Erik Hetzner committed
513 514
            return "P %s %s %s\n" % (
                dateStr, self.maybe_get_ticker(pos.security), pos.unit_price)
515 516


517
class CsvConverter(Converter):
518
    @staticmethod
519
    def make_converter(fieldset, dialect, name=None, **kwargs):
520
        for klass in CsvConverter.descendants():
521
            if klass.FIELDSET <= fieldset:
522
                return klass(dialect, name=name, **kwargs)
523 524
        # Found no class, bail
        raise Exception('Cannot determine CSV type')
525

526 527 528 529 530 531 532
    @classmethod
    def descendants(cls):
        retval = cls.__subclasses__()
        for cls2 in cls.__subclasses__():
            retval.extend(cls2.descendants())
        return retval

533 534 535 536 537
    # By default, return an MD5 of the key-value pairs in the row.
    # If a better ID is available, should be overridden.
    def get_csv_id(self, row):
        h = hashlib.md5()
        for key in sorted(row.keys()):
Erik Hetzner's avatar
Erik Hetzner committed
538
            h.update(("%s=%s\n" % (key, row[key])).encode('utf-8'))
539 540
        return h.hexdigest()

Erik Hetzner's avatar
Erik Hetzner committed
541 542 543 544 545 546 547 548
    def __init__(
            self,
            dialect,
            name=None,
            indent=4,
            ledger=None,
            unknownaccount=None,
            payee_format=None):
549
        super(CsvConverter, self).__init__(
550
            indent=indent,
551 552
            unknownaccount=unknownaccount,
            payee_format=payee_format)
553
        self.name = name
554
        self.dialect = dialect
555

556 557 558 559
    def format_payee(self, row):
        return re.sub(r"\s+", " ",
                      self.payee_format.format(**row).strip())

560 561

class PaypalConverter(CsvConverter):
Erik Hetzner's avatar
Erik Hetzner committed
562 563 564 565 566 567 568 569 570 571 572
    FIELDSET = {
        'Currency',
        'Date',
        'Gross',
        'Item Title',
        'Name',
        'Net',
        'Status',
        'To Email Address',
        'Transaction ID',
        'Type'}
573 574 575

    def __init__(self, *args, **kwargs):
        super(PaypalConverter, self).__init__(*args, **kwargs)
576
        if self.payee_format is None:
577 578
            self.payee_format = \
                "{Name} {To Email Address} {Item Title} ID: {Transaction ID}, {Type}"
579

580
    def get_csv_id(self, row):
Erik Hetzner's avatar
Erik Hetzner committed
581
        return "paypal.%s" % (Converter.clean_id(row['Transaction ID']))
582

Erik Hetzner's avatar
Erik Hetzner committed
583
    def convert(self, row):
Erik Hetzner's avatar
Erik Hetzner committed
584 585
        if (((row['Status'] != "Completed") and (row['Status'] != "Refunded") and (
                row['Status'] != "Reversed")) or (row['Type'] == "Shopping Cart Item")):
586 587
            return ""
        else:
588
            currency = row['Currency']
589
            posting_metadata = {"csvid": self.get_csv_id(row)}
590 591 592
            net = Decimal(row['Net'].replace(',', ''))
            gross = Decimal(row['Gross'].replace(',', ''))

593 594
            if row['Type'] == "Add Funds from a Bank Account" or \
               row['Type'] == "Charge From Debit Card":
595 596 597 598 599
                posting = Posting(self.name,
                                  Amount(net, currency),
                                  metadata=posting_metadata)
                postings = [posting,
                            posting.clone_inverted("Transfer:Paypal")]
600
            else:
601 602 603
                posting = Posting(self.name,
                                  Amount(gross, currency),
                                  metadata=posting_metadata)
Erik Hetzner's avatar
Erik Hetzner committed
604
                postings = [
605 606 607 608 609
                    posting,
                    # TODO Our payees are breaking the payee search in
                    # mk_dynamic_account
                    # self.mk_dynamic_account(payee, exclude=self.name),
                    posting.clone_inverted("Expenses:Misc")]
610 611
            return Transaction(
                date=datetime.datetime.strptime(row['Date'], "%m/%d/%Y"),
612
                payee=self.format_payee(row),
613
                postings=postings)
Erik Hetzner's avatar
Erik Hetzner committed
614

615
# Apparently Paypal has another CSV
Erik Hetzner's avatar
Erik Hetzner committed
616 617


618
class PaypalAlternateConverter(CsvConverter):
Erik Hetzner's avatar
Erik Hetzner committed
619
    FIELDSET = {"Date", "Name", "Type", "Status", "Amount"}
620 621 622 623 624 625

    def __init__(self, *args, **kwargs):
        super(PaypalAlternateConverter, self).__init__(*args, **kwargs)
        if self.payee_format is None:
            self.payee_format = "{Name}: {Type}"

626 627 628 629
    def mk_amount(self, row, reverse=False):
        currency = '$'
        if 'Currency' in row:
            currency = row['Currency']
Erik Hetzner's avatar
Erik Hetzner committed
630 631 632 633 634 635 636 637
        return Amount(
            Decimal(
                re.sub(
                    r"\$",
                    "",
                    row['Amount'])),
            currency,
            reverse=reverse)
638

639
    def convert(self, row):
Erik Hetzner's avatar
Erik Hetzner committed
640 641
        if (((row['Status'] != "Completed") and (row['Status'] != "Refunded") and (
                row['Status'] != "Reversed")) or (row['Type'] == "Shopping Cart Item")):
642 643 644
            return ""
        else:
            posting_metadata = {"csvid": self.get_csv_id(row)}
645 646 647
            posting = Posting(self.name,
                              self.mk_amount(row),
                              metadata=posting_metadata)
648 649
            if row['Type'] == "Add Funds from a Bank Account" \
               or row['Type'] == "Charge From Debit Card":
650 651

                posting2_account="Transfer:Paypal"
652
            else:
653
                posting2_account="Expenses:Misc"
654 655 656
            return Transaction(
                date=datetime.datetime.strptime(row['Date'], "%m/%d/%Y"),
                payee=self.format_payee(row),
657
                postings=[posting,posting.clone_inverted(posting2_account)])
658

Erik Hetzner's avatar
Erik Hetzner committed
659 660

class AmazonConverter(CsvConverter):
Erik Hetzner's avatar
Erik Hetzner committed
661
    FIELDSET = {'Currency', 'Title', 'Order Date', 'Order ID'}
Erik Hetzner's avatar
Erik Hetzner committed
662 663 664

    def __init__(self, *args, **kwargs):
        super(AmazonConverter, self).__init__(*args, **kwargs)
665
        self.dialect.doublequote = True
Erik Hetzner's avatar
Erik Hetzner committed
666 667 668

    def mk_amount(self, row, reverse=False):
        currency = row['Currency']
Erik Hetzner's avatar
Erik Hetzner committed
669 670 671 672 673 674 675 676 677 678
        if currency == "USD":
            currency = "$"
        return Amount(
            Decimal(
                re.sub(
                    r"\$",
                    "",
                    row['Item Total'])),
            currency,
            reverse=reverse)
Erik Hetzner's avatar
Erik Hetzner committed
679

680
    def get_csv_id(self, row):
Erik Hetzner's avatar
Erik Hetzner committed
681
        return "amazon.%s" % (Converter.clean_id(row['Order ID']))
682

Erik Hetzner's avatar
Erik Hetzner committed
683
    def convert(self, row):
684
        posting = Posting(
Erik Hetzner's avatar
Erik Hetzner committed
685 686 687
                    self.name,
                    self.mk_amount(row),
                    metadata={
688
                        "url": "https://www.amazon.com/gp/css/summary/print.html/ref=od_aui_print_invoice?ie=UTF8&orderID=%s" %  # noqa E501
Erik Hetzner's avatar
Erik Hetzner committed
689
                        (row['Order ID']),
690 691 692 693 694 695 696 697 698
                        "csvid": self.get_csv_id(row)})

        return Transaction(
            date=datetime.datetime.strptime(
                row['Order Date'],
                "%m/%d/%y"),
            payee=row['Title'],
            postings=[posting,
                      posting.clone_inverted("Expenses:Misc")])
Erik Hetzner's avatar
Erik Hetzner committed
699

Erik Hetzner's avatar
Erik Hetzner committed
700 701

class MintConverter(CsvConverter):
Erik Hetzner's avatar
Erik Hetzner committed
702 703 704 705 706 707 708
    FIELDSET = {
        'Date',
        'Amount',
        'Description',
        'Account Name',
        'Category',
        'Transaction Type'}
Erik Hetzner's avatar
Erik Hetzner committed
709 710 711 712 713 714 715 716 717 718 719 720

    def __init__(self, *args, **kwargs):
        super(MintConverter, self).__init__(*args, **kwargs)

    def mk_amount(self, row, reverse=False):
        return Amount(Decimal(row['Amount']), '$', reverse=reverse)

    def convert(self, row):
        account = self.name
        if account is None:
            account = row['Account Name']
        postings = []
Erik Hetzner's avatar
Erik Hetzner committed
721
        posting_metadata = {"csvid": "mint.%s" % (self.get_csv_id(row))}
Erik Hetzner's avatar
Erik Hetzner committed
722
        if (row['Transaction Type'] == 'credit'):
723 724 725 726 727
            posting = Posting(account,
                              self.mk_amount(row, reverse=True),
                              metadata=posting_metadata)
            postings = [posting,
                        posting.clone_inverted(row['Category'])]
Erik Hetzner's avatar
Erik Hetzner committed
728
        else:
729 730 731 732 733
            posting = Posting(account,
                              self.mk_amount(row),
                              metadata=posting_metadata)
            postings = [posting,
                        posting.clone_inverted("Expenses:%s" % (row['Category']))]
Erik Hetzner's avatar
Erik Hetzner committed
734 735 736 737 738

        return Transaction(
            date=datetime.datetime.strptime(row['Date'], "%m/%d/%Y"),
            payee=row['Description'],
            postings=postings)
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

# Simple.com
class SimpleConverter(CsvConverter):
    FIELDSET = {
        "Date",
        "Recorded at",
        "Scheduled for",
        "Amount",
        "Activity",
        "Pending",
        "Raw description",
        "Description",
        "Category folder",
        "Category",
        "Street address",
        "City",
        "State",
        "Zip",
        "Latitude",
        "Longitude",
        "Memo"}

    def __init__(self, *args, **kwargs):
        super(SimpleConverter, self).__init__(*args, **kwargs)

    def convert(self, row):
        amount = abs(float(row['Amount']))
        reverse = row['Amount'][0] == '-'

        if reverse:
            account = "Expenses:%s" % (row['Category'])
        else:
            account = "Income:%s" % (row['Category'])

        posting_metadata = {
            "csvid": "simple.%s" % (self.get_csv_id(row)),
            "raw_description": row['Raw description'],
            "activity_type"  : row['Activity'],
        }
        if row['Memo']:
            posting_metadata["memo"] = row["Memo"]

        return Transaction(
           date = datetime.datetime.strptime(row['Date'], "%Y/%m/%d"),
           payee = row['Description'],
           postings = [Posting(self.name, Amount(amount, '$', reverse), metadata = posting_metadata),
                       Posting(account, Amount(amount, '$', reverse = not(reverse)))
                       ]
        )