Welcome, guest | Sign In | My Account | Store | Cart

This little program is used to be record all your daily expenses. It stores all data in SQLite.

Python, 603 lines
  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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#*******************************************************************************
#   Program Name : cash.py (Personal Finance Assistance)
#   Version      : 1.8
#   Desciption   : This program is menu-based program which can connect to database
#                  and then performming addition, updating, deletion and showing
#                  the summary. It use to record personal daily expenses.
#   Working in   : Null
#   Future       : Add "search" function,
#                  Add some "Analysis Tools"                  
#   Ext. Module  : sqlite (DB-API for SQLite)
#   Database     : SQLite (downloadable from www.sqlite.org)
#   Written By   : Chan Wai Keong (waikeong.chan@gmail.com)
#   Status       : Tested
#   Date         : 2005-07-20 (first version)
#*******************************************************************************

#imported library files
import sqlite
import re
import os
import time
import sys

#global variables
sqlite_path = "C:\\sqlite-3_0_8\\"
database = "cash.db"


# format = DD-MM-YYYY
date_format = r'^([0-3][\d])([-])([0-1][\d])([-])([\d]{4})$'
    

def main_menu():
    '''Display main menu (L0)'''
    os.system("cls")
    print "Personal Finance Assistance (PFA)"
    print "================================="
    print "1. ADD Record"
    print "2. MODIFY Record"
    print "3. DELETE Record"
    print "4. SHOW SUMMARY"
    print "5. Exit"
    resp = raw_input("Please enter your choice (1-5): ")
    resp_process(resp)
    

def resp_process(r):
    '''Process the response from user input (L1)'''
    if str(r).isdigit() == 1 and int(r) >= 0 and int(r) <= 5:
        if r == '1':
            add_rec()
        elif r == '2':
            edit_rec()
        elif r == '3':
            del_rec()
        elif r == '4':
            show_all()
#        elif r == '5':
#            show_summ()
        else:
            exit()
    else:
        print "You have enter an invalid input\n"
        time.sleep(2)
        # return to main menu
        main_menu()        

    
def add_rec():
    '''Add data to db from user input (L1)'''
    # get current date
    currDate = time.strftime("%d-%m-%Y", time.localtime(time.time()))
    cont = 1

    os.system("cls")

    #print function header
    print "ADD Record"
    print "=========="
    print "(Key in '-e' to back to main menu)"
    
    while cont == 1:
        print "\nKey in new record .. "
        # get input for date
        date = raw_input("Date : ")
        back_main_menu(date)

        if date == "":
            date = currDate
        else:
            while date_check(date) == 0:
                print "Error! It's not a date.\n"
                date = raw_input("Date : ")
                back_main_menu(date)
                if date == "":
                    date = currDate
                
        # get input for description
        desc = raw_input("For : ")
        back_main_menu(desc)

        # get input for amount
        amt = raw_input("Total : RM ")
        back_main_menu(amt)

        while amt_check(amt) == 0:
            print "Error! It's not a money.\n"
            amt = raw_input("Total : RM")
            back_main_menu(amt)
        amt = "%.2f" % float(amt)

        # insert to sqlite
        add_func(date, desc, amt)

        resp = raw_input("Continue ? ")
        resp = resp.upper()
        if resp == 'N':
            cont = 0
    # return to main menu
    main_menu()
    
        
