-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
1362 lines (1230 loc) · 48.7 KB
/
db.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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#usr/bin/python2.7
import logging
from datetime import date
from datetime import datetime
from datetime import timedelta
from google.appengine.ext import db
# TODO: Split out Accounts into separate entities by type (Checking, Savings, Credit Card)
class Account(db.Model):
name = db.StringProperty()
a_type = db.StringProperty(
choices = set(['Checking', 'Savings', 'Investment', 'Credit Card']))
unv_balance = db.FloatProperty()
ver_balance = db.FloatProperty()
start_date = db.DateProperty()
last_verified = db.DateProperty()
"""
Account keyname format: "<name>-<type>-account"
"""
# tests implemented
@staticmethod
def CreateKeyname(name, type):
key_name = name + '-'
key_name += type + '-'
key_name += 'account'
return CleanKeyName(key_name)
# tests implemented
@staticmethod
def CreateNewAccount(**kwargs):
# create new account entity
key_name = Account.CreateKeyname(kwargs['name'], kwargs['type'])
a = Account(key_name=key_name)
a.name = kwargs['name']
a.a_type = kwargs['type']
a.unv_balance = float(kwargs['starting'])
a.ver_balance = a.unv_balance
a.start_date = DateFromString(kwargs['start-date'])
a.last_verified = DateFromString(kwargs['last-verified'])
# create new PaycheckAccountBalance entities for every paycheck after account start date
future_paychecks = Paycheck.GetAllPaychecksAfterDate(a.start_date)
for p in future_paychecks:
p_a = PaycheckAccountBalance.CreatePaycheckAccountBalance(a, p, a.ver_balance)
return db.get(a.put())
# stubbed tests implemented
@classmethod
def GetAllAccounts(cls):
return cls.all()
# stubbed tests implemented
@classmethod
def GetAllPaymentAccounts(cls):
return cls.all().filter('a_type IN', ['Checking', 'Credit Card']).order('a_type')
# stubbed tests implemented
@classmethod
def GetAllNonCheckingAccounts(cls):
return cls.all().filter('a_type !=', 'Checking')
# stubbed tests implemented
@classmethod
def GetAllCheckingSavingsAccounts(cls):
return cls.all().filter('a_type IN', ['Checking', 'Savings'])
# stubbed tests implemented
@classmethod
def GetAllCreditCardAccounts(cls):
return cls.all().filter('a_type =', 'Credit Card')
# stubbed tests implemented
@classmethod
def GetActiveAccountsAfterDate(cls, start_date):
date_to_use = DateFromString(start_date)
if date_to_use is None:
return None
else:
return cls.all().filter('start_date >=', date_to_use)
# stubbed tests implemented
@classmethod
def GetTotalUnvBalanceFromAllAccounts(cls):
total = 0
for a in cls.GetAllAccounts():
if a.a_type != 'Credit Card':
total += a.unv_balance
else:
total -= a.unv_balance
return total
# stubbed tests implemented
def GetAllExpensesFromAccount(self):
try:
return self.account_expenses.order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllUnverifiedExpensesFromAccount(self):
try:
return self.account_expenses.filter('verified =', False).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedExpensesFromAccount(self):
try:
return self.account_expenses.filter('verified =', True).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedExpensesFromAccountAfterDate(self, date):
try:
q = self.account_expenses.filter('verified =', True)
return q.filter('date >', DateFromString(date)).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllDepositsFromAccount(self):
try:
return self.account_deposits.order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllUnverifiedDepositsFromAccount(self):
try:
return self.account_deposits.filter('verified =', False).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedDepositsFromAccount(self):
try:
return self.account_deposits.filter('verified =', True).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedDepositsFromAccountAfterDate(self, date):
try:
q = self.account_deposits.filter('verified =', True)
return q.filter('date >', DateFromString(date)).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllTransfersOriginatingFromAccount(self):
try:
return self.transfers_origin.order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllUnverifiedTransfersOriginatingFromAccount(self):
try:
return self.transfers_origin.filter('verified =', False).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedTransfersOriginatingFromAccount(self):
try:
return self.transfers_origin.filter('verified =', True).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedTransfersOriginatingFromAccountAfterDate(self, date):
try:
q = self.transfers_origin.filter('verified =', True)
return q.filter('date >', DateFromString(date)).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllTransfersReceivedIntoAccount(self):
try:
return self.transfers_receiving.order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllUnverifiedTransfersReceivedIntoAccount(self):
try:
return self.transfers_receiving.filter('verified =', False).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedTransfersReceivedIntoAccount(self):
try:
return self.transfers_receiving.filter('verified =', True).order('-date')
except IndexError:
return None
# stubbed tests implemented
def GetAllVerifiedTransfersReceivingIntoAccountAfterDate(self, date):
try:
q = self.transfers_receiving.filter('verified =', True)
return q.filter('date >', DateFromString(date)).order('-date')
except IndexError:
return None
"""
Takes current verified balance and then subtracts/adds to it from each transaction
on or after the specified date (depending on the type of transaction) so we can
know what the account balance was on that date.
"""
# stubbed tests implemented
def CalculateBalanceAfterDate(self, date):
balance = self.ver_balance
expenses = self.GetAllVerifiedExpensesFromAccountAfterDate(date)
deposits = self.GetAllVerifiedDepositsFromAccountAfterDate(date)
origin_transfers = self.GetAllVerifiedTransfersOriginatingFromAccountAfterDate(date)
receiving_transfers = self.GetAllVerifiedTransfersReceivingIntoAccountAfterDate(date)
for e in expenses:
balance += e.amount
for d in deposits:
balance -= d.amount
for o in origin_transfers:
balance += o.amount
for r in receiving_transfers:
balance -= r.amount
return balance
# stubbed tests implemented
def GetRecentUnvTransactionBalanceList(self, days=60):
start_date = date.today()
end_date = start_date - timedelta(days=days)
current_date = start_date
unv_balance = self.unv_balance
u_expenses = self.GetAllUnverifiedExpensesFromAccount()
u_origin_transfers = self.GetAllUnverifiedTransfersOriginatingFromAccount()
u_receiving_transfers = self.GetAllUnverifiedTransfersReceivedIntoAccount()
u_deposits = self.GetAllUnverifiedDepositsFromAccount()
t_list = []
e_index = 0
t_o_index = 0
t_r_index = 0
d_index = 0
if u_expenses.count() == 0: e_end = True
else: e_end = False
if u_origin_transfers.count() == 0: t_o_end = True
else: t_o_end = False
if u_receiving_transfers.count() == 0: t_r_end = True
else: t_r_end = False
if u_deposits.count() == 0: d_end = True
else: d_end = False
# unverified transactions to t_list in date/type order
while((e_end and t_o_end and t_r_end and d_end) != True):
#logging.info('TEST: ' + str(e_end and t_o_end and t_r_end and d_end))
try:
if e_end != True and u_expenses[e_index].date == current_date:
t_list.append((u_expenses[e_index], unv_balance))
unv_balance += u_expenses[e_index].amount
e_index += 1
#logging.info('e_index: '+ str(e_index) + ', len: ' + str(u_expenses.count()))
if e_index == u_expenses.count():
e_end = True
continue
except IndexError:
pass
try:
if t_o_end != True and u_origin_transfers[t_o_index].date == current_date:
t_list.append((u_origin_transfers[t_o_index], unv_balance))
unv_balance += u_origin_transfers[t_o_index].amount
t_o_index += 1
#logging.info('t_o_index: '+ str(t_o_index) + ', len: ' + str(len(u_origin_transfers)))
if t_o_index == u_origin_transfers.count():
t_o_end = True
continue
except IndexError:
pass
try:
if t_r_end != True and u_receiving_transfers[t_r_index].date == current_date:
t_list.append((u_receiving_transfers[t_r_index], unv_balance))
unv_balance -= u_receiving_transfers[t_r_index].amount
t_r_index += 1
#logging.info('t_r_index: '+ str(t_r_index) + ', len: ' + str(len(u_receiving_transfers)))
if t_r_index == u_receiving_transfers.count():
t_r_end = True
continue
except IndexError:
pass
try:
if d_end != True and u_deposits[d_index].date == current_date:
t_list.append((u_deposits[d_index], unv_balance))
unv_balance -= u_deposits[d_index].amount
d_index += 1
#logging.info('d_index: '+ str(d_index) + ', len: ' + str(u_deposits.count()))
if d_index == u_deposits.count():
d_end = True
continue
except IndexError:
pass
current_date -= timedelta(days=1)
return t_list
# stubbed tests implemented
def GetRecentVerTransactionBalanceList(self, days=60):
start_date = date.today()
end_date = start_date - timedelta(days=days)
current_date = start_date
unv_balance = self.unv_balance
ver_balance = self.ver_balance
v_expenses = self.GetAllVerifiedExpensesFromAccount()
v_origin_transfers = self.GetAllVerifiedTransfersOriginatingFromAccount()
v_receiving_transfers = self.GetAllVerifiedTransfersReceivedIntoAccount()
v_deposits = self.GetAllVerifiedDepositsFromAccount()
t_list = []
e_index = 0
t_o_index = 0
t_r_index = 0
d_index = 0
# add verified transactions to t_list in date/type order
while(current_date >= end_date):
try:
if v_expenses[e_index].date == current_date:
t_list.append((v_expenses[e_index], ver_balance))
ver_balance += v_expenses[e_index].amount
e_index += 1
continue
except IndexError:
pass
try:
if v_origin_transfers[t_o_index].date == current_date:
t_list.append((v_origin_transfers[t_o_index], ver_balance))
ver_balance += v_origin_transfers[t_o_index].amount
t_o_index += 1
continue
except IndexError:
pass
try:
if v_receiving_transfers[t_r_index].date == current_date:
t_list.append((v_receiving_transfers[t_r_index], ver_balance))
ver_balance -= v_receiving_transfers[t_r_index].amount
t_r_index += 1
continue
except IndexError:
pass
try:
if v_deposits[d_index].date == current_date:
t_list.append((v_deposits[d_index], ver_balance))
ver_balance -= v_deposits[d_index].amount
d_index += 1
continue
except IndexError:
pass
current_date -= timedelta(days=1)
return t_list
def GetPastBalances(self):
return self.account_balances.order('-paycheck.date')
def GetAllBalancesAfterDate(self, date):
return self.account_balances.filter('date >=', date).fetch(100)
# stubbed tests implemented
def GetBalanceAdjustment(self, transaction):
if transaction.__class__.__name__ == 'Expense' or (transaction.__class__.__name__ == 'Transfer' and transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
amount = transaction.amount
else:
amount = transaction.amount * -1
else:
if self.a_type == 'Credit Card':
amount = transaction.amount * -1
else:
amount = transaction.amount
return amount
# stubbed tests implemented
def GetBalanceDifference(self, new_transaction, old_amount):
if new_transaction.__class__.__name__ == 'Expense' or (new_transaction.__class__.__name__ == 'Transfer' and new_transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
diff = new_transaction.amount - old_amount
else:
diff = old_amount - new_transaction.amount
else:
if self.a_type == 'Credit Card':
diff = old_amount - new_transaction.amount
else:
diff = new_transaction.amount - old_amount
return diff
"""
Adjusts verified account balance based on passed transaction amount to be
verified (added/subtracted based on account and transaction types)
"""
def AdjustBalanceToVerifyTransaction(self, transaction, put=''):
if transaction.__class__.__name__ == 'Expense' or (transaction.__class__.__name__ == 'Transfer' and transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
self.ver_balance += transaction.amount
else:
self.ver_balance -= transaction.amount
else:
if self.a_type == 'Credit Card':
self.ver_balance -= transaction.amount
else:
self.ver_balance += transaction.amount
if put == '': self.put()
return self
"""
Adjusts account balances based on passed removed transaction amount
(added/subtracted based on account and transaction types)
"""
def AdjustBalanceToRemoveTransaction(self, transaction, put=''):
if transaction.__class__.__name__ == 'Expense' or (transaction.__class__.__name__ == 'Transfer' and transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
self.unv_balance -= transaction.amount
if transaction.verified:
self.ver_balance -= transation.amount
else:
self.unv_balance += transaction.amount
if transaction.verified:
self.ver_balance += transaction.amount
else:
if self.a_type == 'Credit Card':
self.unv_balance += transaction.amount
if transaction.verified:
self.ver_balance += transaction.amount
else:
self.unv_balance -= transaction.amount
if transaction.verified:
self.ver_balance -= transaction.amount
if put == '': self.put()
return self
"""
Adjusts account balances based on passed removed transaction amount
(added/subtracted based on account and transaction types)
"""
def AdjustBalanceToAddTransaction(self, transaction, put=''):
if transaction.__class__.__name__ == 'Expense' or (transaction.__class__.__name__ == 'Transfer' and transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
self.unv_balance += transaction.amount
if transaction.verified:
self.ver_balance += transation.amount
else:
self.unv_balance -= transaction.amount
if transaction.verified:
self.ver_balance -= transaction.amount
else:
if self.a_type == 'Credit Card':
self.unv_balance -= transaction.amount
if transaction.verified:
self.ver_balance -= transaction.amount
else:
self.unv_balance += transaction.amount
if transaction.verified:
self.ver_balance += transaction.amount
if put == '': self.put()
return self
def AdjustBalanceToEditTransactionAmount(self, transaction, edit_amount, put=''):
if transaction.__class__.__name__ == 'Expense' or (transaction.__class__.__name__ == 'Transfer' and transaction.receiving_account.key() != self.key()):
if self.a_type == 'Credit Card':
self.unv_balance += edit_amount
if transaction.verified:
self.ver_balance += edit_amount
else:
self.unv_balance -= edit_amount
if transaction.verified:
self.ver_balance -= edit_amount
else:
if self.a_type == 'Credit Card':
self.unv_balance -= edit_amount
if transaction.verified:
self.ver_balance -= edit_amount
else:
self.unv_balance += edit_amount
if transaction.verified:
self.ver_balance += edit_amount
if put == '': self.put()
return self
class Category(db.Model):
id = db.StringProperty()
name = db.StringProperty()
type = db.StringProperty()
has_subcats = db.BooleanProperty()
subcats = db.ListProperty(db.Key)
is_subcat = db.BooleanProperty()
parent_cat = db.SelfReferenceProperty(collection_name='child_cats')
"""
Category keyname format: "<name>-<parent/child>-cat"
"""
@staticmethod
def CreateKeyname(name, pc):
key_name = name + '-'
key_name += pc + '-'
key_name += 'cat'
return CleanKeyName(key_name)
@staticmethod
def CreateNewCategory(**kwargs):
key_name = Category.CreateKeyname(kwargs['name'], kwargs['p/c'])
cat = Category(key_name=key_name)
cat.name = kwargs['name']
cat.type = kwargs['type']
if kwargs['p/c'] == 'child':
cat.has_subcats = False
cat.is_subcat = True
cat.parent_cat = kwargs['parent'].key()
else:
cat.has_subcats = True
cat.is_subcat = False
return db.get(cat.put())
@classmethod
def GetAllParentCats(cls):
return cls.all().filter('has_subcats = ', True).order('name')
@classmethod
def GetAllChildCats(cls):
return cls.all().filter('has_subcats = ', False).order('name')
@classmethod
def GetChildCatGroupings(cls):
cat_groups = []
parents = cls.GetAllParentCats()
for cat in parents:
child_cat_list = cat.child_cats.order('name').fetch(100)
if len(child_cat_list) != 0:
cat_groups.append(child_cat_list)
return cat_groups
@staticmethod
def GetExpensesFromCatInMonthBeforeDate(key_name, date):
cat = Category.get_by_key_name(key_name)
end_date = date - timedelta(days=30)
if cat.has_subcats is True:
results = cat.expenses_from_parent.filter('date <', date.isoformat())
else:
results = cat.expenses_from_child.filter('date <', date.isoformat())
return results.filter('date >=', end_date.isoformat())
class Paycheck(db.Model):
date = db.DateProperty()
gross = db.FloatProperty()
ret_401k = db.ReferenceProperty(collection_name='401k')
after_deduction_balance = db.FloatProperty()
after_transfer_balance = db.FloatProperty()
final_balance = db.FloatProperty()
current = db.BooleanProperty()
closed = db.BooleanProperty()
dest_account = db.ReferenceProperty(collection_name='dest_accounts')
deposit_entity = db.ReferenceProperty(collection_name='p_deposits')
"""
Paycheck keyname format: yyyy-mm-dd-<ACCOUNTID>-<GROSSAMOUNT>
"""
@staticmethod
def CreateKeyname(date, account, gross):
key_name = date + '-'
key_name += account + '-'
key_name += str(gross)
return CleanKeyName(key_name)
@staticmethod
def CreateNewPaycheck(**kwargs):
try:
key_name = Paycheck.CreateKeyname(kwargs['date'], kwargs['account'], kwargs['gross'])
new_paycheck = Paycheck(key_name=key_name)
new_paycheck.date = DateFromString(kwargs['date'])
new_paycheck.gross = float(kwargs['gross'])
new_paycheck.after_deduction_balance = new_paycheck.gross
new_paycheck.after_transfer_balance = new_paycheck.gross
new_paycheck.final_balance = new_paycheck.gross
account_key = Account.get_by_key_name(kwargs['account']).key()
new_paycheck.dest_account = account_key
if kwargs['current'] in ['True', True]:
new_paycheck.current = True
else:
new_paycheck.current = False
if kwargs['closed'] in ['True', True]:
new_paycheck.closed = True
else:
new_paycheck.closed = False
# put initial entity into DB
paycheck = db.get(new_paycheck.put())
# create deposit entity
deposit_args = {'date': kwargs['date'],
'account_key_name': kwargs['account'],
'account': account_key,
'gross': kwargs['gross'],
'after_deduction_balance': paycheck.after_deduction_balance,
'paycheck': paycheck.key()}
deposit = Deposit.CreateNewPaycheckDeposit(**deposit_args)
# add deposit entity to paycheck
paycheck.deposit_entity = deposit.key()
# edit future PaycheckAccountBalance entities for paycheck account
PaycheckAccountBalance.AdjustAllBalancesFromAccountAfterDateToAddTransaction(paycheck.dest_account, paycheck.date, deposit)
# create PaycheckAccountBalance entities for other active accounts
active_accounts = Account.GetActiveAccountsAfterDate(kwargs['date'])
for a in active_accounts:
if a != paycheck.dest_account:
balance = a.CalculateBalanceAfterDate(kwargs['date'])
p = PaycheckAccountBalance.CreatePaycheckAccountBalance(a, paycheck, balance)
# put updated paycheck entity and return entity
return db.get(paycheck.put())
except KeyError as error:
logging.info('ERROR: ' + str(error))
return False
def AddNewTax(self, **kwargs):
# create new tax entity
kwargs['paycheck_key'] = self.key()
t = Tax.CreateNewTax(**kwargs)
# adjust paycheck balances
self.after_deduction_balance -= t.amount
self.after_transfer_balance -= t.amount
self.final_balance -= t.amount
# adjust deposit entity amount and account balance
self.deposit_entity.EditPaycheckDepositAmount(t.amount * -1)
self.put()
return self
def AddNewDeduction(self, **kwargs):
# create new deduction entity
kwargs['paycheck_key'] = self.key()
d = Deduction.CreateNewDeduction(**kwargs)
# adjust paycheck balances
self.after_deduction_balance -= d.amount
self.after_transfer_balance -= d.amount
self.final_balance -= d.amount
# adjust deposit entity amount and account balance
self.deposit_entity.EditPaycheckDepositAmount(d.amount * -1)
self.put()
return self
def AddNewDeposit(self, **kwargs):
# create new deposit entity
kwargs['paycheck'] = self
kwargs['account'] = self.dest_account
d = Deposit.CreateNewDeposit(**kwargs)
# adjust paycheck balances
self.after_transfer_balance += d.amount
self.final_balance += d.amount
self.put()
return self
def AddNewTransfer(self, **kwargs):
# create new transfer entity
kwargs['paycheck_key'] = self.key()
t = Transfer.CreateNewTransfer(**kwargs)
# adjust paycheck balances
self.after_transfer_balance -= t.amount
self.final_balance -= t.amount
self.put()
return self
def AddNewExpense(self, **kwargs):
# create new expense entity
e = Expense.CreateNewExpense(**kwargs)
# adjust final paycheck balance
self.final_balance -= e.amount
self.put()
return self
def AttachUnassignedExpense(self, expense):
if expense.__class__.__name__ is not 'Expense':
expense = Expense.get_by_key_name(expense)
expense.AttachToPaycheck(self)
self.final_balance -= expense.amount
self.put()
return self
@classmethod
def GetOpenPaychecks(cls):
return cls.all().filter('closed =', False).order('-date')
def GetAllTaxes(self):
return self.paycheck_taxes
def GetTaxTotal(self):
total = 0
taxes = self.paycheck_taxes.fetch(100)
for tax in taxes:
total += tax.amount
return total
def GetFederalIncomeTax(self):
return self.paycheck_taxes.filter('tax_type =', 'Federal').get()
def GetStateIncomeTax(self):
return self.paycheck_taxes.filter('tax_type =', 'State').get()
def GetOtherTaxes(self):
q = self.paycheck_taxes.filter('tax_type !=', 'Federal')
return q.filter('tax_type !=', 'State').fetch(100)
def GetAllDeductions(self):
return self.paycheck_deductions
def GetDeductionsTotal(self):
total = 0
deductions = self.paycheck_deductions
for deduction in deductions:
total += deduction.amount
return total
def GetMedicalDeduction(self):
return self.paycheck_deductions.filter('deduct_type =', 'Medical').get()
def GetDentalDeduction(self):
return self.paycheck_deductions.filter('deduct_type =', 'Dental').get()
def GetLifeDeduction(self):
return self.paycheck_deductions.filter('deduct_type =', 'Life').get()
def GetVisionDeduction(self):
return self.paycheck_deductions.filter('deduct_type =', 'Vision').get()
def GetOtherDeductions(self):
return self.paycheck_deductions.filter('deduct_type =', 'Other').fetch(100)
def GetAllOtherDeposits(self):
return self.paycheck_deposits.filter('is_paycheck_deposit =', False).fetch(100)
def GetOtherDepositsTotal(self):
total = 0
deposits = self.GetAllOtherDeposits()
for deposit in deposits:
total += deposit.amount
return total
def GetAllTransfers(self):
return self.paycheck_transfers
def GetTransfersTotal(self):
total = 0
transfers = self.GetAllTransfers()
for transfer in transfers:
total += transfer.amount
return total
def GetAllDeposits(self):
return self.paycheck_deposits.filter('is_paycheck_deposit !=', True)
def GetDepositsTotal(self):
total = 0
deposits = self.GetDepositsTotal()
for deposit in deposits:
total += deposit.amount
return total
def GetAllExpenses(self):
return self.paycheck_expenses
def GetExpensesTotal(self):
total = 0
for expense in self.GetAllExpenses():
total += expense.amount
return total
def GetAllFoodExpenses(self):
expenses = self.GetAllExpenses()
food_parent_keyname = 'food-+-dining-parent-cat'
food_cat = Category.get_by_key_name(food_parent_keyname)
return expenses.filter('parent_e_category =', food_cat).fetch(100)
def GetFoodExpensesTotal(self):
total = 0
for e in self.GetAllFoodExpenses():
total += e.amount
return total
def GetAllMiscExpenses(self):
non_misc_parent_cats = ['food-+-dining-parent-cat']
non_misc_child_cats = []
q = self.GetAllExpenses()
for cat in non_misc_parent_cats:
c = Category.get_by_key_name(cat)
q = q.filter('parent_e_category !=', c)
for cat in non_misc_child_cats:
c = Category.get_by_key_name(cat)
q = q.filter('child_e_category !=', c)
return q.fetch(100)
def GetMiscExpensesTotal(self):
total = 0
for e in self.GetAllMiscExpenses():
total += e.amount
return total
def GetAllUnverifiedDeposits(self):
return self.paycheck_deposits.filter('verified =', False).fetch(100)
def GetAllUnverifiedExpenses(self):
return self.paycheck_expenses.filter('verified =', False).fetch(100)
def GetAllExpensesForCreditCard(self, cc_account):
return self.paycheck_expenses.filter('account =', cc_account).fetch(100)
def GetAllCreditCardExpenses(self):
cc_accounts = Account.GetAllCreditCardAccounts()
e_list = []
for index, a in enumerate(cc_accounts):
e_list.append([])
expenses = paycheck.GetAllExpensesForCreditCard(a)
for e in expenses:
e_list[index].append(e)
return e_list
def GetAccountBalances(self):
return PaycheckAccountBalance.GetPaycheckAccountBalances(self)
def GetPreviousPaycheck(self): # still needs to be tested
return Paycheck.all().filter('date >', self.date).fetch(1)
@classmethod
def GetAllPaychecksAfterDate(cls, date):
return cls.all().filter('date >=', date).order('date').fetch(100)
def RemoveTransaction(self, key_name):
# retrieve transaction from DB
transaction = Transaction.GetTransaction(key_name)
# edit paycheck balances and deposit entity amount (if transaction is tax or deduction)
if transaction.__class__.__name__ is 'Deposit':
self.final_balance -= transaction.amount
else:
self.final_balance += transaction.amount
if transaction.__class__.__name__ is not 'Expense':
if transaction.__class__.__name__ is 'Deposit':
self.after_transfer_balance -= transaction.amount
else:
self.after_transfer_balance += transaction.amount
if transaction.__class__.__name__ in ['Tax', 'Deduction']:
self.after_deduction_balance += transaction.amount
self.deposit_entity.EditPaycheckDepositAmount(transaction.amount)
# edit account balances (if transaction is not tax or deduction)
if transaction.__class__.__name__ not in ['Tax', 'Deduction']:
self.dest_account.AdjustBalanceToRemoveTransaction(transaction)
if transaction.__class__.__name__ is 'Transfer':
transaction.receiving_account.AdjustBalanceToRemoveTransaction(transaction)
# edit PaycheckAccountBalance entities
PaycheckAccountBalance.AdjustAllBalancesFromAccountAfterDateToRemoveTransaction(self.dest_account,
transaction.date,
transaction)
if transaction.__class__.__name__ is 'Transfer':
PaycheckAccountBalance.AdjustAllBalancesFromAccountAfterDateToRemoveTransaction(transaction.receiving_account,
transaction.date,
transaction)
# delete actual expense entity
db.delete(transaction.key())
self.put()
return self
class CreditCardPayment(db.Model):
date = db.DateProperty()
total = db.FloatProperty()
paycheck = db.ReferenceProperty(Paycheck,
collection_name='paycheck_cc_payments')
credit_card = db.ReferenceProperty(Account,
collection_name='cc_payments')
"""
CreditCardPayment keyname format: yyyy-mm-dd-<ACCOUNT>-<AMOUNT>-payment
"""
@staticmethod
def CreateKeyname(date, account, amount):
key_name = date + '-'
key_name += account + '-'
key_name += amount + '-'
key_name += 'payment'
return CleanKeyName(key_name)
@staticmethod
def CreateNewPayment(**kwargs):
key_name = CreditCardPayment.CreateKeyname(kwargs['date'], kwargs['account'], kwargs['amount'])
payment = CreditCardPayment(key_name=key_name)
payment.total = float(kwargs['amount'])
payment.date = DateFromString(str(kwargs['date']))
payment.paycheck = kwargs['paycheck']
payment.credit_card = kwargs['account']
# create transfer entity for payment
p_description = payment.credit_card.name + ' credit card payment for '
p_description += payment.paycheck.date + ' paycheck'
transfer_args = {'date': payment.paycheck.date.isoformat(),
'amount': payment.amount,
'origin-account': payment.paycheck.dest_account,
'rec-account': payment.credit_card,
'description': p_description,
'paycheck_key': payment.paycheck}
t = Transfer.CreateNewTransfer(**transfer_args)
return db.get(payment.put())
class Transaction(db.Model):
date = db.DateProperty()
name = db.StringProperty()
description = db.TextProperty()
amount = db.FloatProperty()
frequency = db.StringProperty(
choices = set(['Core', 'Regular', 'One-Time']),
default = 'One-Time')
recurring_date = db.DateProperty()
verified = db.BooleanProperty()
payment = db.ReferenceProperty(CreditCardPayment,
collection_name='cc_payment_transactions')
@staticmethod
def GetTransaction(key_name):
# retrieve transaction from DB
if Expense.get_by_key_name(key_name):
transaction = Expense.get_by_key_name(key_name)
elif Deduction.get_by_key_name(key_name):
transaction = Deduction.get_by_key_name(key_name)
elif Deposit.get_by_key_name(key_name):
transaction = Deposit.get_by_key_name(key_name)
elif Tax.get_by_key_name(key_name):
transaction = Tax.get_by_key_name(key_name)
elif Transfer.get_by_key_name(key_name):
transaction = Transfer.get_by_key_name(key_name)
return transaction
@classmethod
def GetAllTransactionsFromAccount(cls, account):
return cls.all().filter('account =', account).order('date').fetch(100)
def GetClassName(self):
return self.__class__.__name__
def GetNewAccountBalanceAfterRemoval(self, amount, account):
if self.GetClassName() == 'Expense' or (self.GetClassName() == 'Transfer' and self.receiving_account.key() != account.key()):
if account.a_type == 'Credit Card':
return_amount = amount - self.amount
else:
return_amount = amount + self.amount
else:
if account.a_type == 'Credit Card':
return_amount = amount + self.amount
else:
return_amount = amount - self.amount
return return_amount
def Verify(self):
if self.verified != True:
if self.__class__.__name__ == 'Transfer':
self.origin_account.AdjustBalanceToVerifyTransaction(self)
self.receiving_account.AdjustBalanceToVerifyTransaction(self)
else:
self.account.AdjustBalanceToVerifyTransaction(self)
self.verified = True
self.put()
return self
class Expense(Transaction):
paid = db.BooleanProperty()
vendor = db.StringProperty()
parent_e_category = db.ReferenceProperty(Category,
collection_name='expenses_from_parent')
child_e_category = db.ReferenceProperty(Category,
collection_name='expenses_from_child')
paycheck = db.ReferenceProperty(Paycheck,
collection_name='paycheck_expenses')
account = db.ReferenceProperty(Account,
collection_name='account_expenses')
"""
Expense keyname formats:
Expense - yyyy-mm-dd-<VENDOR>-<AMOUNT>-expense
"""
@staticmethod
def CreateKeyname(date, vendor, amount):
key_name = date + '-'
key_name += vendor + '-'
key_name += str(amount) + '-'
key_name += 'expense'
return CleanKeyName(key_name)
@staticmethod
def CreateNewExpense(**kwargs):
key_name = Expense.CreateKeyname(kwargs['date'], kwargs['vendor'], kwargs['amount'])
expense = Expense(key_name=key_name)
expense.vendor = kwargs['vendor']
expense.date = DateFromString(str(kwargs['date']))
expense.description = kwargs['description']
expense.name = expense.description
expense.amount = float(kwargs['amount'])
expense.frequency = kwargs['frequency']
expense.paid = False
if kwargs['parent-cat'].__class__.__name__ is 'Category':
expense.parent_e_category = kwargs['parent-cat']
elif kwargs['parent-cat'] is None:
expense.parent_e_category = None