def post(self, request, *args, **kwargs): answer_sheets = AnswerSheets.objects.all() zero_getter_count = 0 for a_sheet in answer_sheets: try: online_test = a_sheet.online_test exam = online_test.exam subject = online_test.subject student = a_sheet.student the_class = student.current_class section = student.current_section offline_test = ClassTest.objects.get(exam=exam, subject=subject, the_class=the_class, section=section) test_result = TestResults.objects.get(class_test=offline_test, student=student) marks = test_result.marks_obtained except Exception as e: print('exception 05052020-E from online_test views.py %s %s' % (e.message, type(e))) print('failed to retrieve marks') if marks > 0: if not a_sheet.shared: link = a_sheet.link message = 'Dear %s, answer sheet of %s online test attached. link: %s' % \ (student, subject, link) print('message: %s' % message) school = a_sheet.student.school mobile = a_sheet.student.parent.parent_mobile1 sms.send_sms1(school, '*****@*****.**', mobile, message, 'Share Answer sheet') a_sheet.shared = True a_sheet.save() else: zero_getter_count += 1 print( '%s secued zero marks in the online test of %s class %s. hence not sharing' % (student, subject, the_class)) return JSONResponse({'zero_getter_count': zero_getter_count}, status=200)
def report_delay(request): response = { } if request.method == 'POST': data = json.loads(request.body) school_id = data['school_id'] rout = data['rout'] teacher = data['teacher'] message = data['message'] try: school = School.objects.get(id=school_id) configuration = Configurations.objects.get(school=school) r = Bus_Rout.objects.get(school=school_id, bus_root=rout) teacher = Teacher.objects.get(email=teacher) email = teacher.email student_rout = Student_Rout.objects.filter(bus_root=r) school_name = school.school_name for sr in student_rout: parent = sr.student.parent m1 = parent.parent_mobile1 m2 = parent.parent_mobile2 full_message = 'Dear ' + parent.parent_name + ', Delay on Bus rout ' + rout full_message += ': ' + message + '. Regards, ' + teacher.first_name + ' ' + teacher.last_name full_message += ', ' + school_name message_type = 'Bus Delay' sms.send_sms1(school, email, m1, full_message, message_type) if m2 != '': if configuration.send_absence_sms_both_to_parent: sms.send_sms1(school, email, m2, full_message, message_type) print (full_message) except Exception as e: print ('unable to send bus delay message') print ('Exception18 in bus_attendance views.py = %s (%s)' % (e.message, type(e))) return JSONResponse(response, status=200)
def post(self, request, *args, **kwargs): context_dict = {} context_dict['header'] = 'Share Image' try: data = json.loads(request.body) print('Image sharing process started') teacher = data['teacher'] t = Teacher.objects.get(email=teacher) print(t) print(teacher) the_class = data['class'] print(the_class) c = Class.objects.get(school=t.school, standard=the_class) print(c) section = data['section'] print(section) s = Section.objects.get(school=t.school, section=section) print(s) whole_class = data['whole_class'] print('whole class = %s' % whole_class) if whole_class == 'false': student_list = data['student_list'] print(student_list) print(type(student_list)) # 29/08/2019 - when comes from Android, the student id list comes as an array. So we need to break it # into list. But from iOS, it comes as a proper list. So need not break it try: students = ast.literal_eval(student_list) print(students) except Exception as e: print( 'exception 29082019-A from pic_share views.py %s %s' % (e.message, type(e))) print( 'looks the request has come from iOS, hence no need for ast.literal_eval' ) students = student_list image_name = data['image_name'] print(image_name) image = data['image'] image_file = ContentFile(base64.b64decode(image), name=image_name.replace('@', '')) description = data['description'] print(description) # save the image image_video = ImageVideo() image_video.location = image_file image_video.descrition = description image_video.teacher = t image_video.the_class = c image_video.section = s # long_link = 'https://storage.cloud.google.com/classup/classup2/media/prod/image_video/%s' % \ # image_name.replace('@', '') long_link = 'https://classup2.s3.us-east-2.amazonaws.com/media/prod/image_video/%s' % \ image_name.replace('@', '') print('long_link = %s' % long_link) short_link = long_link # prepare short link global_conf = GlobalConf.objects.get(pk=1) key = global_conf.short_link_api url = 'https://cutt.ly/api/api.php?' url += 'key=%s&short=%s' % (key, long_link) print('url for generating short link = %s' % url) try: req = urllib2.Request(url, headers={'User-Agent': "Magic Browser"}) response = urllib2.urlopen(req) print('response for generating short link = %s' % response) outcome = json.loads(response.read()) print('ouctome = ') print(outcome) status = outcome['url']['status'] print('status = %i' % status) if status == 7: short_link = outcome['url']['shortLink'] print('short_lint = %s' % short_link) image_video.short_link = short_link except Exception as e: print('exception 15082019-A from pic_share views.py %s %s' % (e.message, type(e))) print( 'failed to generate short link for the image/video uploaded by %s' % t) image_video.short_link = 'not available' try: image_video.save() print('saved the image uploaded by %s' % t) # now update with the SharedWith table if whole_class == 'true': print('this image/video is shared with whole class %s-%s' % (the_class, section)) students = Student.objects.filter(current_class=c, current_section=s) for student in students: try: shared = ShareWithStudents(image_video=image_video, student=student, the_class=c, section=s) shared.save() print( 'saved the SharedWithStudent for %s of %s-%s' % (student, the_class, section)) parent = student.parent.parent_name message = 'Dear %s new pic uploaded. %s. Click %s' % ( parent, description, short_link) print(message) sms.send_sms1(student.school, teacher, student.parent.parent_mobile1, message, 'Share Pic') except Exception as e: print( 'exception 01082019-A from pic_share views.py %s %s' % (e.message, type(e))) print('failed to save SharedWithStudent object') else: for an_item in students: try: student = Student.objects.get(pk=an_item) shared = ShareWithStudents(image_video=image_video, student=student, the_class=c, section=s) shared.save() print( 'saved the SharedWithStudent for %s of %s-%s. Now sending sms' % (student, c, s)) parent = student.parent.parent_name message = 'Dear %s new pic uploaded. %s. Click %s' % ( parent, description, short_link) print(message) sms.send_sms1(student.school, teacher, student.parent.parent_mobile1, message, 'Share Pic') except Exception as e: print( 'exception 02082019-A from pic_share views.py %s %s' % (e.message, type(e))) print('failed to save SharedWithStudent object') context_dict['status'] = 'success' context_dict['message'] = 'Media upload successful' print(image_video.location) try: action = 'uploading image for %s-%s teacher %s' % ( the_class, section, t) print(action) log_entry(teacher, action, 'Normal', True) except Exception as e: print('unable to crete logbook entry') print( 'Exception 31072019-A from pic_share views.py %s %s' % (e.message, type(e))) return JSONResponse(context_dict, status=200) except Exception as e: print( 'Exception 31072019-B from pic_share views.py = %s (%s)' % (e.message, type(e))) print( 'error while trying to save the image/video uploaded by %s' % t) context_dict['status'] = 'failed' context_dict[ 'message'] = 'error while trying to save the image/video uploaded' return JSONResponse(context_dict, status=201) except Exception as e: print('failed to save image/video') print('Exception 02082019-B from pic_share views.py = %s (%s)' % (e.message, type(e))) context_dict['status'] = 'failed' context_dict[ 'message'] = 'error while trying to save the image/video uploaded' return JSONResponse(context_dict, status=201)
def add_teacher(request): print('adding teacher from device...') response_dict = { } if request.method == 'POST': try: data = json.loads(request.body) print(data) user = data['user'] school_id = data['school_id'] #employee_id = data['employee_id'] email = data['email'] mobile = data['mobile'] full_name = data['full_name'] first_name = full_name.split()[0] last_name = ' ' try: last_name += full_name.split()[1] last_name += ' %s' % full_name.split()[2] except Exception as e: print('exception 03022020-A from teacher views.py %s %s' % (e.message, type(e))) print('last name of teacher not mentioned completely') school = School.objects.get(id=school_id) # check to see if any other teacher in this school has the same login id try: t = Teacher.objects.get(school=school, email=email) response_dict['status'] = 'failed' message = 'login id ' + email + ' is already assigned to ' + t.first_name + ' ' + t.last_name print(message) response_dict['message'] = message response_dict['status'] = 'failed' return JSONResponse(response_dict, status=201) except Exception as e: print('Exception 20 from teacher views.py = %s (%s) ' % (e.message, type(e))) print('login id are available. Hence this teacher can be added...') t = Teacher() t.school = school t.first_name = first_name t.last_name = last_name t.email = email t.mobile = mobile t.active_status = True try: t.save() # now, create a user for this teacher # the user name would be the email, and password would be a random string password = User.objects.make_random_password(length=5, allowed_chars='1234567890') print ('Initial password = '******'Successfully created user for ' + first_name + ' ' + last_name) mapping = UserSchoolMapping(user=u, school=school) mapping.save() except Exception as e: print ('Exception 50 from teacher views.py = %s (%s)' % (e.message, type(e))) print ('Unable to create user or user-school mapping for ' + first_name + ' ' + last_name) # make this user part of the Teachers group try: group = Group.objects.get(name='teachers') u.groups.add(group) print ('Successfully added ' + first_name + ' ' + last_name + ' to the Teachers group') except Exception as e: print ('Exception 60 from teacher views.py = %s (%s)' % (e.message, type(e))) print ('Unable to add ' + first_name + ' ' + last_name + ' to the Teachers group') # get the links of app on Google Play and Apple App store configuration = Configurations.objects.get(school=school) android_link = configuration.google_play_link iOS_link = configuration.app_store_link # send login id and password to teacher via sms message = 'Dear ' + first_name + ' ' + last_name + ', Welcome to ClassUp.' message += ' Your user id is: ' + email + ', and password is: ' + password + '. ' message += 'Please install ClassUp from these links. Android: ' message += android_link message += ', iPhone/iOS: ' message += iOS_link message += 'You can change your password after first login. ' message += 'Enjoy managing your class with ClassUp!' message += ' For support, email to: [email protected]' message_type = 'Welcome Teacher' sender = user sms.send_sms1(school, sender, str(mobile), message, message_type) # 15/07/2017 - Set up Main as default subject for this teacher try: print ('now trying to set teacher subject') s = Subject.objects.get(school=school, subject_name='Main') except Exception as e: print('unable to retrieve Main subject as default for ') print ('Exception 210 from teachers views.py = %s (%s)' % (e.message, type(e))) try: ts = TeacherSubjects.objects.get(teacher=t, subject=s) if ts: print('subject ' + s.subject_name + ' has already been selected by teacher ' + t.first_name + ' ' + t.last_name) pass except Exception as e: print( 'now setting subject ' + s.subject_name + ' for teacher ' + t.first_name + ' ' + t.last_name) ts = TeacherSubjects(teacher=t, subject=s) try: ts.save() print('successfully set subject ' + s.subject_name + ' for teacher ' + t.first_name + ' ' + t.last_name) except Exception as e: print('unable to set subject ' + s.subject_name + ' for teacher ' + t.first_name + ' ' + t.last_name) print ('Exception 211 from teachers views.py = %s (%s)' % (e.message, type(e))) response_dict['status'] = 'success' response_dict['message'] = "Teacher created. Welcome SMS sent to the teacher' mobile" return JSONResponse(response_dict, status=200) except Exception as e: print('Exception 30 from teacher views.py = %s (%s)' % (e.message, type(e))) message = 'Failed to create Teacher. Please contact ClassUp Support' print(message) response_dict['message'] = message response_dict['status'] = 'failed' return JSONResponse(response_dict, status=201) except Exception as e: print('Exception 40 from teachers views.py = %s (%s)' % (e.message, type(e))) message = 'Failed to create Teacher. Please contact ClassUp Support' response_dict['message'] = message response_dict['status'] = 'failed' print(message) return JSONResponse(response_dict, status=201)
def forgot_password(request): return_data = {} if request.method == 'POST': print('request body = ' + request.body) data = json.loads(request.body) print(data) user = data["user"] print(user) # 11/04/2020 - see if we have received the player_id. # If the username is valid then we will send push notification as well try: player_id = data['player_id'] except Exception as e: print('exception 11042019-A from authentication views.py %s %s' % (e.message, type(e))) print('player id not sent by this user') player_id = 'Not Available' print('player_id = %s' % player_id) try: u = User.objects.get(username=user) # 04/03/17 - admin users should not be allowed to reset password from device. They should contact us if u.first_name == 'admin' or u.first_name == 'Admin': log_entry(user, "Forgot Password", "Normal", False) return_data["forgot_password"] = "******" error_message = 'For password reset of Admin user, please contact ClassUp Support' print(error_message) return_data['error_message'] = error_message return JSONResponse(return_data, status=201) else: # 10/02/17 - users sometimes (well, most times) press the forgot password button repeatedly several times. # This causes multiple password generation and sms sending. User receives multiple password so, gets # confused and multiple sms are sent which impacts our profitability. Hence we will not reset pssword, # if it has been reset in last 15 minutes try: lpt = LastPasswordReset.objects.filter( login_id=user).last() print(lpt) last_reset_time = lpt.last_reset_time naive = last_reset_time.replace(tzinfo=None) current_time = datetime.datetime.now() time_difference = current_time - naive print('time_difference = ' + str(time_difference)) if time_difference > datetime.timedelta(minutes=345): print( 'time difference between last password reset and current attempt is more than 15 min.' ) should_reset = True lpt.last_reset_time = datetime.datetime.now() try: lpt.save() except Exception as e: log_entry( user, "Password Change exception (authentication view.py Exception 22", "Normal", False) print( 'unable to reset the last password reset time for user ' + user) print( 'Exception 22 from authentication views.py %s (%s)' % (e.message, type(e))) else: log_entry(user, "Password Change in less than 15 minutes", "Normal", False) print( 'the user ' + user + ' tried to reset password less than 15 min ago. Hence not resetting now' ) should_reset = False return_data["forgot_password"] = "******" except Exception as e: # this user is resetting the password for the first time should_reset = True print(user + ' is changing password for the first time') print( 'Exception 20 from authentication views.py = %s (%s)' % (e.message, type(e))) # create an entry for this user in the LastPasswordReset table try: lpt = LastPasswordReset( login_id=user, last_reset_time=datetime.datetime.now()) lpt.save() except Exception as e: print( 'unable to create an entry in the LastPasswordReset table for user ' + user) print( 'Exception 21 from authentication views.py %s (%s)' % (e.message, type(e))) if should_reset: new_password = User.objects.make_random_password( length=5, allowed_chars='1234567890') print(new_password) u.set_password(new_password) u.save() message_type = 'Forgot Password' message = 'Dear %s %s, %s is your new password. ClassUp Support' % \ (u.first_name, u.last_name, str(new_password)) print(message) # check if user is teacher or parent if u.is_staff: # a teacher's user is created as his/her email id teacher = Teacher.objects.get(email=u.email) mobile = teacher.mobile school = teacher.school # 12/04/2020 - if user device mapping exist, send push notification try: mapping = user_device_mapping.objects.get( mobile_number=mobile) player_id = mapping.player_id one_signal_api = '4f62be3e-1330-4fda-ac23-91757077abe3' header = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" } payload = { "app_id": one_signal_api, "include_player_ids": [player_id], "contents": { "en": message }, } req = requests.post( "https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload)) outcome = '%s %s' % (req.status_code, req.reason) print( 'push notification send attempt result = %s' % outcome) except Exception as e: print( 'exception 12042020-A from authentication %s %s' % (e.message, type(e))) print( 'push notification cound not be sent for this teacher user' ) sms.send_sms1(school, user, mobile, message, message_type) else: # this user is a parent - a parent's mobile is their username # 11/04/2020 - try to send push notification one_signal_api = '4f62be3e-1330-4fda-ac23-91757077abe3' header = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" } payload = { "app_id": one_signal_api, "include_player_ids": [player_id], "contents": { "en": message }, } try: req = requests.post( "https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload)) outcome = '%s %s' % (req.status_code, req.reason) print( 'push notification send attempt result = %s' % outcome) except Exception as e: print( 'exception 11042020-B from atulmala views.py %s %s' % (e.message, type(e))) print( 'push notification for forgot password could not be sent' ) mobile = user # we need to extract the school name this parent belong to. First get the parent try: p = Parent.objects.get( Q(parent_mobile1=mobile) | Q(parent_mobile2=mobile)) # now get the children of this parent ward_list = Student.objects.filter( parent=p, active_status=True) # finally, get the school for student in ward_list: school = student.school sms.send_sms1(school, user, mobile, message, message_type) return_data["forgot_password"] = "******" log_entry(user, "Forgot Password process completed", "Normal", True) return JSONResponse(return_data, status=200) except Exception as e: print( 'exception 17032019-A from setup views.py %s %s' % (e.message, type(e))) print( 'could not find the parent associated with %s' % str(mobile)) return_data["forgot_password"] = "******" log_entry(user, "Forgot Password process Failed", "Normal", True) return JSONResponse(return_data, status=201) except Exception as e: print('unable to reset password for ' + user) print('Exception 6 from authentication views.py = %s (%s)' % (e.message, type(e))) return_data["forgot_password"] = "******" error_message = 'User does not exist' print(error_message) return_data['error_message'] = error_message return JSONResponse(return_data, status=201) return JSONResponse(return_data, status=200)
def post(self, request, *args, **kwargs): message_type = 'Share Lecture' context_dict = {'message_type': message_type} print(request.POST) school_id = request.POST.get('school_id') print('school_id = %s' % school_id) school = School.objects.get(id=school_id) print('school = %s' % school) teacher_email = request.POST.get('teacher') teacher = Teacher.objects.get(email=teacher_email) print('teacher = %s' % teacher) print('school = %s' % school) standard = request.POST.get('the_class') the_class = Class.objects.get(school=school, standard=standard) print('the_class = %s' % the_class) sec = request.POST.get('section') print('sec = %s' % sec) if sec != '': section = sec.split(',') # section = Section.objects.get(school=school, section=sec) print('section = %s' % section) all_sections = request.POST.get('all_sections') print(all_sections) sub = request.POST.get('subject') subject = Subject.objects.get(school=school, subject_name=sub) print('subject = %s' % subject) youtube_link = request.POST.get('youtube_link') print('youtube_link = %s' % youtube_link) if youtube_link == '': youtube_link = 'N/A' lesson_topic = request.POST.get('lesson_topic') print('lesson_topic = %s' % lesson_topic) try: lecture = Lecture(teacher=teacher, the_class=the_class, subject=subject, topic=lesson_topic, youtube_link=youtube_link) lecture.save() except Exception as e: print('exception 29032020-A from lecture views.py %s %s' % (e.message, type(e))) print('failed in creating lecture record') file_included = request.POST.get('file_included') print('file_included = %s' % file_included) if file_included == 'true' or file_included == 'yes': include_link = True doc_file = request.FILES['file'] print(type(doc_file)) print('doc_file = %s' % doc_file) print(doc_file) # 05/04/2020 - a lot of stupid teachers use characters like (, ), & in file name which causes issues file_name3 = request.POST.get('file_name').replace(' ', '_') file_name2 = file_name3.replace('&', '_') file_name1 = file_name2.replace('(', '_') file_name = file_name1.replace(')', '_') # long_link = 'https://storage.cloud.google.com/classup/classup2/media/prod/image_video/%s' % \ # image_name.replace('@', '') long_link = 'https://classup2.s3.us-east-2.amazonaws.com/media/prod/image_video/%s' % \ file_name.replace('@', '') print('long_link = %s' % long_link) short_link = long_link # prepare short link global_conf = GlobalConf.objects.get(pk=1) key = global_conf.short_link_api url = 'https://cutt.ly/api/api.php?' url += 'key=%s&short=%s' % (key, long_link) print('url for generating short link = %s' % url) try: req = urllib2.Request(url, headers={'User-Agent': "Magic Browser"}) response = urllib2.urlopen(req) print('response for generating short link = %s' % response) outcome = json.loads(response.read()) print('ouctome = ') print(outcome) status = outcome['url']['status'] print('status = %i' % status) if status == 7: short_link = outcome['url']['shortLink'] print('short_lint = %s' % short_link) except Exception as e: print('exception 14122019-B-A from lecture views.py %s %s' % (e.message, type(e))) print( 'failed to generate short link for the lesson doc uploaded by %s' % teacher) try: print('doc_file = ') print(doc_file) lecture.pdf_link = short_link lecture.doc_file = doc_file lecture.save() except Exception as e: print('exception 29032020-B from lecture views.py %s %s' % (e.message, type(e))) print('error in saving document pdf') if all_sections == 'true' or all_sections == 'yes': print('this lecture to be shared with all sections of class %s' % the_class) students = Student.objects.filter(current_class=the_class, active_status=True) else: print('this lecture to be shared with class %s-%s' % (the_class, section)) sections = reduce(lambda x, y: x | y, [ Q(current_section=Section.objects.get(school=school, section=a_section)) for a_section in section ]) print(sections) try: students = Student.objects.filter(sections, current_class=the_class, active_status=True) print(students) except Exception as e: print('exception 07042020-A from lecture views.py %s %s' % (e.message, type(e))) for student in students: message = 'Dear %s, class %s %s %s lecture shared. Link: %s ' % \ (student, standard, sub, lesson_topic, youtube_link) if file_included == 'true' or file_included == 'yes': message += ' Assignment link: %s' % short_link print(message) p = student.parent m1 = p.parent_mobile1 sms.send_sms1(school, teacher_email, m1, message, message_type) return JSONResponse(context_dict, status=200)
def send_health_record(request): context_dict = { } context_dict['user_type'] = 'school_admin' context_dict['school_name'] = request.session['school_name'] # first see whether the cancel button was pressed if "cancel" in request.POST: return render(request, 'classup/setup_index.html', context_dict) # now start processing the file upload context_dict['header'] = 'Upload Health Data' if request.method == 'POST': # get the file uploaded by the user form = ExcelFileUploadForm(request.POST, request.FILES) context_dict['form'] = form if form.is_valid(): try: # determine the school for which this processing is done school_id = request.session['school_id'] school = School.objects.get(id=school_id) sender = request.session['user'] print('school=' + school.school_name) print ('now starting to process the uploaded file for sending Health data...') fileToProcess_handle = request.FILES['excelFile'] # check that the file uploaded should be a valid excel # file with .xls or .xlsx if not validate_excel_extension(fileToProcess_handle, form, context_dict): return render(request, 'classup/setup_data.html', context_dict) # if this is a valid excel file - start processing it fileToProcess = xlrd.open_workbook(filename=None, file_contents=fileToProcess_handle.read()) sheet = fileToProcess.sheet_by_index(0) if sheet: print('Successfully got hold of sheet!') for row in range(sheet.nrows): # skip the header rows if row == 0: continue print('Processing a new row') erp_id = sheet.cell(row, 1).value try: student = Student.objects.get(school=school, student_erp_id=erp_id) print ('dealing with % s %s' % (student.fist_name, student.last_name)) parent_name = student.parent.parent_name mobile = student.parent.parent_mobile1 weight = sheet.cell(row, 3).value if weight == '': weight = 'N/A' message = 'Dear %s, weight of your ward %s during last health checkup is %s KG' % \ (parent_name, student.fist_name, weight) message_type = 'Health Data Communication (Web)' print(message) sms.send_sms1(school, sender, mobile, message, message_type) except Exception as e: print ('failed to send health data for %s' % erp_id) print ('Exception 041117-A from parents views.py %s %s ' % (e.message, type(e))) messages.success(request, 'health data sent to parents') except Exception as e: print ('invalid excel file uploaded. Please fix and upload again') print ('Exception 041117-B from parents views.py %s %s ' % (e.message, type(e))) else: # we are arriving at this page for the first time, hence show an empty form form = ExcelFileUploadForm() context_dict['form'] = form return render(request, 'classup/setup_data.html', context_dict)
def submit_parents_communication(request): if request.method == 'POST': data = json.loads(request.body) student_id = data['student_id'] cat = data['category'] communication_text = data['communication_text'] student = Student.objects.get(id=student_id) school = student.school configuration = Configurations.objects.get(school=school) # student and category are foreign keys category = ParentCommunicationCategories.objects.get(category=cat) # now, create the ParentCommunicationObject try: pc = ParentCommunication(student=student, category=category, date_sent=datetime.datetime.now(), communication_text=communication_text) pc.save() print ('successfully saved the message "' + communication_text + '" in the database') try: parent_mobile = student.parent.parent_mobile1 action = 'Submitted Parent Communication' log_entry(parent_mobile, action, 'Normal', True) except Exception as e: print('unable to create logbook entry') print ('Exception 500 from parents views.py %s %s' % (e.message, type(e))) # if the message was for Class Teacher/Principal's immediate attention an sms need to be sent to them if cat == 'Class Teacher/Principal Attention' or cat == 'Leave Application' \ or configuration.send_all_parent_sms_to_principal: try: parent = student.parent parent_name = parent.parent_name parent_mobile = parent.parent_mobile1 the_class = student.current_class section = student.current_section # compose the message message_type = 'Parent Communication' message = communication_text + '. Regards, ' + parent_name + ' (' + parent_mobile + ')' message += ', Parent of ' message += student.fist_name + ' ' + student.last_name + ' (class ' message += the_class.standard + '-' + section.section + ')' print (message) # sometimes class teacher may not be set try: ct = ClassTeacher.objects.get(standard=the_class, section=section) if ct: teacher = ct.class_teacher teacher_mobile = teacher.mobile sms.send_sms1(school, parent_name, teacher_mobile, message, message_type) try: parent_mobile = student.parent.parent_mobile1 action = 'Parent Communication SMS sent to Class Teacher: ' action += teacher.first_name + ' ' + teacher.last_name log_entry(parent_mobile, action, 'Normal', True) except Exception as e: print('unable to create logbook entry') print ('Exception 501 from parents views.py %s %s' % (e.message, type(e))) except Exception as e: print('Class Teacher not set for ' + the_class.standard + '-' + section.section) print ('Exception 1 from parents views.py = %s (%s)' % (e.message, type(e))) # 23/07/2019 leave applications need not be sent to principal if cat != 'Leave Application': try: principal_mobile = configuration.principal_mobile sms.send_sms1(school, parent_name, principal_mobile, message, message_type) except Exception as e: print('unable to send Parent communication to Principal') print ('Exception 502-A from parents views.py %s %s' % (e.message, type(e))) # 21/09/2017 - added so that apart from Principal, some other responsible staff can also receive # the message try: admin1_mobile = configuration.admin1_mobile # sms.send_sms1(school, parent_name, admin1_mobile, message, message_type) except Exception as e: print('unable to send Parent communication to Admin 1') print ('Exception 502-B from parents views.py %s %s' % (e.message, type(e))) try: parent_mobile = student.parent.parent_mobile1 action = 'Parent Communication SMS sent to Principal' log_entry(parent_mobile, action, 'Normal', True) except Exception as e: print('unable to create logbook entry') print ('Exception 502 from parents views.py %s %s' % (e.message, type(e))) except Exception as e: print ('failed to send message ' + communication_text + ' to Class Teacher of class ' + the_class.standard + '-' + section.section) print ('Exception 2 from parents views.py = %s (%s)' % (e.message, type(e))) return HttpResponse('Success') except Exception as e: print ('Error occured while trying to save comments from parents of ' + student.fist_name + ' ' + student.last_name) print ('Exception 3 from parents views.py = %s (%s)' % (e.message, type(e))) return HttpResponse('Failed') return HttpResponse('OK')
def process_attendance1(request, school_id, the_class, section, subject, d, m, y, teacher): response_data = {} message_type = 'Attendance' if request.method == 'POST': log_entry(teacher, "Attendance Processing Started", "Normal", True) school = School.objects.get(id=school_id) # all of the above except date are foreign key in Attendance model. Hence we need to get the actual object c = Class.objects.get(school=school, standard=the_class) s = Section.objects.get(school=school, section=section) sub = Subject.objects.get(school=school, subject_name=subject) the_date = date(int(y), int(m), int(d)) t = Teacher.objects.get(email=teacher) teacher_name = '%s %s' % (t.first_name, t.last_name) today = date.today() time_delta = today - the_date print( 'this attendance taken by %s for class %s-%s for subject %s is %i days old' % (teacher_name, the_class, section, subject, time_delta.days)) data = json.loads(request.body) print(data) absent = 0 for key in data: student_id = data[key] student = Student.objects.get(id=student_id) student_name = '%s %s' % (student.fist_name, student.last_name) absent += 1 # check to see if absence for this student for this date, class, section and subject has already # been marked try: q = Attendance.objects.filter(date=the_date, the_class=c, section=s, subject=sub, student=student) # make an entry to database only it is a fresh entry #if q.count() == 0: if not Attendance.objects.filter(date=the_date, the_class=c, section=s, subject=sub, student=student).exists(): action = 'Absence marked for %s %s' % (student.fist_name, student.last_name) print(action) attendance = Attendance(date=the_date) attendance.the_class = c attendance.section = s attendance.subject = sub attendance.student = student attendance.taken_by = t attendance.save() log_entry(teacher, action, "Normal", True) action = 'Starting to send sms to parents of ' + student.fist_name + ' ' + student.last_name log_entry(teacher, action, "Normal", True) # send sms to the parents of absent students m1 = '' m2 = '' try: p = student.parent m1 = p.parent_mobile1 m2 = p.parent_mobile2 except Exception as e: print('Exception occured during processing of: ') print(student) print('Exception3 from attendance views.py = %s (%s)' % (e.message, type(e))) log_entry( teacher, "Attendance Processing Error. Exception 3 from attendance views.py", "Normal", True) print("mobile1=" + m1) print("mobile2=" + m2) message = '' configuration = Configurations.objects.get(school=school) school_name = school.school_name school_short_name = configuration.school_short_name # 14/04/2018 - for collage students, SMS will be sent to students institute_type = configuration.type try: parent_name = student.parent.parent_name # prepare the message action = 'Absence SMS Drafting for ' + parent_name + ' started' log_entry(teacher, action, "Normal", True) # 17/02/17 we are looking to use student first name in messages. # However, some schools store entire name as first name. T # his need to be checke and split first name if entire name is stored as first name the_name = student.fist_name if ' ' in student.fist_name: (f_name, l_name) = the_name.split(' ') else: f_name = the_name if institute_type == 'Collage': message = 'Dear %s, you' % the_name else: message = 'Dear ' + parent_name + ', your ward ' + f_name if institute_type == 'Collage': if time_delta.days == 0: message += ' are' else: message += ' were' else: if time_delta.days == 0: message += ' is' else: message += ' was' # if subject is main then we need to tell that student was absent if subject == 'Main' or subject == 'main' or subject == 'MAIN': message += ' absent on ' + str(d) + '/' + str( m) + '/' + str(y) else: message += ' absent on ' + str(d) + '/' + str(m) + '/' + str(y) + \ ' in the attendance of ' + subject # 04/05/2017 - coaching classes does not require application for absence if configuration.type != 'school': message += '. Regards %s ' % school_short_name else: message += '. Please send an application (Ignore if already done). Regards, ' + school_short_name except Exception as e: print('Exception4 from attendance views.py = %s (%s)' % (e.message, type(e))) action = 'Error in drafting SMS for ' + parent_name + '. Exception 4 from attendance views.py' log_entry(teacher, action, "Normal", True) print(message) # 10/02/2018 - absence SMS will not be sent if attendance is for a date older than 7 days if time_delta.days < 7: print( 'this attendance is recent. Hence SMS will be sent' ) # for coaching classes and colleges we need to send sms for any kind of absence if configuration.send_period_bunk_sms: sms.send_sms1(school, teacher, m1, message, message_type) action = 'Absence SMS sent to ' + parent_name log_entry(teacher, action, "Normal", True) if m2 != '': if configuration.send_absence_sms_both_to_parent: sms.send_sms1(school, teacher, m2, message, message_type) log_entry(teacher, action, "Normal", True) else: # for schools # if this subject is NOT the main subject, then we will # send sms only if the student was present # in main attendance (means the student has BUNKED this class :) if subject != 'Main' and subject != 'main' and subject != 'MAIN': try: main = Subject.objects.get( school=school, subject_name='Main') q = Attendance.objects.filter( date=the_date, the_class=c, section=s, subject=main, student=student) if q.count() == 0: print( student.fist_name + ' ' + student.last_name + ' was not absent in Main attendance. ' 'Looks he has bunked this class...' ) action = student.fist_name + ' ' + student.last_name action += ' found to be bunking the Class!!!' log_entry(teacher, action, "Normal", True) if configuration.send_period_bunk_sms: sms.send_sms1( school, teacher, m1, message, message_type) action = 'Absence SMS sent to ' + student.parent.parent_name log_entry(teacher, action, "Normal", True) if m2 != '': if configuration.send_absence_sms_both_to_parent: sms.send_sms1( school, teacher, m2, message, message_type) action = 'Absence SMS sent to Mrs. ' + student.parent.parent_name log_entry( teacher, action, "Normal", True) except Exception as e: action = 'Unable to send SMS to ' + student.parent.parent_name log_entry(teacher, action, "Normal", True) print('unable to send sms for ' + f_name) print( 'Exception5 from attendance views.py = %s (%s)' % (e.message, type(e))) else: if configuration.send_absence_sms: sms.send_sms1(school, teacher, m1, message, message_type) action = 'Absence SMS sent to ' + student.parent.parent_name log_entry(teacher, action, "Normal", True) if m2 != '': if configuration.send_absence_sms_both_to_parent: sms.send_sms1( school, teacher, m2, message, message_type) action = 'Absence SMS sent to Mrs. ' + student.parent.parent_name log_entry(teacher, action, "Normal", True) else: print( 'this attendance is more than 7 days old. Hence not sending SMS' ) else: print( 'absence for %s for %s in %s has already been marked.' % (student_name, the_date, subject)) except Exception as e: print('Exception6 from attendance views.py = %s (%s)' % (e.message, type(e))) log_entry( teacher, "Absence was already marked. Exception 6 from attendance views.py", "Normal", True) # 16/07/2019 we are implementing table to store daily attendance summaries. # So that download attendance summary is fast print('now storing the attendance summary for %s-%s of %s date %s' % (the_class, section, school, the_date)) try: total = Student.objects.filter(current_class=c, current_section=s, active_status=True).count() print('total students in %s-%s of %s = %i' % (the_class, section, school, total)) present = total - absent percentage = int(round((float(present) / float(total)) * 100, 0)) print(percentage) print('students present on %s = %i' % (the_date, percentage)) try: summary = DailyAttendanceSummary.objects.get(date=the_date, the_class=c, section=s, subject=sub) summary.total = total summary.present = present summary.absent = absent summary.percentage = percentage summary.save() print( 'attendance summary for class %s-%s of %s date %s is updated' % (the_class, section, school, the_date)) except Exception as ex: print('exception 16072019-X from attendance views.py %s %s' % (ex.message, type(ex))) summary = DailyAttendanceSummary(date=the_date, the_class=c, section=s, subject=sub) summary.total = total summary.present = present summary.absent = absent summary.percentage = percentage summary.save() print( 'attendance summary for class %s-%s of %s date %s is stored' % (the_class, section, school, the_date)) except Exception as ex: print('exception 16072019-B from attendance views.py %s (%s)' % (ex.message, type(ex))) print('failed in storing the attendance summary for %s-%s of %s' % (the_class, section, school)) response_data['status'] = 'success' log_entry(teacher, "Attendance Processing Complete", "Normal", True) return JSONResponse(response_data, status=200)