-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.py
More file actions
1536 lines (1245 loc) · 48.2 KB
/
Copy pathApp.py
File metadata and controls
1536 lines (1245 loc) · 48.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
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
"""
Main api request endpoint
"""
import os
import array
import base64
import tempfile
import datetime
import traceback
from copy import deepcopy
from functools import wraps
import flask_limiter.errors
from bson.objectid import ObjectId
from google.oauth2 import id_token
from google.auth.transport import requests
from flask_cors import CORS
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from Models import Person, Group, Item, TransactionItem, Transaction, Receipt
from mongoengine import *
# setup the Flask server
app = Flask(__name__)
limiter = Limiter(app,
key_func=get_remote_address,
default_limits=['20/second'])
debug = os.environ.get('DEBUG', False)
debug = bool(debug)
print(f"# DEBUG: {debug}")
# If on debug allow cross-origin resource sharing
if debug:
CORS(app)
mongo_host = os.environ.get('MONGO_HOST', 'localhost')
mongo_port = os.environ.get('MONGO_PORT', 27017)
mongo_username = os.environ.get('API_USERNAME', None)
mongo_password = os.environ.get('API_PASSWORD', None)
# If Mongo Username is None, print warning
if mongo_username is None:
print("WARNING: MongoDB username is None!!")
# If Mongo Password is None, print warning
if mongo_password is None:
print("WARNING: MongoDB password is None!!")
app.config['MONGODB_SETTINGS'] = {
'host': mongo_host,
'username': mongo_username,
'password': mongo_password,
'authSource': 'smart-ledger',
'db': 'smart-ledger'
}
db = MongoEngine()
db.init_app(app)
def print_info(func):
"""
verify the given token
:return: return a dictionary of the persons info from google
"""
@wraps(func)
def wrap(*args, **kwargs):
"""
wrap the given function
"""
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
ip = request.environ['REMOTE_ADDR']
else:
ip = request.environ['HTTP_X_FORWARDED_FOR']
path = request.path
print(f"{ip} : {path} : {request} @ {datetime.datetime.now()}")
try:
ret = func(*args, **kwargs)
print(f" |--> {ret[0].get_json()['msg']} : {ret[1]}")
return ret
except flask_limiter.errors.RateLimitExceeded as exp:
print(f"{ip} : {path} => Exception: {exp} @ {datetime.datetime.now()}")
traceback.print_exc()
print(f" |--> Rate limit exceeded. : 429")
return jsonify({'msg': 'Rate limit exceeded.'}), 429
except Exception as exp:
print(f"{ip} : {path} => Exception: {exp} @ {datetime.datetime.now()}")
traceback.print_exc()
print(f" |--> An unexpected error occurred. : 500")
return jsonify({'msg': 'An unexpected error occurred.'}), 500
return wrap
###############################################################################################################
###############################################################################################################
###############################################################################################################
# TEST API ENDPOINTS
@app.route("/test_get", methods=['GET'])
@print_info
@limiter.limit("10/second", override_defaults=False)
def test_get():
"""
Just a test route to verify that the API is working.
:return: Smart Ledger API Endpoint: OK
"""
return jsonify({'msg': "Smart Ledger API Endpoint: OK"}), 200
@app.route("/test_post", methods=['POST'])
@print_info
def test_post():
"""
Just a test route to verify that the API is working.
:return: Smart Ledger API Endpoint: OK
"""
request_data = request.get_json(force=True)
try:
n1 = float(request_data.get('n1'))
n2 = float(request_data.get('n2'))
op = request_data.get('op')
except ValueError:
return jsonify({'msg': "Invalid data"}), 400
if op == "add":
return jsonify({'ans': str(n1 + n2), 'msg': 'Calculated Answer'}), 200
elif op == "sub":
return jsonify({'ans': str(n1 - n2), 'msg': 'Calculated Answer'}), 200
elif op == "mul":
return jsonify({'ans': str(n1 * n2), 'msg': 'Calculated Answer'}), 200
elif op == "div":
return jsonify({'ans': str(n1 / n2), 'msg': 'Calculated Answer'}), 200
else:
return jsonify({'msg': "Unsupported operation"}), 501
###############################################################################################################
###############################################################################################################
###############################################################################################################
# WRAPPERS
def get_token(req):
# if behind a proxy
headers = req.headers
# Get the authorization header
bearer = headers.get('Authorization') # Bearer YourTokenHere
# Get the token from the authorization header
token = bearer.split()[1] # YourTokenHere
return token
def verify_token(func):
"""
verify the given token
:return: return a dictionary of the persons info from google
"""
@wraps(func)
def wrap(*args, **kwargs):
"""
wrap the given function
"""
try:
# Get the token from the authorization header
token = get_token(request)
# verify the token
token_info = id_token.verify_oauth2_token(token, requests.Request(), os.environ['CLIENT_ID'])
# verify the subject
sub = token_info['sub']
# get the person
person = Person.objects.get(sub=sub)
# call the wrapped function
return func(person, *args, **kwargs)
except Exception as exp:
# Invalid token
print(f"verify_token() => Exception: {exp} @ {datetime.datetime.now()}")
return jsonify({'msg': 'Token is unauthorized or user does not exist.'}), 404
return wrap
###############################################################################################################
###############################################################################################################
###############################################################################################################
## PERSON API ENDPOINTS
@app.route('/register', methods=['POST'])
@print_info
def register():
"""
used for logging in a user. creates an account if not already exists
:return: status of the registration
"""
token = get_token(request)
# verify the token
token_info = id_token.verify_oauth2_token(
token,
requests.Request(),
os.environ['CLIENT_ID'],
clock_skew_in_seconds=5
)
# get the subject
sub = token_info['sub']
# attempt to get the person
# NOTE - this needs to not be an objects.get call because that will throw error when there is no user
person = Person.objects(sub=sub)
# if there are more than one people returned. thats a problem
if len(person) > 1:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# get the person that is returned
person = person.first()
# if person not in DB create them
if person is None:
# create the person object
person = Person(first_name=token_info['given_name'],
last_name=token_info['family_name'],
email=token_info['email'],
sub=token_info['sub'],
picture=token_info['picture'])
status_code = 201
else:
status_code = 200
# save the person object
person.date.last_login = datetime.datetime.now(datetime.timezone.utc)
person.save()
# return status message
return jsonify({'msg': 'User successfully retrieved.', 'data': person}), status_code
@app.route('/user/info', methods=['POST'])
@verify_token
@print_info
def user_profile(person):
"""
get a persons profile information.
If the sub param is NOT passed, will return the current users profile info
If the sub param is passed, will return the given sub profile info
:param person: current logged in user
:return: returns json of
"""
request_data = request.get_json(force=True)
# if sub was given to us
if 'sub' in request_data and request_data.get('sub') != person.sub:
person = Person.objects(sub=request_data.get('sub'))
if len(person) == 0:
return jsonify({'msg': 'Token is unauthorized or user does not exist.'}), 404
person = person.first()
# explicitly build the returned json
date = {
'created': person['date']['created']
}
person = {
'sub': person['sub'],
'first_name': person['first_name'],
'last_name': person['last_name'],
'email': person['email'],
'email_verified': person['email_verified'],
'picture': person['picture'],
'date': date,
'pay_with': person['pay_with']
}
# return the users info
return jsonify({'msg': 'User successfully retrieved.', 'data': person}), 200
@app.route('/user/update', methods=['POST'])
@verify_token
@print_info
def update_profile(person):
"""
modify a users profile
:return: returns json of
"""
# get fields
request_data = request.get_json(force=True, silent=True)
profile = request_data['data']
# check for unallowed fields
if set(profile.keys()).difference({'pay_with', 'first_name', 'last_name'}):
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# iterate through given fields
for k, v in profile.items():
if k not in person:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# if key is pay_with must iterate through embedded dictionary
elif k == 'pay_with':
for k2, v2 in v.items():
if k2 == 'preferred' and v2 not in ['paypal', 'venmo', 'cashapp', '']:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
person[k][k2] = v2
# check pay_with method was not skipped over
if person['pay_with']['preferred'] != '' and not person['pay_with'][person['pay_with']['preferred']]:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# set the keyed value
else:
person[k] = v
# save the person
person.date.updated = datetime.datetime.now(datetime.timezone.utc)
person.save()
return jsonify({'msg': 'Successfully updated the user profile.'}), 200
@app.route('/user/delete', methods=['POST'])
@verify_token
@print_info
def delete_profile(person):
"""
delete a users profile
:param person: current logged in user
:return: returns json of
"""
# TODO - we need to figure out a policy to show users past transactions after their account has been deleted
# unlink person from all groups
for g_id in person.groups:
group = Group.objects(id=g_id)
if len(group) == 0:
continue
group = group.first()
if person.sub in group.members:
group.members.remove(person.sub)
# delete the person from the database
person.delete()
return jsonify({'msg': 'Successfully deleted the user profile.'}), 200
###############################################################################################################
###############################################################################################################
###############################################################################################################
## GROUP API ENDPOINTS
###############################################################################################################
## GROUP CREATION/DELETION
@app.route('/group/create', methods=['POST'])
@verify_token
@print_info
def create_group(person):
"""
Create a group add the creator to the group
request must contain:
- token
- data
- name: group name
- desc: [optional]
- invites: [optional] array of emails
:param person: the person making the request
:return: returns json with group id and msg
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
data = request_data.get('data')
if 'name' not in data:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
group_name = data['name']
group_desc = data.get('desc')
invite = data.get('invites')
# create the group
group = Group(name=group_name, desc=group_desc, admin=person.sub)
# add the creating user to the group
group.members.append(person.sub)
# add admin to the balances dict
group.restricted.balances[person.sub] = {}
# add admin to ledger
group.restricted.ledger[person.sub] = 0
# save the group
group.save()
# add the groups id to the persons list of groups
person.groups.append(group.id)
# save the person object
person.date.updated = datetime.datetime.now(datetime.timezone.utc)
person.save()
if invite is not None:
if not isinstance(invite, list):
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
for email in invite:
group.restricted.invite_list.append(email)
# save the invite in the person
p = Person.objects(email=email)
if len(p) == 0:
continue
p = p.first()
if group.id not in p.invites:
p.invites.append(group.id)
p.date.updated = datetime.datetime.now(datetime.timezone.utc)
p.save()
# save the group
group.save()
return jsonify({'msg': 'Group successfully created.', 'data': group}), 200
@app.route('/group/delete', methods=['POST'])
@verify_token
@print_info
def delete_group(person):
"""
Create a group add the creator to the group
request must contain:
- token
- id: group id
:param person: the person making the request
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data['id']
# query the group
group = Group.objects(id=group_id)
if len(group) == 0 or person.sub != group.first().admin:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# Iterate through people and unlink them from the groups
for p_sub in group.members:
# try to get the person from the DB
person = Person.objects(sub=p_sub)
if len(person) == 0:
continue
person = person.first()
# try to remove person from group
person.groups.remove(ObjectId(group_id))
person.date.updated = datetime.datetime.now(datetime.timezone.utc)
person.save()
# iterate through transactions and items to decrement the item counts. waiting on items to be implemented
for t_id in group.restricted.transactions:
# try to get the transaction
transaction = Transaction.objects(id=t_id)
if len(transaction) == 0:
continue
transaction = transaction.first()
_delete_transaction(group, transaction)
return jsonify({'msg': 'Group successfully deleted.'}), 200
@app.route('/group/info', methods=['POST'])
@verify_token
@print_info
def get_group(person):
"""
Return a group the user is in
request must contain:
- token
- id: group id
:param person: the person making the request
:return: returns json with group id and msg
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
if group_id is None:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# get the group
group = Group.objects.get(id=group_id)
# check if user is in group
if person.sub not in group.members:
group.restricted = None
group = group.to_mongo().to_dict()
members = []
for m in group['members']:
try:
p = Person.objects.get(sub=m)
p = {
'sub': p.sub,
'first_name': p.first_name,
'last_name': p.last_name
}
members.append(p)
except:
continue
group['members'] = members
group['_id'] = {'$oid': str(group['_id'])}
# return the group
return jsonify({'msg': 'Group successfully retrieved.', 'data': group}), 200
@app.route('/group/update', methods=['POST'])
@verify_token
@print_info
def update_group(person):
"""
Return a group the user is in
request must contain:
- token
- id: group id
- data: dictionary that holds all fields you want to change
:param person: the person making the request
:return: returns json with group id and msg
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
data = request_data.get('data')
# check for group id
if group_id is None:
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# get the group
group = Group.objects(id=group_id)
if len(group) == 0:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# check if user is in group
if person.sub not in group.members:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
# weed out bad fields
if not set(data.keys()).intersection({'name', 'description', 'restricted'}):
return jsonify({'msg': 'Missing Required Field(s) / Invalid Type(s).'}), 400
# iterate through all items
for k, v in data.items():
# if is join code check if authorized
if k == 'restricted':
for k2, v2 in v.items():
if k2 == 'permissions':
if person.sub != group.admin:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
for k3, v3 in v2.items():
group[k][k2][k3] = v3
else:
group[k] = v
group.restricted.date.update = datetime.datetime.now(datetime.timezone.utc)
# save the group
group.save()
# return the group
return jsonify({'msg': 'Group successfully updated.'}), 200
###############################################################################################################
## GROUP MEMBER ADD/REMOVE
@app.route('/group/join', methods=['POST'])
@verify_token
@print_info
def join_group(person):
"""
Add a member to the group
request must contain:
- token
- id: group id
:param person: the person making the request
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
# query the group
group = Group.objects(id=group_id)
if len(group) == 0:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# check if already a member
if person.sub in group.members:
return jsonify({'msg': 'User is already a member of the group.'}), 409
if person.email in group.restricted.invite_list:
group.restricted.invite_list.remove(person.email)
# add person to group
group.members.append(person.sub)
group.updated = datetime.datetime.now(datetime.timezone.utc)
# add person to the balances dict
group.restricted.balances[person.sub] = {}
for p in group.members:
if p != person.sub:
group.restricted.balances[person.sub][p] = 0
group.restricted.balances[p][person.sub] = 0
# add person to ledger
group.restricted.ledger[person.sub] = 0
# save group
group.save()
# link group to member
person.groups.append(group.id)
# save person
person.date.updated = datetime.datetime.now(datetime.timezone.utc)
person.save()
return jsonify({'msg': 'User joined group.'}), 200
@app.route('/group/invite', methods=['POST'])
@verify_token
@print_info
def invite_group(person):
"""
invite a member to the group
request must contain:
- token
- id: group id
- emails: [list] person to be invited
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
emails = request_data.get('emails')
# query the group
group = Group.objects(id=group_id)
if len(group) == 0:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# if the user is not an admin then cannot invite
if group.restricted.permissions.only_admin_invite and person.sub != group.admin:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
for email in emails:
# check if already invited
if email in group.restricted.invite_list:
return jsonify({'msg': 'User is already a invited.'}), 409
# check if already in the group
for sub in group.members:
p = Person.objects.get(sub=sub)
if p.email == email:
continue
# add person to group invite list
group.restricted.invite_list.append(email)
# if person exists in the db add this to their invites
p = Person.objects(email=email)
if len(p) != 0:
p = p.first()
if group.id not in p.invites:
p.invites.append(group.id)
p.save()
# save group
group.restricted.date.updated = datetime.datetime.now(datetime.timezone.utc)
group.save()
return jsonify({'msg': 'Invitation(s) successfully created.'}), 200
@app.route('/group/remove-member', methods=['POST'])
@verify_token
@print_info
def remove_member(person):
"""
Add a member to the group
request must contain:
- token
- id: group id
- userid: [optional] user to remove from the grou
:param person: the person making the request
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
sub = request_data.get('userid')
# query the group
group = Group.objects(id=group_id)
if len(group) == 0:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# if the user is trying to delete another user in the group
if sub is None:
# if person is trying to delete themselves from the group
sub = person.sub
elif (group.settings.only_admin_remove_user and group.admin != person.sub) or sub == group.admin:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
# check if the given sub is not in group
if sub not in group.members:
return jsonify({'msg': 'User is not a member of the group.'}), 409
# remove the person from the group
group.members.remove(sub)
# save the group
group.updated = datetime.datetime.now(datetime.timezone.utc)
group.save()
# if group is tied to person object
if group_id in person.groups:
# remove group from person
person.groups.remove(group_id)
# save person
person.date.updated = datetime.datetime.now(datetime.timezone.utc)
person.save()
return jsonify({'msg': 'Member successfully removed.'}), 200
@app.route('/group/refresh-id', methods=['POST'])
@verify_token
@print_info
@limiter.limit("1/second", override_defaults=False)
def refresh_id(person):
"""
refreshes the group id
request must contain:
- token
- id: group id
:param person: the person making the request
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
# query the group
group = Group.objects(id=group_id)
if len(group) == 0:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
group = group.first()
# is person admin
if person.sub != group.admin:
return jsonify({'msg': 'Token is unauthorized or group does not exist.'}), 404
old_group = group
group = deepcopy(old_group)
group.id = None
# update times
time = datetime.datetime.now(datetime.timezone.utc)
group.updated = time
group.last_refreshed = time
# save the group
group.save()
# update all people in the group
for p in group.members:
person = Person.objects.get(sub=p)
person.groups.remove(old_group.id)
person.groups.append(group.id)
person.save()
# update all transactions in the group
for t in group.restricted.transactions:
transac = Transaction.objects.get(id=t)
transac.group = group.id
transac.save()
# delete the old group
old_group.delete()
return jsonify({'msg': "Group's unique identifier successfully refreshed.", 'id': str(group.id)}), 200
###############################################################################################################
###############################################################################################################
###############################################################################################################
## TRANSACTIONS
@app.route('/transaction/create', methods=['POST'])
@verify_token
@print_info
def create_transaction(person):
"""
Create a transaction in the group
request must contain:
- id: group id
- title: transaction title required
- desc: optional
- vendor: optional
- date: optional
- who_paid: [dictionary] contains key value pairs of who paid and how much
- items: array containing jsons of items to add to the transaction
- item: can have optional total price
:param person: the person making the request
:return: returns a transaction id used to link items to the transaction
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
group_id = request_data.get('id')
title = request_data.get('title')
desc = request_data.get('desc')
vendor = request_data.get('vendor')
who_paid = request_data.get('who_paid')
date = request_data.get('date')
items = request_data.get('items')
if group_id is None or title is None or items is None:
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
if date is None:
date = datetime.datetime.now(datetime.timezone.utc)
# query the group to make sure it exists
group = Group.objects.get(id=group_id)
# make sure the user belongs to the group
if person.sub not in group.members:
return jsonify({'msg': 'Token is unauthorized.'}), 404
# can't calculate who_paid later on
if items is None and who_paid is None:
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
# create the transaction
transaction = Transaction(title=title,
group=group_id,
desc=desc,
vendor=vendor,
created_by=person.sub,
modified_by=person.sub,
date_purchased=date,
who_paid=who_paid)
# save the transaction
transaction.save()
# init transaction deltas
balance_deltas = {}
for p1 in group.members:
balance_deltas[p1] = {}
for p2 in group.members:
if p1 != p2:
balance_deltas[p1][p2] = 0
transaction.balance_deltas = balance_deltas
transaction.save()
# init the ledger deltas
for p in group.members:
if p in who_paid:
transaction.ledger_deltas[p] = who_paid[p]
else:
transaction.ledger_deltas[p] = 0
transaction.save()
# add all give items
total_used = 0
if items is not None:
for item in items:
person_id = item.get('owed_by')
# get the item data from the request
name = item.get('name')
desc = item.get('desc')
total_price = item.get('total_price')
quantity = item.get('quantity')
unit_price = item.get('unit_price')
if total_price is None and (quantity is None or unit_price is None):
transaction.delete()
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
if (quantity is None and unit_price is None) and total_price is None:
transaction.delete()
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
if name is None:
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
if total_price is not None and (quantity is None or unit_price is None):
quantity = 1
unit_price = total_price
# keep track of the total_used
total_used += (quantity * unit_price)
# add the item to the transaction
_add_item_to_transaction(person, transaction, quantity, person_id, name, desc, unit_price)
transaction.reload()
# update the who paid
total_paid = 0
if who_paid is None:
total_paid = total_used
transaction.who_paid[person.sub] = total_used
else:
for k, v in who_paid.items():
total_paid += v
transaction.who_paid[person.sub] = v
if total_paid != total_used:
_delete_transaction(group, transaction)
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
# update group with the ledger deltas
for k, v in transaction.ledger_deltas.items():
group.restricted.ledger[k] += v
# update group with the balance deltas
for p1, d in transaction.balance_deltas.items():
for p2, v in d.items():
group.restricted.balances[p1][p2] += v
# save the transaction
transaction.save()
# append the transaction to the group
group.restricted.transactions.append(transaction.id)
# save the group
group.save()
return jsonify({'id': str(transaction.id), 'msg': 'Transaction Created Successfully.'}), 200
@app.route('/transaction/update', methods=['POST'])
@verify_token
@print_info
def update_transaction(person):
"""
Create a transaction in the group
request must contain:
- token
- id: transaction id
- data: json containing fields to update
:param person: the person making the request
:return: returns a transaction id used to link items to the transaction
"""
# get the request data
request_data = request.get_json(force=True, silent=True)
transaction_id = request_data.get('id')
transaction_data = request_data.get('data')
if transaction_id is None or transaction_data is None:
return jsonify({'msg': 'Missing required field(s) or invalid type(s).'}), 400
# query the transaction
transaction = Transaction.objects.get(id=transaction_id)
# perform a deep copy of the old transaction
transaction_new = deepcopy(transaction)
transaction_new.id = None
# query the group to make sure it exists
group_id = transaction.group
group = Group.objects.get(id=group_id)
# make sure the user belongs to the group
if person.sub not in group.members: