-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2897 lines (2453 loc) · 118 KB
/
Copy pathapp.py
File metadata and controls
2897 lines (2453 loc) · 118 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
import os
import json
import uuid
import logging
from logging.handlers import RotatingFileHandler
import traceback
from datetime import datetime
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager, create_access_token, verify_jwt_in_request, get_jwt_identity, jwt_required
from functools import wraps
from io import BytesIO
import qrcode
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from sqlalchemy import func
from config import Config
from models import db, User, Submission, FormConfig, ValidationSchema, Application, BasicInfo, EducationalInfo, FamilyInfo, IncomeInfo, CourseInfo, Widget, EmailQueue, OTPVerification, EditToken
from helpers import save_normalized_application
from widget_query_builder import get_widget_metadata, execute_widget_query, get_widget_candidate_ids, get_widget_segment_candidate_ids
# Role-based access control decorators
def require_role(*allowed_roles):
"""Decorator to require specific roles for an endpoint"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
verify_jwt_in_request()
user_id = int(get_jwt_identity())
user = User.query.get(user_id)
if not user:
return jsonify({'msg': 'User not found'}), 401
if user.role not in allowed_roles:
return jsonify({'msg': 'Access denied. Insufficient permissions'}), 403
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
"""Decorator for admin-only endpoints"""
@wraps(f)
def decorated_function(*args, **kwargs):
verify_jwt_in_request()
user_id = int(get_jwt_identity())
user = User.query.get(user_id)
if not user:
return jsonify({'msg': 'User not found'}), 401
if not user.is_admin():
return jsonify({'msg': 'Admin access required'}), 403
return f(*args, **kwargs)
return decorated_function
def can_view_applications(f):
"""Decorator for endpoints that allow viewing applications (all roles)"""
@wraps(f)
def decorated_function(*args, **kwargs):
verify_jwt_in_request()
user_id = int(get_jwt_identity())
user = User.query.get(user_id)
if not user:
return jsonify({'msg': 'User not found'}), 401
if not user.can_view_applications():
return jsonify({'msg': 'Access denied'}), 403
return f(*args, **kwargs)
return decorated_function
def can_edit_applications(f):
"""Decorator for endpoints that allow editing applications (admin and panel_member)"""
@wraps(f)
def decorated_function(*args, **kwargs):
verify_jwt_in_request()
user_id = int(get_jwt_identity())
user = User.query.get(user_id)
if not user:
return jsonify({'msg': 'User not found'}), 401
if not user.can_edit_applications():
return jsonify({'msg': 'Access denied. Edit permission required'}), 403
return f(*args, **kwargs)
return decorated_function
def send_edit_link_email(email, name, edit_link, candidate_id):
"""Send edit link email to user"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_host = os.environ.get('SMTP_HOST', 'smtp.gmail.com')
smtp_port = int(os.environ.get('SMTP_PORT', 587))
smtp_user = os.environ.get('SMTP_USER')
smtp_password = os.environ.get('SMTP_PASSWORD')
sender_name = os.environ.get('SMTP_SENDER_NAME', 'VGLUG Training Program')
if not smtp_user or not smtp_password:
return False, 'Email service not configured'
try:
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Edit Your VGLUG Application'
msg['From'] = f'{sender_name} <{smtp_user}>'
msg['To'] = email
text_content = f"""
Hello {name},
You requested to edit your VGLUG Training Program application.
Click the link below to edit your application:
{edit_link}
This link is valid for 6 hours and can only be used once.
Application ID: {candidate_id}
If you did not request this, please ignore this email.
---
VGLUG Training Program
https://vglug.org
"""
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="text-align: center; margin-bottom: 30px;">
<h2 style="color: #00BAED; margin: 0;">VGLUG Training Program</h2>
<p style="color: #666; margin: 5px 0 0 0;">Edit Your Application</p>
</div>
<div style="background: #f8f9fa; border-radius: 12px; padding: 30px; margin-bottom: 20px;">
<p style="margin: 0 0 15px 0;">Hello <strong>{name}</strong>,</p>
<p style="margin: 0 0 20px 0;">You requested to edit your VGLUG Training Program application.</p>
<div style="text-align: center; margin: 25px 0;">
<a href="{edit_link}" style="background: #00BAED; color: white; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: bold; display: inline-block;">Edit My Application</a>
</div>
<p style="margin: 20px 0 0 0; color: #666; font-size: 14px;">
<strong>Application ID:</strong> {candidate_id}<br>
<strong>Link valid for:</strong> 6 hours
</p>
</div>
<div style="color: #666; font-size: 14px;">
<p style="margin: 0 0 10px 0;">If the button doesn't work, copy and paste this link:</p>
<p style="margin: 0 0 15px 0; word-break: break-all; color: #00BAED;">{edit_link}</p>
<p style="margin: 0; color: #999;">If you did not request this, please ignore this email.</p>
</div>
<hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
<div style="text-align: center; color: #999; font-size: 12px;">
<p style="margin: 0;">VGLUG Training Program</p>
<p style="margin: 5px 0 0 0;">https://vglug.org</p>
</div>
</body>
</html>
"""
msg.attach(MIMEText(text_content, 'plain'))
msg.attach(MIMEText(html_content, 'html'))
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_password)
server.sendmail(smtp_user, email, msg.as_string())
return True, None
except smtplib.SMTPAuthenticationError:
return False, 'Email service authentication failed'
except smtplib.SMTPRecipientsRefused:
return False, 'Invalid email address'
except smtplib.SMTPException as e:
return False, f'Failed to send email: {str(e)}'
except Exception as e:
return False, f'Failed to send email: {str(e)}'
def setup_logging(app):
"""Configure rotating file logging for the application"""
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'application_logs')
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'app.log')
# Rotating file handler: 10MB max per file, keep 5 backup files
file_handler = RotatingFileHandler(
log_file,
maxBytes=10 * 1024 * 1024, # 10MB
backupCount=5
)
file_handler.setLevel(logging.INFO)
# Log format
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler.setFormatter(formatter)
# Add handler to Flask app logger
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
# Also add to werkzeug logger (request logs)
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.addHandler(file_handler)
# Log startup
app.logger.info('Application started - Logging initialized')
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
# Setup logging
setup_logging(app)
db.init_app(app)
CORS(app,
origins=[
'https://t2026.vglug.org',
'http://localhost:5001',
'http://localhost:82', # ✅ Add this
'http://localhost:5173',
'http://localhost:3000',
'http://127.0.0.1:5173',
'http://127.0.0.1:5000',
'http://127.0.0.1:5001',
'http://localhost:5174'
],
supports_credentials=True,
allow_headers=['Content-Type', 'Authorization'],
methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
Migrate(app, db)
jwt = JWTManager(app)
# JWT error handlers - ensure CORS headers are applied to error responses
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jsonify({'msg': 'Token has expired'}), 401
@jwt.invalid_token_loader
def invalid_token_callback(error):
return jsonify({'msg': 'Invalid token'}), 401
@jwt.unauthorized_loader
def missing_token_callback(error):
return jsonify({'msg': 'Missing authorization token'}), 401
@jwt.token_verification_failed_loader
def token_verification_failed_callback(jwt_header, jwt_payload):
return jsonify({'msg': 'Token verification failed'}), 401
with app.app_context():
db.create_all()
@app.route('/auth/register', methods=['POST'])
def register():
data = request.get_json() or {}
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'msg':'email and password required'}), 400
if User.query.filter_by(email=email).first():
return jsonify({'msg':'user exists'}), 400
user = User(email=email)
user.set_password(password)
db.session.add(user)
db.session.commit()
return jsonify({'msg':'registered'}), 201
@app.route('/auth/login', methods=['POST'])
def login():
data = request.get_json() or {}
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'msg':'email and password required'}), 400
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return jsonify({'msg':'invalid credentials'}), 401
token = create_access_token(identity=str(user.id))
return jsonify({'access_token': token}), 200
@app.route('/form', methods=['GET'])
def get_form():
# Get active form configuration from database
active_form = FormConfig.query.filter_by(is_active=True).order_by(FormConfig.year.desc(), FormConfig.version.desc()).first()
if active_form:
return jsonify(active_form.config_json), 200
# Fallback to file if no active form in database
path = os.path.join(os.path.dirname(__file__), '..', 'markdown', 'dynamic_form_json.json')
try:
with open(path, 'r') as f:
data = json.load(f)
return jsonify(data), 200
except Exception as e:
return jsonify({'msg':'cannot load form', 'error': str(e)}), 500
@app.route('/send-otp', methods=['POST'])
def send_otp():
"""Send OTP to email for verification before form access"""
try:
from otp_service import otp_service
from datetime import timedelta
data = request.get_json() or {}
email = data.get('email', '').strip()
if not email:
return jsonify({'success': False, 'message': 'Email address is required'}), 400
# Validate and normalize email
is_valid, error = otp_service.validate_email(email)
if not is_valid:
return jsonify({'success': False, 'message': error}), 400
normalized_email = otp_service.normalize_email(email)
# Rate limiting: Max 3 OTPs per email per 10 minutes
ten_minutes_ago = datetime.utcnow() - timedelta(minutes=10)
recent_otps = OTPVerification.query.filter(
OTPVerification.email == normalized_email,
OTPVerification.created_at > ten_minutes_ago
).count()
if recent_otps >= 3:
app.logger.warning(f'OTP rate limit exceeded for {normalized_email}')
return jsonify({
'success': False,
'message': 'Too many OTP requests. Please try again after 10 minutes.'
}), 429
# Generate OTP
otp_code = otp_service.generate_otp(6)
# Get client IP for tracking
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
if client_ip:
client_ip = client_ip.split(',')[0].strip()
# Create OTP record (expires in 5 minutes)
otp_record = OTPVerification(
email=normalized_email,
otp_code=otp_code,
expires_at=datetime.utcnow() + timedelta(minutes=5),
ip_address=client_ip
)
db.session.add(otp_record)
db.session.commit()
# Send OTP via email
success, error = otp_service.send_otp(normalized_email, otp_code)
if success:
app.logger.info(f'OTP sent successfully to {normalized_email}')
return jsonify({
'success': True,
'message': 'OTP sent successfully to your email',
'email': normalized_email # Return normalized email for frontend
}), 200
else:
app.logger.error(f'Failed to send OTP to {normalized_email}: {error}')
return jsonify({
'success': False,
'message': error or 'Failed to send OTP'
}), 500
except Exception as e:
app.logger.error(f'Error in send_otp: {str(e)}')
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/verify-otp', methods=['POST'])
def verify_otp():
"""Verify OTP and grant form access"""
try:
from otp_service import otp_service
data = request.get_json() or {}
email = data.get('email', '').strip()
otp = data.get('otp', '').strip()
if not email or not otp:
return jsonify({'success': False, 'message': 'Email and OTP are required'}), 400
normalized_email = otp_service.normalize_email(email)
# Find the most recent unexpired OTP for this email
otp_record = OTPVerification.query.filter(
OTPVerification.email == normalized_email,
OTPVerification.expires_at > datetime.utcnow(),
OTPVerification.verified == False
).order_by(OTPVerification.created_at.desc()).first()
if not otp_record:
return jsonify({
'success': False,
'message': 'OTP expired or not found. Please request a new OTP.'
}), 400
# Check attempt limit (max 5 attempts)
if otp_record.attempts >= 5:
return jsonify({
'success': False,
'message': 'Too many failed attempts. Please request a new OTP.'
}), 400
# Increment attempts
otp_record.attempts += 1
db.session.commit()
# Verify OTP
if otp_record.otp_code != otp:
remaining = 5 - otp_record.attempts
return jsonify({
'success': False,
'message': f'Invalid OTP. {remaining} attempt(s) remaining.'
}), 400
# Mark as verified
otp_record.verified = True
db.session.commit()
app.logger.info(f'OTP verified successfully for {normalized_email}')
return jsonify({
'success': True,
'message': 'Email verified successfully',
'verified_email': normalized_email
}), 200
except Exception as e:
app.logger.error(f'Error in verify_otp: {str(e)}')
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/check-email', methods=['POST'])
def check_email():
"""Check if email is already registered with an application"""
try:
from otp_service import otp_service
data = request.get_json() or {}
email = data.get('email', '').strip()
if not email:
return jsonify({'success': False, 'message': 'Email is required'}), 400
normalized_email = otp_service.normalize_email(email)
# Check if email exists in BasicInfo
existing = BasicInfo.query.filter(
func.lower(BasicInfo.email) == normalized_email
).first()
if existing:
return jsonify({
'success': True,
'registered': True,
'message': 'This email is already registered with an application.'
}), 200
else:
return jsonify({
'success': True,
'registered': False
}), 200
except Exception as e:
app.logger.error(f'Error in check_email: {str(e)}')
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/send-edit-link', methods=['POST'])
def send_edit_link():
"""Send an edit link to a registered email"""
try:
from otp_service import otp_service
from datetime import timedelta
import secrets
data = request.get_json() or {}
email = data.get('email', '').strip()
if not email:
return jsonify({'success': False, 'message': 'Email is required'}), 400
normalized_email = otp_service.normalize_email(email)
# Find the application with this email
basic_info = BasicInfo.query.filter(
func.lower(BasicInfo.email) == normalized_email
).first()
if not basic_info:
return jsonify({
'success': False,
'message': 'No application found with this email'
}), 404
# Rate limiting: Max 3 edit links per email per hour
one_hour_ago = datetime.utcnow() - timedelta(hours=1)
recent_tokens = EditToken.query.filter(
EditToken.email == normalized_email,
EditToken.created_at > one_hour_ago
).count()
if recent_tokens >= 3:
app.logger.warning(f'Edit link rate limit exceeded for {normalized_email}')
return jsonify({
'success': False,
'message': 'Too many edit link requests. Please try again after an hour.'
}), 429
# Generate secure token
token = secrets.token_urlsafe(32)
# Get client IP for tracking
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
if client_ip:
client_ip = client_ip.split(',')[0].strip()
# Create edit token (expires in 6 hours)
edit_token = EditToken(
token=token,
candidate_id=basic_info.candidate_id,
email=normalized_email,
expires_at=datetime.utcnow() + timedelta(hours=6),
ip_address=client_ip
)
db.session.add(edit_token)
db.session.commit()
# Build edit link URL
frontend_url = os.environ.get('FRONTEND_URL', 'http://localhost:5173')
edit_link = f"{frontend_url}/edit/{token}"
# Send email with edit link
success, error = send_edit_link_email(normalized_email, basic_info.full_name, edit_link, basic_info.candidate_id)
if success:
app.logger.info(f'Edit link sent to {normalized_email}')
return jsonify({
'success': True,
'message': 'Edit link has been sent to your email. It is valid for 6 hours.'
}), 200
else:
app.logger.error(f'Failed to send edit link to {normalized_email}: {error}')
return jsonify({
'success': False,
'message': error or 'Failed to send edit link email'
}), 500
except Exception as e:
app.logger.error(f'Error in send_edit_link: {str(e)}')
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/validate-edit-token/<token>', methods=['GET'])
def validate_edit_token(token):
"""Validate edit token and return application data"""
try:
# Find the token
edit_token = EditToken.query.filter_by(token=token).first()
if not edit_token:
return jsonify({
'success': False,
'message': 'Invalid edit link'
}), 404
# Check if expired
if datetime.utcnow() > edit_token.expires_at:
return jsonify({
'success': False,
'message': 'This edit link has expired. Please request a new one.'
}), 400
# Check if already used
if edit_token.used:
return jsonify({
'success': False,
'message': 'This edit link has already been used.'
}), 400
# Get application data
application = Application.query.filter_by(candidate_id=edit_token.candidate_id).first()
if not application:
return jsonify({
'success': False,
'message': 'Application not found'
}), 404
# Build form data from normalized tables
form_data = {}
if application.basic_info:
bi = application.basic_info
form_data.update({
'full_name': bi.full_name,
'dob': bi.dob.isoformat() if bi.dob else None,
'gender': bi.gender,
'email': bi.email,
'differently_abled': bi.differently_abled,
'contact': bi.contact,
'contact_as_whatsapp': bi.contact_as_whatsapp,
'whatsapp_contact': bi.whatsapp_contact,
'has_laptop': bi.has_laptop,
'laptop_ram': bi.laptop_ram,
'laptop_processor': bi.laptop_processor
})
if application.educational_info:
ei = application.educational_info
form_data.update({
'college_name': ei.college_name,
'degree': ei.degree,
'department': ei.department,
'year': ei.year,
'tamil_medium': ei.tamil_medium,
'6_to_8_govt_school': ei.six_to_8_govt_school,
'6_to_8_school_name': ei.six_to_8_school_name,
'9_to_10_govt_school': ei.nine_to_10_govt_school,
'9_to_10_school_name': ei.nine_to_10_school_name,
'11_to_12_govt_school': ei.eleven_to_12_govt_school,
'11_to_12_school_name': ei.eleven_to_12_school_name,
'present_work': ei.present_work,
'received_scholarship': ei.received_scholarship,
'scholarship_details': ei.scholarship_details,
'transport_mode': ei.transport_mode,
'vglug_applied_before': ei.vglug_applied_before
})
if application.family_info:
fi = application.family_info
form_data.update({
'family_environment': fi.family_environment,
'single_parent_info': fi.single_parent_info,
'family_members_count': fi.family_members_count,
'family_members_details': fi.family_members_details,
'earning_members_count': fi.earning_members_count,
'earning_members_details': fi.earning_members_details,
'guardian_details': fi.guardian_details
})
if application.income_info:
ii = application.income_info
form_data.update({
'total_family_income': ii.total_family_income,
'own_land_size': ii.own_land_size,
'house_ownership': ii.house_ownership,
'full_address': ii.full_address,
'pincode': ii.pincode,
'district': ii.district
})
if application.course_info:
ci = application.course_info
form_data.update({
'preferred_course': ci.preferred_course,
'training_benefit': ci.training_benefit,
'heard_about_vglug': ci.heard_about_vglug,
'participated_in_vglug_events': ci.participated_in_vglug_events
})
return jsonify({
'success': True,
'candidate_id': edit_token.candidate_id,
'email': edit_token.email,
'form_data': form_data,
'expires_at': edit_token.expires_at.isoformat()
}), 200
except Exception as e:
app.logger.error(f'Error in validate_edit_token: {str(e)}')
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/update-application/<token>', methods=['PUT'])
def update_application_via_token(token):
"""Update an existing application using edit token"""
try:
# Find and validate the token
edit_token = EditToken.query.filter_by(token=token).first()
if not edit_token:
return jsonify({'success': False, 'message': 'Invalid edit link'}), 404
if datetime.utcnow() > edit_token.expires_at:
return jsonify({'success': False, 'message': 'This edit link has expired'}), 400
if edit_token.used:
return jsonify({'success': False, 'message': 'This edit link has already been used'}), 400
# Get payload
payload = request.get_json() or {}
# Get application
application = Application.query.filter_by(candidate_id=edit_token.candidate_id).first()
if not application:
return jsonify({'success': False, 'message': 'Application not found'}), 404
# Update application data using helper function
from helpers import update_normalized_application
update_normalized_application(application.candidate_id, payload)
# Mark token as used
edit_token.used = True
edit_token.used_at = datetime.utcnow()
db.session.commit()
app.logger.info(f'Application {edit_token.candidate_id} updated via edit link')
return jsonify({
'success': True,
'message': 'Application updated successfully',
'candidate_id': edit_token.candidate_id
}), 200
except Exception as e:
app.logger.error(f'Error in update_application: {str(e)}')
db.session.rollback()
return jsonify({'success': False, 'message': 'Server error'}), 500
@app.route('/submit', methods=['POST'])
def submit():
try:
payload = request.get_json() or {}
app.logger.info(f"New application submission received")
# Generate UUID and candidate ID
submission_uuid = str(uuid.uuid4())
now = datetime.utcnow()
current_year = now.strftime('%Y')
# Count applications for current year to generate sequential number starting from 1001
count_year = Application.query.filter(
Application.candidate_id.like(f'CID{current_year}%')
).count()
candidate_id = f'CID{current_year}{count_year + 1001:04d}'
# Get active form config
active_form_config = FormConfig.query.filter_by(is_active=True).first()
form_config_id = active_form_config.id if active_form_config else None
# Save to normalized database structure
application = save_normalized_application(
structured_data=payload,
candidate_id=candidate_id,
uuid=submission_uuid,
form_config_id=form_config_id
)
# Also save to legacy Submission table for backwards compatibility
submission = Submission(
uuid=submission_uuid,
candidate_id=candidate_id,
data=payload
)
db.session.add(submission)
db.session.commit()
# Queue verification email for background processing via Celery
email_queued = False
try:
from email_service import email_service
if email_service.is_configured() and application.basic_info and application.basic_info.email:
# Create email queue record
email_record = EmailQueue(
candidate_id=candidate_id,
to_email=application.basic_info.email,
recipient_name=application.basic_info.full_name,
email_type='verification',
status='pending'
)
db.session.add(email_record)
db.session.commit()
# Queue the Celery task
try:
from tasks import send_verification_email_task
send_verification_email_task.delay(email_record.id)
email_queued = True
app.logger.info(f"Email queued for {candidate_id} (queue_id: {email_record.id})")
except Exception as celery_error:
# Celery not available, fall back to direct send
app.logger.warning(f"Celery not available, sending directly: {str(celery_error)}")
success, error = email_service.send_verification_email(
to_email=application.basic_info.email,
candidate_name=application.basic_info.full_name,
candidate_id=candidate_id
)
email_record.status = 'sent' if success else 'failed'
email_record.sent_at = datetime.utcnow() if success else None
email_record.error_message = error if not success else None
if application.basic_info:
application.basic_info.email_sent_at = datetime.utcnow()
application.basic_info.email_verified = success
application.basic_info.email_verified_at = datetime.utcnow() if success else None
application.basic_info.email_error = error if not success else None
db.session.commit()
email_queued = success
except Exception as e:
# Don't fail the submission if email queueing fails
app.logger.error(f"Email queue exception for {candidate_id}: {str(e)}")
return jsonify({
'msg': 'submitted',
'id': application.id,
'uuid': submission_uuid,
'candidate_id': candidate_id,
'email_queued': email_queued
}), 201
except Exception as e:
app.logger.error(f"Submission error: {traceback.format_exc()}")
return jsonify({'msg':'submission failed', 'error': str(e)}), 500
@app.route('/download-pdf/<submission_uuid>', methods=['GET'])
def download_pdf(submission_uuid):
# Get from Application table (normalized structure)
application = Application.query.filter_by(uuid=submission_uuid).first()
if not application:
return jsonify({'msg': 'Application not found'}), 404
# Also get from Submission table for backward compatibility
submission = Submission.query.filter_by(uuid=submission_uuid).first()
# Create PDF in memory
buffer = BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=A4, topMargin=0.5*inch, bottomMargin=0.5*inch)
elements = []
styles = getSampleStyleSheet()
# Blue and White Color Theme
PRIMARY_COLOR = '#00BAED' # Blue
SECONDARY_COLOR = '#0095C8' # Darker Blue
ACCENT_COLOR = '#000000' # Black
LIGHT_BG = '#E7F7FF' # Light blue background
# Custom styles
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=22,
textColor=colors.HexColor(PRIMARY_COLOR),
spaceAfter=30,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=15,
textColor=colors.HexColor(SECONDARY_COLOR),
spaceAfter=12,
spaceBefore=12,
fontName='Helvetica-Bold',
alignment=TA_CENTER
)
# Logo
logo_path = os.path.join(os.path.dirname(__file__), 'assets', 'images', 'vglug.png')
if os.path.exists(logo_path):
logo_img = Image(logo_path, width=1.2*inch, height=1.2*inch)
logo_table = Table([[logo_img]], colWidths=[2*inch])
logo_table.setStyle(TableStyle([
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
]))
elements.append(logo_table)
elements.append(Spacer(1, 0.2*inch))
# Title
elements.append(Paragraph('VGLUG APPLICATION FORM 2025', title_style))
elements.append(Spacer(1, 0.2*inch))
# Application Number
app_num_style = ParagraphStyle(
'AppNumber',
parent=styles['Normal'],
fontSize=16,
textColor=colors.black,
spaceAfter=20,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
elements.append(Paragraph(f'Candidate ID: {application.candidate_id}', app_num_style))
elements.append(Spacer(1, 0.1*inch))
# Generate QR Code
qr = qrcode.QRCode(version=1, box_size=10, border=4)
qr.add_data(application.uuid)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color="white")
qr_buffer = BytesIO()
qr_img.save(qr_buffer, format='PNG')
qr_buffer.seek(0)
qr_image = Image(qr_buffer, width=1.5*inch, height=1.5*inch)
# Create table for QR code (centered)
qr_table = Table([[qr_image]], colWidths=[2*inch])
qr_table.setStyle(TableStyle([
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
]))
elements.append(qr_table)
elements.append(Spacer(1, 0.3*inch))
# Form data from normalized tables
basic = application.basic_info
# Candidate Info Section with improved design
elements.append(Paragraph('Candidate Information', heading_style))
# Format date properly
dob = basic.dob.strftime('%d %B %Y') if basic.dob else 'N/A'
candidate_data = [
['Name', basic.full_name or 'N/A'],
['Date of Birth', dob],
['Gender', basic.gender or 'N/A'],
['Email', basic.email or 'N/A'],
['Contact Number', basic.contact or 'N/A'],
]
candidate_table = Table(candidate_data, colWidths=[2.2*inch, 4.3*inch])
candidate_table.setStyle(TableStyle([
# Header column styling - using VGLUG maroon
('BACKGROUND', (0, 0), (0, -1), colors.HexColor(PRIMARY_COLOR)),
('TEXTCOLOR', (0, 0), (0, -1), colors.white),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (0, -1), 11),
# Data column styling
('BACKGROUND', (1, 0), (1, -1), colors.white),
('TEXTCOLOR', (1, 0), (1, -1), colors.black),
('FONTNAME', (1, 0), (1, -1), 'Helvetica'),
('FONTSIZE', (1, 0), (1, -1), 11),
# Borders and spacing - using VGLUG red
('GRID', (0, 0), (-1, -1), 1, colors.HexColor(SECONDARY_COLOR)),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('LEFTPADDING', (0, 0), (-1, -1), 12),
('RIGHTPADDING', (0, 0), (-1, -1), 12),
('TOPPADDING', (0, 0), (-1, -1), 10),
('BOTTOMPADDING', (0, 0), (-1, -1), 10),
# Alternating row colors for better readability
('ROWBACKGROUNDS', (1, 0), (1, -1), [colors.white, colors.HexColor(LIGHT_BG)]),
]))
elements.append(candidate_table)
elements.append(Spacer(1, 0.4*inch))
# Footer
footer_text = f"Generated on: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC"
footer_style = ParagraphStyle(
'Footer',
parent=styles['Normal'],
fontSize=8,
textColor=colors.grey,
alignment=TA_CENTER
)
elements.append(Paragraph(footer_text, footer_style))
# Build PDF
doc.build(elements)
buffer.seek(0)
return send_file(
buffer,
as_attachment=True,