Пример #1
0
    def _save_contact(self, data):
        """Save contact to database"""

        # Create connection, or if this is a re-register, just use (one
        # of) the old one(s).
        old_connections = self.connections.filter(contact__isnull=True)
        if len(old_connections) > 0:
            conn = old_connections[0]
        else:
            gsm_backend = Backend.objects.get(name='gsm')
            #gsm_backend = Backend.objects.get(name='message_tester')
            conn = Connection(backend=gsm_backend, identity=data['phone_no'])

        # Create contact
        contact = Contact(name=data['name'],
                          language=data['lang'],
                          is_active=False,
                          only_important=data['only_important'])
        contact.save()
        contact.categories = data['categories']
        contact.save()
        conn.contact = contact
        conn.save()

        return contact
Пример #2
0
def registration(req, pk=None):
    contact = None

    if pk is not None:
        contact = get_object_or_404(
            Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(
                reverse(registration))

        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))
        else:
            contact_form = ContactForm(
                instance=contact,
                data=req.POST)

            if contact_form.is_valid():
                contact = contact_form.save()
                return HttpResponseRedirect(
                    reverse(registration))

    else:
        contact_form = ContactForm(
            instance=contact)
        bulk_form = BulkRegistrationForm()

    return render_to_response(
        "registration/dashboard.html", {
            "contacts_table": ContactTable(Contact.objects.all(), request=req),
            "contact_form": contact_form,
            "bulk_form": bulk_form,
            "contact": contact
        }, context_instance=RequestContext(req)
    )
 def create_message_without_batch(self, id, backend):
     fake_connection = Connection(identity=str(id))
     fake_connection.backend, created = Backend.objects.get_or_create(name=backend)
     fake_connection.save()
     message = Message(status='Q', direction="O")
     message.text = "this is an important message"
     message.connection = fake_connection
     message.batch = None
     message.save()
     return message
Пример #4
0
    def create_message(self, id, backend):
	fake_connection = Connection(identity=str(id))
	fake_connection.backend, created = Backend.objects.get_or_create(name=backend)
	fake_connection.save()
	message = Message(status='Q', direction="O")
	message.connection = fake_connection

	message.batch = self.batch1;
	message.save()
	return message
Пример #5
0
    def create_message(self, id, backend):
        fake_connection = Connection(identity=str(id))
        fake_connection.backend, created = Backend.objects.get_or_create(
            name=backend)
        fake_connection.save()
        message = Message(status='Q', direction="O")
        message.connection = fake_connection

        message.batch = self.batch1
        message.save()
        return message
Пример #6
0
def registration(req, pk=None):
    contact = None
    bulk_form = None

    if pk is not None:
        contact = get_object_or_404(Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(reverse(registration))

        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))
        else:
            contact_form = ContactForm(instance=contact, data=req.POST)

            if contact_form.is_valid():
                contact = contact_form.save()
                return HttpResponseRedirect(reverse(registration))

    else:
        contact_form = ContactForm(instance=contact)
        bulk_form = BulkRegistrationForm()

    return render_to_response(
        "auth/dashboard.html", {
            "contacts_table": ContactTable(Contact.objects.all(), request=req),
            "contact_form": contact_form,
            "bulk_form": bulk_form,
            "contact": contact
        },
        context_instance=RequestContext(req))
Пример #7
0
 def save(self, commit=True):
     model = super(ContactDetailForm, self).save(commit=False)
     if commit:
         model.save()
         conn = model.default_connection 
         if not conn:
             if settings.DEFAULT_BACKEND:
                 backend = Backend.objects.get(name=settings.DEFAULT_BACKEND)
             else:
                 backend = Backend.objects.all()[0]
             conn = Connection(backend=backend,
                               contact=model.contact_ptr)
         conn.identity = self.cleaned_data['phone']
         conn.save()
         print conn
     return model            
Пример #8
0
 def create_trans(self, s1='Q', s2='Q'):
     Connection.objects.bulk_create((
         Connection(identity='1111111111', backend=self.backend),
         Connection(identity='2222222222', backend=self.backend),
         Connection(identity='3333333333', backend=self.backend),
         Connection(identity='4444444444', backend=self.backend),
     ))
     dbm = Message.objects.create(text="test", direction="O")
     for connection in Connection.objects.order_by('id')[:2]:
         dbm.transmissions.create(connection=connection, status=s1)
     for connection in Connection.objects.order_by('id')[2:]:
         dbm.transmissions.create(connection=connection, status=s2)
     ids = dbm.transmissions.order_by('id').values_list('id', flat=True)
     trans1 = dbm.transmissions.filter(id__in=ids[:2])
     trans2 = dbm.transmissions.filter(id__in=ids[2:])
     return self.backend, dbm, trans1, trans2
Пример #9
0
 def save(self, commit=True):
     model = super(ContactDetailForm, self).save(commit=False)
     if commit:
         model.save()
         conn = model.default_connection
         if not conn:
             if settings.DEFAULT_BACKEND:
                 backend = Backend.objects.get(
                     name=settings.DEFAULT_BACKEND)
             else:
                 backend = Backend.objects.all()[0]
             conn = Connection(backend=backend, contact=model.contact_ptr)
         conn.identity = self.cleaned_data['phone']
         conn.save()
         print conn
     return model
