|
| 1 | +import csv |
| 2 | +import sys |
| 3 | +import datetime |
| 4 | + |
| 5 | + |
| 6 | +def read_statement(filename): |
| 7 | + source_data = [] |
| 8 | + with open('source.csv', 'rb') as sourcefile: |
| 9 | + reader = csv.DictReader(sourcefile) |
| 10 | + for row in reader: |
| 11 | + source_data.append(row) |
| 12 | + return source_data |
| 13 | + |
| 14 | +def normalize_source(source_data): |
| 15 | + normalized_data = [] |
| 16 | + |
| 17 | + # Remove transactions without reference ID -- we don't want currency conversion transactions |
| 18 | + for row in source_data: |
| 19 | + if row[' Reference Txn ID'] == '': |
| 20 | + normalized_data.append(row) |
| 21 | + |
| 22 | + transactions = {row[' Transaction ID']: row for row in normalized_data} |
| 23 | + |
| 24 | + # Replace USD values with GBP values if transaction currency was converted |
| 25 | + for row in source_data: |
| 26 | + if row[' Currency'] == 'USD' and row[' Reference Txn ID'] != '': |
| 27 | + id = row[' Reference Txn ID'] |
| 28 | + if id in transactions: |
| 29 | + transactions[id][' Fee'] = row[' Fee'] |
| 30 | + transactions[id][' Gross'] = row[' Gross'] |
| 31 | + transactions[id][' Net'] = row[' Net'] |
| 32 | + transactions[id][' Currency'] = row[' Currency'] |
| 33 | + |
| 34 | + return transactions.values() |
| 35 | + |
| 36 | +def write_csv(data): |
| 37 | + fieldnames = ['Description on bank statement', 'Item', 'Category', 'Date', 'Money in USD', 'Money in GBP', 'Money out USD', 'Money out GBP', 'Account', 'Is refunded?'] |
| 38 | + output_filename = 'paypal_{}.csv'.format(datetime.datetime.now().strftime('%Y%m%d')) |
| 39 | + |
| 40 | + with open(output_filename, 'w') as csvfile: |
| 41 | + writer = csv.writer(csvfile) |
| 42 | + writer.writerow(fieldnames) |
| 43 | + |
| 44 | + for row in data: |
| 45 | + name = '{} / {}'.format(row[' Name'], row[' Transaction ID']) |
| 46 | + if row[' Currency'] == 'GBP' and '-' in row[' Net']: |
| 47 | + writer.writerow([name, '', '', row['Date'], '', '', '', row[' Net'].replace('-', ''), 'PayPal', '-']) |
| 48 | + elif row[' Currency'] == 'GBP' and not '-' in row[' Net']: |
| 49 | + writer.writerow([name, '', '', row['Date'], '', row[' Net'], '', '', 'PayPal', '-']) |
| 50 | + elif row[' Currency'] == 'USD' and '-' in row[' Net']: |
| 51 | + writer.writerow([name, '', '', row['Date'], '', row[' Net'].replace('-', ''), '', '', 'PayPal', '-']) |
| 52 | + elif row[' Currency'] == 'USD' and not '-' in row[' Net']: |
| 53 | + writer.writerow([name, '', '', row['Date'], row[' Net'], '', '', '', 'PayPal', '-']) |
| 54 | + print 'Transaction {} on {} processed'.format(name, row['Date']) |
| 55 | + |
| 56 | + print 'CSV saved to {}'.format(output_filename) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + source_data = read_statement(sys.argv[1]) |
| 61 | + normalized_data = normalize_source(source_data) |
| 62 | + write_csv(normalized_data) |
0 commit comments