def handle(self, text): if not self.msg.contact: self.respond(self.UNGREGISTERED) return text = text.strip() if not text: self.respond(self.HELP_TEXT) return clinic_code = text[:6] try: location = Location.objects.get(slug=clinic_code) except Location.DoesNotExist: self.respond(self.UNKNOWN_LOCATION, code=clinic_code) return contact = self.msg.contact TrainingSession.objects.create(trainer=contact, location=location) for help_admin in Contact.active.filter(is_help_admin=True): ha_msg = OutgoingMessage(help_admin.default_connection, "Training is starting at %s, %s" ". Notification was sent by %s, %s" % (location.name, location.slug, contact.name, contact.default_connection.identity)) ha_msg.send() self.respond("Thanks %(name)s for your message that training is " "starting for %(clinic)s. At end of training please send TRAINING STOP", name=contact.name, clinic=location.name)
def handle(self, text): if not self.msg.contact: self.respond(self.UNGREGISTERED) return text = text.strip() if not text: self.respond(self.HELP_TEXT) return clinic_code = text[:6] try: location = Location.objects.get(slug=clinic_code) except Location.DoesNotExist: self.respond(self.UNKNOWN_LOCATION, code=clinic_code) return contact = self.msg.contact TrainingSession.objects.create(trainer=contact, location=location) for help_admin in Contact.active.filter(is_help_admin=True): ha_msg = OutgoingMessage( help_admin.default_connection, "Training is starting at %s, %s" ". Notification was sent by %s, %s" % (location.name, location.slug, contact.name, contact.default_connection.identity)) ha_msg.send() self.respond( "Thanks %(name)s for your message that training is " "starting for %(clinic)s. At end of training please send TRAINING STOP", name=contact.name, clinic=location.name)
def status_update(self): """ cron job handler """ from goals.models import Goal self.debug('{0} running'.format(SCHEDULE_DESC)) now = datetime.datetime.now() goals = Goal.active.filter(date_next_notified__lt=now) goals = goals.exclude(schedule_start_date__isnull=True, schedule_frequency='') self.info('found {0} goals'.format(goals.count())) for goal in goals: msg = OutgoingMessage(connection=goal.contact.default_connection, template=self.template, goal=goal.body, month=goal.date_created.strftime('%b')) try: msg.send() except Exception, e: self.exception(e) # Disable this goal if it was a one-time notification (we just # sent it). This will make get_next_date() return None below. if goal.schedule_frequency == 'one-time': goal.schedule_frequency = '' goal.date_last_notified = now goal.date_next_notified = goal.get_next_date() goal.in_session = True goal.save()
def sms_password_complete(request, template_name='accounts/sms_password_done.html'): contact_detail = ContactDetail.objects.get(user=request.user.ilsgatewayuser) default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("Your password is: password")) m.send() return render_to_response(template_name, context_instance=RequestContext(request, {'login_url': settings.LOGIN_URL}))
def notify_clinic_of_changed_records(self, clinic): """Notifies clinic of the new status for changed results.""" changed_results = [] updated_results = self._updated_results(clinic) if not updated_results: return for updated_result in updated_results: if updated_result.record_change: changed_results.append(updated_result) if not changed_results: return contacts = \ Contact.active.filter(Q(location=clinic)|Q(location__parent=clinic), Q(types=const.get_clinic_worker_type())).\ order_by('pk') if not contacts: self.warning("No contacts registered to receive results at %s! " "These will go unreported until clinic staff " "register at this clinic." % clinic) return RESULTS_CHANGED = "URGENT: A result sent to your clinic has changed. Please send your pin, get the new result and update your logbooks." if len(changed_results) > 1: RESULTS_CHANGED = "URGENT: Some results sent to your clinic have changed. Please send your pin, get the new results and update your logbooks." all_msgs = [] help_msgs = [] for contact in contacts: msg = OutgoingMessage(connection=contact.default_connection, template=RESULTS_CHANGED) all_msgs.append(msg) contact_details = [] for contact in contacts: contact_details.append("%s:%s" % (contact.name, contact.default_connection.identity)) if all_msgs: self.send_messages(all_msgs) self._mark_results_pending(changed_results, (msg.connection for msg in all_msgs)) for help_admin in Contact.active.filter(is_help_admin=True): h_msg = OutgoingMessage( help_admin.default_connection, "Make a followup for changed results %s: %s. Contacts = %s" % (clinic.name, ";****".join("ID=" + res.requisition_id + ", Result=" + res.result + ", old value=" + res.old_value for res in changed_results), ", ".join(contact_detail for contact_detail in contact_details)) ) help_msgs.append(h_msg) if help_msgs: self.send_messages(help_msgs) logger.info("sent following message to help admins: %s" % help_msgs[0].text) else: logger.info("There are no help admins")
def send_messages(self): """ send queued for delivery messages """ messages = SendReminder.objects.filter(status='queued')[:50] self.info('found {0} reminder(s) to send'.format(messages.count())) for message in messages: connection = message.recipient.default_connection template = u'{reminder} {content}'.format( reminder=self.reminder, content=message.message or "" ) if len(template) > 160: # Truncate at 160 characters but keeping whole words template = template[:160] words = template.split(' ')[:-1] template = u' '.join(words) + u'...' msg = OutgoingMessage(connection=connection, template=template) success = True try: self.router.outgoing(msg) except Exception, e: self.exception(e) success = False if success and msg.sent: self.debug('message sent successfully') message.status = 'sent' message.date_sent = datetime.datetime.now() else: self.debug('message failed to send') message.status = 'error' message.save()
def patient_onetime_message(request, patient_id): """Send a onetime message to a patient. Default to getting it from their feeds but allow editing that.""" patient = get_object_or_404(patients.Patient, pk=patient_id) if request.method == 'POST': form = PatientOnetimeMessageForm(request.POST) if form.is_valid(): message = form.cleaned_data['message'] connection = patient.contact.default_connection msg = OutgoingMessage(connection, message) router = Router() success = True try: router.outgoing(msg) except Exception, e: logger.exception(e) success = False if success: messages.success( request, "Message sent to patient %s" % patient.subject_number) else: messages.error( request, "An error occurred while trying to send the message to patient %s" % patient.subject_number) return redirect('patient-list')
def responder_loop(self, seconds=10): self.info("Starting responder...") while True: # look for any new handled messages # in the database, and send the responses for msg_in_waiting in MessageInWaiting.objects.filter(status="H"): self.info("Responding to %s.", msg_in_waiting) for response in msg_in_waiting.responses.all(): self.info("Response: %s.", response) # only send confirmed or added responses if response.type != "O": db_connection = msg_in_waiting.get_connection() if db_connection is not None: db_backend = db_connection.backend # we need to get the real backend from the router # to properly send it real_backend = self.router.get_backend(db_backend.slug) if real_backend: connection = Connection(real_backend, db_connection.identity) response_msg = OutgoingMessage(connection, response.text) self.router.outgoing(response_msg) else: # TODO: should we fail harder here? This will permanently # disable responses to this message which is bad. self.error("Can't find backend %s. Messages will not be sent") # mark the original message as responded to msg_in_waiting.status="R" msg_in_waiting.save() # wait until it's time to check again time.sleep(seconds)
def send_endof_training_notification(router): logger.info('checking pending training sessions') pending_trainings = TrainingSession.objects.filter(is_on=True) for training in pending_trainings: OutgoingMessage(training.trainer.default_connection, DELAYED_TRAINING_TRAINER_MSG % (training.trainer.name, training.location.name) ).send() for help_admin in Contact.active.filter(is_help_admin=True): OutgoingMessage(help_admin.default_connection, DELAYED_TRAINING_ADMIN_MSG % (training.trainer.name, training.trainer.default_connection.identity, training.location.name, training.location.slug) ).send()
def save(self): number = self.cleaned_data['number'] backend = self.cleaned_data['backend'] connection, _ = Connection.objects.get_or_create(backend=backend, identity=number) msg = OutgoingMessage(connection, self.cleaned_data['message']) router = Router() return router.backends[backend.name].send(msg)
def session_end(sender, **kwargs): session = kwargs['session'] canceled = kwargs['canceled'] message = kwargs['message'] # for convenience PatientSurvey = aremind.apps.adherence.models.PatientSurvey # find the patient connection = session.connection try: patient = Patient.objects.get(contact=connection.contact) except Patient.DoesNotExist: # No patient, this session might not be relevant to this app return survey = PatientSurvey.find_active(patient, QUERY_TYPE_SMS) if not survey: return if canceled: survey.completed(PatientSurvey.STATUS_NOT_COMPLETED) return tree = session.tree entries = session.entries if entries.count() < 1: survey.completed(PatientSurvey.STATUS_NOT_COMPLETED) return entry = entries.all()[0] # Pick the relevant part of the answer text = re.match(ANSWER_RE, entry.text).group(1) num_pills = int(text) if not survey.is_test: aremind.apps.adherence.models.PillsMissed( patient=patient, num_missed=num_pills, source=QUERY_TYPE_SMS).save() survey.completed(PatientSurvey.STATUS_COMPLETE) # After completing survey, tell patient what their current adherence is connection = patient.contact.default_connection adherence = patient.adherence() # integer percentage response_text = _( "Thank you. Your adherence is %(adherence)s%%, as measured by the black study pillbox." ) kwargs = dict(adherence=adherence) if message: message.respond(response_text, **kwargs) else: msg = OutgoingMessage(connection, response_text, **kwargs) router = Router() router.outgoing(msg)
def _send_question(self, session, msg=None): '''Sends the next question in the session, if there is one''' state = session.state if state and state.question: response = _(state.question.text, get_language_code(session.connection)) self.info("Sending: %s" % response) if msg: msg.respond(response) else: # we need to get the real backend from the router # to properly send it real_backend = self.router.get_backend(session.connection.backend.slug) if real_backend: connection = Connection(real_backend, session.connection.identity) outgoing_msg = OutgoingMessage(connection, response) outgoing_msg.send() else: # todo: do we want to fail more loudly than this? error = "Can't find backend %s. Messages will not be sent" % connection.backend.slug self.error(error)
def get_message(contact_detail, msg_code, **kwargs): str = '' message_dict = {} if msg_code == "alert_parent_district_delivery_received_sent_facility": if kwargs['sdp']: message_dict['district_name'] = kwargs['sdp'].name str = "District %(district_name)s has reported that they received their delivery from MSD." if msg_code == "alert_parent_district_sent_randr": if kwargs['sdp']: message_dict['district_name'] = kwargs['sdp'].name str = "District %(district_name)s has reported that they sent their R&R forms to MSD." if msg_code == "lost_adjusted_reminder_sent_facility": str = "Please send in your adjustments in the format 'la <product> +-<amount> +-<product> +-<amount>...'" if msg_code == "soh_reminder_sent_facility": # updated str = "Please send in your stock on hand information in the format 'soh <product> <amount> <product> <amount>...'" if msg_code == "r_and_r_reminder_sent_district": # updated str = "How many R&R forms have you submitted to MSD? Reply with 'submitted A <number of R&Rs submitted for group A> B <number of R&Rs submitted for group B>'" if msg_code == "delivery_received_reminder_sent_facility": # updated str = "Did you receive your delivery yet? Please reply 'delivered <product> <amount> <product> <amount>...'" if msg_code == "supervision_reminder_sent_facility": # updated str = "Have you received supervision this month? Please reply 'supervision yes' or 'supervision no'" if msg_code == "delivery_received_reminder_sent_district": # updated str = "Did you receive your delivery yet? Please reply 'delivered' or 'not delivered'" if msg_code == "r_and_r_reminder_sent_facility": # updated str = "Have you sent in your R&R form yet for this quarter? Please reply \"submitted\" or \"not submitted\"" if msg_code == "alert_delinquent_delivery_sent_district": sdp = contact_detail.service_delivery_point message_dict = { 'not_responded_count': sdp.child_sdps_not_responded_delivery_this_month(), 'not_received_count': sdp.child_sdps_not_received_delivery_this_month() } total = sum([i for i in message_dict.values()]) if total: message_dict['group_name'] = current_delivering_group() message_dict['group_total'] = sdp.child_sdps_receiving().count() str = "Facility deliveries for group %(group_name)s (out of %(group_total)d): %(not_responded_count)d haven't responded and %(not_received_count)d have reported not receiving. See ilsgateway.com" else: str = '' if str != '': m = OutgoingMessage(contact_detail.default_connection, str, **message_dict) else: m = None return m
def send_messages(self): """ send queued for delivery messages """ messages = BroadcastMessage.objects.filter(status='queued')[:50] self.info('found {0} message(s) to send'.format(messages.count())) for message in messages: connection = message.recipient.default_connection msg = OutgoingMessage(connection=connection, template=message.broadcast.body) success = True try: msg.send() except Exception, e: self.exception(e) success = False if success and msg.sent: self.debug('message sent successfully') message.status = 'sent' message.date_sent = datetime.datetime.now() else: self.debug('message failed to send') message.status = 'error' message.save()
def send_messages(self): """ send queued for delivery messages """ messages = BroadcastMessage.objects.filter(status="queued")[:50] if messages.count() > 0: self.info("found {0} message(s) to send".format(messages.count())) for message in messages: connection = message.recipient.default_connection msg = OutgoingMessage(connection=connection, template=message.broadcast.body) success = True try: msg.send() except Exception, e: self.exception(e) success = False if success and msg.sent: self.debug("message sent successfully") message.status = "sent" message.date_sent = datetime.datetime.now() else: self.debug("message failed to send") message.status = "error" message.save()
def results_avail_messages(self, clinic): results = self._pending_results(clinic) contacts = \ Contact.active.filter(Q(location=clinic)|Q(location__parent=clinic), Q(types=const.get_clinic_worker_type())) if not contacts: self.warning("No contacts registered to receiver results at %s! " "These will go unreported until clinic staff " "register at this clinic." % clinic) all_msgs = [] for contact in contacts: msg = OutgoingMessage(connection=contact.default_connection, template=RESULTS_READY, name=contact.name, count=results.count()) all_msgs.append(msg) return all_msgs, results
def send(text, connections): """ Creates an outgoing message and passes it to the router to be processed and sent via the respective backend. """ from rapidsms.router import get_router from rapidsms.messages import OutgoingMessage if not isinstance(connections, collections.Iterable): connections = [connections] router = get_router()() router.start() messages = [] for connection in connections: message = OutgoingMessage(connection, text) router.send_outgoing(message) messages.append(message) router.stop() return messages
def send_results (self, message): """ Sends the actual results in response to the message (comes after PIN workflow). """ results = self.waiting_for_pin[message.connection] clinic = get_clinic_or_default(message.contact) if not results: # how did this happen? self.error("Problem reporting results for %s to %s -- there was nothing to report!" % \ (clinic, message.connection.contact)) message.respond("Sorry, there are no new EID results for %s." % clinic) self.waiting_for_pin.pop(message.connection) else: responses = build_results_messages(results) for resp in responses: message.respond(resp) message.respond(INSTRUCTIONS, name=message.connection.contact.name) for r in results: r.notification_status = 'sent' r.result_sent_date = datetime.now() r.save() self.waiting_for_pin.pop(message.connection) # remove pending contacts for this clinic and notify them it # was taken care of clinic_connections = [contact.default_connection for contact in \ Contact.active.filter\ (location=clinic)] for conn in clinic_connections: if conn in self.waiting_for_pin: self.waiting_for_pin.pop(conn) OutgoingMessage(conn, RESULTS_PROCESSED, name=message.connection.contact.name).send() self.last_collectors[clinic] = \ message.connection.contact
def handle(self, text): if not self.msg.contact: self.respond(self.UNGREGISTERED) return text = text.strip() if not text: self.respond(self.HELP_TEXT) return clinic_code = text[:6] try: location = Location.objects.get(slug=clinic_code) except Location.DoesNotExist: self.respond(self.UNKNOWN_LOCATION, code=clinic_code) return contact = self.msg.contact trainings_at_site = TrainingSession.objects.filter(trainer=contact, location=location, is_on=True) for training in trainings_at_site: training.is_on = False training.end_date = datetime.utcnow() training.save() for help_admin in Contact.active.filter(is_help_admin=True): OutgoingMessage( help_admin.default_connection, "Training has stopped at %s, %s" ". Notification was sent by %s, %s" % (location.name, location.slug, contact.name, contact.default_connection.identity)).send() self.respond( "Thanks %(name)s for your message that training has " "stopped for %(clinic)s.", name=contact.name, clinic=location.name)
def _send_question(self, session, msg=None): """Sends the next question in the session, if there is one""" state = session.state if state and state.question: response = state.question.text logger.info("Sending: %s", response) if msg: msg.respond(response) else: # we need to get the real backend from the router # to properly send it real_backend = self.router.get_backend( session.connection.backend.slug) if real_backend: connection = Connection(real_backend, session.connection.identity) outgoing_msg = OutgoingMessage(connection, response) self.router.outgoing(outgoing_msg) else: # todo: do we want to fail more loudly than this? logger.error( "Can't find backend %s. Messages will not " "be sent", connection.backend.slug)
def handle(self, text): result = text.lower().split() command = result.pop(0) msd_code = result.pop(0) extra = '' while len(result) > 0: extra = extra + ' ' + result.pop(0) if command != 'send_inquiry_message': try: sdp = ServiceDeliveryPoint.objects.get( msd_code=msd_code.upper()) except: self.respond("Invalid msd code %s" % msd_code) return contact_details_to_remind = ContactDetail.objects.filter( service_delivery_point=sdp) if command in ['la']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("Please send in your adjustments in the format 'la <product> +-<amount> +-<product> +-<amount>...'" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="lost_adjusted_reminder_sent_facility" )[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") if command in ['fw']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _(extra)) m.send() self.respond("Sent '%s'" % _(extra)) if command in ['supervision']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("Have you received supervision this month? Please reply 'supervision yes' or 'supervision no'" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="supervision_reminder_sent_facility" )[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") if command in ['soh', 'hmk']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("Please send in your stock on hand information in the format 'soh <product> <amount> <product> <amount>...'" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="soh_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") elif command in ['si']: product = Product.objects.get(product_code=addl_parameter) if not product: self.respond("Invalid product code %s" % addl_parameter) return if sdp.service_delivery_point_type.name == "FACILITY": contact_details_to_remind = ContactDetail.objects.filter( service_delivery_point=sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter))) m.send() self.respond("Sent") else: self.respond( "Can only initiate product inquiry for a single facility via SMS - %s is a %s" % (sdp.name, sdp.service_delivery_point_type.name)) return elif command in ['send_inquiry_message']: product = Product.objects.get(product_code=addl_parameter) if not product: self.respond("Invalid product code %s" % addl_parameter) return try: sdp = ServiceDeliveryPoint.objects.get(id=msd_code) except: self.respond("Invalid ID %s" % msd_code) return if sdp.service_delivery_point_type.name == "FACILITY": contact_details_to_remind = ContactDetail.objects.filter( service_delivery_point=sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter))) m.send() elif sdp.service_delivery_point_type.name == "DISTRICT": for facility_sdp in sdp.child_sdps(): contact_details_to_remind = ContactDetail.objects.filter( service_delivery_point=facility_sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter))) m.send() elif sdp.service_delivery_point_type.name == "REGION": for district_sdp in sdp.child_sdps(): for facility_sdp in district_sdp.child_sdps: contact_details_to_remind = ContactDetail.objects.filter( service_delivery_point=facility_sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage( default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter))) m.send() elif command in ['randr']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: if sdp.service_delivery_point_type.name == "DISTRICT": m = OutgoingMessage( default_connection, _("How many R&R forms have you submitted to MSD? Reply with 'submitted A <number of R&Rs submitted for group A> B <number of R&Rs submitted for group B>'" )) m.send() elif sdp.service_delivery_point_type.name == "FACILITY": m = OutgoingMessage( default_connection, _("Have you sent in your R&R form yet for this quarter? Please reply \"submitted\" or \"not submitted\"" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="r_and_r_reminder_sent_facility" )[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") elif command in ['delivery']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: if contact_detail.service_delivery_point.service_delivery_point_type.name == "FACILITY": m = OutgoingMessage( default_connection, _("Did you receive your delivery yet? Please reply 'delivered <product> <amount> <product> <amount>...'" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="delivery_received_reminder_sent_facility" )[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() elif contact_detail.service_delivery_point.service_delivery_point_type.name == "DISTRICT": m = OutgoingMessage( default_connection, _("Did you receive your delivery yet? Please reply 'delivered' or 'not delivered'" )) m.send() st = ServiceDeliveryPointStatusType.objects.filter( short_name="r_and_r_reminder_sent_district" )[0:1].get() ns = ServiceDeliveryPointStatus( service_delivery_point=contact_detail. service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() else: self.respond( "Sorry there was a problem with your service delivery point setup. Please check via the admin." ) self.respond("Sent") elif command in ['latedelivery']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: service_delivery_point = contact_detail.service_delivery_point kwargs = { "group_name": current_delivering_group(), "group_total": service_delivery_point.child_sdps().filter( delivery_group__name=current_delivering_group( )).count(), "not_responded_count": service_delivery_point. child_sdps_not_responded_delivery_this_month(), "not_received_count": service_delivery_point. child_sdps_not_received_delivery_this_month() } m = OutgoingMessage( default_connection, _("Facility deliveries for group %(group_name)s (out of %(group_total)d): %(not_responded_count)d haven't responded and %(not_received_count)d have reported not receiving. See ilsgateway.com" ), **kwargs) m.send() self.respond("Sent")
def handle(self, text): result = text.lower().split() command = result.pop(0) msd_code = result.pop(0) extra = '' while len(result) > 0: extra = extra + ' ' + result.pop(0) if command != 'send_inquiry_message': try: sdp = ServiceDeliveryPoint.objects.get(msd_code=msd_code.upper()) except: self.respond("Invalid msd code %s" % msd_code) return contact_details_to_remind = ContactDetail.objects.filter(service_delivery_point=sdp) if command in ['la']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("Please send in your adjustments in the format 'la <product> +-<amount> +-<product> +-<amount>...'")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="lost_adjusted_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") if command in ['fw']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _(extra)) m.send() self.respond("Sent '%s'" % _(extra)) if command in ['supervision']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("Have you received supervision this month? Please reply 'supervision yes' or 'supervision no'")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="supervision_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") if command in ['soh','hmk']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("Please send in your stock on hand information in the format 'soh <product> <amount> <product> <amount>...'")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="soh_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") elif command in ['si']: product = Product.objects.get(product_code=addl_parameter) if not product: self.respond("Invalid product code %s" % addl_parameter) return if sdp.service_delivery_point_type.name == "FACILITY": contact_details_to_remind = ContactDetail.objects.filter(service_delivery_point=sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter) )) m.send() self.respond("Sent") else: self.respond("Can only initiate product inquiry for a single facility via SMS - %s is a %s" % (sdp.name, sdp.service_delivery_point_type.name) ) return elif command in ['send_inquiry_message']: product = Product.objects.get(product_code=addl_parameter) if not product: self.respond("Invalid product code %s" % addl_parameter) return try: sdp = ServiceDeliveryPoint.objects.get(id=msd_code) except: self.respond("Invalid ID %s" % msd_code) return if sdp.service_delivery_point_type.name == "FACILITY": contact_details_to_remind = ContactDetail.objects.filter(service_delivery_point=sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter) )) m.send() elif sdp.service_delivery_point_type.name == "DISTRICT": for facility_sdp in sdp.child_sdps(): contact_details_to_remind = ContactDetail.objects.filter(service_delivery_point=facility_sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter) )) m.send() elif sdp.service_delivery_point_type.name == "REGION": for district_sdp in sdp.child_sdps(): for facility_sdp in district_sdp.child_sdps: contact_details_to_remind = ContactDetail.objects.filter(service_delivery_point=facility_sdp) for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: m = OutgoingMessage(default_connection, _("How much %s (msd code %s) do you have in stock? Please respond 'si %s <amount>'" % (product.name, addl_parameter, addl_parameter) )) m.send() elif command in ['randr']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: if sdp.service_delivery_point_type.name == "DISTRICT": m = OutgoingMessage(default_connection, _("How many R&R forms have you submitted to MSD? Reply with 'submitted A <number of R&Rs submitted for group A> B <number of R&Rs submitted for group B>'")) m.send() elif sdp.service_delivery_point_type.name == "FACILITY": m = OutgoingMessage(default_connection, _("Have you sent in your R&R form yet for this quarter? Please reply \"submitted\" or \"not submitted\"")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="r_and_r_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() self.respond("Sent") elif command in ['delivery']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: if contact_detail.service_delivery_point.service_delivery_point_type.name == "FACILITY": m = OutgoingMessage(default_connection, _("Did you receive your delivery yet? Please reply 'delivered <product> <amount> <product> <amount>...'")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="delivery_received_reminder_sent_facility")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() elif contact_detail.service_delivery_point.service_delivery_point_type.name == "DISTRICT": m = OutgoingMessage(default_connection, _("Did you receive your delivery yet? Please reply 'delivered' or 'not delivered'")) m.send() st = ServiceDeliveryPointStatusType.objects.filter(short_name="r_and_r_reminder_sent_district")[0:1].get() ns = ServiceDeliveryPointStatus(service_delivery_point=contact_detail.service_delivery_point, status_type=st, status_date=datetime.now()) ns.save() else: self.respond("Sorry there was a problem with your service delivery point setup. Please check via the admin.") self.respond("Sent") elif command in ['latedelivery']: for contact_detail in contact_details_to_remind: default_connection = contact_detail.default_connection if default_connection: service_delivery_point = contact_detail.service_delivery_point kwargs = {"group_name": current_delivering_group(), "group_total": service_delivery_point.child_sdps().filter(delivery_group__name=current_delivering_group()).count(), "not_responded_count": service_delivery_point.child_sdps_not_responded_delivery_this_month(), "not_received_count": service_delivery_point.child_sdps_not_received_delivery_this_month()} m = OutgoingMessage(default_connection, _("Facility deliveries for group %(group_name)s (out of %(group_total)d): %(not_responded_count)d haven't responded and %(not_received_count)d have reported not receiving. See ilsgateway.com"), **kwargs) m.send() self.respond("Sent")
def notify_help_admins(self, msg): for help_admin in Contact.active.filter(is_help_admin=True): OutgoingMessage(help_admin.default_connection, msg).send()