def edit_rec():
    ''' Edit / Modify record in db(L1)'''
    os.system("cls")
    
    #print function header
    print "MODIFY Record"
    print "============="
    print "(Key in '-e' to back to main menu)"
    
    s_date = raw_input("Enter the DATE of record you want to modify: ")
    back_main_menu(s_date)

    col = "date"
    result = search_func(col, s_date)
    
    # print search result    
    if len(result) > 0:
        for i in range (len(result)):
            dt = result[i][0]
            ds = result[i][1]
            at = result[i][2]
            at = "%.2f" % float(at)
            print i+1, ")",  ("%s%s%s%s%s%s%s%s%s") % ((" " * (2 - (i + len(")")))), "Date: ", dt, (" " * (20 - len(dt))), "Desc: ", ds, (" " * (25 - len(ds))), "Amount: RM", at)

        row = raw_input("Enter the number of row you want to modify: ")
        back_main_menu(row)
        
        if row.isdigit() == 1:
            row = int(row)
            if row >= 0 and row <= i+1:
                rowNo = int(row) - 1
                last_date = result[rowNo][0]
                last_desc = result[rowNo][1]
                last_amt = result[rowNo][2]
                
                print "Key in the new version of record"
                print "(Press <enter> if no update on that field)"
                e_date = raw_input("NEW date: ")
                back_main_menu(e_date)

                if e_date == "":
                    e_date = last_date
                    
                e_desc = raw_input("NEW description: ")
                back_main_menu(e_desc)

                if e_desc == "":
                    e_desc = last_desc

                e_amt = raw_input("NEW amount: RM ")
                back_main_menu(e_amt)

                if e_amt == "":
                    e_amt = last_amt

                edit_func(e_date, e_desc, e_amt, last_date, last_desc, last_amt)
            
    else:
        print "Sorry, NO data match with '", s_date, "'"
    # return to main menu
    main_menu()
        

def del_rec():
    '''Delete record from db(L1)'''
    os.system("cls")
    
    #print function header
    print "DELETE Record"
    print "============="
    print "(Key in '-e' to back to main menu)"
    
    s_date = raw_input("Enter the DATE of record you want to delete: ")
    back_main_menu(s_date)

    col = "date"
    result = search_func(col, s_date)
    
    # print search result    
    if len(result) > 0:
        for i in range (len(result)):
            dt = result[i][0]
            ds = result[i][1]
            at = result[i][2]
            print i+1, ")",  ("%s%s%s%s%s%s%s%s%s") % ((" " * (2 - (i + len(")")))), "Date: ", dt, (" " * (20 - len(dt))), "Desc: ", ds, (" " * (25 - len(ds))), "Amount: RM", at)
    
        row = raw_input("Enter the number of row you want to delete: ")
        back_main_menu(row)

        if row.isdigit() == 1:
            row = int(row)
            if row >= 0 and row <= i+1:
                rowNo = int(row) - 1
                d_date = result[rowNo][0]
                d_desc = result[rowNo][1]
                d_amt = result[rowNo][2]
                print "You been choosen "
                print row, ")", "Date: ", d_date, "\tDesc: ", d_desc, "\t\tAmount: ", d_amt
                resp = raw_input("Are you sure want to delete? (Y/N): ")
                resp = resp.upper()
                back_main_menu(resp)

                if resp == 'Y':
                     delete_func(d_date, d_desc, d_amt)
    else:
        print "Sorry, NO data match with '", s_date, "'"
    # return to main menu
    main_menu()


def show_all():
    '''Get details of attribute for the records(L1)'''

    currDate = time.strftime("%d-%m-%Y", time.localtime(time.time()))
    nowDate = str(currDate).split("-")
    month = nowDate[1]
    year = nowDate[2][2:]
    
    os.system("cls")

    print "SHOW ALL Record"
    print "==============="
    print "Enter details of the record you want"
    print "Press <enter> for current year or month"
    print "(Key in '-e' to back to main menu)"
    
    yr = raw_input("Year (YY) : ")

    if yr == "":
        yr = year

   
    mth = raw_input("Month (MM) : ")
    back_main_menu(mth)
    
    if mth == "":
        mth = month
        fg = 1
    else:
        if 1 < int(mth) <= 12:
            fg = 1
        else:
            fg = 0

    if fg == 1:
        show_all_sql(yr, mth)
    else:
        print "Unvalid date"
        time.sleep(2)
        # return to main menu
        main_menu()
    

