-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
285 lines (243 loc) · 11.7 KB
/
models.py
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
Ledger Assistant - a GUI front end for entering Ledger-compatible transactions.
Copyright (C) 2023 Robert T. Fowler IV
This program 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.
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
"""
import decimal
import re
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
class Transaction:
def __init__(self,date,description):
"""
date = YYYY-MM-DD
"""
self.date = date
self.description = description
self.memo = ""
self.splits = []
def add_split(self,memo,account,amount):
# Amounts are provided as numbers with two decimal places.
# Stored as integers in which the last two digits represent cents.
split = TransactionSplit(memo, account, amount)
self.splits.append(split)
def balance(self):
bal = decimal.Decimal('0.00')
for split in self.splits:
bal += decimal.Decimal(split.amount)
return str(bal)
def printout(self):
print(self.date, self.description)
for split in self.splits:
print(f" {split.account} {split.amount} {split.memo}")
print(f"Balance: {self.balance()}")
def hledger_format(self):
# return the transaction in hledger format
hledger_text = f"{self.date} {self.description}\n"
for split in self.splits:
amount = str("{:.2f}".format(decimal.Decimal(split.amount)/100))
num_spaces = (60-len(split.account)-len(amount))
spacing = num_spaces * " "
hledger_text += f" {split.account}{spacing}{amount}"
if split.memo != "":
# sanitize memo field
memo = split.memo
memo = memo.replace(","," ")
memo = memo.replace(".","_")
memo = memo.replace(" "," ")
memo = memo.replace(":"," ")
memo = memo.replace("\n"," ")
memo = memo.strip()
hledger_text += f" ; {memo}"
hledger_text +="\n"
hledger_text +="\n"
return hledger_text
class TransactionSplit:
def __init__(self,memo,account,amount):
self.memo = memo
self.account = account
self.amount = amount
class Journal:
def __init__(self,filepath):
self.transactions = []
self.filepath = filepath
def balance(self):
bal = decimal.Decimal("0.00")
for transaction in self.transactions:
bal += decimal.Decimal(transaction.balance())
return str(bal)
def GetJournalAccounts(self):
"""
Return a list of accounts from the journal
"""
with open(self.filepath,"r",encoding="utf-8") as f:
accounts = []
for line in list(f.read().split("\n")):
if line.startswith("account "):
accounts.append(line[8:])
return accounts
def get_hledger_trans(self,ledger_file):
"""
Get transactions from an hledger formatted file.
"""
journal = []
with open(ledger_file,"r",encoding="utf-8") as f:
lines = f.read().split("\n")
for n in range(len(lines)):
if lines[n].startswith("account") or lines[n].startswith("commodity") or lines[n] == "" or lines[n] == "\n":
continue
else:
if re.match("^\d\d\d\d-\d\d-\d\d",lines[n]):
trans_date = re.match("^\d\d\d\d-\d\d-\d\d",lines[n])[0]
trans_description = lines[n][11:]
new_trans = Transaction(trans_date,trans_description)
else:
# split_line includes account, amount and memo.
split_line = lines[n]
split_account = split_line[4:split_line.find(" ",4)]
if ";" in lines[n]:
split_memo = split_line[split_line.find(";")+1:].strip()
split_amount = split_line[len(split_account)+5:split_line.find(";")].strip()
else:
split_memo = ""
split_amount = split_line[len(split_account)+5:].strip()
new_trans.add_split(split_memo,split_account,split_amount)
try:
if re.match("^\d\d\d\d-\d\d-\d\d",lines[n+1]) or lines[n+1] == "\n" or lines[n+1] == "":
journal.append(new_trans)
except IndexError:
continue
except UnboundLocalError:
pass
self.transactions = journal
def hledger_journal_text(self):
"""
return raw hledger formatted text from transactions.
"""
self.transactions.sort(key=lambda x: x.date)
hledger_text = ""
for transaction in self.transactions:
hledger_text += f"{transaction.date} {transaction.description}\n"
for split in transaction.splits:
num_spaces = (60-len(split.account)-len(split.amount))
spacing = num_spaces * " "
hledger_text += f" {split.account}{spacing}{split.amount}"
if split.memo != "":
# sanitize memo field
memo = split.memo
memo = memo.replace(","," ")
memo = memo.replace(".","_")
memo = memo.replace(" "," ")
memo = memo.replace(":"," ")
memo = memo.replace("\n"," ")
memo = memo.strip()
hledger_text += f" ; {memo}"
hledger_text +="\n"
hledger_text +="\n"
return hledger_text
def export_hledger(self,file_path):
"""
Export to hledger format. Accounts file : list of account and
commodity declarations to put at beginning of ledger.
"""
# sort transactions by date
self.transactions.sort(key=lambda x: x.date)
# add account declarations
hledger_text = ""
for account in self.GetJournalAccounts():
hledger_text += "account " + account + "\n"
hledger_text += "commodity 1000.00\n\n"
# convert the transactions to hledger format
hledger_text += self.hledger_journal_text()
with open(file_path,"w",encoding="utf-8") as file:
file.write(hledger_text)
def get_ebay_trans(self,ebay_file):
with open(ebay_file,"r",encoding="utf-8") as file:
ebay_text = file.read()
# deal with files that have double quotes on all fields
ebay_text = ebay_text[ebay_text.find("Transaction creation date")-1:]
if ebay_text.startswith("\n"):
ebay_text = ebay_text[1:]
ebay_dict_text = csv.DictReader(ebay_text.splitlines())
rows = [row for row in ebay_dict_text]
payout_journal = []
payout_trans = None
prev_payout_id = ""
for row in rows:
if row["Type"] == "Payout":
continue
if row["Payout ID"] != prev_payout_id:
if payout_trans != None:
payment_account = "Assets:BrightStar Checking"
payment_amount = abs(payout_trans.balance())
split = TransactionSplit("", payment_account, payment_amount)
payout_trans.splits.insert(0,split)
payout_journal.append(payout_trans)
prev_payout_id = row["Payout ID"]
payout_id = row["Payout ID"]
payout_date = date_fixer(row["Payout date"])
payout_description = "Ebay payout ID " + payout_id
payout_trans = Transaction(payout_date,payout_description)
if row["Type"] == "Shipping label":
split_memo = " ; memo: Shipping label - " + row["Description"]
split_account = "Expenses:Cost of Sales:Shipping Costs"
split_amount = -int(decimal.Decimal(row["Net amount"])*100)
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
if row["Type"] == "Other fee":
split_memo = " ; memo: " + row["Description"]
split_account = "Expenses:Cost of Sales:Ebay Fees"
split_amount = abs(int(decimal.Decimal(row["Net amount"])*100))
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
if row["Type"] == "Order":
# record the sale as a credit (-)
split_memo = " ; memo: " + row["Custom label"] + " " + row["Item title"]
split_account = "Income:Current Income:Sales"
split_amount = -abs(int(decimal.Decimal(row["Item subtotal"])*100))
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
# record buyer paid shipping amount as a credit to shipping costs
split_memo = " ; memo: Buyer paid shipping"
split_account = "Expenses:Cost of Sales:Shipping Costs"
split_amount = -abs(int(decimal.Decimal(row["Shipping and handling"])*100))
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
# record final value fees
split_memo = ""
split_account = "Expenses:Cost of Sales:Ebay Fees"
split_amount = abs(int(decimal.Decimal(row["Final Value Fee - fixed"])*100))
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
split_memo = ""
split_account = "Expenses:Cost of Sales:Ebay Fees"
split_amount = abs(int(decimal.Decimal(row["Final Value Fee - variable"])*100))
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
if row["Type"] == "Hold" or row["Type"] == "Claim" or row["Type"] == "Refund":
# these are too freaking complicated to deal with. Just charge them off
# to sales.
split_memo = f" ; memo: {row['Type']} - " + row["Custom label"] + " " + row["Item title"]
split_account = "Income:Current Income:Sales"
split_amount = row["Net amount"]
if split_amount == "0" or split_amount == "--":
split_amount = 0
else:
split_amount = -int(decimal.Decimal(split_amount)*100)
split = TransactionSplit(split_memo, split_account, split_amount)
payout_trans.splits.append(split)
if rows.index(row) == len(rows) - 1:
payment_account = "Assets:BrightStar Checking"
payment_amount = abs(payout_trans.balance())
split = TransactionSplit("", payment_account, payment_amount)
payout_trans.splits.insert(0,split)
payout_journal.append(payout_trans)
self.transactions = payout_journal