File: paypal.py

package info (click to toggle)
ofxstatement-plugins 20210310
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,964 kB
  • sloc: python: 7,219; xml: 1,027; makefile: 167; sh: 92
file content (201 lines) | stat: -rw-r--r-- 5,865 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# -*- coding: utf-8 -*-

import locale
import itertools
import csv

from datetime import datetime

from contextlib import contextmanager
from ofxstatement.parser import StatementParser
from ofxstatement.plugin import Plugin
from ofxstatement.statement import Statement, StatementLine, generate_transaction_id


def take(iterable, n):
    """Return first n items of the iterable as a list."""
    return list(itertools.islice(iterable, n))


def drop(iterable, n):
    """Drop first n items of the iterable and return result as a list."""
    return list(itertools.islice(iterable, n, None))


def head(iterable):
    """Return first element of the iterable."""
    return take(iterable, 1)[0]


@contextmanager
def scoped_setlocale(category, loc=None):
    """Scoped version of locale.setlocale()"""
    orig = locale.getlocale(category)
    try:
        yield locale.setlocale(category, loc)
    finally:
        locale.setlocale(category, orig)


def atof(string, loc=None):
    """Locale aware atof function for our parser."""
    with scoped_setlocale(locale.LC_NUMERIC, loc):
        return locale.atof(string)


class PayPalStatementParser(StatementParser):
    bank_id = 'PayPal'
    date_format = '%Y/%m/%d'
    valid_header = [
        u"Date",
        u"Time",
        u"Time Zone",
        u"Name",
        u"Type",
        u"Status",
        u"Currency",
        u"Gross",
        u"Fee",
        u"Net",
        u"From Email Address",
        u"To Email Address",
        u"Transaction ID",
        u"Counterparty Status",
        u"Address Status",
        u"Item Title",
        u"Item ID",
        u"Shipping and Handling Amount",
        u"Insurance Amount",
        u"Sales Tax",
        u"Option 1 Name",
        u"Option 1 Value",
        u"Option 2 Name",
        u"Option 2 Value",
        u"Auction Site",
        u"Buyer ID",
        u"Item URL",
        u"Closing Date",
        u"Escrow Id",
        u"Invoice Id",
        u"Reference Txn ID",
        u"Invoice Number",
        u"Custom Number",
        u"Receipt ID",
        u"Balance",
        u"Address Line 1",
        u"Address Line 2/District/Neighborhood",
        u"Town/City",
        u"State/Province/Region/County/Territory/Prefecture/Republic",
        u"Zip/Postal Code",
        u"Country",
        u"Contact Phone Number",
        u"",
    ]

    def __init__(self, fin, account_id, currency, encoding=None, locale=None, analyze=False):
        self.account_id = account_id
        self.currency = currency
        self.locale = locale
        self.encoding = encoding
        self.analyze = analyze

        with open(fin, 'r', encoding=self.encoding) as f:
            self.lines = f.readlines()

        self.validate()
        self.statement = Statement(
            bank_id=self.bank_id,
            account_id=self.account_id,
            currency=self.currency
        )

    @property
    def reader(self):
        return csv.reader(self.lines, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)

    @property
    def header(self):
        return [c.strip() for c in head(self.reader)]

    @property
    def rows(self):
        rs = drop(self.reader, 1)
        currency_idx = self.valid_header.index("Currency")
        return [r for r in rs if r[currency_idx] == self.currency]

    def validate(self):
        """
        Validate to ensure csv has the same header we expect.
        """

        expected = self.valid_header
        actual = self.header
        if expected != actual:
            msg = "\n".join([
                "Header template doesn't match:",
                "expected: %s" % expected,
                "actual  : %s" % actual
            ])
            raise ValueError(msg)

    def split_records(self):
        for row in self.rows:
            yield row

    def parse_record(self, row):

        id_idx = self.valid_header.index("Transaction ID")
        date_idx = self.valid_header.index("Date")
        memo_idx = self.valid_header.index("Name")
        refnum_idx = self.valid_header.index("Reference Txn ID")
        amount_idx = self.valid_header.index("Gross")
        payee_idx = self.valid_header.index("To Email Address")
        title_idx = self.valid_header.index("Item Title")

        stmt_line = StatementLine()
        stmt_line.id = row[id_idx]
        stmt_line.date = datetime.strptime(row[date_idx], self.date_format)
        stmt_line.memo = row[memo_idx]

        if self.analyze:
            memo_parts = [
                row[memo_idx]
            ]

            payee = row[payee_idx]
            if payee and (payee.lower() == 'steamgameseu@steampowered.com'):
                memo_parts.append(row[title_idx])

            stmt_line.memo = ' / '.join(filter(bool, memo_parts))

        stmt_line.refnum = row[refnum_idx]
        stmt_line.amount = atof(row[amount_idx].replace(" ", ""), self.locale)

        return stmt_line


def parse_bool(value):
    if value in ('True', 'true', '1'):
        return True
    if value in ('False', 'false', '0'):
        return False
    raise ValueError("Can't parse boolean value: %s" % value)


class PayPalPlugin(Plugin):
    def get_parser(self, fin):
        kwargs = {
            'encoding': 'iso8859-1',
        }
        if self.settings:
            if 'account_id' in self.settings:
                kwargs['account_id'] = self.settings.get('account_id')
            if 'currency' in self.settings:
                kwargs['currency'] = self.settings.get('currency')
            if 'locale' in self.settings:
                kwargs['locale'] = self.settings.get('locale')
            if 'encoding' in self.settings:
                kwargs['encoding'] = self.settings.get('encoding')
            if 'analyze' in self.settings:
                kwargs['analyze'] = parse_bool(self.settings.get('analyze'))
        return PayPalStatementParser(fin, **kwargs)