Пример #10
0
 def test_404_is_raised_when_no_poll_exists(self):
     backend = Backend(name="test")
     self.view.get_connection = Mock(return_value=Connection(identity="77777", backend=backend))
     self.view.get_backend = Mock(return_value=backend)
     self.view.contact_exists = Mock(return_value=True)
     with self.assertRaises(Http404):
         response = self.get_http_response_from_view(self.build_kwargs("my_backend","77777","12"), self.view)
Пример #11
0
 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)
Пример #12
0
 def default_connection(self, identity):
     # when you re-assign default connection, should you delete the unused connection? probably.
     from rapidsms.models import Connection
     backend = self.default_backend
     default = self.default_connection
     if default is not None:
         if default.identity == identity and default.backend == backend:
             # our job is done
             return
         default.delete()
     try:
         conn = Connection.objects.get(backend=backend, identity=identity)
     except Connection.DoesNotExist:
         # good, it doesn't exist already
         conn = Connection(backend=backend, identity=identity)
     conn.contact = self
     conn.save()
 def test_that_if_there_are_no_polls_for_the_user_it_returns_success_and_an_empty_list(self):
     backend = Backend(id=89)
     connection = Connection(identity=999, backend=backend, contact=Contact())
     fake_request = self.setup_get_request(backend, connection)
     self.view.get_polls_for_contact = Mock(return_value=[])
     response = self.view.dispatch(fake_request)
     data = json.loads(response.content)
     self.assertEqual(True, data['success'])
     self.assertEqual([], data['poll_topics'])
Пример #14
0
 def default_connection(self, identity):
     # when you re-assign default connection, should you delete the unused connection? probably.
     from rapidsms.models import Connection
     backend = self.default_backend
     default = self.default_connection
     if default is not None:
         if default.identity == identity and default.backend == backend:
             # our job is done
             return
         default.delete()
     try:
         conn = Connection.objects.get(backend=backend, identity=identity)
     except Connection.DoesNotExist:
         # good, it doesn't exist already
         conn = Connection(backend=backend,
                           identity=identity)
     conn.contact = self
     conn.save()
Пример #15
0
def get_ussd_connection(fallback_connection):
    backend = ussd_push_backend()
    if not backend:
        return fallback_connection

    return Connection(
        backend=backend,
        identity=fallback_connection.identity,
        contact=fallback_connection.contact
    )
Пример #16
0
def forward(message, identity, text):

    if message.connection:
        conn = Connection(backend=message.connection.backend,
                          identity=identity)
        send(text, conn)
        #print conn, text
        return True
    else:
        return False
Пример #17
0
def send_bulk_message_from_csv(path, text='coffee'):
    backend_name = "TLS-TT"
    file = open(path)
    for line in file:
        line_list = line.split(',')
        name = line_list[0].strip()
        identity = line_list[1].strip()        
#        if Connection.objects.filter(identity=identity).count() == 0:
        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()
#       else:
#            connection = Connection.objects.get(identity=identity)
        post = {"connection_id": unicode(connection.id), "text": text}
        call_router("messaging", "send_message", **post)
Пример #18
0
 def test_that_return_not_registered_if_contact_does_not_exist(self):
     view = ViewUReporter()
     fake_check = Mock()
     fake_check.return_value = {"id": "", "language": "", "registered": False}
     view.get_contact = fake_check
     kwargs = {"backend": "console", "user_address": "999"}
     view.get_backend = Mock(return_value=Backend(name="my_backend"))
     view.get_connection = Mock(return_value=Connection(identity="999"))
     http_response = self.get_http_response_from_view(kwargs, view)
     json_string = http_response.content
     data = json.loads(json_string)
     self.assertDictEqual({"success": False, "reason": "Ureporter not found"}, data)
Пример #19
0
    def _save_contact (self, data):
        """Save contact to database"""

        # Create connection, or if this is a re-register, just use (one
        # of) the old one(s).
        old_connections = self.connections.filter(contact__isnull=True)
        if len(old_connections) > 0:
            conn = old_connections[0]
        else:
            gsm_backend = Backend.objects.get(name='gsm')
            #gsm_backend = Backend.objects.get(name='message_tester')
            conn = Connection(backend=gsm_backend, identity=data['phone_no'])

        # Create contact
        contact = Contact(name=data['name'], language=data['lang'],
            is_active=False, only_important=data['only_important'])
        contact.save()
        contact.categories = data['categories']
        contact.save()
        conn.contact = contact
        conn.save()

        return contact
Пример #20
0
 def test_that_return_registered_true_if_contact_exists(self):
     view = ViewUReporter()
     fake_check = Mock()
     fake_check.return_value = {"id": 12, "language": "en", "registered": True}
     view.get_contact = fake_check
     kwargs = {"backend": "console", "user_address": "999"}
     view.get_backend = Mock(return_value=Backend(name="my_backend"))
     view.get_connection = Mock(return_value=Connection(identity="999"))
     http_response = self.get_http_response_from_view(kwargs, view)
     json_string = http_response.content
     data = json.loads(json_string)
     self.assertEqual(True, data['success'])
     self.assertEqual(True, data['user']['registered'])
     self.assertEqual('en', data['user']['language'])
