def request_details(request, request_pk): """Supply request details view""" sreq = get_object_or_404(SupplyRequest, id=request_pk) if request.method == "POST": original_status = sreq.status form = SupplyRequestForm(request.POST, instance=sreq) if form.is_valid(): sreq = form.save(commit=False) sreq.modified = datetime.utcnow() sreq.save() if sreq.status != original_status and \ sreq.requested_by and \ sreq.requested_by.default_connection: # if the status has changed, let's send a message # to the original requester so they know things are # proceeding. text = ("Your request for more %(supply)s at %(loc)s has been updated! " +\ "The new status is: %(status)s.") % \ {"supply": sreq.type.name, "loc": sreq.location.name, "status": sreq.get_status_display().upper()} send_message(sreq.requested_by.default_connection, text) return web_message(request, "Supply request %d status set to %s" % \ (sreq.pk, sreq.get_status_display()), link=reverse("supply_dashboard")) elif request.method == "GET": form = SupplyRequestForm(instance=sreq) return render_to_response(request, "supply/single_request.html", {"sreq": sreq, "form": form})
def group_message(request): fn_tree = get_fn_tree() success_count = 0 failures = [] if request.method == "POST": msg = request.POST.get("msg") contacts = post_to_contact_set(request) if not msg: messages.error(request, "No message supplied.") elif not contacts: messages.error(request, "No contacts selected.") else: for contact in contacts: try: send_message(contact.default_connection, msg) success_count += 1 except Exception, e: failures.append(contact.name) if success_count: messages.success(request, "Sent message to %d people." % success_count) else: messages.warning(request, "Didn't send any messages.") if failures: messages.error( request, "Failed to send message to %d people (%s)" % (len(failures), ", ".join(failures)) )
def send_nag_messages(warnings): for w in warnings: for hsa in w["hsas"]: previous_nags = NagRecord.objects.filter(supply_point=hsa, nag_type=w["code"]).order_by("-report_date") if previous_nags: # don't nag anyone we've nagged for the same reason in the last 24 hours last_nag_date = previous_nags[0].report_date if datetime.utcnow() - last_nag_date < timedelta(hours=MIN_NAG_INTERVAL): continue try: contact = Contact.objects.get(supply_point=hsa) send_message(contact.default_connection, w["message"] % {"hsa": contact.name, "days": w["days"]}) NagRecord(supply_point=hsa, warning=w["number"], nag_type=w["code"]).save() except Contact.DoesNotExist: logging.error("Contact does not exist for HSA: %s" % hsa.name) continue if w["flag_supervisor"]: for supervisor in Contact.objects.filter( is_active=True, role=ContactRole.objects.get(code=config.Roles.HSA_SUPERVISOR), supply_point=hsa.supplied_by, ): send_message(supervisor.default_connection, w["supervisor_message"] % {"hsa": contact.name})
def send_text_message(mothers = None, message = None, mothers_messages = None): # mass SMS sender is used to send a message to a # list of mothers. success = 0 mother_received = [] mother_not_received = [] # send personalized message mothers # mother_message is list of dictionary dictionary data type. # the dictioanry has "mother" and "message" keys if mothers_messages is not None: for mother_message in mothers_messages: try: connection = mother_message["mother"].default_connection send_message(connection, mother_message["message"]) success += 1 mother_received.append(mother_message["mother"]) except Exception, e: pass for mother_message in mothers_messages: if mother_message["mother"] not in mother_received: mother_not_received.append(mother_message["mother"])
def send_text_message(reporters = None, message = None, reporters_messages = None): # mass SMS sender is used to send a message to a # list of reporters. success = 0 reporter_received = [] reporter_not_received = [] # send personalized message reporters # reporter_message is list of dictionary dictionary data type. # the dictioanry has "reporter" and "message" keys if reporters_messages is not None: for reporter_message in reporters_messages: try: connection = reporter_message["reporter"].default_connection send_message(connection, reporter_message["message"]) success += 1 reporter_received.append(reporter_message["reporter"]) except Exception, e: pass for reporter_message in reporters_messages: if reporter_message["reporter"] not in reporter_received: reporter_not_received.append(reporter_message["reporter"])
def send_nag_messages(warnings): for w in warnings: for hsa in w["hsas"]: previous_nags = NagRecord.objects.filter(supply_point=hsa, nag_type=w['code'])\ .order_by('-report_date') if previous_nags: # don't nag anyone we've nagged for the same reason in the last 24 hours last_nag_date = previous_nags[0].report_date if datetime.utcnow() - last_nag_date < timedelta( hours=MIN_NAG_INTERVAL): continue try: contact = Contact.objects.get(supply_point=hsa) send_message( contact.default_connection, w["message"] % { 'hsa': contact.name, 'days': w['days'] }) NagRecord(supply_point=hsa, warning=w["number"], nag_type=w['code']).save() except Contact.DoesNotExist: logging.error("Contact does not exist for HSA: %s" % hsa.name) continue if w["flag_supervisor"]: for supervisor in Contact.objects.filter( is_active=True, role=ContactRole.objects.get( code=config.Roles.HSA_SUPERVISOR), supply_point=hsa.supplied_by): send_message( supervisor.default_connection, w["supervisor_message"] % {'hsa': contact.name})
def send_notification (router, patient_pk, day): """send the notification for day N""" reg = Registration.objects.get(pk=patient_pk) send_message(reg.connection, get_notification(day, reg.language)) #check for success? log = SentNotif(patient_id=reg, day=day) log.save()
def randr_summary(): """ "R&R - 6/10 submitted, 2/10 did not submit, 3/10 did not reply" - 17th of the month @ 3pm """ for contact in get_district_people(): if contact.default_connection: send_message(contact.default_connection, construct_randr_summary_message(contact.supply_point))
def soh_summary(): """ "SOH - 6/10 reported, 4/10 did not reply" - 6th of the month @ 3pm """ for contact in get_district_people(): if contact.default_connection: send_message(contact.default_connection, construct_soh_summary_message(contact.supply_point))
def delivery_summary(): """ "Deliveries - 5/10 received, 4/10 did not receive, 1/10 users did not reply" - last business day of month 3pm """ for contact in get_district_people(): if contact.default_connection: send_message(contact.default_connection, construct_delivery_summary_message(contact.supply_point))
def delivery_summary(): """ "Deliveries - 5/10 received, 4/10 did not receive, 1/10 users did not reply" - last business day of month 3pm """ for contact in get_district_people(): if contact.default_connection: send_message( contact.default_connection, construct_delivery_summary_message(contact.supply_point))
def send(req): text = req.POST["text"] data = json.loads(req.POST["recipients"]) sent_to = [] for item in data: contact = get_object_or_404(Contact, pk=item) send_message(contact.default_connection, text) sent_to.append(contact) return HttpResponse("'%s' sent to %s" % (text, ", ".join(str(c) for c in sent_to)))
def sms_send(user, content): try: conn = Connection.objects.get(contact__user=user) except: print 'user [%s] has no contact info; can\'t send sms alert' % user_name(user) logging.exception('error retriving contact info for user [%s]; can\'t send sms alert' % user_name(user)) return send_message(conn, content) print 'sent sms alert to [%s]' % user_name(user)
def request_details(request, request_pk): """Supply request details view""" sreq = get_object_or_404(SupplyRequest, id=request_pk) if request.method == "POST": original_status = sreq.status form = SupplyRequestForm(request.POST, instance=sreq) if form.is_valid(): sreq = form.save(commit=False) sreq.modified = datetime.utcnow() sreq.save() if sreq.status != original_status and \ sreq.requested_by and \ sreq.requested_by.default_connection: # if the status has changed, let's send a message # to the original requester so they know things are # proceeding. text = ("Your request for more %(supply)s at %(loc)s has been updated! " +\ "The new status is: %(status)s.") % \ {"supply": sreq.type.name, "loc": sreq.location.name, "status": sreq.get_status_display().upper()} send_message(sreq.requested_by.default_connection, text) return web_message(request, "Supply request %d status set to %s" % \ (sreq.pk, sreq.get_status_display()), link=reverse("supply_dashboard")) elif request.method == "GET": form = SupplyRequestForm(instance=sreq) return render_to_response(request, "supply/single_request.html", { "sreq": sreq, "form": form })
def registration(req, pk=None, template="registration/dashboard.html", contact_form=CommoditiesContactForm): contact = None connection = None bulk_form = None search = None registration_view = 'registration' registration_edit = 'registration_edit' if hasattr(settings, 'SMS_REGISTRATION_VIEW'): registration_view = settings.SMS_REGISTRATION_VIEW if hasattr(settings, 'SMS_REGISTRATION_EDIT'): registration_edit = settings.SMS_REGISTRATION_EDIT if pk is not None: contact = get_object_or_404( Contact, pk=pk) try: connection = Connection.objects.get(contact=contact) except Connection.DoesNotExist: connection = None if req.method == "POST": if req.POST["submit"] == "Delete Contact": name = unicode(contact) contact.delete() return HttpResponseRedirect("%s?deleted=%s" % (reverse(registration_view), name)) elif "bulk" in req.FILES: # TODO use csv module #reader = csv.reader(open(req.FILES["bulk"].read(), "rb")) #for row in reader: for line in req.FILES["bulk"]: line_list = line.split(',') name = line_list[0].strip() backend_name = line_list[1].strip() identity = line_list[2].strip() contact = Contact(name=name) contact.save() # TODO deal with errors! backend = Backend.objects.get(name=backend_name) connection = Connection(backend=backend, identity=identity,\ contact=contact) connection.save() return HttpResponseRedirect( reverse(registration_view)) else: contact_form = contact_form( instance=contact, data=req.POST) if contact_form.is_valid(): created = False if contact is None: created = True contact = contact_form.save() if created: response = "Dear %(name)s, you have been registered on %(site)s" % \ {'name': contact.name, 'site': Site.objects.get(id=settings.SITE_ID).domain } send_message(contact.default_connection, response) return HttpResponseRedirect("%s?created=%s" % (reverse(registration_edit, kwargs={'pk':contact.pk}), unicode(contact))) else: if pk is None: supplypoint = None if "supplypoint" in req.GET and req.GET["supplypoint"]: try: supplypoint = SupplyPoint.objects.get(code=req.GET["supplypoint"]) except SupplyPoint.DoesNotExist, SupplyPoint.MultipleObjectsReturned: pass contact_form = contact_form( instance=contact, initial={'supply_point':supplypoint}) else:
def send_reminders(contacts, message): for contact in contacts: if contact.default_connection: send_message(contact.default_connection, _(message))
def run(*args, **kwargs): for service in Service.objects.filter(active=True): if service.service_type == SERVICE_MONITOR__SMS: # # Handle SMS Monitoring # if service.can_ping_again(): # Mark the request as being sent for this service current_date = datetime.datetime.now(tz=pytz.utc) service.last_request_date = current_date service.last_response_date = None service.ping_state = SERVICE_MONITOR__REQUEST_SENT service.save() # Create an entry in the PingLog pinglog_entry = PingLog(service=service,date=current_date,ping_state=service.ping_state) pinglog_entry.save() # Send the SMS send_message(service.connection, service.sms_to_send) elif service.ping_state == SERVICE_MONITOR__REQUEST_SENT and service.has_timed_out(): # Mark the request as having no response service.ping_state = SERVICE_MONITOR__NO_RESPONSE service.save() # Create an entry in the PingLog current_date = datetime.datetime.now(tz=pytz.utc) pinglog_entry = PingLog(service=service,date=current_date,ping_state=service.ping_state) pinglog_entry.save() # Send an email notification send_notification_email(service) elif service.service_type == SERVICE_MONITOR__HTTP: # # Handle HTTP Monitoring # if service.can_ping_again(): # Mark the request as being sent for this service current_date = datetime.datetime.now(tz=pytz.utc) service.last_request_date = current_date service.last_response_date = None service.ping_state = SERVICE_MONITOR__REQUEST_SENT service.save() # Create an entry in the PingLog pinglog_entry = PingLog(service=service,date=current_date,ping_state=service.ping_state) pinglog_entry.save() # Try to send the request try: result = urllib2.urlopen(service.url,timeout=service.timeout_minutes*60) # Mark the service as having responded current_date = datetime.datetime.now(tz=pytz.utc) service.last_response_date = current_date service.ping_state = SERVICE_MONITOR__VALID_RESPONSE_RECEIVED service.save() # Create an entry in the PingLog pinglog_entry = PingLog(service=service,date=current_date,ping_state=service.ping_state) pinglog_entry.save() except URLError as e: # Mark the request as having no response service.ping_state = SERVICE_MONITOR__NO_RESPONSE service.save() # Create an entry in the PingLog current_date = datetime.datetime.now(tz=pytz.utc) pinglog_entry = PingLog(service=service,date=current_date,ping_state=service.ping_state) pinglog_entry.save() # Send an email notification send_notification_email(service,urlerror=e)
def save(self): number = self.cleaned_data['number'] backend = self.cleaned_data['backend'] connection, _ = Connection.objects.get_or_create(backend=backend, identity=number) return send_message(connection, self.cleaned_data['message'])
def registration(req, pk=None, template="registration/dashboard.html", contact_form=CommoditiesContactForm): contact = None connection = None bulk_form = None search = None registration_view = 'registration' registration_edit = 'registration_edit' if hasattr(settings, 'SMS_REGISTRATION_VIEW'): registration_view = settings.SMS_REGISTRATION_VIEW if hasattr(settings, 'SMS_REGISTRATION_EDIT'): registration_edit = settings.SMS_REGISTRATION_EDIT if pk is not None: contact = get_object_or_404(Contact, pk=pk) try: connection = Connection.objects.get(contact=contact) except Connection.DoesNotExist: connection = None if req.method == "POST": if req.POST["submit"] == "Delete Contact": name = unicode(contact) contact.delete() return HttpResponseRedirect("%s?deleted=%s" % (reverse(registration_view), name)) elif "bulk" in req.FILES: # TODO use csv module #reader = csv.reader(open(req.FILES["bulk"].read(), "rb")) #for row in reader: for line in req.FILES["bulk"]: line_list = line.split(',') name = line_list[0].strip() backend_name = line_list[1].strip() identity = line_list[2].strip() contact = Contact(name=name) contact.save() # TODO deal with errors! backend = Backend.objects.get(name=backend_name) connection = Connection(backend=backend, identity=identity,\ contact=contact) connection.save() return HttpResponseRedirect(reverse(registration_view)) else: contact_form = contact_form(instance=contact, data=req.POST) if contact_form.is_valid(): created = False if contact is None: created = True contact = contact_form.save() if created: response = "Dear %(name)s, you have been registered on %(site)s" % \ {'name': contact.name, 'site': Site.objects.get(id=settings.SITE_ID).domain } send_message(contact.default_connection, response) return HttpResponseRedirect( "%s?created=%s" % (reverse(registration_edit, kwargs={'pk': contact.pk}), unicode(contact))) else: if pk is None: supplypoint = None if "supplypoint" in req.GET and req.GET["supplypoint"]: try: supplypoint = SupplyPoint.objects.get( code=req.GET["supplypoint"]) except SupplyPoint.DoesNotExist, SupplyPoint.MultipleObjectsReturned: pass contact_form = contact_form(instance=contact, initial={'supply_point': supplypoint}) else:
success += 1 reporter_received.append(reporter_message["reporter"]) except Exception, e: pass for reporter_message in reporters_messages: if reporter_message["reporter"] not in reporter_received: reporter_not_received.append(reporter_message["reporter"]) else: # a message to list of reporters for reporter in reporters: try: connection = reporter.default_connection send_message(connection, message) success += 1 reporter_received.append(reporter) except Exception, e: pass #print e reporter_not_received = filter(lambda reporters: reporters not in reporter_received, reporters) return (message, reporter_received, reporter_not_received) def get_late_reporters(): current_period = get_or_generate_reporting_period()