def show_summ():
    # unused function #
    '''Get details of attribute for the records(L1)'''

    currDate = time.strftime("%d-%m-%Y", time.localtime(time.time()))
    nowDate = str(currDate).split("-")
    month = nowDate[1]
    year = nowDate[2][2:]
 
    os.system("cls")

    print "SHOW SUMMARY Record"
    print "==================="
    print "Enter details of the record you want"
    print "Press <enter> for current year or month"
    print "(Key in '-e' to back to main menu)"
    
    #yr = raw_input("Year (YYYY) : ")
    #if yr == "":
    yr = year

    mth = raw_input("Month (MM) : ")
    back_main_menu(mth)
    
    if mth == "":
        mth = month
        fg = 1
    else:
        if 1 < int(mth) <= 12:
            fg = 1
        else:
            fg = 0
        
    if fg == 1:
        show_summ_sql(yr, mth)
    else:
        print "Unvalid date"
        time.sleep(2)
        # return to main menu
        main_menu()


def exit():
    '''Exit from the program(L1)'''
    os.system("cls")
    print "Thank you for using PFA v1.8"
    print "Closing Connections & Programs... "
    time.sleep(1)
    print "Good Bye\n"
    print "another waikeong-made program"
    print "All Rights Reserved (C)"
    time.sleep(2)
    sys.exit()


def add_func(dt, ds, at):
    '''Insert data into db(L2)'''
    sql_insert = """
    INSERT INTO expenses (date, desc, amount)
    VALUES ('%s', '%s', '%s')
    """ % (dt, ds, at)

    os.chdir(sqlite_path)

    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " +str(errmsg)

    # insert data into table
    try:
        cu = cx.cursor()
        cu.execute(sql_insert)
        cx.commit()
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()
    

def search_func(field, key):
    '''Search Function (L2)'''
    data = []
    
    os.chdir(sqlite_path)

    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " +str(errmsg)

    # select data from table
    try:
        cu = cx.cursor()
        cu.execute(""" SELECT * FROM expenses""" +
                   ' WHERE ("' +str(field)+ '") like ("' '%'+str(key)+'%' '")' )
        data = cu.fetchall()
        cx.commit()
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()
    return data


def edit_func(new_date, new_desc, new_amt, old_date, old_desc, old_amt):
    '''Edit / Update function (L2)'''
    os.chdir(sqlite_path)
    
    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " +str(errmsg)

    # select data from table
    try:
        cu = cx.cursor()
        cu.execute(""" UPDATE expenses """ +
                   ' SET date = ("' +str(new_date)+ '"), desc = ("' +str(new_desc)+ '"), amount = ("' +str(new_amt)+ '") WHERE date = ("' +str(old_date)+ '") AND desc = ("' +str(old_desc)+ '") AND amount = ("' +str(old_amt)+ '") ')
        cx.commit()
        print "Update Complete."
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()


def delete_func(del_date, del_desc, del_amt):
    '''Delete Function (L2)'''
    os.chdir(sqlite_path)
    
    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " +str(errmsg)

    # select data from table
    try:
        cu = cx.cursor()
        cu.execute(""" DELETE FROM expenses """ +
                   ' WHERE date = ("' +str(del_date)+ '") AND desc = ("' +str(del_desc)+ '") AND amount = ("' +str(del_amt)+ '") ')
        cx.commit()
        print "The record of "
        print del_date, del_desc, del_amt, " been Deleted."
        main_menu()
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()
   

