-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapplication.py
2442 lines (2049 loc) · 104 KB
/
application.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
#
# application.py
# Nicholas Boucher 2017
#
# Contains the main application code for NOVA. This code maps
# all URL endpoints to FLASK functions
#
import atexit
from flask import Flask, flash, redirect, render_template, request, session, url_for, jsonify, send_from_directory, Response, stream_with_context
from sqlalchemy.exc import IntegrityError
from datetime import datetime, timezone, timedelta
from sqlalchemy.sql.expression import or_ as OR, and_ as AND
from flask_login import login_required, fresh_login_required, login_user, logout_user, current_user
from re import match
from flask_mail import Mail, Message
from sys import argv
from pytz import timezone, utc
from flask_migrate import Migrate
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from flask_wtf import Form
from wtforms_sqlalchemy.orm import model_form, model_fields
from os.path import join, exists
from os import makedirs
from werkzeug.utils import secure_filename
from time import strftime
from database_models import *
from helpers import *
# create Flask server
app = Flask(__name__)
# Add support for database migrations
migrate = Migrate(app, db)
# Set uploaded file directory
app.config['UPLOAD_FOLDER'] = join(app.instance_path, "uploads")
if not exists(app.config['UPLOAD_FOLDER']):
makedirs(app.config['UPLOAD_FOLDER'])
# ensure responses aren't cached
if app.config["DEBUG"]:
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
else:
# Send owed money emails every 14 days if not debug
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
func=send_owe_money_emails,
trigger=IntervalTrigger(days=14),
id='send_owed_money_emails_job',
name='Sends Owed Money Emails',
replace_existing=True)
# Send receipts emails every 14 days if not debug
scheduler.add_job(
func=send_receipt_reminder_emails,
trigger=IntervalTrigger(days=14),
id='send_receipts_reminder_emails_job',
name='Sends Receipts Emails',
replace_existing=True)
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
# custom filters
app.jinja_env.filters["usd"] = usd
app.jinja_env.filters["two_decimals"] = number
app.jinja_env.filters["number"] = number
app.jinja_env.filters["suppress_none"] = suppress_none
app.jinja_env.filters["datetime"] = utc_to_east_datetime
app.jinja_env.filters["date"] = utc_to_east_date
app.jinja_env.filters["percentage"] = percentage
app.jinja_env.filters["swap_quotes"] = swap_quotes
# Set cryptographic key for Sessions
install_secret_key(app)
# setup database connection
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
# Enable authentication
login_manager = LoginManager()
login_manager.init_app(app)
# Tell Authenticator where the login page is located
login_manager.login_view = "login"
login_manager.login_message_category = "message"
# Enable email system
if "installation" not in argv[0]:
# Due to Flask-Mail Limitations, We must create a seperate App Context for Treasurer Emails
treasurer_app = Flask("treasurer")
# Must manually use app context to access database since not handling request
with app.app_context():
grants_email_username = Config.query.filter_by(key="grants_email_username").first().value
grants_email_password = Config.query.filter_by(key="grants_email_password").first().value
treasurer_email_username = Config.query.filter_by(key="treasurer_email_username").first().value
treasurer_email_password = Config.query.filter_by(key="treasurer_email_password").first().value
server_name = Config.query.filter_by(key="server_name").first().value
# Change the first argument below to configure the sender name on all emails
app.config['MAIL_DEFAULT_SENDER'] = ('UC Grants', grants_email_username)
# Let's assume we are using gmail configuration options
app.config['MAIL_SERVER'] = "smtp.gmail.com"
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = grants_email_username
app.config['MAIL_PASSWORD'] = grants_email_password
# Set server name for email URLs without app context
app.config['SERVER_NAME'] = server_name
# Should help with request file size limits
app.config['MAIL_MAX_EMAILS'] = 5
# Setup default Grants Sender Email
mail = Mail(app)
# Setup Treasurer Sener Email
treasurer_app.config['MAIL_DEFAULT_SENDER'] = ('UC Treasurer', treasurer_email_username)
# Let's assume we are using gmail configuration options
treasurer_app.config['MAIL_SERVER'] = "smtp.gmail.com"
treasurer_app.config['MAIL_PORT'] = 587
treasurer_app.config['MAIL_USE_TLS'] = True
treasurer_app.config['MAIL_USERNAME'] = treasurer_email_username
treasurer_app.config['MAIL_PASSWORD'] = treasurer_email_password
# Set server name for email URLs without app context
treasurer_app.config['SERVER_NAME'] = server_name
# Should help with request file size limits
treasurer_app.config['MAIL_MAX_EMAILS'] = 5
treasurer_mail = Mail(treasurer_app)
# Define authentication function to lookup users
@login_manager.user_loader
def user_loader(email):
return User.query.get(email)
@app.route('/')
def index():
return render_template("index.html")
@app.route('/login', methods=['GET','POST'])
def login():
""" Allows users to login to the system """
# User is requesting login page
if request.method == 'GET':
# Render page to user
return render_template('login.html')
# User is submitting login data
else:
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
# Verify that email and password were submitted
if not email or not password:
flash("Must enter username and password", 'error')
return render_template('login.html')
# Query for User
user = User.query.get(email)
# Verify that user exists
if not user:
flash("Username or password incorrect", 'message')
return redirect(url_for('login'))
# Verify that password is correct
if not verify_password(user, password):
flash("Username or password incorrect", 'message')
return redirect(url_for('login'))
# User has successfully authenticated, log them in
login_user(user, remember=remember)
# Redirect user to the correct page
if user.force_pw_update:
return redirect(url_for('change_password'))
else:
return redirect(url_for('index'))
@app.route("/logout")
@login_required
def logout():
logout_user()
flash("Successfully logged out", 'message')
return redirect(url_for('login'))
@app.route('/new_grant')
def new_grant():
""" Inserts new grant applications into database from query strings passed by qualtrics survey """
# get arguments from query string
args = get_grant_args(request.query_string)
# Verify security key
sec_key = Config.query.filter_by(key='security_key').first().value
if not args.get('k') or sec_key != args.get('k')[0]:
return "Invalid Security Key. You do not have access to this system."
# This system only works for Upfront and Retroactive UC Grants, so filter others out
if not args.get('is_upfront') or (args.get('is_upfront')[0] != '1' and args.get('is_upfront')[0] != '2'):
# This could be updated to do something helpful with notifying on receipt of non-nova application (such as GOHC)
return redirect(url_for('non_nova_application_submit'))
# Get Next Grant ID
council_semester = Config.query.filter_by(key='council_semester').first()
current_week = Config.query.filter_by(key='grant_week').first()
grant_prefix = council_semester.value + '-' + current_week.value
grant_number = Grants_Week.query.filter_by(grant_week=grant_prefix).first()
# This is not atomic, which seems like a potential problem...
grant_number.num_grants += 1
db.session.commit()
grant_id = grant_prefix + "-" + str(grant_number.num_grants)
# Create New Grant
grant = Grant(grant_id)
# Timezones will be converted to UTC
eastern = timezone('US/Eastern')
# Add Grant Values from Parsed Query String
if args.get('amount_requested'): grant.amount_requested = float(args.get('amount_requested')[0])
if args.get('is_collaboration'): grant.is_collaboration = (True if args.get('is_collaboration')[0] == "Yes" else False)
if args.get('collaborators'): grant.collaborators = args.get('collaborators')[0]
if args.get('collaboration_explanation'): grant.collaboration_explanation = args.get('collaboration_explanation')[0]
if args.get('contact_first_name'): grant.contact_first_name = args.get('contact_first_name')[0]
if args.get('contact_last_name'): grant.contact_last_name = args.get('contact_last_name')[0]
if args.get('contact_email'): grant.contact_email = args.get('contact_email')[0]
if args.get('contact_phone'): grant.contact_phone = args.get('contact_phone')[0]
if args.get('contact_role'): grant.contact_role = args.get('contact_role')[0]
if args.get('is_upfront'): grant.is_upfront = (True if args.get('is_upfront')[0] == "1" else False)
if args.get('organization'): grant.organization = args.get('organization')[0]
if args.get('tax_id'): grant.tax_id = args.get('tax_id')[0]
if args.get('project'): grant.project = args.get('project')[0]
if args.get('project_description'): grant.project_description = args.get('project_description')[0]
if args.get('is_event'): grant.is_event = (True if args.get('is_event')[0] == "Event" else False)
if args.get('project_location'): grant.project_location = args.get('project_location')[0]
if args.get('project_start'): grant.project_start = eastern.localize(datetime.strptime(args.get('project_start')[0], '%m/%d/%Y')).astimezone(utc)
if args.get('project_end'): grant.project_end = eastern.localize(datetime.strptime(args.get('project_end')[0], '%m/%d/%Y')).astimezone(utc)
if args.get('college_attendees'): grant.college_attendees = int(args.get('college_attendees')[0])
if args.get('facebook_link'): grant.facebook_link = args.get('facebook_link')[0]
if args.get('revenue1_type'): grant.revenue1_type = args.get('revenue1_type')[0]
if args.get('revenue1_description'): grant.revenue1_description = args.get('revenue1_description')[0]
if args.get('revenue1_amount'): grant.revenue1_amount = float(args.get('revenue1_amount')[0])
if args.get('revenue2_type'): grant.revenue2_type = args.get('revenue2_type')[0]
if args.get('revenue2_description'): grant.revenue2_description = args.get('revenue2_description')[0]
if args.get('revenue2_amount'): grant.revenue2_amount = float(args.get('revenue2_amount')[0])
if args.get('revenue3_type'): grant.revenue3_type = args.get('revenue3_type')[0]
if args.get('revenue3_description'): grant.revenue3_description = args.get('revenue3_description')[0]
if args.get('revenue3_amount'): grant.revenue3_amount = float(args.get('revenue3_amount')[0])
if args.get('revenue4_type'): grant.revenue4_type = args.get('revenue4_type')[0]
if args.get('revenue4_description'): grant.revenue4_description = args.get('revenue4_description')[0]
if args.get('revenue4_amount'): grant.revenue4_amount = float(args.get('revenue4_amount')[0])
if args.get('revenue5_type'): grant.revenue5_type = args.get('revenue5_type')[0]
if args.get('revenue5_description'): grant.revenue5_description = args.get('revenue5_description')[0]
if args.get('revenue5_amount'): grant.revenue5_amount = float(args.get('revenue5_amount')[0])
if args.get('revenue6_type'): grant.revenue6_type = args.get('revenue6_type')[0]
if args.get('revenue6_description'): grant.revenue6_description = args.get('revenue6_description')[0]
if args.get('revenue6_amount'): grant.revenue6_amount = float(args.get('revenue6_amount')[0])
if args.get('revenue7_type'): grant.revenue7_type = args.get('revenue7_type')[0]
if args.get('revenue7_description'): grant.revenue7_description = args.get('revenue7_description')[0]
if args.get('revenue7_amount'): grant.revenue7_amount = float(args.get('revenue7_amount')[0])
if args.get('revenue8_type'): grant.revenue8_type = args.get('revenue8_type')[0]
if args.get('revenue8_description'): grant.revenue8_description = args.get('revenue8_description')[0]
if args.get('revenue8_amount'): grant.revenue8_amount = float(args.get('revenue8_amount')[0])
if args.get('revenue9_type'): grant.revenue9_type = args.get('revenue9_type')[0]
if args.get('revenue9_amount'): grant.revenue9_amount = float(args.get('revenue9_amount')[0])
if args.get('revenue10_type'): grant.revenue10_type = args.get('revenue10_type')[0]
if args.get('revenue10_description'): grant.revenue10_description = args.get('revenue10_description')[0]
if args.get('revenue10_amount'): grant.revenue10_amount = float(args.get('revenue10_amount')[0])
if args.get('app_expense1_type'): grant.app_expense1_type = args.get('app_expense1_type')[0]
if args.get('app_expense1_description'): grant.app_expense1_description = args.get('app_expense1_description')[0]
if args.get('app_expense1_amount'): grant.app_expense1_amount = float(args.get('app_expense1_amount')[0])
if args.get('app_expense2_type'): grant.app_expense2_type = args.get('app_expense2_type')[0]
if args.get('app_expense2_description'): grant.app_expense2_description = args.get('app_expense2_description')[0]
if args.get('app_expense2_amount'): grant.app_expense2_amount = float(args.get('app_expense2_amount')[0])
if args.get('app_expense3_type'): grant.app_expense3_type = args.get('app_expense3_type')[0]
if args.get('app_expense3_description'): grant.app_expense3_description = args.get('app_expense3_description')[0]
if args.get('app_expense3_amount'): grant.app_expense3_amount = float(args.get('app_expense3_amount')[0])
if args.get('app_expense4_type'): grant.app_expense4_type = args.get('app_expense4_type')[0]
if args.get('app_expense4_description'): grant.app_expense4_description = args.get('app_expense4_description')[0]
if args.get('app_expense4_amount'): grant.app_expense4_amount = float(args.get('app_expense4_amount')[0])
if args.get('app_expense5_type'): grant.app_expense5_type = args.get('app_expense5_type')[0]
if args.get('app_expense5_description'): grant.app_expense5_description = args.get('app_expense5_description')[0]
if args.get('app_expense5_amount'): grant.app_expense5_amount = float(args.get('app_expense5_amount')[0])
if args.get('app_expense6_type'): grant.app_expense6_type = args.get('app_expense6_type')[0]
if args.get('app_expense6_description'): grant.app_expense6_description = args.get('app_expense6_description')[0]
if args.get('app_expense6_amount'): grant.app_expense6_amount = float(args.get('app_expense6_amount')[0])
if args.get('app_expense7_type'): grant.app_expense7_type = args.get('app_expense7_type')[0]
if args.get('app_expense7_description'): grant.app_expense7_description = args.get('app_expense7_description')[0]
if args.get('app_expense7_amount'): grant.app_expense7_amount = float(args.get('app_expense7_amount')[0])
if args.get('app_expense8_type'): grant.app_expense8_type = args.get('app_expense8_type')[0]
if args.get('app_expense8_description'): grant.app_expense8_description = args.get('app_expense8_description')[0]
if args.get('app_expense8_amount'): grant.app_expense8_amount = float(args.get('app_expense8_amount')[0])
if args.get('app_expense9_type'): grant.app_expense9_type = args.get('app_expense9_type')[0]
if args.get('app_expense9_description'): grant.app_expense9_description = args.get('app_expense9_description')[0]
if args.get('app_expense9_amount'): grant.app_expense9_amount = float(args.get('app_expense9_amount')[0])
if args.get('app_expense10_type'): grant.app_expense10_type = args.get('app_expense10_type')[0]
if args.get('app_expense10_description'): grant.app_expense10_description = args.get('app_expense10_description')[0]
if args.get('app_expense10_amount'): grant.app_expense10_amount = float(args.get('app_expense10_amount')[0])
if args.get('app_expense11_type'): grant.app_expense11_type = args.get('app_expense11_type')[0]
if args.get('app_expense11_description'): grant.app_expense11_description = args.get('app_expense11_description')[0]
if args.get('app_expense11_amount'): grant.app_expense11_amount = float(args.get('app_expense11_amount')[0])
if args.get('app_expense12_type'): grant.app_expense12_type = args.get('app_expense12_type')[0]
if args.get('app_expense12_description'): grant.app_expense12_description = args.get('app_expense12_description')[0]
if args.get('app_expense12_amount'): grant.app_expense12_amount = float(args.get('app_expense12_amount')[0])
if args.get('application_comments'): grant.application_comments = args.get('application_comments')[0]
# Determine if Small Grant
# (small_grant_cap and small_grant_expense_types defined in databse_models.py for convenience)
if nfloat(grant.amount_requested) and nfloat(grant.amount_requested) < small_grant_cap:
# Parse small grant candidate to rule out grants that are applying for inelligible categories
expenses = [grant.app_expense1_type,grant.app_expense2_type,grant.app_expense3_type,grant.app_expense4_type,grant.app_expense5_type,grant.app_expense6_type,grant.app_expense7_type,grant.app_expense8_type,grant.app_expense9_type,grant.app_expense10_type,grant.app_expense11_type,grant.app_expense12_type]
grant.is_small_grant = True
for expense in expenses:
if expense and expense not in small_grant_expense_types:
grant.is_small_grant = False
# If the organization does not yet exist in our Organizations Database, add the organization
if grant.organization:
org = Organization.query.filter_by(name=grant.organization).first()
if org == None:
org = Organization(grant.organization)
db.session.add(org)
# Commit New Grant to Database
try:
db.session.add(grant)
db.session.commit()
except IntegrityError:
return "Error: Grant already exists"
# Send Confirmation Email
email_application_submitted(grant)
return redirect(url_for('application_submitted', grant_id=grant_id))
@app.route('/application-submitted/<grant_id>')
def application_submitted(grant_id):
return render_template("application_submitted.html", grant_id=grant_id)
@app.route('/application-submit')
def non_nova_application_submit():
return render_template("application_submitted.html", grant_id=None)
@app.route('/receipts')
def receipts(overwrite = False):
""" Adds completed project info (including receipts) to existing grant record """
# Get arguments from query string
args = get_grant_args(request.query_string)
# Check for grant_id, which is necessary to update database record
if not args.get('grant_id'):
return "Error: No Grant ID submitted"
# Query for the relevant grant
grant = Grant.query.filter_by(grant_id=args['grant_id'][0]).first()
# Return error without updating data if grant does not exist
if grant == None:
return "Invalid Grant ID"
if grant.receipts_submitted and not overwrite:
return 'Receipts have already been submitted for this grant. To overwrite your previous receipt submission with this one, <a href="/resubmit-receipts?' + request.query_string.decode() + '">click here</a>.'
if overwrite:
# Zero out all previous values if overwriting a receipts record
grant.expense1_description=grant.expense1_amount=grant.expense2_description=grant.expense2_amount=grant.expense3_description=\
grant.expense3_amount=grant.expense4_description=grant.expense4_amount=grant.expense5_description=grant.expense5_amount=\
grant.expense6_description=grant.expense6_amount=grant.expense7_description=grant.expense7_amount=grant.expense8_description=\
grant.expense8_amount=grant.expense9_description=grant.expense9_amount=grant.expense10_description=grant.expense10_amount=\
grant.expense11_description=grant.expense11_amount=grant.expense12_description=grant.expense12_amount=grant.completed_proj_comments\
= None
# update receipt resubmission history
if grant.receipts_resubmit_history:
grant.receipts_resubmit_history += ", " + grant.receipts_submit_date.strftime("%Y-%m-%d %H:%M:%S")
else:
grant.receipts_resubmit_history = grant.receipts_submit_date.strftime("%Y-%m-%d %H:%M:%S")
# Parse Recipts images comma-separated list
if args.get('receipt_images'):
# Remove all unecessary commas
receipts = args['receipt_images'][0].replace(', ,', '')
# trim trailing whitespace
receipts = receipts.rstrip()
# Remove final comma (fencepost error)
if receipts[-1] == ',': receipts = receipts[:-1]
# trim trailing whitespace
receipts = receipts.rstrip()
# Update databse record
grant.receipt_images = receipts
# Add Other Grant Values from Parsed Query String
if args.get('expense1_description'): grant.expense1_description = args.get('expense1_description')[0]
if args.get('expense1_amount'): grant.expense1_amount = float(args.get('expense1_amount')[0])
if args.get('expense2_description'): grant.expense2_description = args.get('expense2_description')[0]
if args.get('expense2_amount'): grant.expense2_amount = float(args.get('expense2_amount')[0])
if args.get('expense3_description'): grant.expense3_description = args.get('expense3_description')[0]
if args.get('expense3_amount'): grant.expense3_amount = float(args.get('expense3_amount')[0])
if args.get('expense4_description'): grant.expense4_description = args.get('expense4_description')[0]
if args.get('expense4_amount'): grant.expense4_amount = float(args.get('expense4_amount')[0])
if args.get('expense5_description'): grant.expense5_description = args.get('expense5_description')[0]
if args.get('expense5_amount'): grant.expense5_amount = float(args.get('expense5_amount')[0])
if args.get('expense6_description'): grant.expense6_description = args.get('expense6_description')[0]
if args.get('expense6_amount'): grant.expense6_amount = float(args.get('expense6_amount')[0])
if args.get('expense7_description'): grant.expense7_description = args.get('expense7_description')[0]
if args.get('expense7_amount'): grant.expense7_amount = float(args.get('expense7_amount')[0])
if args.get('expense8_description'): grant.expense8_description = args.get('expense8_description')[0]
if args.get('expense8_amount'): grant.expense8_amount = float(args.get('expense8_amount')[0])
if args.get('expense9_description'): grant.expense9_description = args.get('expense9_description')[0]
if args.get('expense9_amount'): grant.expense9_amount = float(args.get('expense9_amount')[0])
if args.get('expense10_description'): grant.expense10_description = args.get('expense10_description')[0]
if args.get('expense10_amount'): grant.expense10_amount = float(args.get('expense10_amount')[0])
if args.get('expense11_description'): grant.expense11_description = args.get('expense11_description')[0]
if args.get('expense11_amount'): grant.expense11_amount = float(args.get('expense11_amount')[0])
if args.get('expense12_description'): grant.expense12_description = args.get('expense12_description')[0]
if args.get('expense12_amount'): grant.expense12_amount = float(args.get('expense12_amount')[0])
if args.get('completed_proj_comments'): grant.completed_proj_comments = args.get('completed_proj_comments')[0]
# Set Submission Metadata
grant.receipts_submit_date = datetime.now(utc)
grant.receipts_submitted = True
# Send notification email to user that the receipts were received
email_receipts_submitted(grant)
# Commit database changes
db.session.commit()
return 'Your receipts have been received. As always, you can check the status of your grant application <a href="' + url_for("grant", grant_id=grant.grant_id) + '">here</a>.'
@app.route('/resubmit-receipts')
def resubmit_receipts():
""" Handles the case in which a user would like to re-submit receipts and overwrite previous record """
return receipts(True)
@app.route('/grant/<grant_id>')
def grant(grant_id):
""" Retrieves grant info for applicants to track grant progress """
# Verify that a grant id was specified
if not grant_id:
return "Error: No Grant ID specified"
# Query for grant information
grant = Grant.query.filter_by(grant_id=grant_id.upper()).first()
# Check if grant exists in database
if not grant:
return "Error: Grant does not exist."
# See if the edit key was supplied
if grant.key:
editable = grant.key == request.args.get('key')
else:
# If this grant doesn't have an edit key, anyone can edit it
editable = True
# Calculate Progress through grant process for template progress bar
progress = {'percentage': 0, 'message': ""}
# Upfront Grants
if grant.is_upfront:
# Upfront small grant
if grant.is_small_grant:
if grant.hearing_requested and not grant.hearing_occurred:
progress['percentage'] = 0.9
progress['message'] = "Hearing Requested."
elif grant.must_reimburse_uc:
if grant.reimbursed_uc:
progress['percentage'] = 1.0
progress['message'] = "Reimbursement Processed. Grant Complete."
else:
progress['percentage'] = 0.9
progress['message'] = "Some money unspent. Reimbursement required."
elif grant.receipts_reviewed:
progress['percentage'] = 1.0
progress['message'] = "Receipts Reviewed. Grant Complete."
elif grant.receipts_submitted:
progress['percentage'] = 0.85
progress['message'] = "Receipts Processing"
elif grant.is_paid:
progress['percentage'] = 0.68
if grant.is_direct_deposit == None:
progress['message'] = "Submit Receipts"
elif grant.is_direct_deposit:
if grant.pay_date:
progress['message'] = "Funds Direct Deposited on " + utc_to_east_date(grant.pay_date) +". Submit Receipts."
else:
progress['message'] = "Funds Direct Deposited. Submit Receipts."
else:
progress['message'] = "Check Written. Submit Receipts."
elif grant.council_approved and grant.amount_allocated:
progress['percentage'] = 0.51
progress['message'] = "Funds Processing"
elif grant.council_approved:
progress['percentage'] = 1.0
progress['message'] = "Grant Denied"
elif grant.small_grant_is_reviewed:
progress['percentage'] = 0.34
progress['message'] = "Docketed for Council Vote"
else:
progress['percentage'] = 0.17
progress['message'] = "Application Being Reviewed"
# Upfront non-small grant
else:
if grant.hearing_requested and not grant.hearing_occurred:
progress['percentage'] = 0.9
progress['message'] = "Hearing Requested."
elif grant.must_reimburse_uc:
if grant.reimbursed_uc:
progress['percentage'] = 1.0
progress['message'] = "Reimbursement Processed. Grant Complete."
else:
progress['percentage'] = 0.9
progress['message'] = "Some money unspent. Reimbursement required."
elif grant.receipts_reviewed:
progress['percentage'] = 1.0
progress['message'] = "Receipts Reviewed. Grant Complete."
elif grant.receipts_submitted:
progress['percentage'] = 0.84
progress['message'] = "Receipts Processing"
elif grant.is_paid:
progress['percentage'] = 0.70
if grant.is_direct_deposit == None:
progress['message'] = "Submit Receipts"
elif grant.is_direct_deposit:
if grant.pay_date:
progress['message'] = "Funds Direct Deposited on " + utc_to_east_date(grant.pay_date) +". Submit Receipts."
else:
progress['message'] = "Funds Direct Deposited. Submit Receipts."
else:
progress['message'] = "Check Written. Submit Receipts."
elif grant.council_approved and grant.amount_allocated:
progress['percentage'] = 0.56
progress['message'] = "Funds Processing"
elif grant.council_approved:
progress['percentage'] = 1.0
progress['message'] = "Grant Denied"
elif grant.interview_occurred:
progress['percentage'] = 0.42
progress['message'] = "Docketed for Council Vote"
elif grant.interview_schedule_date:
progress['percentage'] = 0.28
progress['message'] = "Interview scheduled for " + utc_to_east_datetime(grant.interview_schedule_date)
else:
progress['percentage'] = 0.14
progress['message'] = "Interview being scheduled"
# Retroactive Grants
else:
# Retroactive small grant
if grant.is_small_grant:
if grant.hearing_requested and not grant.hearing_occurred:
progress['percentage'] = 0.9
progress['message'] = "Hearing Requested."
elif grant.is_paid:
progress['percentage'] = 1.0
if grant.is_direct_deposit == None:
progress['message'] = "Grant Completed."
elif grant.is_direct_deposit:
if grant.pay_date:
progress['message'] = "Funds Direct Deposited on " + utc_to_east_date(grant.pay_date)
else:
progress['message'] = "Funds Direct Deposited into Your Account"
else:
progress['message'] = "Check Written"
elif grant.receipts_submitted:
progress['percentage'] = 0.8
progress['message'] = "Receipts Processing"
elif grant.council_approved:
progress['percentage'] = 0.6
progress['message'] = "Submit Receipts"
elif grant.small_grant_is_reviewed:
progress['percentage'] = 0.4
progress['message'] = "Docketed for Council Vote"
else:
progress['percentage'] = 0.2
progress['message'] = "Application Being Reviewed"
# Retroactive non-small grant
else:
if grant.hearing_requested and not grant.hearing_occurred:
progress['percentage'] = 0.9
progress['message'] = "Hearing Requested."
elif grant.is_paid:
progress['percentage'] = 1.0
if grant.is_direct_deposit == None:
progress['message'] = "Grant Completed."
elif grant.is_direct_deposit:
if grant.pay_date:
progress['message'] = "Funds Direct Deposited on " + utc_to_east_date(grant.pay_date)
else:
progress['message'] = "Funds Direct Deposited into Your Account"
else:
progress['message'] = "Check Written"
elif grant.receipts_submitted:
progress['percentage'] = 0.81
progress['message'] = "Receipts Processing"
elif grant.council_approved:
progress['percentage'] = 0.65
progress['message'] = "Submit Receipts"
elif grant.interview_occurred:
progress['percentage'] = 0.49
progress['message'] = "Docketed for Council Vote"
elif grant.interview_schedule_date:
progress['percentage'] = 0.33
progress['message'] = "Interview scheduled for " + utc_to_east_datetime(grant.interview_schedule_date)
else:
progress['percentage'] = 0.17
progress['message'] = "Interview being scheduled"
# Render grant status page to user
return render_template("grant_status.html", grant=grant, progress=progress, editable=editable)
@app.route('/grant/<grant_id>/application')
def grant_application(grant_id):
""" Retrieves the original grant application for applicants to review """
# Verify that a grant id was specified
if not grant_id:
return "Error: No Grant ID specified"
# Query for grant information
grant = Grant.query.filter_by(grant_id=grant_id.upper()).first()
# Check if grant exists in database
if not grant:
return "Error: Grant does not exist."
# Render application page to user
return render_template("grant_application.html", grant=grant)
@app.route('/grant/<grant_id>/allocations')
def grant_allocations(grant_id):
""" Retrieves the categories and amounts allocated for this grant """
# Verify that a grant id was specified
if not grant_id:
return "Error: No Grant ID specified"
# Query for grant information
grant = Grant.query.filter_by(grant_id=grant_id.upper()).first()
# Check if grant exists in database
if not grant:
return "Error: Grant does not exist."
# Ensure that the council has voted on this before displaying
if not grant.council_approved:
return "This information is not yet available."
# Render application page to user
return render_template("grant_allocations.html", grant=grant)
@app.route('/interview')
@login_required
def interviews():
""" Displays a searchable list of grants eligible for interviews """
# Get list of all grants eligible for interviews
grants = Grant.query.filter_by(interview_occurred=False, is_small_grant=False).all()
# Render page to user
return render_template("interviews.html", grants=grants)
@app.route('/interview/<grant_id>', methods=['GET','POST'])
@login_required
def grant_interview(grant_id):
""" Displays interview page for FiCom Members to conduct grant interviews and processes responses """
# Verify that a grant id was specified
if not grant_id:
return "Error: No Grant ID specified"
# Query for grant information
grant = Grant.query.filter_by(grant_id=grant_id.upper()).first()
# Check if grant exists in database
if not grant:
return "Error: Grant does not exist."
# Check if we need to return to the grants pack review page
review = request.args.get('review')
# User is requesting the interview form
if request.method == 'GET':
# If the grant is a small grant, forward to right place
if grant.is_small_grant:
return redirect(url_for('small_grant_review', grant_id=grant.grant_id, review=review))
# Calculate a suggested receipts due date
if grant.project_end:
grant.receipts_due = grant.project_end + timedelta(weeks=2)
else:
grant.receipts_due = datetime.now() + timedelta(weeks=2)
# Render page to user
return render_template('interview_grant.html', grant=grant, review=review)
# User is submitting the form data
else:
# Get Relevant Form Data
if request.form.get('interviewer_notes'): grant.interviewer_notes = request.form.get('interviewer_notes')
if request.form.get('food_allocated'): grant.food_allocated = request.form.get('food_allocated', type=float)
if request.form.get('food_allocated_notes'): grant.food_allocated_notes = request.form.get('food_allocated_notes')
if request.form.get('travel_allocated'): grant.travel_allocated = request.form.get('travel_allocated', type=float)
if request.form.get('travel_allocated_notes'): grant.travel_allocated_notes = request.form.get('travel_allocated_notes')
if request.form.get('publicity_allocated'): grant.publicity_allocated = request.form.get('publicity_allocated', type=float)
if request.form.get('publicity_allocated_notes'): grant.publicity_allocated_notes = request.form.get('publicity_allocated_notes')
if request.form.get('materials_allocated'): grant.materials_allocated = request.form.get('materials_allocated', type=float)
if request.form.get('materials_allocated_notes'): grant.materials_allocated_notes = request.form.get('materials_allocated_notes')
if request.form.get('venue_allocated'): grant.venue_allocated = request.form.get('venue_allocated', type=float)
if request.form.get('venue_allocated_notes'): grant.venue_allocated_notes = request.form.get('venue_allocated_notes')
if request.form.get('decorations_allocated'): grant.decorations_allocated = request.form.get('decorations_allocated', type=float)
if request.form.get('decorations_allocated_notes'): grant.decorations_allocated_notes = request.form.get('decorations_allocated_notes')
if request.form.get('media_allocated'): grant.media_allocated = request.form.get('media_allocated', type=float)
if request.form.get('media_allocated_notes'): grant.media_allocated_notes = request.form.get('media_allocated_notes')
if request.form.get('admissions_allocated'): grant.admissions_allocated = request.form.get('admissions_allocated', type=float)
if request.form.get('admissions_allocated_notes'): grant.admissions_allocated_notes = request.form.get('admissions_allocated_notes')
if request.form.get('hupd_allocated'): grant.hupd_allocated = request.form.get('hupd_allocated', type=float)
if request.form.get('hupd_allocated_notes'): grant.hupd_allocated_notes = request.form.get('hupd_allocated_notes')
if request.form.get('personnel_allocated'): grant.personnel_allocated = request.form.get('personnel_allocated', type=float)
if request.form.get('personnel_allocated_notes'): grant.personnel_allocated_notes = request.form.get('personnel_allocated_notes')
if request.form.get('other_allocated'): grant.other_allocated = request.form.get('other_allocated', type=float)
if request.form.get('receipts_due'): grant.receipts_due = datetime.strptime(request.form.get('receipts_due'), '%Y-%m-%d')
if request.form.get('other_allocated_notes'): grant.other_allocated_notes = request.form.get('other_allocated_notes')
if request.form.get('is_collaboration_confirmed'): grant.is_collaboration_confirmed = request.form.get('is_collaboration_confirmed')
if not review:
# Add Relevant Meta Data
grant.interview_occurred = True
grant.interview_date = datetime.now(utc)
# Add interviewer information for grant record
grant.interviewer = current_user.first_name + " " + current_user.last_name
# Send notification email to user
email_interview_completed(grant)
# Generate Flashed Success Message
flash('\'' + grant.organization + '\' Interview Submitted Successfully', 'success')
else:
# Generate Flashed Success Message
flash('\'' + grant.organization + '\' Interview Updated Successfully', 'success')
# Commit Changes to Database
db.session.commit()
if review:
return redirect(url_for('grants_pack_edit_pack', grants_pack=review))
else:
return redirect(url_for('interviews'))
@app.route('/small-grant-review')
@login_required
def small_grants():
""" Displays a list of grants eligible for small-grant processing """
# Get list of all small-grant elligible grants
grants = Grant.query.filter_by(is_small_grant=True, small_grant_is_reviewed=False).all()
# Render page to user
return render_template("small_grants.html", grants=grants)
@app.route('/small-grant-review/<grant_id>', methods=['GET','POST'])
@login_required
def small_grant_review(grant_id):
""" Displays review page for FiCom Members to conduct small grant reviews and processes responses """
# Verify that a grant id was specified
if not grant_id:
return "Error: No Grant ID specified"
# Query for grant information
grant = Grant.query.filter_by(grant_id=grant_id.upper()).first()
# Check if grant exists in database
if not grant:
return "Error: Grant does not exist."
# Check if we need to return to the grants pack review page
review = request.args.get('review')
# User is requesting the interview form
if request.method == 'GET':
# If the grant is not a small grant, forward to right place
if not grant.is_small_grant:
return redirect(url_for('grant_interview', grant_id=grant.grant_id, review=review))
# Render page to user
return render_template('review_small_grant.html', grant=grant, review=review)
# User is submitting the form data
else:
# Get Relevant Form Data
if request.form.get('interviewer_notes'): grant.interviewer_notes = request.form.get('interviewer_notes')
if request.form.get('food_allocated'): grant.food_allocated = request.form.get('food_allocated', type=float)
if request.form.get('food_allocated_notes'): grant.food_allocated_notes = request.form.get('food_allocated_notes')
if request.form.get('publicity_allocated'): grant.publicity_allocated = request.form.get('publicity_allocated', type=float)
if request.form.get('publicity_allocated_notes'): grant.publicity_allocated_notes = request.form.get('publicity_allocated_notes')
if request.form.get('is_collaboration_confirmed'): grant.is_collaboration_confirmed = request.form.get('is_collaboration_confirmed')
if request.form.get('receipts_due'): grant.receipts_due = datetime.strptime(request.form.get('receipts_due'), '%Y-%m-%d')
# Add Relevant Meta Data
grant.small_grant_is_reviewed = True
grant.small_grant_review_date = datetime.now(utc)
# Add interviewer information for grant record
grant.small_grant_reviewer = current_user.first_name + " " + current_user.last_name
# Commit Changes to Databse
db.session.commit()
# Generate Flashed Success Message
flash('\'' + grant.organization + '\' Small Grant Review Submitted Successfully', 'success')
if review:
return redirect(url_for('grants_pack_edit_pack', grants_pack=review))
else:
return redirect(url_for('small_grants'))
@app.route('/grants-pack/edit', methods=['GET','POST'])
@login_required
@admin_required
def grants_pack_edit(grants_pack=None):
""" Displays page to review and select grants that are elligible for adding to a grants pack,
and processes updates POSTed by the page """
# User is requesting the form page
if request.method == 'GET':
# Create Variable for holding grants_pack row from DB
grants_pack_db = None
if grants_pack:
# If user-specified grants pack does not exist, return an error
grants_pack_db = Grants_Week.query.filter_by(grant_week=grants_pack).first()
if not grants_pack_db:
return "Grants Pack " + grants_pack + " does not exist.",400
# Default to current Grants Pack
else:
# Get Current Grants Pack
council_semester = Config.query.filter_by(key='council_semester').first()
current_week = Config.query.filter_by(key='grant_week').first()
grants_pack = council_semester.value + '-' + current_week.value
grants_pack_db = Grants_Week.query.filter_by(grant_week=grants_pack).first()
# Ensure that the grants pack has not been locked (by approved council vote)
if grants_pack_db.grants_pack_finalized:
return "This grants pack has already been finalized and approved by the council."
# query for all grants currently without a grants pack
orphan_grants = Grant.query.filter(OR(AND(Grant.grants_pack==None,Grant.interview_occurred==True), AND(Grant.grants_pack==None,Grant.small_grant_is_reviewed==True))).all()
child_grants = Grant.query.filter_by(grants_pack=grants_pack).all()
# Render page to user
return render_template('grants_pack_edit.html', orphan_grants=orphan_grants, child_grants=child_grants, grants_pack=grants_pack)
# User is POSTing form data updates back to the server
else:
# Ensure that that grant_pack value was sent
grants_pack = request.json.get('grants_pack')
if grants_pack:
# Ensure that at least one grant was sent
grants = request.json.get('grants')
if grants and len(grants) > 0:
# Ensure that the grants pack has not been locked (by approved council vote)
grants_pack_db = Grants_Week.query.filter_by(grant_week=grants_pack).first()
if grants_pack_db.grants_pack_finalized:
return "This grants pack has already been finalized and approved by the council.",400
# For each grant, update its value in the database
for grant in grants:
grant_id = grant.get('grant_id')
selected = grant.get('selected')
# Ensure that grant_id was provided and selected is valid
if grant_id and selected != None:
# This slightly ugly syntax uses far fewer SQL calls than the alternative
if selected:
Grant.query.filter(Grant.grant_id==grant_id).update({ "grants_pack" : grants_pack })
else:
Grant.query.filter(Grant.grant_id==grant_id).update({ "grants_pack" : None })
db.session.commit()
return "OK"
# On failure, return error with HTTP 400 "Bad Request" Status Code
return 'Error',400
@app.route('/grants-pack/<grants_pack>/edit')
@login_required
@admin_required
def grants_pack_edit_pack(grants_pack):
""" Allows editing of a specific grants pack """
return grants_pack_edit(grants_pack)
@app.route('/grants-pack/cuts', methods=['GET','POST'])
@login_required
@admin_required
def grants_pack_cuts(grants_pack=None):
""" Displays a page to the user with the calculated cut amounts """
# User is requesting the form page
if request.method == 'GET':
# Create Variable for holding grants_pack row from DB
grants_pack_db = None
if grants_pack:
# If user-specified grants pack does not exist, return an error
grants_pack_db = Grants_Week.query.filter_by(grant_week=grants_pack).first()
if not grants_pack_db:
return "Grants Pack " + grants_pack + " does not exist.",400
# Default to current Grants Pack
else:
# Get Current Grants Pack
council_semester = Config.query.filter_by(key='council_semester').first()
current_week = Config.query.filter_by(key='grant_week').first()
grants_pack = council_semester.value + '-' + current_week.value
grants_pack_db = Grants_Week.query.filter_by(grant_week=grants_pack).first()
# Ensure that the grants pack has not been locked (by approved council vote)
if grants_pack_db.grants_pack_finalized:
return "This grants pack has already been finalized and approved by the council."
# Get all grants in grants pack from the DB
grants = Grant.query.filter_by(grants_pack=grants_pack).all()
# Get this grants pack's budget
budget = grants_pack_db.budget
# Calculate expendature for this week
allocated = 0
cut_immune = 0
for grant in grants:
# Sum grant
grant.amount_allocated = 0
if grant.food_allocated: grant.amount_allocated += grant.food_allocated
if grant.travel_allocated: grant.amount_allocated += grant.travel_allocated
if grant.publicity_allocated: grant.amount_allocated += grant.publicity_allocated
if grant.materials_allocated: grant.amount_allocated += grant.materials_allocated
if grant.venue_allocated: grant.amount_allocated += grant.venue_allocated
if grant.decorations_allocated: grant.amount_allocated += grant.decorations_allocated
if grant.media_allocated: grant.amount_allocated += grant.media_allocated
if grant.admissions_allocated: grant.amount_allocated += grant.admissions_allocated
if grant.hupd_allocated: grant.amount_allocated += grant.hupd_allocated
if grant.personnel_allocated: grant.amount_allocated += grant.personnel_allocated
if grant.other_allocated: grant.amount_allocated += grant.other_allocated
# Add to allocated costs
allocated += grant.amount_allocated
# If immune from cuts, add to cut_immune
if grant.is_collaboration_confirmed:
cut_immune += grant.amount_allocated
# See if we went overbudget, and calculate cut percentage
cuts = 0
if allocated > budget:
deductable = allocated - cut_immune
remaining = budget - cut_immune
cuts = 1.0 - (remaining / deductable)
# Apply the recommended cuts for each grant
for grant in grants:
if grant.is_collaboration_confirmed:
grant.percentage_cut = 0.0
else:
grant.percentage_cut = cuts
percentage_cut = round(100 * cuts, 2)
cut_multiplier = 1.0 - cuts
return render_template('grants_pack_cuts.html', grants=grants, grants_pack=grants_pack, budget=budget, allocated=allocated, cut_immune=cut_immune, percentage_cut=percentage_cut, cut_multiplier=cut_multiplier)
# User is POSTing form data updates back to the server
else:
# Format posted data and get grant_pack value
values = dict(request.form)
grants_pack = values.pop('grants_pack')[0]
# Update Weekly running total while calculating grants
grant_week = Grants_Week.query.filter_by(grant_week=grants_pack).first()
grant_week.allocated = 0.0
grant_week.requested = 0.0
# Process each grant
for grant_id,cut in values.items():
# Get the percentage gut in the correct format
cut = float(cut[0])
# Update grant record with cut and final allocated amount
grant = Grant.query.filter_by(grant_id=grant_id).first()
# Sum grant
allocated = 0
if grant.food_allocated: allocated += grant.food_allocated
if grant.travel_allocated: allocated += grant.travel_allocated
if grant.publicity_allocated: allocated += grant.publicity_allocated
if grant.materials_allocated: allocated += grant.materials_allocated
if grant.venue_allocated: allocated += grant.venue_allocated