Пример #21
0
    def test_that_valid_get_request_returns_poll_summary(self):
        backend = Backend(name="test")
        self.view.get_connection = Mock(return_value=Connection(identity="77777", backend=backend))
        self.view.get_backend = Mock(return_value=backend)
        self.view.contact_exists = Mock(return_value=True)
        self.view.get_poll = Mock(return_value=Poll(question="Testing?"))
        poll_summary = {"total": 1, "responses": [{"name": "T", "count": 1}]}
        self.view.get_poll_summary = Mock(return_value=poll_summary)
        expected_data = { "success": True, "poll_result": poll_summary }

        response = self.get_http_response_from_view(self.build_kwargs("my_backend","77777","12"), self.view)
        data = json.loads(response.content)

        self.assertEquals(200,response.status_code)
        self.assertDictEqual(expected_data, data)
Пример #22
0
    def setUp(self):
        settings.LOGISTICS_STOCKED_BY = 'user'
        TestScript.setUp(self)
        location = Location.objects.get(code='de')
        facilitytype = SupplyPointType.objects.get(code='hc')
        self.rms = SupplyPoint.objects.get(code='garms')
        facility, created = SupplyPoint.objects.get_or_create(code='dedh',
                                                           name='Dangme East District Hospital',
                                                           location=location, active=True,
                                                           type=facilitytype, supplied_by=self.rms)
        assert facility.supplied_by == self.rms
        mc = Product.objects.get(sms_code='mc')
        self.lf = Product.objects.get(sms_code='lf')
        ProductStock(product=mc, supply_point=facility,
                     monthly_consumption=8).save()
        ProductStock(product=self.lf, supply_point=facility,
                     monthly_consumption=5).save()
        facility = SupplyPoint(code='tf', name='Test Facility',
                       location=location, active=True,
                       type=facilitytype, supplied_by=self.rms)
        facility.save()
        mc = Product.objects.get(sms_code='mc')
        mg = Product.objects.get(sms_code='mg')
        self.mc_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=mc, monthly_consumption=10)
        self.mc_stock.save()
        self.lf_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=self.lf, monthly_consumption=10)
        self.lf_stock.save()
        self.mg_stock = ProductStock(is_active=False, supply_point=facility,
                                     product=mg, monthly_consumption=10)
        self.mg_stock.save()

        ng = Product.objects.get(sms_code='ng')
        self.ng_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=ng, monthly_consumption=None)
        self.ng_stock.save()
        
        self.contact = Contact(name='test user')
        self.contact.save()
        self.connection = Connection(backend=Backend.objects.all()[0],
                                     identity="888",
                                     contact=self.contact)
        self.connection.save()
        self.contact.supply_point = facility
        self.contact.save()
        self.contact.commodities.add(ng)
Пример #23
0
    def test_should_insert_a_classifier_message_for_each_category(self):
        categories = self.create_dummy_categories()

        self.load_ibm_seed_data.create_ibm_message_category = self.create_ibm_message_category_mock
        self.load_ibm_seed_data.create_backend = lambda name: Backend(name=name
                                                                      )
        self.load_ibm_seed_data.create_connection = lambda backend, identity: Connection(
            backend=backend, identity=identity)
        self.load_ibm_seed_data.create_message = lambda connection, text, direction, status: (
            Message(connection=connection,
                    text=text,
                    direction=direction,
                    status=status), True)

        self.load_ibm_seed_data.create_seed_data(categories)

        self.assertEquals(self.categories_with_messages_inserted, categories)
Пример #24
0
 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)
Пример #25
0
def registration(req, pk=None):
    contact = None
    sellerSummary = None

    if pk is not None:
        contact = get_object_or_404(
            Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(
                reverse(registration))

        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))
        else:
            contact_form = ContactForm(
                instance=contact,
                data=req.POST)

            if contact_form.is_valid():
                contact = contact_form.save()
                return HttpResponseRedirect(
                    reverse(registration))

    else:
        contact_form = ContactForm(
            instance=contact)
            #Not allowing user to add contacts through the UI for now
            #If we eventually do, the line below sets the new contacts'
            #organization to that of the logged in user
            #################
            #instance=Contact(organization=req.user.get_profile().organization))
        seller_summary = getSellerSummary(contact)
        bulk_form = BulkRegistrationForm()

    if req.user.is_staff:
        ctable = ContactTable(Contact.objects.exclude(alias='nobody'), request=req)
        org = None
    else:
        ctable = ContactTable(Contact.objects.filter(organization=req.user.get_profile().organization), request=req)
        org = req.user.get_profile().organization

    return render_to_response(
        "registration/dashboard.html", {
            "organization": org,
            "contacts_table": ctable,
            "contact_form": contact_form,
            "bulk_form": bulk_form,
            "contact": contact,
            "seller_summary": seller_summary
        }, context_instance=RequestContext(req)
    )
