def post(self, request, uidb64=None, token=None, *arg, **kwargs): UserModel = get_user_model() form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) user = Client.objects.get(user=User.objects.get(id=uid)) u = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and shareable_link_token.check_token(u, token): if form.is_valid(): phone_number = form.cleaned_data['phone_number'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] gender = form.cleaned_data['gender'] date_of_birth = form.cleaned_data['date_of_birth'] email_address = form.cleaned_data['email_address'] language = form.cleaned_data['language'] country = Country.objects.get(country_name='Kenya') county = form.cleaned_data['county'] constituency = form.cleaned_data['constituency'] ward = form.cleaned_data['ward'] format_number = SMS() phone_number = format_number.format_phone_number(phone_number) if self.validate_phone_number(phone_number, user) is True: asp = Client.objects.get(user=User.objects.get(id=uid)) new_subscriber = Subscriber(first_name=first_name, last_name=last_name, gender=gender, date_of_birth=date_of_birth, email_address=email_address, language=language, is_active=True, phone_number=phone_number, client=asp, country=country, county=county, constituency=constituency, ward=ward) new_subscriber.save() messages.success(request, 'Successful subscription.') return self.render_to_response( self.get_context_data(form=form)) else: messages.error( request, 'Unsuccessful subscription.You are already subscribed to this client.' ) return self.form_invalid(form) else: messages.error(request, 'Unsuccessful subscription.') return self.form_invalid(form) else: messages.error(request, 'The subscription link is no longer valid.') return self.form_invalid(form)
def register_single_subscriber(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') date_of_birth = request.POST.get('date_of_birth') phone_number = request.POST.get('phone_number') phone_number = phone_number.replace(' ', '') gender = request.POST.get('gender') language_id = request.POST.get('language_id') county_id = request.POST.get('county_id') constituency_id = request.POST.get('constituency_id') ward_id = request.POST.get('ward_id') subscriber = Subscriber() subscriber.first_name = first_name subscriber.last_name = last_name subscriber.email_address = email subscriber.date_of_birth = datetime.datetime.strptime( date_of_birth, '%Y-%m-%d') sms = SMS() subscriber.phone_number = sms.format_phone_number(phone_number) subscriber.gender = gender subscriber.language = Language.objects.get(id=language_id) subscriber.county = County.objects.get(id=county_id) if constituency_id.isdigit(): subscriber.constituency = Constituency.objects.get( id=constituency_id) if ward_id.isdigit(): subscriber.ward = Ward.objects.get(id=ward_id) subscriber.is_active = True subscriber.aspirant = Volunteer.objects.get(user=request.user).aspirant subscriber.volunteer = Volunteer.objects.get(user=request.user) subscriber.date = datetime.datetime.now() try: subscriber.save() return_data['STATUS'] = '1' return_data[ 'MESSAGE'] = 'Subscriber has been registered on the system' except Exception, exp: return_data['STATUS'] = '0' return_data[ 'MESSAGE'] = 'Subscriber failed to be registered {}'.format( str(exp))
def approve_batch_aspirants_upload(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: return_data['ASPIRANTS_REG'] = [] excel_file = ExcelFile(request.session['ASPIRANTS_FILE_URL']) records = excel_file.get_records(True) for record in records: record = list(record) aspirant_reg = {'full_name': '{} {}'.format(record[0], record[1])} try: user_create = User.objects.create_user( first_name=record[0], last_name=record[1], username=record[4], email=record[4], is_superuser=False, is_staff=True, date_joined=datetime.datetime.now()) aspirant_reg['registered_as_user'] = '******' aspirant = Client() aspirant.alias_name = record[2] aspirant.phone_number = SMS.format_phone_number(record[3]) aspirant.user = User.objects.get(username=record[4]) aspirant.seat = Seat.objects.get( Q(seat_name__icontains=record[5]) | Q(short_code__icontains=record[5])) aspirant.region_name = record[6] aspirant.country = Country.objects.get(country_name='Kenya') aspirant.county = County.objects.get(county_name=record[7]) aspirant.constituency = Constituency.objects.get( constituency_name=record[8]) aspirant.ward = Ward.objects.get(ward_name=record[9]) try: aspirant.save() aspirant_reg['registered_as_aspirant'] = '1' except: aspirant_reg['registered_as_aspirant'] = '0' except: aspirant_reg['registered_as_user'] = '******' return_data['ASPIRANTS_REG'].append(aspirant_reg) return HttpResponse(json.dumps(return_data))
def broadcast_survey(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: survey_id = request.POST.get('survey_id') survey = Survey.objects.get(id=survey_id) survey_recipients = SurveyRecipient.objects.filter(survey=survey) sms_util = SmsUtil() shortcode = 1234 try: for recipient in survey_recipients: subscriber = recipient.subscriber phone_number = sms_util.format_phone_number(subscriber.phone_number) try: if len(subscriber.first_name) > 0: msg = """{}, {} is requesting that you participate in this survey. To participate in this survey, send 1 to {}""".format( subscriber.first_name, subscriber.aspirant.alias_name, shortcode) except: msg = """Dear subscriber, {} is requesting that you participate in this survey. To participate in this survey, send 1 to {}""".format( subscriber.aspirant.alias_name, shortcode) sms_menu_log = SMSMenuLog( phone_number=phone_number, date_created=datetime.datetime.now(), menu_type='SURVEY', allowed_options=json.dumps([1]), extra_info=json.dumps({ 'WAS_QUESTION': 0, 'SURVEY_ID': survey_id, 'NEXT_QUESTION_NUMBER': 1 })) sms_menu_log.save() sms_util.send_single_sms(phone_number, msg) recipient.has_been_notified = True recipient.date_notified = datetime.datetime.now() recipient.save() survey.is_sent = True survey.save() return_data['STATUS'] = '1' return_data['MESSAGE'] = 'Survey has been sent to the set subscribers' except Exception, e: return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Survey failed to be sent. Error {}'.format(str(e))
def post(self, request, uidb64=None, token=None, *arg, **kwargs): UserModel = get_user_model() form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) asp = Client.objects.get(user=User.objects.get(id=uid)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and shareable_link_token.check_token(user, token): if form.is_valid(): phone_number = form.cleaned_data['phone_number'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] county = form.cleaned_data['county'] constituency = form.cleaned_data['constituency'] ward = form.cleaned_data['ward'] country = Country.objects.get(country_name='Kenya') format_number = SMS() phone_number = format_number.format_phone_number(phone_number) if self.validate_phone_number(phone_number, asp): new_user = User.objects.create_user(first_name=first_name, last_name=last_name, username=email, password=password, email=email, is_staff=False, is_superuser=False, is_active=True) new_volunteer = Volunteer(phone_number=phone_number, aspirant=asp, user=new_user, country=country, county=county, constituency=constituency, ward=ward, is_active=True) try: new_volunteer.save() messages.success( request, format_html( "{}<a id='anchor_redirect' href='{}://{}/{}'>{}</a>{}", 'Successful volunteer registration.', 'http', request.META['HTTP_HOST'], 'login_page', 'Click Here', ' to access your account.')) txt_template = 'email/volunteer_registration_email.txt' html_template = 'email/volunteer_registration_email.html' recipient = [new_user] try: email = SendEmail() email.tuma_mail(recipient, txt_template, html_template) except Exception, e: print(str(e)) return self.form_valid(form) except Exception, e: new_user.delete() messages.error( request, format_html( "<span class='w3-text-red'>{}</span>", 'Unsuccessful volunteer registration.')) return self.render_to_response( self.get_context_data(form=form)) else: messages.error( request, 'Phone Number exists.Unsuccessful volunteer registration.' ) return self.form_invalid(form)
def batch_approve_subscribers_from_file(request): password = request.POST.get('password') user = User.objects.get(id=request.user.id) return_data = {} if not user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: excel_file = ExcelFile(request.session['SUBSCRIBERS_FILE_URL']) records = excel_file.get_records(True) num_of_records = len(records) i = 0 return_data['MESSAGE'] = [] for record in records: try: record = list(record) subscriber = Subscriber() subscriber.first_name = record[0] subscriber.last_name = record[1] sms_utility = SMS() subscriber.phone_number = sms_utility.format_phone_number( record[2]) subscriber.email_address = record[3] subscriber.country = Country.objects.get(country_name='Kenya') subscriber.gender = record[6] if request.user.is_staff is True and request.user.is_superuser is False: subscriber.aspirant = Client.objects.get(user=request.user) elif request.user.is_staff is False and request.user.is_superuser is False: subscriber.aspirant = Volunteer.objects.get( user=request.user).aspirant subscriber.volunteer = Volunteer.objects.get( user=request.user) if len(record[7]) > 0: subscriber.county = County.objects.get( county_name=record[7]) if len(record[8]) > 0: subscriber.constituency = Constituency.objects.get( constituency_name=record[8]) if len(record[9]) > 0: subscriber.ward = Ward.objects.get(ward_name=record[9]) try: subscriber.date_of_birth = record[5] get_age = lambda dob: datetime.datetime.today().year - dob.year \ - ((datetime.datetime.today().month, datetime.datetime.today().day) \ < (dob.month, dob.day)) subscriber.current_age = get_age(record[5]) except: pass subscriber.date = datetime.datetime.now() subscriber.is_active = True subscriber.save() i += 1 return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': '{} {} has been registered successfully'.format( record[0], record[1]) }) except Exception as exp: print('Errorr while registering {}'.format(exp)) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': '{} {} has not been registered'.format( record[0], record[1]) }) return_data['STATUS'] = '1' return_data['FINAL_MSG'] = '{} subscribers have been uploaded'.format( i) return HttpResponse(json.dumps(return_data))
def register_single_aspirant(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') alias_name = request.POST.get('alias_name') sms = SMS() phone_number = sms.format_phone_number( request.POST.get('phone_number')) seat = Seat.objects.get(id=request.POST.get('seat')) region_name = request.POST.get('region_name') county_id = request.POST.get('county_id') constituency_id = request.POST.get('constituency_id') ward_id = request.POST.get('ward_id') try: user_create = User.objects.create_user( first_name=first_name, last_name=last_name, username=email, email=email, is_superuser=False, is_staff=True, date_joined=datetime.datetime.now()) aspirant_reg = {'full_name': '{} {}'.format(first_name, last_name)} return_data['MESSAGE'] = [] return_data['STATUS'] = '1' return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Client has been registered as system user' }) aspirant = Client() aspirant.alias_name = alias_name aspirant.phone_number = phone_number aspirant.user = User.objects.get(username=email) aspirant.seat = seat aspirant.region_name = region_name aspirant.country = Country.objects.get(country_name='Kenya') aspirant.county = County.objects.get(id=county_id) if len(constituency_id) > 0 and constituency_id != 'NULL': aspirant.constituency = Constituency.objects.get( id=constituency_id) if len(ward_id) > 0 and ward_id != 'NULL': aspirant.ward = Ward.objects.get(id=ward_id) try: aspirant.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Client has been registered as a system admin for {}'. format(region_name) }) try: recipient = [user_create] email = SendEmail() txt_template = 'email/email_temlate_aspirant_registration.txt' print("0000000") html_template = 'email/email_template_aspirant_registration.html' print("11111111") send_mail = email.send_email(recipient, request, txt_template, html_template) print("222222222") if send_mail[0]['STATUS'] == '1': return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'An email has been sent to the client' }) else: print("*****") print(send_mail) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Email delivery to client failed permanently' }) except Exception, exp: print(str(exp)) return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Email delivery to client failed permanently' }) except: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Client has not been registered as a system admin for {}'. format(region_name) }) except: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Client was not registered' }) return HttpResponse(json.dumps(return_data))
def inbox_list(request, offset=0): template = 'sms/inbox_list.html' inboxmsgs = Inbox.objects.filter( message_type='CHAT', user=request.user, is_archived=False).order_by('-date_received') context = {} if request.method == 'POST': start_date = str(request.POST.get('start_date')) end_date = str(request.POST.get('end_date')) sentiment = str(request.POST.get('sentiment')) key_word = str(request.POST.get('key_word')) key_word = str(key_word.strip()) if len(start_date) == 10 and len(end_date) == 10: start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') end_date += datetime.timedelta(days=1) inboxmsgs = inboxmsgs.filter(date_received__gte=start_date, date_received__lte=end_date) elif len(start_date) == 10 and len(end_date) != 10: start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') inboxmsgs = inboxmsgs.filter(date_received__gte=start_date) elif len(end_date) == 10 and len(start_date) != 10: end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') end_date += datetime.timedelta(days=1) inboxmsgs = inboxmsgs.filter(date_received__lte=end_date) if len(key_word) != 0: if key_word.isdigit() and len(key_word) >= 10: sms_util = SMS() phone_number = sms_util.format_phone_number(key_word) inboxmsgs = inboxmsgs.filter(phone_number=phone_number) else: inboxmsgs = inboxmsgs.filter(message__icontains=key_word) if len(sentiment) != 0: inboxmsgs = inboxmsgs.filter(sentiment__icontains=sentiment) context["inboxmsgs"] = inboxmsgs else: offset = int(offset) limit = offset + settings.PAGINATION_OFFSET prev_offset = offset - settings.PAGINATION_OFFSET if prev_offset < 0: prev_offset = 0 next_offset = (offset + settings.PAGINATION_OFFSET) if next_offset > len(inboxmsgs): next_offset = offset print("{} {}".format(offset, limit)) context["inboxmsgs"] = inboxmsgs[offset:limit] context["prevOffset"] = prev_offset context["nextOffset"] = next_offset context["currentOffset"] = offset context["offsetExist"] = True return render(request, template, context)
def receive_sms(request): try: f = open("log.log", "a+") data_to_log = request.POST data_to_log['date_time'] = str(datetime.datetime.now()) f.write("{}\n".format(json.dumps(data_to_log))) f.close() except Exception as e: f = open("log.log", "a+") f.write(str(e)) f.close() sender = request.POST.get( 'from') # phone number from which the message originated from message = request.POST.get('text') # Message from sender message = message.strip() date = request.POST.get('date') # Date time when the message was sent msg_id = request.POST.get('id') # Message ID from Africa's Talking aspirant = Client.objects.all()[0] sms_inbox = Inbox(africastalking_msg_id=msg_id, phone_number=sender, message=message, date_created=datetime.datetime.now(), date_received=date, user=aspirant.user) subscriber_exist = Subscriber.objects.filter(phone_number=sender).exists() volunteer_exist = Volunteer.objects.filter(phone_number=sender).exists() try: message_arr = message.split(' ') first_word = message_arr[0].lower() first_word = first_word.strip() sms_util = SMS() if len(message_arr) == 1: if first_word == 'vote' and subscriber_exist is False: # subscriber user sms_inbox.message_type = 'SUBSCRIBE' sms_inbox.save() subscriber = Subscriber( phone_number=sms_util.format_phone_number(sender), aspirant=aspirant, is_active=True) subscriber.save() ret_msg = """You have successfully subscribe to {}. Send the word campaign to {} to view his campaign."""\ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() return elif first_word == 'volunteer': ret_msg = """To register as {}'s volunteer, send the word volunteer followed by your email address to {}.""" \ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() elif first_word.isdigit(): # SMS menu phone_number = sms_util.format_phone_number(sender) sms_menu_log = SMSMenuLog.objects.filter( phone_number=phone_number).order_by('-date_created')[0] allowed_options = json.loads(sms_menu_log.allowed_options) extra_info = json.loads(sms_menu_log.extra_info) menu_type = sms_menu_log.menu_type menu_option = int(first_word) if menu_option not in allowed_options: msg = extra_info['FALL_BACK_SMS'] sms_util.send_single_sms(phone_number, msg) return if menu_type == 'MANIFESTO': #Send campaign sms_inbox.message_type = 'MANIFESTO' sms_inbox.save() manifesto_id = extra_info['MANIFESTO_ID'] options_mapping = extra_info['OPTIONS_MAPPING'] manifesto = Campaign.objects.get(id=manifesto_id) manifesto_item_id = options_mapping[first_word] manifesto_item = CampaignItems.objects.get( campaign=manifesto, id=manifesto_item_id) manifesto_msg = """{}\n{}""".format( manifesto_item.title, manifesto_item.content) sms_util.send_single_sms(phone_number, manifesto_msg) manifesto_item_reception = CampaignItemsReception( campaign_item=CampaignItems.objects.get( id=manifesto_item_id), date_read=datetime.datetime.now()) try: manifesto_item_reception.subscriber = Subscriber.objects.get( phone_number=phone_number) except: pass manifesto_item_reception.save() elif menu_type == 'SURVEY': #Send survey sms_inbox.message_type = 'SURVEY' sms_inbox.save() survey_id = extra_info['SURVEY_ID'] was_question = extra_info['WAS_QUESTION'] if was_question == 1: # Save survey response options_mapping = extra_info['OPTIONS_MAPPING'] survey_response = SurveyResponse() survey_response.survey_option = SurveyOptions.objects.get( id=options_mapping[first_word]) try: survey_response.subscriber = Subscriber.objects.get( phone_number=sms_util.format_phone_number( phone_number)) except: pass survey_response.save() next_question_number = extra_info['NEXT_QUESTION_NUMBER'] survey = Survey.objects.get(id=survey_id) try: survey_question = SurveyQuestion.objects.get( survey=survey, question_number=next_question_number) question_options = SurveyOptions.objects.filter( survey_question=survey_question) msg = "{}\n".format(survey_question.question) fall_back_sms = "Invalid option.\n" allowed_options = [] options_mapping = {} for i in range(0, len(question_options)): msg += "{}. {}\n".format( i + 1, question_options[i].option) fall_back_sms += "{}. {}\n".format( i + 1, question_options[i].option) allowed_options.append(i + 1) options_mapping[i + 1] = question_options[i].id SMSMenuLog(date_created=datetime.datetime.now(), phone_number=phone_number, menu_type='SURVEY', allowed_options=json.dumps(allowed_options), extra_info=json.dumps({ 'WAS_QUESTION': 1, 'NEXT_QUESTION_NUMBER': next_question_number + 1, 'SURVEY_ID': survey_id, 'FALL_BACK_SMS': fall_back_sms, 'OPTIONS_MAPPING': options_mapping })).save() sms_util.send_single_sms(phone_number, msg) except: msg = "Thank you for participating in this survey." sms_util.send_single_sms(phone_number, msg) elif first_word == 'volunteer' and volunteer_exist is False: # Register volunteer sms_inbox.message_type = 'VOLUNTEER' sms_inbox.save() email_address = message_arr[1] try: validate_email(email_address) user = User(username=email_address, email=email_address) user.save() volunteer = Volunteer( phone_number=sms_util.format_phone_number(sender), aspirant=aspirant, is_active=True, user=user) volunteer.save() try: recipient = [user] email = SendEmail() txt_template = 'email/email_template_volunteer_registration.txt' html_template = 'email/email_template_volunteer_registration.html' send_mail = email.tuma_mail(recipient, txt_template, html_template) if send_mail: ret_msg = """You have successfully been registered as {}'s volunteer. A verification link has been sent to {}.""" \ .format(aspirant.alias_name, email_address) else: ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \ .format(email_address) volunteer.delete() user.delete() except Exception, e: ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \ .format(email_address) volunteer.delete() user.delete() sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), message=ret_msg, message_type="ACK", is_sent=True, user=aspirant.user, date_sent=datetime.datetime.now()).save() return except: ret_msg = """Invalid email address.Please send the word volunteer followed by a valid email address to {}.""" \ .format(aspirant.alias_name, settings.SMS_SHORT_CODE) sms_util.send_single_sms(sms_util.format_phone_number(sender), ret_msg) Outbox(phone_number=sms_util.format_phone_number(sender), user=aspirant.user, message=ret_msg, message_type="ACK", is_sent=True, date_sent=datetime.datetime.now()).save()