-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1821 lines (1315 loc) · 67 KB
/
app.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
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify,abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_
from flask_migrate import Migrate
from datetime import datetime, timedelta
from werkzeug.utils import secure_filename
import os
import uuid
from flask import send_from_directory
import plotly.express as px
import plotly.graph_objects as go
from plotly.io import to_html
import pandas as pd
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
base_dir = os.path.abspath(os.path.dirname(__file__))
countries_df = pd.read_csv(os.path.join(base_dir, 'static/csv/countries.csv'), usecols=['id', 'name'])
states_df = pd.read_csv(os.path.join(base_dir, 'static/csv/states.csv'), usecols=['id', 'name', 'country_id'])
cities_df = pd.read_csv(os.path.join(base_dir, 'static/csv/cities.csv'), usecols=['id', 'name', 'state_name'])
country_codes_df = pd.read_csv(os.path.join(base_dir, 'static/csv/country-codes.csv'), usecols=['Country', 'Code'])
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
upload_folder = os.path.join(app.root_path, 'static', 'profile pic')
app.config['UPLOAD_FOLDER'] = upload_folder
app.static_folder = 'static'
UPLOAD_FOLDER = 'static/profile_pic' # Folder to store uploaded profile pictures
UPLOAD_FILE_FOLDER = os.path.join(app.root_path, 'static', 'upload_file')
app.config['UPLOAD_FILE_FOLDER'] = UPLOAD_FILE_FOLDER
ALLOWED_FILE_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3', 'wav', 'ogg', 'mp4', 'avi', 'mkv', 'doc', 'docx'}
def allowed_file_upload(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_FILE_EXTENSIONS
# Initialize the app with the extension
db.init_app(app)
migrate = Migrate(app, db)
class users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True,nullable=False)
password = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
role = db.Column(db.String(20), default='user')
uuid = db.Column(db.String(36), unique=True, nullable=False, server_default=str(uuid.uuid4()))
profile_picture = db.Column(db.String(255), default='avatar.avif')
status = db.Column(db.String(20), default='active')
deactivated_at = db.Column(db.DateTime, default=None)
def __repr__(self):
return f"User(id={self.id}, username={self.username}, email={self.email}, role={self.role}, profile_picture={self.profile_picture})"
class Form(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
form_title = db.Column(db.String(100), nullable=False)
form_description = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
category = db.Column(db.String(255), nullable=False)
uuid = db.Column(db.String(36), unique=True, nullable=False)
form_link = db.Column(db.String(255))
form_header = db.Column(db.String(255))
created_by = db.Column(db.String(100))
creator = db.Column(db.String(100))
edited = db.Column(db.String(3), default='No')
edited_at = db.Column(db.DateTime)
questions = db.relationship('Question', backref='form', lazy=True, cascade='all, delete-orphan')
responses = db.relationship('FormResponse', backref='form', lazy=True, cascade='all, delete-orphan')
class Question(db.Model):
id = db.Column(db.Integer, primary_key=True)
question_text = db.Column(db.String(255), nullable=False)
question_type = db.Column(db.String(20), nullable=False)
char_limit = db.Column(db.Integer)
mandatory = db.Column(db.String(10), default='non_mandatory', nullable=False)
form_id = db.Column(db.Integer, db.ForeignKey('form.id', ondelete='CASCADE'), nullable=False)
options = db.relationship('Option', backref='question', lazy=True, cascade='all, delete-orphan')
class Option(db.Model):
id = db.Column(db.Integer, primary_key=True)
option_text = db.Column(db.String(255), nullable=False)
question_id = db.Column(db.Integer, db.ForeignKey('question.id'), nullable=False)
file_type = db.Column(db.String(50))
max_file_size = db.Column(db.Integer)
class FormResponse(db.Model):
id = db.Column(db.Integer, primary_key=True)
form_id = db.Column(db.Integer, db.ForeignKey('form.id', ondelete='CASCADE'), nullable=False)
submitted_at = db.Column(db.DateTime, default=datetime.utcnow)
answers = db.relationship('ResponseAnswer', backref='form_response', lazy=True, cascade='all, delete-orphan')
class ResponseAnswer(db.Model):
id = db.Column(db.Integer, primary_key=True)
question_id = db.Column(db.Integer, db.ForeignKey('question.id', ondelete='CASCADE'), nullable=False)
response_id = db.Column(db.Integer, db.ForeignKey('form_response.id', ondelete='CASCADE'), nullable=False)
answer = db.Column(db.String(255))
file_path = db.Column(db.String(255))
question = db.relationship('Question', backref='response_answers')
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False)
message = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
with app.app_context():
db.create_all()
app.secret_key = 'secret_key'
@app.route('/')
def home():
user=get_current_user
return render_template('index.html',user=user)
@app.route('/form_responses/<int:form_id>', methods=['GET'])
def form_responses(form_id):
form = Form.query.get_or_404(form_id)
responses = FormResponse.query.filter_by(form_id=form_id).all()
return render_template('form_responses.html', form=form, responses=responses)
@app.route('/response_details/<int:response_id>', methods=['GET'])
def response_details(response_id):
response = FormResponse.query.get_or_404(response_id)
# Fetch data using a join between ResponseAnswer and Question
questions_and_answers = (
db.session.query(ResponseAnswer, Question.question_text, Question.question_type)
.join(Question, ResponseAnswer.question_id == Question.id)
.filter(ResponseAnswer.response_id == response.id)
.all()
)
return render_template('response_details.html', response=response, questions_and_answers=questions_and_answers)
def get_option_text(response, question):
if question.question_type in ['multiple_choice', 'dropdown', 'checkboxes']:
option = Option.query.get(response)
if option:
return option.option_text
return response
@app.route('/view_pie_chart/<int:form_id>/<string:question_type>', methods=['GET'])
def view_pie_chart(form_id, question_type):
form = Form.query.get_or_404(form_id)
# Fetch questions of the specified question type
questions = Question.query.filter(Question.form_id == form_id, Question.question_type == question_type).all()
# Check if there is a "gender" question in the form
gender_question = next((q for q in form.questions if q.question_type == 'gender'), None)
# Prepare data for the pie chart
labels = []
values = []
for question in questions:
options = Option.query.filter_by(question_id=question.id).all()
for option in options:
option_text = get_option_text(option.id, question)
# Add a check for non-empty option text before appending to labels
if option_text:
labels.append(option_text)
values.append(0) # Initialize values to 0 for each option
# Count occurrences of each option in responses
total_responses = len(form.responses)
for response in form.responses:
for answer in response.answers:
if answer.question_id in [q.id for q in questions]:
# Check if answer is a comma-separated list for checkboxes
if ',' in answer.answer:
option_ids = [int(option_id) for option_id in answer.answer.split(',')]
for option in options:
if option.id in option_ids:
option_text = get_option_text(option.id, question)
# Add a check for non-empty option text before incrementing values
if option_text:
values[labels.index(option_text)] += 1
else:
# Single option answer
option_text = get_option_text(answer.answer, question)
# Add a check for non-empty option text before incrementing values
if option_text:
values[labels.index(option_text)] += 1
# Calculate percentages
percentages = [(value / total_responses) * 100 if total_responses > 0 else 0 for value in values]
# Create pie chart using Plotly
fig = px.pie(names=labels, values=values, title=f'Responses for {question_type.capitalize()} Questions')
# Update the hover text to include percentages
hover_info = [f'{label}: {value} ({percentage:.2f}%)' for label, value, percentage in zip(labels, values, percentages)]
fig.update_traces(textinfo='percent+label', hoverinfo='text', text=hover_info)
# Convert the Plotly figure to HTML
plot_html = to_html(fig, full_html=False)
# Check if there is a "gender" question in the form
show_gender_filter = False
gender_chart_html = ''
gender_options = []
if gender_question:
show_gender_filter = True
# Retrieve gender responses from the database
gender_responses = []
for response in form.responses:
answer = ResponseAnswer.query.filter_by(response_id=response.id, question_id=gender_question.id).first()
if answer:
gender_responses.append(answer.answer)
# Create a dictionary to count gender responses
gender_counts = {
'Male': gender_responses.count('Male'),
'Female': gender_responses.count('Female'),
'Rather Not Say': gender_responses.count('Rather Not Say')
}
# Create a Plotly pie chart for gender distribution
gender_fig = px.pie(
values=list(gender_counts.values()),
names=list(gender_counts.keys()),
title=f'Gender Distribution for Form {form_id}'
)
# Convert the Plotly figure to HTML
gender_chart_html = to_html(gender_fig, full_html=False)
# Get the options for the gender filter
gender_options = list(gender_counts.keys())
return render_template(
'view_pie_chart.html',
plot_html=plot_html,
form=form,
show_gender_filter=show_gender_filter,
gender_chart_html=gender_chart_html,
gender_options=gender_options
)
@app.route('/view_bar_chart/<int:form_id>/<string:question_type>', methods=['GET'])
def view_bar_chart(form_id, question_type):
form = Form.query.get_or_404(form_id)
# Fetch questions of the specified question type
questions = Question.query.filter(Question.form_id == form_id, Question.question_type == question_type).all()
# Prepare data for the bar chart
labels = []
values = []
for question in questions:
options = Option.query.filter_by(question_id=question.id).all()
for option in options:
option_text = get_option_text(option.id, question)
# Add a check for non-empty option text before appending to labels
if option_text:
labels.append(option_text)
values.append(0) # Initialize values to 0 for each option
# Count occurrences of each option in responses
total_responses = len(form.responses)
for response in form.responses:
for answer in response.answers:
if answer.question_id in [q.id for q in questions]:
# Check if answer is a comma-separated list for checkboxes
if ',' in answer.answer:
# Handle multiple options
option_ids = [int(option_id) for option_id in answer.answer.split(',')]
for option in options:
if option.id in option_ids:
option_text = get_option_text(option.id, question)
# Add a check for non-empty option text before incrementing values
if option_text:
values[labels.index(option_text)] += 1
else:
# Single option answer
option_text = get_option_text(answer.answer, question)
# Add a check for non-empty option text before incrementing values
if option_text:
values[labels.index(option_text)] += 1
# Create a bar chart using Plotly
fig = go.Figure(data=[go.Bar(x=labels, y=values)])
fig.update_layout(
title=f'Responses for {question_type.capitalize()} Questions',
xaxis_title='Options',
yaxis_title='Frequency',
)
# Convert the Plotly figure to HTML
bar_chart_html = fig.to_html(full_html=False)
return render_template(
'view_bar_chart.html',
bar_chart_html=bar_chart_html,
form=form
)
@app.route('/fill_form/<int:form_id>', methods=['GET', 'POST'])
def fill_form(form_id):
# Retrieve the form based on the form_id
form = Form.query.get_or_404(form_id)
countries = countries_df.to_dict(orient='records')
states = states_df.to_dict(orient='records')
cities = cities_df.to_dict(orient='records')
country_codes_df = pd.read_csv(os.path.join(base_dir, 'static/csv/country-codes.csv'), usecols=['Country', 'Code'])
country_codes = country_codes_df.to_dict(orient='records')
form_response = FormResponse(form_id=form.id) # Initialize form_response here
if request.method == 'POST':
# Handle form submission
answers = {} # Store user's answers here, where keys are question IDs
if not os.path.exists(app.config['UPLOAD_FILE_FOLDER']):
os.makedirs(app.config['UPLOAD_FILE_FOLDER'])
for question in form.questions:
field_name = f'question_{question.id}'
if question.question_type == 'file_upload':
file = request.files.get(field_name)
if file and allowed_file_upload(file.filename):
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FILE_FOLDER'], filename)
file.save(file_path)
file_path = filename # Store only the filename, not the entire path
# Create a ResponseAnswer instance with file_path
response_answer = ResponseAnswer(question_id=question.id, file_path=file_path)
form_response.answers.append(response_answer)
else:
flash('Invalid file format. Allowed formats are: txt, pdf, png, jpg, jpeg, gif', 'danger')
return redirect(url_for('fill_form', form_id=form_id))
elif question.question_type == 'multiple_choice':
# Handle multiple-choice questions
selected_option_id = request.form.get(field_name)
answers[question.id] = selected_option_id
elif question.question_type == 'checkboxes':
# Handle checkbox questions with multiple options
selected_option_ids = request.form.getlist(field_name)
# Store selected option IDs as a comma-separated string
answers[question.id] = ','.join(selected_option_ids)
elif question.question_type == 'dropdown':
# Handle dropdown questions
selected_option_id = request.form.get(field_name)
answers[question.id] = selected_option_id
elif question.question_type in ['short_answer', 'paragraph', 'text']:
# Handle text-based input questions
answer_text = request.form.get(field_name)
answers[question.id] = answer_text
elif question.question_type == 'gender':
# Handle gender dropdown questions
selected_gender = request.form.get(f'question_{question.id}')
answers[question.id] = selected_gender
elif question.question_type == 'email':
# Handle email input questions
email_value = request.form.get(f'question_{question.id}')
answers[question.id] = email_value
elif question.question_type == 'tel':
# Handle telephone input questions
selected_country_code = request.form.get('country_code')
phone_number = request.form.get('phone')
if selected_country_code and phone_number:
full_phone_number = f'{phone_number}'
answers[question.id] = full_phone_number
else:
answers[question.id] = None
elif question.question_type == 'cnic':
# Handle CNIC input questions
cnic_value = request.form.get(f'question_{question.id}')
answers[question.id] = cnic_value
elif question.question_type == 'rating':
# Handle rating questions
rating_value = request.form.get(field_name)
answers[question.id] = rating_value
elif question.question_type in ['date', 'time']:
# Handle date and time questions
date_time_value = request.form.get(field_name)
answers[question.id] = date_time_value
# Inside the loop where you handle different question types
elif question.question_type == 'address':
# Handle address input questions
country_id = request.form.get('country')
selected_country = next((country['name'] for country in countries if country['id'] == int(country_id)), None)
country = selected_country if selected_country is not None else ''
state = request.form.get('state')
city = request.form.get('city')
postal_code = request.form.get('postal_code')
# Check if city, state, and postal code are None or empty, and replace them with 'null'
city = city if city else 'null'
state = state if state else 'null'
postal_code = postal_code if postal_code else 'null'
# Concatenate address components with labels
address_string = f'Country: {country}, State: {state}, City: {city}, Postal Code: {postal_code}' \
if country or state or city or postal_code else None
# Store the address string in the answer field
answers[question.id] = address_string
# Iterate through the user's answers and create ResponseAnswer instances
for question_id, answer in answers.items():
if question_id not in form_response.answers:
if isinstance(answer, str):
response_answer = ResponseAnswer(question_id=question_id, answer=answer)
elif isinstance(answer, int): # Assuming IDs are integers
response_answer = ResponseAnswer(question_id=question_id, option_id=answer)
else:
response_answer = ResponseAnswer(question_id=question_id, file_path=answer)
form_response.answers.append(response_answer)
# Add and commit the form response and answers to the database
try:
# Add and commit the form response and answers to the database
db.session.add(form_response)
db.session.commit()
flash('Form submitted successfully!', 'success')
except Exception as e:
# Rollback changes in case of an error
db.session.rollback()
flash('Error submitting the form. Please try again.', 'danger')
# Render the same template with the success message
return render_template('fill_form.html', form=form, success_message='Form submitted successfully!', show_submit_another=True,
countries=countries,
states=states,
cities=cities,
country_codes=country_codes)
return render_template('fill_form.html', form=form, show_submit_another=False, countries=countries, states=states,country_codes=country_codes, cities=cities)
@app.route('/country_codes')
def get_country_codes():
# Read the country-codes.csv file
country_codes_df = pd.read_csv(os.path.join(base_dir, 'static/csv/country-codes.csv'), usecols=['Country', 'Code'])
# Convert the DataFrame to a list of dictionaries
country_codes_list = country_codes_df.to_dict(orient='records')
# Return the list of country codes as JSON
return jsonify({'country_codes': country_codes_list})
@app.route('/profile_redirect')
def profile_redirect():
user = get_current_user()
if user:
# User is logged in, redirect to their profile
return redirect(url_for('profile', uuid=user.uuid))
else:
# User is not logged in, redirect to login page
return redirect(url_for('login'))
def get_current_user():
if 'user_id' in session:
user_id = session['user_id']
user = users.query.get(user_id) # Assuming you have a User model with an 'id' field
if user:
return user
return None
@app.route('/view_responses/<int:form_id>', methods=['GET'])
def view_responses(form_id):
# Retrieve the form based on the form_id
form = Form.query.get_or_404(form_id)
# Get all responses for the given form
responses = FormResponse.query.filter_by(form_id=form_id).all()
# Create a dictionary to store responses for each question
question_responses = {}
# Define the get_option_text function to fetch option_text based on response
def get_option_text(response, question):
if question.question_type in ['multiple_choice', 'dropdown', 'checkboxes']:
option = Option.query.get(response)
if option:
return option.option_text
return response
# Iterate through the questions associated with the form
for question in form.questions:
question_responses[question] = []
# Iterate through the responses and their answers
for response in responses:
for answer in response.answers:
question = Question.query.get(answer.question_id)
question_responses[question].append(answer) # Store the raw answers
return render_template('view_responses.html', form=form, question_responses=question_responses, get_option_text=get_option_text)
@app.route('/download_file/<filename>', methods=['GET'])
def download_file(filename):
try:
return send_from_directory(app.config['UPLOAD_FILE_FOLDER'], filename, as_attachment=True)
except FileNotFoundError:
abort(404) # or return a custom error page
except Exception as e:
# Log the exception and return an appropriate error response
print(f"Error during file download: {e}")
abort(500) # or return a custom error page
# Modify your Flask route to include the response count for each form
@app.route('/analytics', methods=['GET', 'POST'])
def analytics():
# Get the current user
current_user = get_current_user()
if current_user is None:
return redirect(url_for('login')) # Redirect to the login page if the user is not logged in
# Get all forms created by the currently logged-in user
user_forms = Form.query.filter_by(uuid=current_user.uuid).all()
# Calculate the response count for each form
for user_form in user_forms:
user_form.response_count = FormResponse.query.filter_by(form_id=user_form.id).count()
form = None
form_fill_count = None
if request.method == 'POST':
# Handle form submission to view analytics for a specific form
selected_form_id = request.form.get('selected_form')
if selected_form_id is not None:
# Redirect to the analytics page for the selected form
return redirect(url_for('analytics', form_id=selected_form_id))
# Check if the URL contains a form_id parameter (indicating a specific form's analytics)
form_id = request.args.get('form_id')
# If no form_id is provided, load analytics for the first form by default
if not form_id and user_forms:
form_id = user_forms[0].id
if form_id:
# Get the form for which you want to display analytics
form = Form.query.get_or_404(form_id)
# Ensure that the form belongs to the current user
if form.username != current_user.username:
return "Unauthorized"
# Count the number of times the form has been filled out
form_fill_count = FormResponse.query.filter_by(form_id=form_id).count()
# You can add more analytics here based on your requirements
return render_template('analytics.html', user_forms=user_forms, form=form, form_fill_count=form_fill_count, form_id=form_id)
@app.route('/gender_pie_chart/<int:form_id>')
def gender_pie_chart(form_id):
current_user = get_current_user()
if current_user is None:
return redirect(url_for('login')) # Redirect to the login page if the user is not logged in
# Check if the form contains a "gender" question
form = Form.query.get_or_404(form_id)
gender_question = next((q for q in form.questions if q.question_type == 'gender'), None)
if gender_question:
# Query the database to get real data for the "gender" question
gender_responses = []
form_responses = FormResponse.query.filter_by(form_id=form_id).all()
for response in form_responses:
answer = ResponseAnswer.query.filter_by(
response_id=response.id, question_id=gender_question.id).first()
if answer:
gender_responses.append(answer.answer)
# Create a dictionary to count gender responses
gender_counts = {
'Male': gender_responses.count('Male'),
'Female': gender_responses.count('Female'),
'Rather Not Say': gender_responses.count('Rather Not Say')
}
# Create a Plotly pie chart
fig = px.pie(
values=list(gender_counts.values()),
names=list(gender_counts.keys()),
title=f'Gender Distribution for Form {form_id}'
)
# Convert the Plotly figure to HTML
chart_html = fig.to_html()
else:
chart_html = 'No data available for gender question.'
return render_template('gender_pie_chart.html', chart_html=chart_html)
@app.route('/address_pie_chart/<int:form_id>')
def address_pie_chart(form_id):
current_user = get_current_user()
if current_user is None:
return redirect(url_for('login'))
# Check if the form contains an "address" question
form = Form.query.get_or_404(form_id)
address_question = next((q for q in form.questions if q.question_type == 'address'), None)
chart_type = request.args.get('chart_type', 'country') # Initialize chart_type with a default value
if address_question:
# Query the database to get real data for the "address" question
address_responses = []
form_responses = FormResponse.query.filter_by(form_id=form_id).all()
for response in form_responses:
answer = ResponseAnswer.query.filter_by(
response_id=response.id, question_id=address_question.id).first()
if answer and answer.answer: # Check if answer is not None and not an empty string
address_responses.append(answer.answer)
# Create a Plotly pie chart based on the selected chart type
if chart_type == 'country':
chart_data = []
for response in address_responses:
if response:
parts = response.split(', ')
if len(parts) >= 1:
country_info = parts[0].split(': ')
if len(country_info) == 2:
country = country_info[1]
chart_data.append(country)
title = 'Country Distribution'
elif chart_type == 'state':
chart_data = []
for response in address_responses:
if response:
parts = response.split(', ')
if len(parts) >= 2:
state_info = parts[1].split(': ')
if len(state_info) == 2:
state = state_info[1]
chart_data.append(state)
title = 'State Distribution'
elif chart_type == 'city':
chart_data = []
for response in address_responses:
if response:
parts = response.split(', ')
if len(parts) >= 3:
city_info = parts[2].split(': ')
if len(city_info) == 2:
city = city_info[1]
chart_data.append(city)
title = 'City Distribution'
else:
chart_html = 'Invalid chart type.'
return render_template('address_pie_chart.html', chart_html=chart_html, chart_type=chart_type, form=form)
# Create a Plotly pie chart
fig = px.pie(
values=[chart_data.count(value) for value in set(chart_data)],
names=list(set(chart_data)),
title=title
)
# Convert the Plotly figure to HTML
chart_html = fig.to_html()
else:
chart_html = 'No data available for address question.'
# Pass 'form' along with other variables to the template
return render_template('address_pie_chart.html', chart_html=chart_html, chart_type=chart_type, form=form)
@app.route('/recent_forms_activity/<int:form_id>')
def recent_forms_activity(form_id):
# Your route logic here, using the form_id parameter
# Get the current user
current_user = get_current_user()
if current_user is None:
return redirect(url_for('login')) # Redirect to the login page if the user is not logged in
# Calculate the date range for the last 10 days
today = datetime.utcnow().date()
date_range = [(today - timedelta(days=i)) for i in range(10)]
# Query the database to get the number of times the specific form has been filled out for each of the last 10 days
form_counts = []
for date in date_range:
count = FormResponse.query.filter(FormResponse.form_id == form_id, FormResponse.submitted_at >= date, FormResponse.submitted_at < date + timedelta(days=1)).count()
form_counts.append(count)
# Create a DataFrame to store the data
df = pd.DataFrame({'Date': date_range, 'Forms Filled': form_counts})
# Create a Plotly bar chart
fig = px.bar(df, x='Date', y='Forms Filled', title=f'Forms Filled for Form {form_id} in the Last 10 Days')
# You can customize the appearance of the chart if needed
return fig.to_html()
def generate_form_link(form_id):
return f"http://127.0.0.1:5000/fill_form/{form_id}"
@app.route('/admin_users')
def admin_users():
user = get_current_user()
if user is None:
return redirect(url_for('login'))
# Check if the user has the 'admin' role
if user.role != 'admin':
flash('You do not have permission to access the admin dashboard.', 'error')
return redirect(url_for('login')) # Redirect to a different page if not an admin
# Fetch and display the list of users from the database
users_list = users.query.all()
return render_template('admin_users.html', users_list=users_list)
@app.route('/admin/edit_user/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
user = users.query.get_or_404(user_id)
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
role = request.form['role']
password = request.form['password']
confirm_password = request.form['confirm_password']
if password == confirm_password:
user.username = username
user.email = email
user.role = role
# Check if a new password was provided and update it
if password:
user.password = password
db.session.commit()
flash('User details updated successfully.', 'success')
return redirect(url_for('admin_users'))
else:
flash('Password and confirm password do not match.', 'error')
return render_template('edit_user.html', user=user)
@app.route('/deactivate_user/<int:user_id>', methods=['GET', 'POST'])
def deactivate_user(user_id):
# Check if the user is logged in
user = get_current_user()
if user is None:
return redirect(url_for('login'))
# Check if the user has the 'admin' role
if user.role != 'admin':
flash('You do not have permission to access the admin dashboard.', 'error')
return redirect(url_for('login')) # Redirect to a different page if not an admin
# Retrieve the user with the given user_id from the database
user = users.query.get_or_404(user_id)
if request.method == 'POST':
# Check the user's status and toggle it
if user.status == 'active':
user.status = 'deactive'
user.deactivated_at = datetime.now() # Save the deactivation time
flash('User account deactivated successfully.', 'success')
else:
user.status = 'active'
flash('User account activated successfully.', 'success')
db.session.commit()
# Redirect back to the user management page
return redirect(url_for('deactivate_user', user_id=user.id))
# Calculate the time difference
time_difference = datetime.now() - user.deactivated_at if user.deactivated_at else None
# Pass the current time to the template
current_time = datetime.now()
return render_template('deactivate_user.html', user=user, time_difference=time_difference, current_time=current_time)
@app.route('/admin/update_user/<int:user_id>', methods=['POST'])
def update_user(user_id):
# Retrieve the user with the given user_id from the database
user = users.query.get_or_404(user_id)
if request.method == 'POST':
# Update user details and role based on form submission
username = request.form['username']
email = request.form['email']
role = request.form['role']
# Update the user's details and role in the database
user.username = username
user.email = email
user.role = role
db.session.commit()
flash('User details updated successfully.', 'success')
# Redirect back to the user management page
return redirect(url_for('manage_users'))
return render_template('edit_user.html', user=user)
@app.route('/register', methods=['GET', 'POST'])
def register():
username_message = None
email_message = None
password_message = None
registration_message = None
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
# Check if username or email already exists
existing_user = users.query.filter_by(username=username).first()
existing_email = users.query.filter_by(email=email).first()
if existing_user:
username_message = 'Username already taken. Please choose a different username.'
elif existing_email:
email_message = 'Email already in use. Please use a different email address.'
else:
# Add the new user to the database with the default 'user' role
new_user = users(username=username, password=password, email=email, role='user', uuid=str(uuid.uuid4()))
db.session.add(new_user)
db.session.commit()
flash('Registration successful. You can now log in.', 'success')
# Set a success message in the session for the login page
session['registration_success'] = 'Registration successful. You can now log in.'
# Redirect to the login page
return redirect(url_for('login'))
return render_template('register.html', username_message=username_message, email_message=email_message, password_message=password_message, registration_message=registration_message)
@app.route('/login', methods=['GET', 'POST'])
def login():
deactivation_message = request.args.get('deactivation_message')
success_message = session.pop('registration_success', None)
invalid_credentials_message = None # New message for invalid email/username or password
if request.method == 'POST':
identifier = request.form['identifier']
password = request.form['password']
user = users.query.filter(or_(users.username == identifier, users.email == identifier)).first()
if user:
if user.status == 'deactive':
deactivation_time = user.deactivated_at.strftime('%Y-%m-%d %I:%M %p')
deactivation_message = f'Your account is deactivated. Time was {deactivation_time}.'
return redirect(url_for('login', deactivation_message=deactivation_message))
else:
if user.password == password:
session['user_id'] = user.id
session['username'] = user.username
success_message = 'Login successful.'
flash(success_message, 'success')
if user.role == 'admin':
session['role'] = 'admin'
return redirect(url_for('admin_dashboard'))
else:
return redirect(url_for('profile', uuid=user.uuid, success_message=success_message))
else:
invalid_credentials_message = 'Invalid email/username or password. Please try again.'
else:
invalid_credentials_message = 'Invalid email/username or password. Please try again.'
return render_template('login.html', deactivation_message=deactivation_message,
registration_success_message=success_message,
invalid_credentials_message=invalid_credentials_message)