Пример #26
0
    def setUp(self):
        settings.LOGISTICS_STOCKED_BY = 'user'
        TestScript.setUp(self)
        location = Location.objects.get(code='de')
        facilitytype = SupplyPointType.objects.get(code='hc')
        self.rms = SupplyPoint.objects.get(code='garms')
        facility, created = SupplyPoint.objects.get_or_create(
            code='dedh',
            name='Dangme East District Hospital',
            location=location,
            active=True,
            type=facilitytype,
            supplied_by=self.rms)
        assert facility.supplied_by == self.rms
        mc = Product.objects.get(sms_code='mc')
        self.lf = Product.objects.get(sms_code='lf')
        ProductStock(product=mc, supply_point=facility,
                     monthly_consumption=8).save()
        ProductStock(product=self.lf,
                     supply_point=facility,
                     monthly_consumption=5).save()
        facility = SupplyPoint(code='tf',
                               name='Test Facility',
                               location=location,
                               active=True,
                               type=facilitytype,
                               supplied_by=self.rms)
        facility.save()
        mc = Product.objects.get(sms_code='mc')
        mg = Product.objects.get(sms_code='mg')
        self.mc_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=mc,
                                     monthly_consumption=10)
        self.mc_stock.save()
        self.lf_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=self.lf,
                                     monthly_consumption=10)
        self.lf_stock.save()
        self.mg_stock = ProductStock(is_active=False,
                                     supply_point=facility,
                                     product=mg,
                                     monthly_consumption=10)
        self.mg_stock.save()

        ng = Product.objects.get(sms_code='ng')
        self.ng_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=ng,
                                     monthly_consumption=None)
        self.ng_stock.save()

        self.contact = Contact(name='test user')
        self.contact.save()
        self.connection = Connection(backend=Backend.objects.all()[0],
                                     identity="888",
                                     contact=self.contact)
        self.connection.save()
        self.contact.supply_point = facility
        self.contact.save()
        self.contact.commodities.add(ng)
