forked from xujinzheng0610/transactServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1364 lines (1188 loc) · 47.2 KB
/
app.py
File metadata and controls
1364 lines (1188 loc) · 47.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
from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
from pymongo import MongoClient
from bson.objectid import ObjectId
import blockchainSetup
import datetime
from blockchainSetup import web3
from pymongo.errors import ConnectionFailure
from bson.json_util import dumps
import os
import hashlib
import pandas as pd
from pathlib import Path
import copy
import io
import base64
from PIL import Image
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Personalization, Email, Content
app = Flask(__name__)
title = "TransACT Server"
CORS(app)
client = MongoClient('localhost', 27017)
db = client['transact']
# Sending email functions
def send_email_donation(recipient, projectName, amount):
html = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen" />
</head>
<body>
"""
html += "<p>Dear donor,</p>"
html += "<p>-------------------------------------------</p>"
html += "<p>Thank you for your kindness in project: " + projectName + ". The charity has received your donation: " + amount + " dollars."
html += " We will keep updating you the project progress and money usage. You can also visit out website for more information!</p>"
html += """
<p>-------------------------------------------</p>
<p>Best regards,<br>TransACT team</p>
<p>http://localhost:3001/ </p>
</body>
</html> """
subject = "TransACT - Thank you for your donation!"
message = Mail(
from_email='no-reply@transact.sg',
to_emails=[recipient],
subject=subject,
html_content=html)
client = SendGridAPIClient("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")
response = client.send(message)
print(response)
def send_email_confirmation(recipients, projectName, amount, description):
html = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen" />
</head>
<body>
"""
html += "<p>Dear donor,</p>"
html += "<p>-------------------------------------------</p>"
html += "<p>The project you donated: " + projectName + " has new money confirmaton.</p"
html += "<p>The charity has claimed: " + amount + " dollars. </p>"
html += "<p>This money is used in: " + description + " .</p>"
html += "<p>We will keep updating you the project progress and money usage. You can also visit out website for more information!</p>"
html += """
<p>-------------------------------------------</p>
<p>Best regards,<br>TransACT team</p>
<p>http://localhost:3001/ </p>
</body>
</html> """
subject = "TransACT - New Project Update!"
message = Mail()
for to_email in recipients:
# Create new instance for each email
personalization = Personalization()
# Add email addresses to personalization instance
personalization.add_to(Email(to_email))
# Add personalization instance to Mail object
message.add_personalization(personalization)
# Add data that is common to all personalizations
message.from_email = Email('no-reply@transact.sg')
message.subject = subject
message.add_content(Content('text/html', html))
client = SendGridAPIClient("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")
response = client.send(message)
print(response)
def send_email_charity_approval(recipient, charityName):
html = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen" />
</head>
<body>
"""
html += "<p>Dear charity,</p>"
html += "<p>-------------------------------------------</p>"
html += "<p>We have approved your charity registration in TransACT: " + charityName + ". Funding in TransACT will bring you brandly new expriences and great impacts."
html += " We hope you can help more people through our platform. Let's create a new funding project! </p>"
html += "<p> If you have any problems, please contact us through support@transact.com . </p>"
html += """
<p>-------------------------------------------</p>
<p>Best regards,<br>TransACT team</p>
<p>http://localhost:3001/ </p>
</body>
</html> """
subject = "TransACT - Your registration has been approved!"
message = Mail(
from_email='no-reply@transact.sg',
to_emails=[recipient],
subject=subject,
html_content=html)
client = SendGridAPIClient("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")
response = client.send(message)
print(response)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/test", methods=['GET'])
def testGet():
dic = {"value": 1}
return jsonify(dic)
# For donors to make donoation
@app.route("/makeDonation", methods=['POST'])
def donate():
try:
amount = request.form.get("amount")
pid = request.form.get("project_id")
donor = request.form.get("donor_id")
result = db.donors.find_one({"_id": ObjectId(donor)})
result1 = db.projects.find_one({"_id": ObjectId(pid)})
anonymous = request.form.get("anonymous")
# To protect user privacy, we will use sha256 to hash the donor' eth address
txn = blockchainSetup.make_donation(int(amount), int(
result1['project_solidity_id']), result['eth_address'])
print(txn)
new_donation = {
"amount": amount,
"project_id": ObjectId(pid),
"donor_id": ObjectId(donor),
"donor_address": request.form.get("donor_address"),
"donation_time": str(datetime.datetime.now().strftime("%Y-%m-%d")),
"donation_hash": txn,
"anonymous": anonymous
}
donation_id = db.donations.insert_one(new_donation)
# send email
donor_obj = db.donors.find_one({'_id': ObjectId(donor)})
project_obj = db.projects.find_one({'_id': ObjectId(pid)})
send_email_donation(donor_obj["email"],
project_obj["projectName"], amount)
return jsonify({'code': 200})
except Exception as ex:
print(ex)
print(type(ex))
return jsonify(
{"code": 400,
"error": str(ex)}
)
@app.route("/registerInspector", methods=['POST'])
def registerInspector():
# address = request.form.get("inspectorAddress")
# print(address)
address = request.args.get("inspectorAddress")
# print(address)
txn = blockchainSetup.registerInspector(address)
dic = {"txn": txn}
return jsonify(dic)
# For donor to register
@app.route("/registerDonor", methods=['POST'])
def registerDonor():
donor_id = ''
try:
address = request.form.get("eth_address")
# check whether those critical information is unique
unique_username = db.donors.find_one(
{'username': request.form.get("username")})
unique_eth_add = db.donors.find_one(
{'eth_address': request.form.get("eth_address")})
if unique_username is not None:
return jsonify({
"code": 400,
"message": 'This username has been taken, please try another one'})
if unique_eth_add is not None:
return jsonify({
"code": 400,
"message": 'This ethereum address already has an account'})
txn = blockchainSetup.registerDonor(
address, request.form.get("full_name"))
# hash password
salt = os.urandom(32)
password = request.form.get("password")
key = hashlib.pbkdf2_hmac(
'sha256', password.encode('utf-8'), salt, 100000)
# Store them as:
passwordStorage = salt + key
new_donor = {
"username": request.form.get("username"),
"password": passwordStorage,
"email": request.form.get("email"),
"eth_address": request.form.get("eth_address"),
"card_number": request.form.get("card_number"),
"card_expiry_date": request.form.get("card_expiry_date"),
"physical_address": request.form.get("physical_address"),
"full_name": request.form.get("full_name"),
"contact_number": request.form.get("contact_number"),
"financial_info": request.form.get("financial_info"),
"registration_hash": txn,
"approval_hash": ''
}
donor_id = db.donors.insert_one(new_donor)
except Exception as ex:
if(str(type(ex)) == "<class 'web3.exceptions.InvalidAddress'>"):
return jsonify(
{
"code": 400,
"message": "Invalid Eth Address"
}
)
return jsonify(
{
"code": 400,
"message": str(ex)
}
# {"error": str(ex.args[0]['message'])}
)
return jsonify({"code": 200})
# Update donor profile
@app.route("/updateDonor", methods=['POST'])
def updateDonor():
donors = db.donors
donor = request.form.get("eth_address")
try:
txn = blockchainSetup.updateDonor(donor, request.form.get("full_name"))
updateDic = {
"username": request.form.get("username"),
"email": request.form.get("email"),
"card_number": request.form.get("card_number"),
"card_expiry_date": request.form.get("card_expiry_date"),
"physical_address": request.form.get("physical_address"),
"full_name": request.form.get("full_name"),
"contact_number": request.form.get("contact_number"),
}
if "password" in request.form:
password = request.form.get("password")
salt = os.urandom(32)
key = hashlib.pbkdf2_hmac(
'sha256', password.encode('utf-8'), salt, 100000)
passwordStorage = salt + key
updateDic["password"] = passwordStorage
result = donors.find_one_and_update(
{"eth_address": donor},
{"$set": updateDic
}
)
dic = {"code": 200}
return jsonify(dic)
except Exception as ex:
return jsonify({"error": str(ex)})
# Approve the registration of donors
@app.route("/approveDonor", methods=['POST'])
def approveDonor():
donors = db.donors
donor = request.form.get("donorAddress")
inspector = request.form.get("inspectorAddress")
try:
txn = blockchainSetup.approveDonor(donor, inspector)
result = donors.find_one_and_update(
{"eth_address": donor},
{"$set": {
"approval_hash": txn
}
}
)
# dic = {"txn": txn}
return jsonify({
"code": 200,
"message": "Approve Donor"
})
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# Reject the registration of donors
@app.route("/rejectDonor", methods=['POST'])
def rejectDonor():
donors = db.donors
donor = request.form.get("donorAddress")
inspector = request.form.get("inspectorAddress")
try:
txn = blockchainSetup.rejectDonor(donor, inspector)
result = donors.find_one_and_update(
{"eth_address": donor},
{"$set": {
"approval_hash": txn
}
}
)
return jsonify({
"code": 200,
"message": "Reject Donor"
})
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# Rtrieve the donor details
@app.route("/getDonorDetails", methods=['GET'])
def getDonorDetails():
donor = request.args.get("donorAddress")
print(donor)
try:
db_result = db.donors.find_one({"eth_address": donor})
db_result['_id'] = str(db_result['_id'])
db_result['password'] = ""
db_result["code"] = "200"
return jsonify(db_result)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
@app.route("/getAllDonors", methods=['GET'])
def getAllDonors():
try:
db_result = db.donors.find()
result_list = []
for result in db_result:
result['_id'] = str(result['_id'])
print(result)
result_list.append(result)
return jsonify(
{"code": 200,
"items": result_list}
)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# Retrieve all donors that waiting for approval
@app.route("/getAllPendingDonors", methods=['GET'])
def getAllPendingDonors():
try:
db_result = db.donors
result_list = []
all_result = db_result.find(
{"approval_hash": ''}
)
for result in all_result:
result['_id'] = str(result['_id'])
result['password'] = ""
result_list.append(result)
return jsonify(
{"code": 200,
"items": result_list}
)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# Retrieve all projects that belonged to a specific charity organization
@app.route("/getProjectsByOrganization", methods=['GET'])
def getProjectsByOrganization():
charity = request.args.get("charityAddress")
try:
db_result = db.projects.find({"charityAddress": charity})
result_list = []
for result in db_result:
donations = list(db.donations.find(
{"project_id": ObjectId(result['_id'])}))
num = 0
numDonors = 0
stop = blockchainSetup.checkProjectStop(result['approval_hash'], result['project_solidity_id'])
aproval = blockchainSetup.checkProjectApproval(result['approval_hash'], result['project_solidity_id'])
reject = blockchainSetup.checkProjectReject(result['approval_hash'], result['project_solidity_id'])
if(stop):
result['stop'] = "1" #project stopped
elif(reject):
result['stop'] = "10" #rejected
elif(aproval): # approved
result['stop'] = "0"
else: #wait approval
result['stop'] = '-1'
for d in donations:
num += int(d['amount'])
numDonors += 1
confirmations = list(db.confirmations.find(
{"project_id": ObjectId(result['_id'])}))
total_confirm = 0
for c in confirmations:
total_confirm += int(c['amount'])
result['actual_amount'] = num
result['confirmed_amount'] = total_confirm
result['num_donors'] = numDonors
result['_id'] = str(result['_id'])
result['charity_id'] = str(result['charity_id'])
result_list.append(result)
dic = {"code": 200, "items": result_list}
return jsonify(dic)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# Retrieve all projects that donated by a specific donor
@app.route("/getProjectsByDonor", methods=['GET'])
def getProjectsByDonor():
donor = request.args.get("donorAddress")
print(donor)
try:
donation_result = db.donations.find({"donor_address": donor})
unique_projects = list(
set([str(result["project_id"]) for result in donation_result]))
result_list = []
for project_id in unique_projects:
project = db.projects.find_one({"_id": ObjectId(project_id)})
donations = list(db.donations.find(
{"project_id": ObjectId(project_id)}))
self_donations = list(db.donations.find({
"project_id": ObjectId(project_id),
"donor_address": donor
}))
result = {}
result['_id'] = project_id
stop = blockchainSetup.checkProjectStop(
project['approval_hash'], project['project_solidity_id'])
if(stop):
result['stop'] = "1"
elif(project['approval_hash'] == ''):
result['stop'] = "-1"
else:
result['stop'] = "0"
num = 0
for d in donations:
num += int(d['amount'])
# total amount: $$ of donations
confirmations = list(db.confirmations.find(
{"project_id": ObjectId(project_id)}))
total_confirm = 0
for c in confirmations:
total_confirm += int(c['amount'])
totl_contributed = 0
for s in self_donations:
totl_contributed += int(s["amount"])
result['actual_amount'] = num
result['confirmed_amount'] = total_confirm
result['amount'] = totl_contributed
result['projectName'] = project['projectName']
result['expirationDate'] = project['expirationDate']
result['fundTarget'] = project['fundTarget']
result_list.append(result)
dic = {"code": 200, "items": result_list}
return jsonify(dic)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# For charity organization to register an account
@app.route("/registerOrganization", methods=['POST'])
def registerOrganization():
charity = request.form.get("eth_address")
try:
unique_username = db.charities.find_one(
{'username': request.form.get("username")})
unique_eth_add = db.charities.find_one(
{'eth_address': request.form.get("eth_address")})
if unique_username is not None:
return jsonify({
"code": 400,
"message": 'This username has been taken, please try another one'})
if unique_eth_add is not None:
return jsonify({
"code": 400,
"message": 'This ethereum address already has an account'})
txn = blockchainSetup.registerOrganization(
charity, request.form.get("full_name"))
# hash password
salt = os.urandom(32)
password = request.form.get("password")
key = hashlib.pbkdf2_hmac(
'sha256', password.encode('utf-8'), salt, 100000)
# Store them as:
passwordStorage = salt + key
new_charity = {
"username": request.form.get("username"),
"password": passwordStorage,
"email": request.form.get("email"),
"eth_address": request.form.get("eth_address"),
"card_number": request.form.get("card_number"),
"card_expiry_date": request.form.get("card_expiry_date"),
"physical_address": request.form.get("physical_address"),
"full_name": request.form.get("full_name"),
"contact_number": request.form.get("contact_number"),
"description": request.form.get("description"),
"registration_hash": txn,
"approval_hash": ''
}
charity_id = str(db.charities.insert_one(new_charity).inserted_id)
# store certificate
certificate = request.files["certificate"]
folder_path = "./certificate/" + request.form.get("eth_address") + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "certificate.pdf"
certificate.save(os.path.join(folder_path, filename))
except Exception as ex:
print(ex)
print(type(ex))
return jsonify(
{"code": 400,
"message": str(ex)}
# {"error": str(ex.args[0]['message'])}
)
return jsonify({"code": 200, "charity_id": charity_id})
# For admin to approve charity registration
@app.route("/approveOrganization", methods=['POST'])
def approveOrganization():
charities = db.charities
charity = request.form.get("charityAddress")
inspector = request.form.get("inspectorAddress")
try:
txn = blockchainSetup.approveOrganization(charity, inspector)
result = charities.find_one_and_update(
{"eth_address": charity},
{"$set": {
"approval_hash": txn
}
}
)
#send email
charity_obj = charities.find_one({"eth_address" : charity})
print(charity_obj["email"], charity_obj["full_name"])
send_email_charity_approval(charity_obj["email"], charity_obj["full_name"])
return jsonify({
"code": 200,
"message": "Approve organization"
})
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# For admin to reject charity registration
@app.route("/rejectOrganization", methods=['POST'])
def rejectOrganization():
charities = db.charities
charity = request.form.get("charityAddress")
inspector = request.form.get("inspectorAddress")
try:
txn = blockchainSetup.rejectOrganization(charity, inspector)
result = charities.find_one_and_update(
{"eth_address": charity},
{"$set": {
"approval_hash": txn
}
}
)
# dic = {"txn": txn}
return jsonify({
"code": 200,
"message": "Reject organization"
})
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# For charity to update their profile
@app.route("/updateOrganization", methods=['POST'])
def updateOrganization():
charities = db.charities
charity = request.form.get("eth_address")
try:
txn = blockchainSetup.updateOrganization(
charity, request.form.get("full_name"))
updateDic = {
"username": request.form.get("username"),
"email": request.form.get("email"),
"card_number": request.form.get("card_number"),
"card_expiry_date": request.form.get("card_expiry_date"),
"physical_address": request.form.get("physical_address"),
"full_name": request.form.get("full_name"),
"contact_number": request.form.get("contact_number"),
"description": request.form.get("description"),
}
if "password" in request.form:
password = request.form.get("password")
salt = os.urandom(32)
key = hashlib.pbkdf2_hmac(
'sha256', password.encode('utf-8'), salt, 100000)
passwordStorage = salt + key
updateDic["password"] = passwordStorage
result = charities.find_one_and_update(
{"eth_address": charity},
{"$set": updateDic
}
)
# update certificate
if "certificate" in request.files:
certificate = request.files["certificate"]
folder_path = "./certificate/" + charity + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "certificate.pdf"
certificate.save(os.path.join(folder_path, filename))
dic = {"code": 200}
return jsonify(dic)
except Exception as ex:
return jsonify({"error": str(ex)})
# Retrieve all charities which are waiting for approval
@app.route("/getAllPendingOrganizations", methods=['GET'])
def getAllPendingOrganizations():
try:
db_result = db.charities
result_list = []
all_result = db_result.find(
{"approval_hash": ''}
)
for result in all_result:
result['_id'] = str(result['_id'])
result['password'] = ""
result_list.append(result)
return jsonify(
{"code": 200,
"items": result_list}
)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# For admin to approve charity registration
@app.route("/approvedOrganization", methods=['GET'])
def approvedOrganization():
charity = request.args.get("charityAddress")
print(charity)
txn = blockchainSetup.approvedOrganization(charity)
dic = {"txn": txn}
return jsonify(dic)
# Retrieve charity profile
@app.route("/getCharityDetails", methods=['GET'])
def getCharityDetails():
charity = request.args.get("charityAddress")
print(charity)
try:
db_result = db.charities.find_one({"eth_address": charity})
db_result['_id'] = str(db_result['_id'])
db_result["password"] = ""
db_result["code"] = 200,
return jsonify(db_result)
except Exception as ex:
return jsonify({
"code": 400,
"message": str(ex)
})
# For charity to confirm their money usage for donations
@app.route("/confirmMoney", methods=['POST'])
def confirmMoney():
try:
amount = request.form.get("amount")
project_id = request.form.get("project_id")
description = request.form.get("description")
charity = request.form.get("charity_id")
result = db.charities.find_one({"_id": ObjectId(charity)})
result1 = db.projects.find_one({"_id": ObjectId(project_id)})
txn = blockchainSetup.confirmMoney(int(amount), int(
result1['project_solidity_id']), result['eth_address'])
new_confirmation = {
"amount": amount,
"project_id": ObjectId(project_id),
"description": description,
"confirmation_time": str(datetime.datetime.now().strftime("%Y-%m-%d")),
"confirmation_hash": txn
}
confirmation_id = db.confirmations.insert_one(new_confirmation)
#send email
donations = list(db.donations.find({"project_id": ObjectId(project_id)}))
print(len(donations))
emails = []
for d in donations:
donor = db.donors.find_one({"_id": ObjectId(d["donor_id"])})
emails.append(donor["email"])
emails = list(set(emails))
projectName = db.projects.find_one({"_id": ObjectId(project_id)})["projectName"]
print("emails: ", emails)
send_email_confirmation(emails, projectName, amount, description)
return jsonify({'code': 200})
except Exception as ex:
return jsonify({"code": 400, "message": str(ex)})
# Retrieve all confiamtions that have been made by charity for a specific project
@app.route("/retrieveConfirmation", methods=['GET'])
def retrieveConfirmation():
try:
project_id = request.args.get("project_id")
result = list(db.confirmations.find(
{"project_id": ObjectId(project_id)}))
# print(result)
result_list = []
num = 0
for i in result:
project = db.projects.find_one({"_id": i['project_id']})
# Check the confirmation information from blockchain to make sure this confirmation is valid
check = blockchainSetup.checkConfirmation(
i['confirmation_hash'], project['project_solidity_id'], i['amount'])
if(check):
i['_id'] = str(i['_id'])
i['project_id'] = str(i['project_id'])
num += int(i['amount'])
result_list.append(i)
result1={'confirmations':result_list,'total_confirmation':num}
return jsonify({"code": 200, "result": result1})
except Exception as ex:
return jsonify({"code": 400, "message": str(ex)})
def get_byte_image(image_path):
img = Image.open(image_path, mode='r')
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='JPEG')
encoded_img = base64.encodebytes(img_byte_arr.getvalue()).decode('ascii')
return encoded_img
# Retrieve projet profile
@app.route("/retrieveProjectDetails", methods=['GET'])
def retrieveProjectDetails():
try:
result = db.projects.find_one(
{"_id": ObjectId(request.args.get("id"))})
approval = blockchainSetup.checkProjectApproval(
result['approval_hash'], result['project_solidity_id'])
stop = blockchainSetup.checkProjectStop(
result['approval_hash'], result['project_solidity_id'])
if(not approval and not stop):
return jsonify({"code": 400, "error": "This Project is still waiting for approval!"})
if(stop):
result['stop'] = "1"
else:
result['stop'] = "0"
result['_id'] = str(result['_id'])
image_path = './projectCover/' + result['_id'] + '/cover.jpg'
image = get_byte_image(image_path)
result["image"] = image
result['charity_id'] = str(result['charity_id'])
charity = db.charities.find_one(
{"_id": ObjectId(result['charity_id'])})
result['charity_name'] = charity['full_name']
result['charity_description'] = charity['description']
result['charity_number'] = charity['contact_number']
result['charity_email'] = charity['email']
result['charity_address'] = charity['physical_address']
donations = list(db.donations.find(
{"project_id": ObjectId(result['_id'])}))
num = 0
for d in donations:
donor = db.donors.find_one({"_id": d['donor_id']})
check = blockchainSetup.checkDonation(
d['donation_hash'], donor['eth_address'])
if (check == True):
num += int(d['amount'])
# print(num)
result['actual_amount'] = num
result['fundTarget'] = int(result['fundTarget'])
return jsonify({'code': 200, "result": result})
except Exception as ex:
return jsonify({"code": 400, "message": str(ex)})
# For charity to register a new funding project
@app.route("/registerProject", methods=['POST'])
def registerProject():
projectId = request.form.get("projectId")
print(projectId)
try:
if projectId == "0":
beneficiaryListFile = request.files["beneficiaryList"]
df = pd.read_excel(beneficiaryListFile)
if list(df.columns) != ["beneficiary", "remark"]:
return jsonify({"code": 400, "message": "Invalid beneficiary file format."})
beneficiaryList = []
for index, row in df.iterrows():
beneficiaryList.append({
"name": row["beneficiary"],
"remark": row["remark"]
})
# register to blockchain
charity = request.form.get("charityAddress")
beneficiaryGainedRatio = request.form.get('beneficiaryGainedRatio')
txn, numProjects = blockchainSetup.registerProject(
charity, int(beneficiaryGainedRatio))
# numProjects = 0
# txn = blockchainSetup.registerProject(charity, int(beneficiaryGainedRatio))
# store in DB
new_project = {
"projectName": request.form.get('projectName'),
"projectCategory": request.form.get('projectCategory'),
"project_solidity_id": numProjects,
"charity_id": ObjectId(request.form.get('charity_id')),
"charityAddress": charity,
"beneficiaryList": beneficiaryList,
"breakdownList": request.form.get('breakdownList'),
"expirationDate": request.form.get('expirationDate'),
"fundTarget": request.form.get('fundTarget'),
"description": request.form.get("description"),
"registration_hash": txn,
"approval_hash": '',
}
project_id = str(db.projects.insert_one(new_project).inserted_id)
# store cover image
projectCover = request.files["projectCover"]
folder_path = "./projectCover/" + project_id + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "cover.jpg"
projectCover.save(os.path.join(folder_path, filename))
# store beneficiary file
folder_path = "./beneficiary/" + project_id + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "beneficiary.xlsx"
# export df to excel
df.to_excel(os.path.join(folder_path, filename), index=False)
return jsonify({
"code": 200,
"project_id": project_id,
})
else:
beneficiaryList = []
if "beneficiaryList" in request.files:
beneficiaryListFile = request.files["beneficiaryList"]
df = pd.read_excel(beneficiaryListFile)
if list(df.columns) != ["beneficiary", "remark"]:
return jsonify({"code": 400, "message": "Invalid beneficiary file format."})
for index, row in df.iterrows():
beneficiaryList.append({
"name": row["beneficiary"],
"remark": row["remark"]
})
# store beneficiary file
folder_path = "./beneficiary/" + projectId + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "beneficiary.xlsx"
# export df to excel
df.to_excel(os.path.join(folder_path, filename), index=False)
else:
print("file unchanged")
update_dic = {
"projectName": request.form.get('projectName'),
"projectCategory": request.form.get('projectCategory'),
"breakdownList": request.form.get('breakdownList'),
"expirationDate": request.form.get('expirationDate'),
"fundTarget": request.form.get('fundTarget'),
"description": request.form.get("description"),
}
if len(beneficiaryList) > 0:
update_dic["beneficiaryList"] = beneficiaryList
# update in DB
result = db.projects.find_one_and_update(
{"_id": ObjectId(projectId)},
{"$set": update_dic
})
if "projectCover" in request.files:
projectCover = request.files["projectCover"]
folder_path = "./projectCover/" + projectId + "/"
Path(folder_path).mkdir(parents=True, exist_ok=True)
filename = "cover.jpg"
projectCover.save(os.path.join(folder_path, filename))
else:
print("projectCover unchanged")