-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpense-tracker.py
More file actions
455 lines (408 loc) · 17.2 KB
/
Copy pathexpense-tracker.py
File metadata and controls
455 lines (408 loc) · 17.2 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
"""
The view function only uses one search parameter at a time and is unable to use more than one filter. This is something I'll work on later by redesigning how the viewby function works. I would like to think that the solve for this would be to use a results list, similar to how I have within it for exporting results to a file. I could then get it to add or remove items from that list if they don't match the users filters. I.e. populate the temporary list variable with all the expenses in there as each list item. Then take many parameters from the user i.e. date and description and for each item that doesn't match those queries remove them from that list and then use the export function to save to file.
"""
import os
import sys
from datetime import datetime
import csv
import time
import argparse
# Global Variables:
FILE = "expenses.csv"
def on_load():
clear_screen()
# AI did help me make this as this was my first use of argparse. While it didn't give me the code for it, I used AI to tell me what sort of functions this module uses and how to use it correctly within my script. After spending some time on an external file and knowing how it works. I made some edits to it and then imported it on. This is a really useful feature for commmand line utilities or tools that you can build on Python
parser = argparse.ArgumentParser(
prog="expense-tracker.py",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=f"Welcome to the Python Expense Tracker CLI. This program was made as part of one of the projects in Roadmap.sh to learn the Python programming language.",
epilog="Use -h for help. GitHub: Sheikh-H",
)
subparsers = parser.add_subparsers(required=True, dest="InitialCommand")
add_parser = subparsers.add_parser(
name="add",
help="Add a new expense - 4 positional arguments [--description, --amount, --date, --category]",
)
add_parser.add_argument("--description", required=True, type=str)
add_parser.add_argument("--amount", required=True, type=float)
add_parser.add_argument("--category", required=True, type=str)
add_parser.add_argument("--date", required=True, type=str)
update_parser = subparsers.add_parser(
name="update",
help="Update an existing expense - 4 optional arguments [--id OR --description] followed by one or more of these: [--newdescription, --amount, --date, --category]",
)
update_parser.add_argument("--id", type=int)
update_parser.add_argument("--description", type=str)
update_parser.add_argument("--newdescription", type=str)
update_parser.add_argument("--amount", type=float)
update_parser.add_argument("--category", type=str)
update_parser.add_argument("--date", type=str)
delete_parser = subparsers.add_parser(
name="delete",
help="Delete an expense - 1 of 2 optional arguments [--id, --description]",
)
delete_parser_group = delete_parser.add_mutually_exclusive_group(required=True)
delete_parser_group.add_argument("--description", type=str)
delete_parser_group.add_argument("--id", type=int)
view_parser = subparsers.add_parser(
name="view",
help="View expenses - 9 optional arguments [--id, --description, --category, --amount, --date, --day, --month, --year]",
)
view_parser.add_argument("--description", required=False, type=str)
view_parser.add_argument("--amount", required=False, type=float)
view_parser.add_argument("--category", required=False, type=str)
view_parser.add_argument("--date", required=False, type=str)
view_parser.add_argument("--id", required=False, type=int)
view_parser.add_argument("--month", required=False, type=str)
view_parser.add_argument("--year", required=False, type=str)
view_parser.add_argument("--day", required=False, type=str)
return parser, parser.parse_args()
def error_messages(*messages):
clear_screen()
for message in messages:
print(message)
time.sleep(0.5)
time.sleep(3)
clear_screen()
exit()
def load_file(file=FILE):
fieldnames = ["ID", "Date", "Description", "Amount", "Category"]
if not os.path.exists(file):
with open(file, "w") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, dialect="excel")
writer.writeheader()
with open(file, "r") as f:
data = csv.DictReader(f, dialect="excel")
return list(data)
def save_data(DATA, file=FILE):
fieldnames = ["ID", "Date", "Description", "Amount", "Category"]
with open(file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for field in DATA:
writer.writerow(field)
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def add_expense(description, amount, category, date):
DATA = load_file()
new_id = max(int(row["ID"]) for row in DATA) + 1 if DATA else 1
try:
formatted_date = datetime.strptime(date, "%d-%m-%Y").date()
except:
error_messages("Please re-enter the date in the following format 'dd-mm-yyy'")
new_expense = {
"ID": new_id,
"Description": description,
"Amount": amount,
"Category": category.upper(),
"Date": formatted_date,
}
DATA.append(new_expense)
save_data(DATA, FILE)
error_messages(
f"Added '{description}' under '{category}' for the amount of £{amount:.2f} at {formatted_date}!"
)
def delete_expense(expense_id, description):
DATA = load_file()
expense = []
if expense_id != None:
for i, row in enumerate(DATA):
if int(row["ID"]) == expense_id:
expense.append(row.copy())
del DATA[i]
break
if description != None:
counter = 0
for i, row in enumerate(DATA):
if str(row["Description"]).lower() == str(description).lower():
counter += 1
if counter == 1:
for i, row in enumerate(DATA):
if str(row["Description"]).lower() == description.lower():
expense.append(row.copy())
del DATA[i]
break
else:
print(
"You have more than one expense with the same description, please use ID field instead!"
)
print("Here is a list of all expenses with the same description:")
for i, row in enumerate(DATA):
if str(row["Description"]).lower() == description.lower():
print("-" * 50)
print(f"ID: {row['ID']}\t\t\t\tDate: {row['Date']}")
print(f"Description: {row['Description']}")
print(f"Category: {row['Category']}")
print(f"Amount: £{row['Amount']}")
save_data(DATA, FILE)
if expense:
print(f"Expense '{expense[0]['Description']}' Deleted!")
else:
error_messages("Unable to delete this, try again")
def update_expense(
expense_id, description, new_description, new_amount, new_date, new_category
):
expense_list = []
DATA = load_file()
if expense_id is not None and description is not None:
error_messages(
"Please use either expense id or expense description to search, refer to manual [-h]"
)
if expense_id is not None:
for i, row in enumerate(DATA):
if int(row["ID"]) == expense_id:
expense_list.append(row.copy())
if new_description != None:
print(row["Description"])
row["Description"] = new_description
if new_amount != None:
row["Amount"] = new_amount
if new_date != None:
formatted_date = datetime.strptime(new_date, "%d/%m/%Y").date()
row["Date"] = formatted_date
if new_category != None:
row["Category"] = new_category
break
if description is not None:
count = 0
for row in DATA:
if row["Description"].lower().strip() == description.lower().strip():
count += 1
if count > 1:
print(
f"You have {count} expenses with the same description, please use expense id"
)
print("Here is a list of all the expenses with the same description:")
for row in DATA:
if row["Description"].lower().strip() == description.lower().strip():
print("-" * 50)
print(f"ID: {row['ID']}\t\t\t\tDate: {row['Date']}")
print(f"Description: {row['Description']}")
print(f"Category: {row['Category']}")
print(f"Amount: £{row['Amount']}")
if count == 1:
for i, row in enumerate(DATA):
if row["Description"].lower().strip() == description.lower().strip():
expense_list.append(row.copy())
if new_description != None:
row["Description"] = new_description.strip()
if new_amount != None:
row["Amount"] = new_amount
if new_category != None:
row["Category"] = new_category.strip()
if new_date != None:
formatted_date = datetime.strptime(new_date, "%d/%m/%Y").date()
row["Date"] = formatted_date
break
save_data(DATA, FILE)
if expense_list:
error_messages(f"Expense '{expense_list[0]['Description']}' has been updated!")
else:
error_messages("Unable to update this expense, please try again!")
def view_all():
DATA = load_file()
clear_screen()
print("Here is a list of all your expenses: ")
time.sleep(2)
for row in DATA:
print("-" * 50)
print(f"ID: {row['ID']}\t\t\t\tDate: {row['Date']}")
print(f"Description: {row['Description']}")
print(f"Category: {row['Category']}")
print(f"Amount: £{row['Amount']}")
def export_to_csv(expenses):
# This function needs fixing, the parameters passed into it should be what is used from the view function. After someone views their expenses using a certain filter, they should be presented with the option to save to file for that result.
option = (
input("Would you like to export this result to a csv file? ").lower().strip()
)
if option == "yes":
fieldnames = ["ID", "Date", "Description", "Amount", "Category"]
with open("filtered_expense.csv", "w") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for key, value in enumerate(
expenses
): # When taking my code through AI it suggested that I shouldn't enumerate and separate key, value pairs and store like this. But my original version did have that method and it didn't work which is why i opted to use this method and it worked fine. This is my code nevertheless and would like to keep it so anyone else can view and criticise and help me improve.
writer.writerow(value)
else:
exit()
def view_by(
expense_id=None,
description=None,
category=None,
month=None,
year=None,
day=None,
date=None,
):
DATA = load_file()
results = []
if expense_id is not None:
print("Here is the expenses with that ID:")
time.sleep(2)
for row in DATA:
if int(row["ID"]) == expense_id:
results.append(row)
print(row)
export_to_csv(results)
if description is not None:
print("Here is the expenses with that description:")
time.sleep(2)
for row in DATA:
if row["Description"].lower() == description.lower():
results.append(row)
print(row)
export_to_csv(results)
if category is not None:
print(f"Here are the expenses in '{category}':")
time.sleep(2)
for row in DATA:
if row["Category"].lower() == category.lower().strip():
results.append(row)
print(row)
export_to_csv(results)
if date is not None:
print(f"Here are the expenses made on '{date}'")
formatted_date = datetime.strptime(date, "%d-%m-%Y").date()
time.sleep(2)
for row in DATA:
if datetime.strptime(row["Date"], "%Y-%m-%d").date() == formatted_date:
print(row)
results.append(row)
export_to_csv(results)
if year is not None:
print(f"Here are all the expenses made in year '{year}'")
formatted_year = datetime.strptime(year, "%Y").year
time.sleep(2)
for row in DATA:
if datetime.strptime(row["Date"], "%Y-%m-%d").year == formatted_year:
print(row)
results.append(row)
export_to_csv(results)
if day is not None:
str_day = ""
if day == "1":
str_day = "st"
elif day == "2":
str_day = "nd"
elif day == "3":
str_day = "rd"
else:
str_day = "nth"
print(f"Here are all the expenses made on the '{day}{str_day}'")
formatted_day = datetime.strptime(day, "%d").day
time.sleep(2)
for row in DATA:
if datetime.strptime(row["Date"], "%Y-%m-%d").day == formatted_day:
print(row)
results.append(row)
export_to_csv(results)
if month is not None:
if month.isdigit():
formatted_month = datetime.strptime(month, "%m").month
month_name = datetime.strptime(month, "%m").strftime("%B")
print(f"Here are all the expenses made in '{month_name}':")
time.sleep(2)
for row in DATA:
if datetime.strptime(row["Date"], "%Y-%m-%d").month == formatted_month:
print(row)
results.append(row)
export_to_csv(results)
else:
if len(month) > 3:
formatted_month = datetime.strptime(month, "%B").month
print(f"Here are all the expenses made in '{month.title()}':")
time.sleep(2)
for row in DATA:
if (
datetime.strptime(row["Date"], "%Y-%m-%d").month
== formatted_month
):
print(row)
results.append(row)
export_to_csv(results)
elif len(month) == 3:
formatted_month = datetime.strptime(month, "%b").month
month_name = datetime.strptime(month, "%b").strftime("%B")
print(f"Here are all the expenses made in '{month_name}':")
time.sleep(2)
for row in DATA:
if (
datetime.strptime(row["Date"], "%Y-%m-%d").month
== formatted_month
):
print(row)
results.append(row)
export_to_csv(results)
def main():
parser, args = on_load()
if args.InitialCommand == "add":
if not [args.description, args.amount, args.category, args.date]:
print(
parser.error(
"Please enter all the fields needed to generate a new expense!"
)
)
else:
add_expense(args.description, args.amount, args.category, args.date)
elif args.InitialCommand == "delete":
if not any([args.id, args.description]):
print(
parser.error(
"Please enter the ID or description of the expense you would like to delete!"
)
)
else:
delete_expense(args.id, args.description)
elif args.InitialCommand == "update":
if not any(
[
args.amount,
args.category,
args.date,
args.newdescription,
]
):
print(
parser.error(
"Please enter the fields that you would like to update for this expense!"
)
)
else:
update_expense(
args.id,
args.description,
args.newdescription,
args.amount,
args.date,
args.category,
)
elif args.InitialCommand == "view":
if not any(
[
args.id,
args.description,
args.category,
args.date,
args.day,
args.month,
args.year,
]
):
view_all()
elif args.id:
view_by(args.id)
elif args.description:
view_by(description=args.description)
elif args.category:
view_by(category=args.category)
elif args.date:
view_by(date=args.date)
elif args.month:
view_by(month=args.month)
elif args.day:
view_by(day=args.day)
elif args.year:
view_by(year=args.year)
if __name__ == "__main__":
main()