Пример #27
0
class TestStockOnHand(TestScript):
    apps = ([logistics_app.App])
    fixtures = ["ghana_initial_data.json"]

    def setUp(self):
        settings.LOGISTICS_STOCKED_BY = 'user'
        TestScript.setUp(self)
        location = Location.objects.get(code='de')
        facilitytype = SupplyPointType.objects.get(code='hc')
        self.rms = SupplyPoint.objects.get(code='garms')
        facility, created = SupplyPoint.objects.get_or_create(
            code='dedh',
            name='Dangme East District Hospital',
            location=location,
            active=True,
            type=facilitytype,
            supplied_by=self.rms)
        assert facility.supplied_by == self.rms
        mc = Product.objects.get(sms_code='mc')
        self.lf = Product.objects.get(sms_code='lf')
        ProductStock(product=mc, supply_point=facility,
                     monthly_consumption=8).save()
        ProductStock(product=self.lf,
                     supply_point=facility,
                     monthly_consumption=5).save()
        facility = SupplyPoint(code='tf',
                               name='Test Facility',
                               location=location,
                               active=True,
                               type=facilitytype,
                               supplied_by=self.rms)
        facility.save()
        mc = Product.objects.get(sms_code='mc')
        mg = Product.objects.get(sms_code='mg')
        self.mc_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=mc,
                                     monthly_consumption=10)
        self.mc_stock.save()
        self.lf_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=self.lf,
                                     monthly_consumption=10)
        self.lf_stock.save()
        self.mg_stock = ProductStock(is_active=False,
                                     supply_point=facility,
                                     product=mg,
                                     monthly_consumption=10)
        self.mg_stock.save()

        ng = Product.objects.get(sms_code='ng')
        self.ng_stock = ProductStock(is_active=True,
                                     supply_point=facility,
                                     product=ng,
                                     monthly_consumption=None)
        self.ng_stock.save()

        self.contact = Contact(name='test user')
        self.contact.save()
        self.connection = Connection(backend=Backend.objects.all()[0],
                                     identity="888",
                                     contact=self.contact)
        self.connection.save()
        self.contact.supply_point = facility
        self.contact.save()
        self.contact.commodities.add(ng)

    def testProductReportsHelper(self):
        sdp = SupplyPoint()
        m = Message()
        p = ProductReportsHelper(sdp, Reports.SOH, m)
        p.add_product_stock('lf', 10, save=False)
        p.add_product_stock('mc', 30, save=False)
        p.add_product_stock('aa', 0, save=False)
        p.add_product_stock('oq', 0, save=False)
        self.assertEquals(p.all(), "lf 10, aa 0, oq 0, mc 30")
        self.assertEquals(p.stockouts(), "aa oq")
        my_iter = p._getTokens("ab10cd20")
        self.assertEquals(my_iter.next(), 'ab')
        self.assertEquals(my_iter.next(), '10')
        self.assertEquals(my_iter.next(), 'cd')
        self.assertEquals(my_iter.next(), '20')

    def testStockOnHand(self):
        a = """
           16176023315 > register stella dedh
           16176023315 < Congratulations stella, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           16176023315 > soh lf 10 mc 20
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           16176023315 > SOH LF 10 MC 20
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           """
        self.runScript(a)

    def testNothing(self):
        a = """
           16176023315 > register stella dedh
           16176023315 < Congratulations stella, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 >
           16176023315 < Sorry, I could not understand your message. Please contact your DHIO for help, or visit http://www.ewsghana.com
           16176023315 > soh
           16176023315 < To report stock on hand, send SOH [space] [product code] [space] [amount] 
           """
        self.runScript(a)

    def testStockout(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 0 mc 0
           16176023315 < Dear cynthia, these items are stocked out: lf mc. Please order 24 mc, 15 lf.
           """
        self.runScript(a)

    def testStockoutNoConsumption(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh ng 0
           16176023315 < Dear cynthia, these items are stocked out: ng.
           """
        self.runScript(a)

    def testLowSupply(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 7 mc 9
           16176023315 < Dear cynthia, these items need to be reordered: lf mc. Please order 15 mc, 8 lf.
           """
        self.runScript(a)

    def testLowSupplyNoConsumption(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh ng 3
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           """
        self.runScript(a)

    def testOverSupply(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 30 mc 40
           16176023315 < Dear cynthia, these items are overstocked: lf mc. The district admin has been informed.
           """
        self.runScript(a)

    def testSohAndReceipts(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10 20 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 20.
           """
        self.runScript(a)

    def testCombined1(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh lf 0 mc 1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Lofem; below reorder level Male Condom
           pharmacist < Dear cynthia, these items are stocked out: lf. these items need to be reordered: mc. Please order 29 mc, 30 lf.
           """
        self.runScript(a)

    def testCombined2(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > mc 0 mg 1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           pharmacist > mc 0 mg 1 lf 100
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G; overstocked Lofem
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined3(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh mc 0 mg 1 ng 300
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist <  Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           pharmacist > soh mc 0-2 mg 1-1 ng 300-1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist <  Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined4(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh mc 0 mg 1 ng300-4
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined5(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > mc 16 lf 16 mg300
           super < Dear super, Test Facility is experiencing the following problems: overstocked Micro-G
           pharmacist < Dear cynthia, these items are overstocked: mg. The district admin has been informed.
           """
        self.runScript(a)

    def testStringCleaner(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10-20 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 20.
           """
        self.runScript(a)

    def testBadCode(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > lf 0 badcode 10
           16176023315 < You reported: lf, but there were errors: Unrecognized commodity codes: badcode. Please contact your DHIO for assistance.
           16176023315 > badcode 10
           16176023315 < badcode is not a recognized commodity code. Please contact your DHIO for assistance.
           16176023315 > soh lf 10.10 m20
           16176023315 < You reported: lf, but there were errors: Unrecognized commodity codes: m. Please contact your DHIO for assistance.
           16176023315 > ad50 -0 as65-0 al25-0 qu0-0 sp0-0 rd0-0
           16176023315 < You reported: rd, sp, qu, ad, al, but there were errors: Unrecognized commodity codes: as. Please contact your DHIO for assistance.
           """
        self.runScript(a)

    def FAILSbadcode(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 0 bad_code 10
           16176023315 < You reported: lf, but there were errors: BAD_CODE is/are not part of our commodity codes. Please contact your DHIO for assistance.
           16176023315 > soh bad_code 10
           16176023315 < BAD_CODE is/are not part of our commodity codes. Please contact your DHIO for assistance.
           """
        self.runScript(a)

    def testPunctuation(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 >   soh lf 10 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > sohlf10mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > lf10mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10MC 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-1MC 20,3
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 1, mc 3.
           16176023315 > LF(10), mc (20)
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-mc20-
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-3mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 3.
           16176023315 > LF10----3mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 3.
           """
        self.runScript(a)

    def failTestRMSStockout(self):
        """ This test doesn't pass yet. Something about signals not firing? """
        a = """
           111 > register garep garms
           111 < Congratulations garep, you have successfully been registered for the Early Warning System. Your facility is Greater Accra Regional Medical Store
           222 > register derep dedh
           222 < Congratulations derep, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           111 > soh lf 0
           111 < Dear garep, these items are stocked out: lf.
           222 < Dear derep, Greater Accra Regional Medical Store is STOCKED OUT of: lf
           111 > soh lf 10
           111 < Dear garep, thank you for reporting the commodities you have in stock.
           222 < Dear derep, Greater Accra Regional Medical Store has RESOLVED the following stockouts: lf
           """
        self.runScript(a)

    def tearDown(self):
        TestScript.tearDown(self)
        self.mc_stock.delete()
        self.mg_stock.delete()
        self.lf_stock.delete()
Пример #28
0
def registration(req, pk=None):
    contact = None
    sellerSummary = None

    if pk is not None:
        contact = get_object_or_404(Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(reverse(registration))

        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))
        else:
            contact_form = ContactForm(instance=contact, data=req.POST)

            if contact_form.is_valid():
                contact = contact_form.save()
                return HttpResponseRedirect(reverse(registration))

    else:
        contact_form = ContactForm(instance=contact)
        #Not allowing user to add contacts through the UI for now
        #If we eventually do, the line below sets the new contacts'
        #organization to that of the logged in user
        #################
        #instance=Contact(organization=req.user.get_profile().organization))
        seller_summary = getSellerSummary(contact)
        bulk_form = BulkRegistrationForm()

    if req.user.is_staff:
        ctable = ContactTable(Contact.objects.exclude(alias='nobody'),
                              request=req)
        org = None
    else:
        ctable = ContactTable(Contact.objects.filter(
            organization=req.user.get_profile().organization),
                              request=req)
        org = req.user.get_profile().organization

    return render_to_response("registration/dashboard.html", {
        "organization": org,
        "contacts_table": ctable,
        "contact_form": contact_form,
        "bulk_form": bulk_form,
        "contact": contact,
        "seller_summary": seller_summary
    },
                              context_instance=RequestContext(req))
Пример #29
0
class TestStockOnHand (TestScript):
    apps = ([logistics_app.App])
    fixtures = ["ghana_initial_data.json"] 
    def setUp(self):
        settings.LOGISTICS_STOCKED_BY = 'user'
        TestScript.setUp(self)
        location = Location.objects.get(code='de')
        facilitytype = SupplyPointType.objects.get(code='hc')
        self.rms = SupplyPoint.objects.get(code='garms')
        facility, created = SupplyPoint.objects.get_or_create(code='dedh',
                                                           name='Dangme East District Hospital',
                                                           location=location, active=True,
                                                           type=facilitytype, supplied_by=self.rms)
        assert facility.supplied_by == self.rms
        mc = Product.objects.get(sms_code='mc')
        self.lf = Product.objects.get(sms_code='lf')
        ProductStock(product=mc, supply_point=facility,
                     monthly_consumption=8).save()
        ProductStock(product=self.lf, supply_point=facility,
                     monthly_consumption=5).save()
        facility = SupplyPoint(code='tf', name='Test Facility',
                       location=location, active=True,
                       type=facilitytype, supplied_by=self.rms)
        facility.save()
        mc = Product.objects.get(sms_code='mc')
        mg = Product.objects.get(sms_code='mg')
        self.mc_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=mc, monthly_consumption=10)
        self.mc_stock.save()
        self.lf_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=self.lf, monthly_consumption=10)
        self.lf_stock.save()
        self.mg_stock = ProductStock(is_active=False, supply_point=facility,
                                     product=mg, monthly_consumption=10)
        self.mg_stock.save()

        ng = Product.objects.get(sms_code='ng')
        self.ng_stock = ProductStock(is_active=True, supply_point=facility,
                                    product=ng, monthly_consumption=None)
        self.ng_stock.save()
        
        self.contact = Contact(name='test user')
        self.contact.save()
        self.connection = Connection(backend=Backend.objects.all()[0],
                                     identity="888",
                                     contact=self.contact)
        self.connection.save()
        self.contact.supply_point = facility
        self.contact.save()
        self.contact.commodities.add(ng)
    
    
    def testProductReportsHelper(self):
        sdp = SupplyPoint()
        m = Message()
        p = ProductReportsHelper(sdp, Reports.SOH, m)
        p.add_product_stock('lf',10, save=False)
        p.add_product_stock('mc',30, save=False)
        p.add_product_stock('aa',0, save=False)
        p.add_product_stock('oq',0, save=False)
        self.assertEquals(p.all(), "lf 10, aa 0, oq 0, mc 30")
        self.assertEquals(p.stockouts(), "aa oq")
        my_iter = p._getTokens("ab10cd20")
        self.assertEquals(my_iter.next(),'ab')
        self.assertEquals(my_iter.next(),'10')
        self.assertEquals(my_iter.next(),'cd')
        self.assertEquals(my_iter.next(),'20')

    def testStockOnHand(self):
        a = """
           16176023315 > register stella dedh
           16176023315 < Congratulations stella, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           16176023315 > soh lf 10 mc 20
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           16176023315 > SOH LF 10 MC 20
           16176023315 < Dear stella, thank you for reporting the commodities you have in stock.
           """
        self.runScript(a)

    def testNothing(self):
        a = """
           16176023315 > register stella dedh
           16176023315 < Congratulations stella, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 >
           16176023315 < Sorry, I could not understand your message. Please contact your DHIO for help, or visit http://www.ewsghana.com
           16176023315 > soh
           16176023315 < To report stock on hand, send SOH [space] [product code] [space] [amount] 
           """
        self.runScript(a)

    def testStockout(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 0 mc 0
           16176023315 < Dear cynthia, these items are stocked out: lf mc. Please order 24 mc, 15 lf.
           """
        self.runScript(a)

    def testStockoutNoConsumption(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh ng 0
           16176023315 < Dear cynthia, these items are stocked out: ng.
           """
        self.runScript(a)

    def testLowSupply(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 7 mc 9
           16176023315 < Dear cynthia, these items need to be reordered: lf mc. Please order 15 mc, 8 lf.
           """
        self.runScript(a)

    def testLowSupplyNoConsumption(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh ng 3
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           """
        self.runScript(a)

    def testOverSupply(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 30 mc 40
           16176023315 < Dear cynthia, these items are overstocked: lf mc. The district admin has been informed.
           """
        self.runScript(a)

    def testSohAndReceipts(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10 20 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 20.
           """
        self.runScript(a)

    def testCombined1(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh lf 0 mc 1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Lofem; below reorder level Male Condom
           pharmacist < Dear cynthia, these items are stocked out: lf. these items need to be reordered: mc. Please order 29 mc, 30 lf.
           """
        self.runScript(a)

    def testCombined2(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > mc 0 mg 1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           pharmacist > mc 0 mg 1 lf 100
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G; overstocked Lofem
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined3(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh mc 0 mg 1 ng 300
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist <  Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           pharmacist > soh mc 0-2 mg 1-1 ng 300-1
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist <  Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined4(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > soh mc 0 mg 1 ng300-4
           super < Dear super, Test Facility is experiencing the following problems: stockouts Male Condom; below reorder level Micro-G
           pharmacist < Dear cynthia, these items are stocked out: mc. these items need to be reordered: mg. Please order 30 mc, 29 mg.
           """
        self.runScript(a)

    def testCombined5(self):
        a = """
           pharmacist > register cynthia tf
           pharmacist < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           super > register super tf incharge
           super < Congratulations super, you have successfully been registered for the Early Warning System. Your facility is Test Facility
           pharmacist > mc 16 lf 16 mg300
           super < Dear super, Test Facility is experiencing the following problems: overstocked Micro-G
           pharmacist < Dear cynthia, these items are overstocked: mg. The district admin has been informed.
           """
        self.runScript(a)

    def testStringCleaner(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 10-20 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 20.
           """
        self.runScript(a)

    def testBadCode(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > lf 0 badcode 10
           16176023315 < You reported: lf, but there were errors: Unrecognized commodity codes: badcode. Please contact your DHIO for assistance.
           16176023315 > badcode 10
           16176023315 < badcode is not a recognized commodity code. Please contact your DHIO for assistance.
           16176023315 > soh lf 10.10 m20
           16176023315 < You reported: lf, but there were errors: Unrecognized commodity codes: m. Please contact your DHIO for assistance.
           16176023315 > ad50 -0 as65-0 al25-0 qu0-0 sp0-0 rd0-0
           16176023315 < You reported: rd, sp, qu, ad, al, but there were errors: Unrecognized commodity codes: as. Please contact your DHIO for assistance.
           """
        self.runScript(a)

    def FAILSbadcode(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 > soh lf 0 bad_code 10
           16176023315 < You reported: lf, but there were errors: BAD_CODE is/are not part of our commodity codes. Please contact your DHIO for assistance.
           16176023315 > soh bad_code 10
           16176023315 < BAD_CODE is/are not part of our commodity codes. Please contact your DHIO for assistance.
           """
        self.runScript(a)

    def testPunctuation(self):
        a = """
           16176023315 > register cynthia dedh
           16176023315 < Congratulations cynthia, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           16176023315 >   soh lf 10 mc 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > sohlf10mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > lf10mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10MC 20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-1MC 20,3
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 1, mc 3.
           16176023315 > LF(10), mc (20)
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-mc20-
           16176023315 < Dear cynthia, thank you for reporting the commodities you have in stock.
           16176023315 > LF10-3mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 3.
           16176023315 > LF10----3mc20
           16176023315 < Dear cynthia, thank you for reporting the commodities you have. You received lf 3.
           """
        self.runScript(a)

    def failTestRMSStockout(self):
        """ This test doesn't pass yet. Something about signals not firing? """
        a = """
           111 > register garep garms
           111 < Congratulations garep, you have successfully been registered for the Early Warning System. Your facility is Greater Accra Regional Medical Store
           222 > register derep dedh
           222 < Congratulations derep, you have successfully been registered for the Early Warning System. Your facility is Dangme East District Hospital
           111 > soh lf 0
           111 < Dear garep, these items are stocked out: lf.
           222 < Dear derep, Greater Accra Regional Medical Store is STOCKED OUT of: lf
           111 > soh lf 10
           111 < Dear garep, thank you for reporting the commodities you have in stock.
           222 < Dear derep, Greater Accra Regional Medical Store has RESOLVED the following stockouts: lf
           """
        self.runScript(a)

    def tearDown(self):
        TestScript.tearDown(self)
        self.mc_stock.delete()
        self.mg_stock.delete()
        self.lf_stock.delete()
Пример #30
0
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:
Пример #31
0
 def test_that_if_the_user_address_does_not_exist_you_get_a_404(self):
     backend = Backend(id=89)
     connection = Connection(identity=999, backend=backend)
     fake_request = self.setup_post_request(backend, connection)
     with self.assertRaises(Http404):
         response = self.view.dispatch(fake_request)
Пример #32
0
 def build_connection(self, contact=Contact()):
     return Connection(identity=77777,
                       backend=Backend(name='my backend'),
                       contact=contact)
Пример #33
0
def register_user(request, template="malawi/register-user.html"):
    context = dict()
    context['facilities'] = SupplyPoint.objects.filter(type__code="hf").order_by('code')
    context['backends'] = Backend.objects.all()
    context['dialing_code'] = settings.COUNTRY_DIALLING_CODE # [sic]
    if request.method != 'POST':
        return render_to_response(template, context, context_instance=RequestContext(request))

    id = request.POST.get("id", None)
    facility = request.POST.get("facility", None)
    name = request.POST.get("name", None)
    number = request.POST.get("number", None)
    backend = request.POST.get("backend", None)

    if not (id and facility and name and number and backend):
        messages.error(request, "All fields must be filled in.")
        return render_to_response(template, context, context_instance=RequestContext(request))
    hsa_id = None
    try:
        hsa_id = format_id(facility, id)
    except IdFormatException:
        messages.error(request, "HSA ID must be a number between 0 and 99.")
        return render_to_response(template, context, context_instance=RequestContext(request))

    try:
        parent = SupplyPoint.objects.get(code=facility)
    except SupplyPoint.DoesNotExist:
        messages.error(request, "No facility with that ID.")
        return render_to_response(template, context, context_instance=RequestContext(request))

    if Location.objects.filter(code=hsa_id).exists():
        messages.error(request, "HSA with that code already exists.")
        return render_to_response(template, context, context_instance=RequestContext(request))

    try:
        number = int(number)
    except ValueError:
        messages.error(request, "Phone number must contain only numbers.")
        return render_to_response(template, context, context_instance=RequestContext(request))

    hsa_loc = Location.objects.create(name=name, type=config.hsa_location_type(),
                                          code=hsa_id, parent=parent.location)
    sp = SupplyPoint.objects.create(name=name, code=hsa_id, type=config.hsa_supply_point_type(),
                                        location=hsa_loc, supplied_by=parent, active=True)
    sp.save()
    contact = Contact()
    contact.name = name
    contact.supply_point = sp
    contact.role = ContactRole.objects.get(code=config.Roles.HSA)
    contact.is_active = True
    contact.save()

    connection = Connection()
    connection.backend = Backend.objects.get(pk=int(backend))
    connection.identity = "+%s%s" % (settings.COUNTRY_DIALLING_CODE, number) #TODO: Check validity of numbers
    connection.contact = contact
    connection.save()

    messages.success(request, "HSA added!")

    return render_to_response(template, context, context_instance=RequestContext(request))
Пример #34
0
 def test_that_contact_exists_when_connection_has_contact(self):
     view = UReporterApiView()
     connection = Connection(contact=Contact())
     self.assertEqual(True, view.contact_exists(connection))
Пример #35
0
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:
Пример #36
0
def populate_user(row):
    for k, v in row.items():
        if v == '':
            del row[k]

    NON_REQUIRED_FIELDS = ['email', 'supervisor', 'phone']

    for k, v in row.iteritems():
        if v is None and k not in NON_REQUIRED_FIELDS:
            print '%s is required' % k
            return

    try:
        User.objects.get(username=row['username'])
        print 'user %s already exists' % row['username']
        return
    except User.DoesNotExist:
        pass

    ALLOWED_STATES = ('fct', 'nasawara', 'national')
    if not row['state'] in ALLOWED_STATES:
        print 'state must be one of: %s' % ', '.join(ALLOWED_STATES)
        return

    ALLOWED_PROGRAMS = ('pbf', 'fadama', 'both')
    if not row['program'] in ALLOWED_PROGRAMS:
        print 'program must be one of: %s' % ', '.join(ALLOWED_PROGRAMS)
        return

    PROGRAM_PERMS = {
        'pbf': 'pbf_view',
        'fadama': 'fadama_view',
    }
    perms = []
    if row['program'] == 'both':
        perms.extend(PROGRAM_PERMS.values())
    else:
        perms.append(PROGRAM_PERMS[row['program']])

    is_supervisor = (row.get('supervisor', '').lower() in ('y', 'yes', 'x'))
    if is_supervisor:
        perms.append('supervisor')

    def add_perm(u, perm_name):
        u.user_permissions.add(Permission.objects.get(codename=perm_name))

    u = User()
    u.username = row['username']
    u.first_name = row['first name']
    u.last_name = row['last name']
    u.email = row.get('email', '*****@*****.**')
    u.set_password(row['password'])
    u.save()

    for p in perms:
        add_perm(u, p)
    u.save()

    try:
        contact = Contact.objects.get(user__username=row['username'])
        return
    except Contact.DoesNotExist:
        pass

    if row['state'] == 'national':
        loc = Location.objects.get(slug='nigeria')
    else:
        loc = Location.objects.get(type__slug='state', slug=row['state'])

    c = Contact()
    c.name = '%s %s' % (u.first_name, u.last_name)
    c.first_name = u.first_name
    c.last_name = u.last_name
    c.email = row.get('email', '')
    c.user = u
    c.location = loc
    c.save()

    backend = Backend.objects.get(name='httptester')

    if row.get('phone'):
        conn = Connection()
        conn.backend = backend
        conn.identity = row['phone']
        conn.contact = c
        conn.save()
Пример #37
0
def parse_message_pieces (conn_recvd_from, subscribing, site_id, patient_id, patient_phone_str, contact_time_str, lang):
    """parse the sms message, either raising a variety of exceptions, or returning patient id,
    contact time as integer minutes since midnight, and language code to use for future notifications"""

    #language code
    if subscribing:
        validated_language = get_validated_language(lang) 
        if not validated_language:
            raise ValueError(get_text('language-unrecognized', config.default_language))
        else:
            lang = validated_language
    else:
        lang = config.default_language

    #site
    location = get_validated_site(site_id)
    if not location:
        raise ValueError(get_text('site-unrecognized', lang))
    
    #patient ID
    if not validate_patient_id_format(patient_id):
        raise ValueError(get_text('patid-unrecognized', lang))
    
    #patient phone # (optional -- use incoming connection if missing)
    if patient_phone_str:
        phone = parse_phone(patient_phone_str)
        if phone == None:
            raise ValueError(get_text('cannot-parse-phone', lang))
        try:
            patient_conn = Connection.objects.get(backend=conn_recvd_from.backend, identity=phone)
        except Connection.DoesNotExist:
            patient_conn = Connection(backend=conn_recvd_from.backend, identity=phone)
            patient_conn.save()
    else:
        if subscribing:
            patient_conn = conn_recvd_from
        else:
            patient_conn = None
    if patient_conn and conn_is_banned(patient_conn):
        raise ValueError(get_text('banned-phone', lang))

    #check if patient has already been registered
    try:
        reg = Registration.objects.get(patient_id=patient_id)
        patid_already_registered = True
    except Registration.DoesNotExist:
        patid_already_registered = False
        
    #check if phone number has already been registered
    phone_already_registered = False
    if patient_conn:
        try:
            Registration.objects.get(connection=patient_conn)
            phone_already_registered = True
        except Registration.DoesNotExist:
            pass
    
    #todo: change behavior if existing registration is completed/expired
    if patid_already_registered:
        if phone_already_registered or not subscribing:
            raise ValueError(get_text('already-registered', lang) % reg.registered_on.strftime('%d-%m-%Y'))
        else:
            raise ValueError(get_text('patid-already-registered', lang))
    elif phone_already_registered:
        raise ValueError(get_text('phone-already-registered', lang))
    
    if subscribing:
        contact_time = parse_contact_time(contact_time_str)
        if contact_time == None:
            raise ValueError(get_text('cannot-parse-time', lang))
    else:
        contact_time = None
    
    return (location, patient_id, patient_conn, contact_time, lang)