def show_all_sql(y, m):
    '''Display the all of records(L2)'''

    j = -1
    
    os.chdir(sqlite_path)
    os.system("cls")
    
    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " + str(errmsg)

    # select data from table
    try:
        cu = cx.cursor()

        cu.execute("""SELECT * from expenses""" +
                  ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") ORDER BY date')
        summ = cu.fetchall()

        cu.execute("""SELECT date, sum(amount) from expenses """ +
                   ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") GROUP BY date ')
        dailySum = cu.fetchall()

        cu.execute("""SELECT SUM(amount) from expenses""" +
                   ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '")' )
        total = cu.fetchone()

        cx.commit()
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()
 
    if len(summ) > 0:
        # print function header
        print "\nFull Records for", m, "/", y
        print "==========================="

        # print the report
        print "Date", ('%s%s%s%s') % ((" " * (20 - len("Date"))), "Desc", (" " * (28 - len("Desc"))), "Total(RM)")
        print "====", ('%s%s%s%s') % ((" " * (20 - len("===="))), "====", (" " * (28 - len("===="))), "=========")

        for i in range(0, len(summ)):
            date = summ[i][0]
            desc = summ[i][1]
            amt = "%6.2f" % float(summ[i][2])
                    
            if date != summ[i-1][0]:
                # print daily subtotal
                if j > -1:
                    dailyTot = "%6.2f" % float(dailySum[j][1])
                    print ('%s%s') % (" " * 49, "--------")
                    print ('%s%s%s%s') % (" " * 49, "RM", dailyTot, "\n")
                j += 1

            #print daily expenses
            print date, ('%s%s%s%s') %((" " * (20 - len(date))), desc, (" " * (30 - len(desc))), amt)

        # print daily subtotal (for the current day)            
        dailyTot = "%6.2f" % float(dailySum[j][1])
        print ('%s%s') % (" " * 49, "--------")
        print ('%s%s%s%s') % (" " * 49, "RM", dailyTot, "\n")

        #print total of month
        tot = "%6.2f" % float(total[0])
        print "=========================================================="
        print "Grant total until", date, "\t\t\t RM", tot
                   
        wait = raw_input("\nPress <enter> to continue")
        
    else:
        print "No data for Month ", m, "\n"
        wait = raw_input("Press <enter> to continue")
        
    # return to main menu
    main_menu()


def show_summ_sql(y, m):
    # unused function #
    '''Display the summary of records(L2)'''

    os.system("cls")
    os.chdir(sqlite_path)
    
    # open connection to database
    try:
        cx = sqlite.connect(database)
    except sqlit.Error, errmsg:
        print "Can not open " + str(errmsg)

    # insert data into table
    try:
        cu = cx.cursor()

        cu.execute("""SELECT date, sum(amount) from expenses """ +
                   ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") GROUP BY date ')
        summ = cu.fetchall()
        
        cu.execute("""SELECT SUM(amount) from expenses""" +
                   ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '")')
        total = cu.fetchone()

        cx.commit()
    except sqlite.Error, errmsg:
        print "Can not execute: " +str(errmsg)

    # close connection
    cx.close()

    if len(summ) > 0:
        # print function header
        print "\nDaily Based Summary for", m, "/", y
        print "================================="

        # print the report
        for i in range(len(summ)):
            date = summ[i][0]
            amt = "%6.2f" % float(summ[i][1])
            print "Date: ", date, "\t   Total: RM", amt

        tot = "%6.2f" % float(total[0])
        print "==========================================="
        print "Grant total until", date, "     RM", tot

        wait = raw_input("Press <enter> to continue")

    else:
        print "No data for month ", m, ", year", y, "\n"
        wait = raw_input("Press <enter> to continue")
        
    # return to main menu
    main_menu()


def date_check(data):
    '''Data validation for date'''
    if re.match(date_format, data) != None:
        return 1
    return 0


def amt_check(data):
    '''Check the data is in the form of money or not'''
#   format = 123.45
    data = str(data)
    if data.isdigit():
        return 1
    else: 
        try: 
            new = "%.2f" % float(data)
            return 1
        except:
            return 0


def back_main_menu(data):
    '''Check input data for requist back to main menu (L3)'''
    data = data.upper()
    if data == "-E":
        main_menu()
        

if __name__ == '__main__':
    main_menu()
    

I think there are many things can be improve on this program, so i need help and advise from you guys to make this program better.. may be we can do the coding in different way or re-design the program structure... Lets make the world better.. ;-)

1 comment

Jarek Zgoda 17 years, 10 months ago  # | flag

The UI would greatly benefit from using cmd module. Check it out.