def handle(self, message): entry = ScriptProgress.objects.filter( script__slug__startswith='hotline_script', connection=message.connection) text = (message.text).lower() if (not entry.exists()): matches = difflib.get_close_matches( text, settings.REPORT_KEYWORDS.keys(), 1) if not matches: return False keyword = matches[0] language = settings.REPORT_KEYWORDS[keyword] slug_name = 'hotline_script_%s' % language ScriptProgress.objects.create( script=Script.objects.get(slug=slug_name), connection=message.connection) report = IGReport.objects.create(connection=message.connection, keyword=message.text) contact = Contact(name=message.connection.identity, language=language) contact.save() report.connection.contact = contact report.connection.save() return True return False
def handle (self, message): entry = ScriptProgress.objects.filter(script__slug__startswith='hotline_script', connection=message.connection) text = (message.text).lower() if (not entry.exists()): matches = difflib.get_close_matches(text, settings.REPORT_KEYWORDS.keys(), 1) if not matches: send_default = getattr(settings, 'SEND_DEFAULT_RESPONSE', True) if not send_default: return True return False keyword = matches[0] language = settings.REPORT_KEYWORDS[keyword] slug_name = 'hotline_script_%s' % language ScriptProgress.objects.create(script=Script.objects.get(slug=slug_name), connection=message.connection) report = Report.objects.create(connection=message.connection, keyword=message.text) contact = Contact(name=message.connection.identity, language=language) contact.save() report.connection.contact = contact report.connection.save() return True return False
def registration(req, pk=None, template="registration/dashboard.html"): contact = None connection = None bulk_form = None if pk is not None: contact = get_object_or_404(Contact, pk=pk) connection = get_object_or_404(Connection, contact__name=contact.name) 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) connection_form = ConnectionForm(req.POST, instance=connection) if contact_form.is_valid() and connection_form.is_valid(): contact = contact_form.save() connection = connection_form.save(commit=False) connection.contact = contact connection.save() return HttpResponseRedirect(reverse(registration)) else: contact_form = ContactForm(instance=contact) bulk_form = BulkRegistrationForm() connection_form = ConnectionForm(instance=connection) return render_to_response( template, { "contacts_table": ContactTable(Contact.objects.all(), request=req), "contact_form": contact_form, "connection_form": connection_form, "bulk_form": bulk_form, "contact": contact }, context_instance=RequestContext(req))
def get_or_create_contact(self): if self.contact is not None: return self.contact contact = Contact(name=self.user.username) contact.save() self.contact = contact self.save() return self.contact
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 handle(self, text): tokens = self.check_message_valid_and_clean(text) if not tokens: return clinic_code = LocationCode(tokens[0]) name = tokens[2] pin = tokens[4] worker_type = clinic_code.get_worker_type() location_type = clinic_code.get_location_type() if is_already_valid_connection_type(self.msg.connection, worker_type): # refuse re-registration if they're still active and eligible self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=self.msg.connection.contact.location) return False try: location = Location.objects.get(slug__iexact=clinic_code.slug, type__slug__in=location_type) if self.msg.connection.contact is not None \ and self.msg.connection.contact.is_active: # this means they were already registered and active, but not yet # receiving results. clinic = get_clinic_or_default(self.msg.connection.contact) if clinic != location: self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=clinic) return True else: contact = self.msg.contact else: contact = Contact(location=location) clinic = get_clinic_or_default(contact) contact.name = name contact.pin = pin contact.save() contact.types.add(worker_type) self.msg.connection.contact = contact self.msg.connection.save() self.respond("Hi %(name)s, thanks for registering for " "Results160 from %(location)s. " "Your PIN is %(pin)s. " "Reply with keyword 'HELP' if this is " "incorrect", name=contact.name, location=clinic.name, pin=pin) except Location.DoesNotExist: self.respond("Sorry, I don't know about a location with code %(code)s. Please check your code and try again.", code=clinic_code)
def testSaveSameContactTwice(self): NAME = "newuser" PHONE = "+233123" contact = Contact(name=NAME) form = CommoditiesContactForm({'name':NAME, 'phone':PHONE}, instance=contact) self.assertTrue(form.is_valid()) # this time around, the form should NOT throw an error on re-registration contact.save() contact.set_default_connection_identity(PHONE, settings.DEFAULT_BACKEND) form = CommoditiesContactForm({'name':NAME, 'phone':PHONE}, instance=contact) self.assertTrue(form.is_valid()) # this time around, the form should throw an error on duplicate registration NEWNAME = "newname" new_contact = Contact(name=NEWNAME) form = CommoditiesContactForm({'name':NEWNAME, 'phone':PHONE}, instance=new_contact) self.assertFalse(form.is_valid())
def handle(self, seller_alias): try: seller = Contact.by_alias(seller_alias) except: self.respond("Sorry, user %s was not found. Please check your spelling and try again" % seller_alias) else: response = self.get_current_stock(seller) self.respond("Stock for %s: %s" % (seller.alias, response))
def setUp(self): # Create some patients to correspond to the test messages self.patient = None for p in self.patients: contact = Contact(name=p["subject_number"]) contact.save() patient = Patient(subject_number=p["subject_number"], contact=contact) patient.save() if not self.patient: self.patient = patient for testmsg in self.testmsgs: patient = Patient.objects.get(subject_number=testmsg["subject_number"]) self.assertTrue(patient is not None) patient.wisepill_msisdn = testmsg["msisdn"] patient.save() testmsg["patient"] = patient self.assertEquals(patient.wisepill_msisdn, testmsg["msisdn"])
def testSaveSameContactTwice(self): NAME = "newuser" PHONE = "+233123" contact = Contact(name=NAME) form = CommoditiesContactForm({ 'name': NAME, 'phone': PHONE }, instance=contact) self.assertTrue(form.is_valid()) # this time around, the form should NOT throw an error on re-registration contact.save() contact.set_default_connection_identity(PHONE, settings.DEFAULT_BACKEND) form = CommoditiesContactForm({ 'name': NAME, 'phone': PHONE }, instance=contact) self.assertTrue(form.is_valid()) # this time around, the form should throw an error on duplicate registration NEWNAME = "newname" new_contact = Contact(name=NEWNAME) form = CommoditiesContactForm({ 'name': NEWNAME, 'phone': PHONE }, instance=new_contact) self.assertFalse(form.is_valid())
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
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'])
def setUp(self): # Create some patients to correspond to the test messages self.patient = None for p in self.patients: contact = Contact(name=p['subject_number']) contact.save() patient = Patient(subject_number=p['subject_number'], contact=contact) patient.save() if not self.patient: self.patient = patient for testmsg in self.testmsgs: patient = Patient.objects.get(subject_number=testmsg['subject_number']) self.assertTrue(patient is not None) patient.wisepill_msisdn = testmsg['msisdn'] patient.save() testmsg['patient'] = patient self.assertEquals(patient.wisepill_msisdn,testmsg['msisdn'])
def handle(self, seller_alias): try: seller = Contact.by_alias(seller_alias) except: self.respond( "Sorry, user %s was not found. Please check your spelling and try again" % seller_alias) else: response = self.get_current_stock(seller) self.respond("Stock for %s: %s" % (seller.alias, response))
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)
def contact(request, pk=None): if pk: contact = get_object_or_404(Contact, pk=pk) else: contact = Contact() contact_form = ContactForm(instance=contact) connection_formset = ConnectionFormSet(instance=contact) if request.method == 'POST': data = {} for key in request.POST: val = request.POST[key] if isinstance(val, basestring): data[key] = val else: try: data[key] = val[0] except (IndexError, TypeError): data[key] = val # print repr(data) del data if pk: if request.POST["submit"] == "Delete Contact": contact.delete() messages.add_message(request, messages.INFO, "Deleted contact") return HttpResponseRedirect(reverse(registration)) contact_form = ContactForm(request.POST, instance=contact) else: contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact = contact_form.save(commit=False) connection_formset = ConnectionFormSet(request.POST, instance=contact) if connection_formset.is_valid(): contact.save() connection_formset.save() messages.add_message(request, messages.INFO, "Added contact") return HttpResponseRedirect(reverse(registration)) return render(request, 'registration/contact_form.html', { "contact": contact, "contact_form": contact_form, "connection_formset": connection_formset, })
def sites_postsave_handler(sender, **kwargs): if 'django.contrib.sites' in settings.INSTALLED_APPS: if ((sender == Contact or sender in Contact.__subclasses__()) and kwargs['created']): ContactSite.objects.create(contact=kwargs['instance'], site=Site.objects.get_current()) elif ((sender == User or sender in User.__subclasses__()) and kwargs['created']): UserSite.objects.create(user=kwargs['instance'], site=Site.objects.get_current()) elif ((sender == Group or sender in Group.__subclasses__()) and kwargs['created']): GroupSite.objects.create(group=kwargs['instance'], site=Site.objects.get_current()) # elif (sender == Connection and kwargs['created']): # ConnectionSite.objects.create(connection = kwargs['instance'], site=Site.objects.get_current()) elif ((sender == Message or sender in Message.__subclasses__()) and kwargs['created']): MessageSite.objects.create(message=kwargs['instance'], site=Site.objects.get_current())
def testFormWithNoPhoneNumber(self): NAME = "newuser" PHONE = "+233123" contact = Contact(name=NAME) form = CommoditiesContactForm({'name': NAME}, instance=contact) self.assertFalse(form.is_valid()) form = CommoditiesContactForm({ 'name': NAME, 'phone': PHONE }, instance=contact) self.assertTrue(form.is_valid())
def handle(self, text): tokens = self.check_message_valid_and_clean(text) if not tokens: return clinic_code = LocationCode(tokens[0]) name = tokens[2] pin = tokens[4] worker_type = clinic_code.get_worker_type() location_type = clinic_code.get_location_type() if is_already_valid_connection_type(self.msg.connection, worker_type): # refuse re-registration if they're still active and eligible self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=self.msg.connection.contact.location) return False try: location = Location.objects.get(slug__iexact=clinic_code.slug, type__slug__in=location_type) if self.msg.connection.contact is not None \ and self.msg.connection.contact.is_active: # this means they were already registered and active, but not yet # receiving results. clinic = get_clinic_or_default(self.msg.connection.contact) if clinic != location: self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=clinic) return True else: contact = self.msg.contact else: contact = Contact(location=location) clinic = get_clinic_or_default(contact) contact.name = name contact.pin = pin contact.save() contact.types.add(worker_type) self.msg.connection.contact = contact self.msg.connection.save() self.respond( "Hi %(name)s, thanks for registering for " "Results160 from %(location)s. " "Your PIN is %(pin)s. " "Reply with keyword 'HELP' if this is " "incorrect", name=contact.name, location=clinic.name, pin=pin) except Location.DoesNotExist: self.respond( "Sorry, I don't know about a location with code %(code)s. Please check your code and try again.", code=clinic_code)
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 contact(request, pk=None): if pk: contact = get_object_or_404(Contact, pk=pk) else: contact = Contact() contact_form = ContactForm(instance=contact) connection_formset = ConnectionFormSet(instance=contact) if request.method == 'POST': data = {} for key in request.POST: val = request.POST[key] if isinstance(val, basestring): data[key] = val else: try: data[key] = val[0] except (IndexError, TypeError): data[key] = val # print repr(data) del data if pk: if request.POST["submit"] == "Delete Contact": contact.delete() messages.add_message(request, messages.INFO, "Deleted contact") return HttpResponseRedirect(reverse(registration)) contact_form = ContactForm(request.POST, instance=contact) else: contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact = contact_form.save(commit=False) connection_formset = ConnectionFormSet(request.POST, instance=contact) if connection_formset.is_valid(): contact.save() connection_formset.save() messages.add_message(request, messages.INFO, "Added contact") return HttpResponseRedirect(reverse(registration)) return render( request, 'registration/contact_form.html', { "contact": contact, "contact_form": contact_form, "connection_formset": connection_formset, })
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
Manager to filter by a location looking in both the location and location parent field. Call it like: objects.location(my_loc).filter(name="mary") """ def location(self, location): return self.get_query_set().location(location) def get_query_set(self): return SelfOrParentLocationQuerySet(self.model) # override the Contacts manager so you can do location aware queries Contact.add_to_class("objects", SelfOrParentLocationContactManager()) class ActiveContactManager(SelfOrParentLocationContactManager): """Filter contacts by who is active""" def get_query_set(self): return super(ActiveContactManager, self).get_query_set().filter(is_active=True) # add the active manager to the Contact class. You can reference this # instead of objects like: # Contact.active.all() # Contact.active.filter(name="mary") # etc. Contact.add_to_class("active", ActiveContactManager())
def handle(self, text): # expected format: # # register wheeler 3 unicef house # | | | | # V | | | # handler V | | # surname | | # V | # facility code | # V # facility name known_contact = None possible_contacts_by_name = None possible_contacts = [] facility = None possible_facilities = [] possible_fac_by_code = None possible_fac_by_name = None fac_by_code = None fac_by_name = None if self.msg.connection.identity is not None: try: known_contact = Contact.objects.get(phone=self.msg.connection.identity) self.msg.connection.contact = known_contact self.msg.connection.save() self.debug('KNOWN CONTACT') except MultipleObjectsReturned: #TODO do something? self.debug('MULTIPLE IDENTITIES') pass except ObjectDoesNotExist: self.debug('NO PERSON FOUND') else: self.debug('NO IDENTITY') if True: expected_tokens = ['word', 'number', 'words'] token_labels = ['surname', 'facility_code', 'facility_name'] tokens = utils.split_into_tokens(expected_tokens, token_labels, text) self.debug(tokens) if not tokens['surname'].isdigit(): possible_contacts_by_name = Contact.closest_by_spelling(tokens['surname']) if len(possible_contacts_by_name) == 1: known_contact = possible_contacts_by_name[0][1] self.msg.connection.contact = known_contact self.msg.connection.save() possible_contacts_by_sound = Contact.closest_by_sound(tokens['surname']) if len(possible_contacts_by_sound) == 1: known_contact = possible_contacts_by_sound[0][0] self.msg.connection.contact = known_contact self.msg.connection.save() if tokens['facility_code'].isdigit(): possible_fac_by_code = School.closest_by_code(tokens['facility_code']) self.debug("%s possible facilities by code" % (str(len(possible_fac_by_code)))) if len(possible_fac_by_code) == 1: if possible_fac_by_code[0][2] == 0 and possible_fac_by_code[0][3] == 0 and possible_fac_by_code[0][4] == 1.0: self.debug('PERFECT LOC MATCH BY CODE') fac_by_code = possible_fac_by_code[0][1] if not tokens['facility_name'].isdigit(): possible_fac_by_name = School.closest_by_spelling(tokens['facility_name']) self.debug("%s possible facilities by name" % (str(len(possible_fac_by_name)))) if len(possible_fac_by_name) == 1: if possible_fac_by_name[0][2] == 0 and possible_fac_by_name[0][3] == 0 and possible_fac_by_name[0][4] == 1.0: self.debug('PERFECT LOC MATCH BY NAME') fac_by_name = possible_fac_by_name[0][1] # see if either facility lookup returned a perfect match if fac_by_code or fac_by_name is not None: if fac_by_code and fac_by_name is not None: # if they are both the same perfect match we have a winner if fac_by_code.pk == fac_by_name.pk: facility = fac_by_code # if we have two different perfect matches, add to list else: possible_facilities.append(fac_by_code) self.debug("%s possible facilities" % (str(len(possible_facilities)))) possible_facilities.append(fac_by_name) self.debug("%s possible facilities" % (str(len(possible_facilities)))) else: # perfect match by either is also considered a winner facility = fac_by_code if fac_by_code is not None else fac_by_name self.debug(facility) # neither lookup returned a perfect match else: # make list of facility objects that are in both fac_by_code and fac_by_name if possible_fac_by_code and possible_fac_by_name is not None: possible_facilities.extend([l[1] for l in filter(lambda x:x in possible_fac_by_code, possible_fac_by_name)]) self.debug("%s possible facilities by both" % (str(len(possible_facilities)))) if len(possible_facilities) == 0: possible_facilities.extend([l[1] for l in possible_fac_by_code if possible_fac_by_code is not None]) possible_facilities.extend([l[1] for l in possible_fac_by_name if possible_fac_by_name is not None]) self.debug("%s possible facilities by both" % (str(len(possible_facilities)))) if len(possible_facilities) == 1: facility = possible_facilities[0] if known_contact is None: if possible_contacts_by_name is not None: possible_contacts_by_both = [] # gather the Contacts from the match tuples possible_contacts = [c[1] for c in possible_contacts_by_name] self.debug("%s possible contacts by name" % (str(len(possible_contacts)))) self.debug(possible_contacts) # add Contacts from phonetic match tuples [possible_contacts.append(c[0]) for c in possible_contacts_by_sound] self.debug("%s possible contacts by name" % (str(len(possible_contacts)))) self.debug(possible_contacts) # lookup all the contacts associated with each possible_facilities from above possible_contacts_by_loc_raw = [list(f.facilitycontact.all()) for f in possible_facilities] # flatten list possible_contacts_by_loc = [item for sublist in possible_contacts_by_loc_raw for item in sublist] self.debug("%s possible contacts by location" % (str(len(possible_contacts_by_loc)))) self.debug(possible_contacts_by_loc) if len(possible_contacts_by_loc) > 0: possible_contacts_by_both = filter(lambda x:x in possible_contacts, possible_contacts_by_loc) self.debug("%s possible contacts by BOTH" % (str(len(possible_contacts_by_both)))) if len(possible_contacts_by_both) == 0: possible_contacts_by_both.extend(possible_contacts) if possible_contacts_by_loc: possible_contacts_by_both.extend(possible_contacts_by_loc) self.debug("%s possible contacts by BOTH" % (str(len(possible_contacts_by_both)))) if len(possible_contacts_by_both) == 1: known_contact = possible_contacts_by_both[0] known_contact.phone = self.msg.connection.identity self.msg.connection.contact = known_contact self.msg.connection.save() known_contact.save() else: possible_contacts_names = [c.name for c in possible_contacts_by_both] self.respond("Did you mean one of: %s?" % (", ".join(possible_contacts_names))) else: if facility is not None: self.respond("Hello %s, this phone number is now registered for %s (code: %s)" %\ (known_contact.name, facility.name,\ str(facility.code) + str(facility.satellite_number))) else: possible_facilities_names = [str(f.name) + " " + str(f.code) + str(f.satellite_number) for f in possible_facilities] self.respond("Hello %s, did you mean one of: %s?" %\ (known_contact.name, " ,".join(possible_facilities_names)))
def build_connection(self, contact=Contact()): return Connection(identity=77777, backend=Backend(name='my backend'), contact=contact)
def handle(self, text): stocker = self.msg.connection.contact args = text.partition(' ') if args[0] == 'cancel': self.cancel_restocks(stocker) return True target_alias = args[0].lower() restock_list = self.parse_restock_string(args[2].lower()) if not restock_list: self.help() return True # confirm that alias exists try: target = Contact.objects.get(alias=target_alias) except: self.respond( "Sorry, user %s was not found. Please check your spelling and try again" % target_alias) return True errors = [] stockouts = [] pending = [] response = "" notification = "" #admin must create this user, for holding pending stock transactions nobody = Contact.by_alias("nobody") for code, amount in restock_list: if amount == 0: errors.append(code) if amount == -1 or code == '': self.respond( "Missing product code or amount. Restock messages cannot contain spaces.\nExample: restock dnombo 5ew" ) return True else: current_stock = Stock.get_existing(stocker.alias, code) #make sure the initiator of the transaction has enough stock if current_stock is None or current_stock.stock_amount < amount: stockouts.append(code) else: target_product = Product.by_code(code) s = Stock(seller=nobody, product=target_product, stock_amount=amount) s.save() pending.append(s) current_stock.stock_amount -= amount current_stock.save() if pending: #create the transaction object and add stock to be moved trans = StockTransaction(initiator=stocker, recipient=target, status=2, date_initiated=datetime.now()) trans.save( ) #need to generate a primary key before adding products for p in pending: trans.to_transfer.add(p) response += "%s %s " % (p.stock_amount, p.product.display_name) notification += "%s %s " % (p.stock_amount, p.product.display_name) trans.save() response += "sent to %s. " % target.alias if stockouts: for out in stockouts: response += "%s " % out response += "out of stock. " if errors: for err in errors: response += "%s " % err response += "not recognized." self.respond(response) if notification: notification += "being sent by %s. Reply 'yes' to accept, 'no' to reject." % stocker.alias target.message(notification)
class HSARegistrationHandler(RegistrationBaseHandler): """ Registration for HSAs """ keyword = "reg|register" def help(self): self.respond(config.Messages.HSA_HELP) def handle(self, text): if self.handle_preconditions(text): return # default to HSA role = ContactRole.objects.get(code=config.Roles.HSA) try: hsa_id = format_id(self.supply_point.code, self.extra) except IdFormatException, e: self.respond(str(e)) return if Location.objects.filter(code=hsa_id, is_active=True).exists(): self.respond( "Sorry, a location with %(code)s already exists. Another HSA may have already registered this ID", code=hsa_id) return if SupplyPoint.objects.filter(code=hsa_id, contact__is_active=True).exists(): self.respond( "Sorry, a supply point with %(code)s already exists. Another HSA may have already registered this ID", code=hsa_id) return # create a location and supply point for the HSA if SupplyPoint.objects.filter(code=hsa_id, type=config.hsa_supply_point_type(), active=False).exists(): # We have a previously deactivated HSA. Reassociate. sp = SupplyPoint.objects.get(code=hsa_id, type=config.hsa_supply_point_type(), active=False) sp.name = self.contact_name sp.active = True sp.save() sp.location.is_active = True sp.location.name = self.contact_name sp.location.save() else: hsa_loc = Location.objects.create( name=self.contact_name, type=config.hsa_location_type(), code=hsa_id, parent=self.supply_point.location) sp = SupplyPoint.objects.create( name=self.contact_name, code=hsa_id, type=config.hsa_supply_point_type(), location=hsa_loc, supplied_by=self.supply_point) # overwrite the existing contact data if it was already there # we know at least they were not active since we checked above contact = self.msg.logistics_contact if hasattr( self.msg, 'logistics_contact') else Contact() contact.name = self.contact_name contact.supply_point = sp contact.role = role contact.is_active = True if not settings.LOGISTICS_APPROVAL_REQUIRED: contact.is_approved = True contact.save() self.msg.connection.contact = contact self.msg.connection.save() if settings.LOGISTICS_APPROVAL_REQUIRED: try: sh = Contact.objects.get( supply_point__location=self.supply_point.location, role=ContactRole.objects.get(code=Roles.HSA_SUPERVISOR)) sh.message(config.Messages.APPROVAL_REQUEST, hsa=contact.name, code=hsa_id) self.respond(_(config.Messages.APPROVAL_WAITING), hsa=contact.name) except Contact.DoesNotExist: # If there's no HSA supervisor registered, we silently approve them. Oh well. contact.is_approved = True self.respond(_(config.Messages.REGISTRATION_CONFIRM), sp_name=self.supply_point.name, contact_name=contact.name, role=contact.role.name) else: self.respond(_(config.Messages.REGISTRATION_CONFIRM), sp_name=self.supply_point.name, contact_name=contact.name, role=contact.role.name)
def handle(self, text): stocker = self.msg.connection.contact args = text.partition(" ") if args[0] == "cancel": self.cancel_restocks(stocker) return True target_alias = args[0].lower() restock_list = self.parse_restock_string(args[2].lower()) if not restock_list: self.help() return True # confirm that alias exists try: target = Contact.objects.get(alias=target_alias) except: self.respond("Sorry, user %s was not found. Please check your spelling and try again" % target_alias) return True errors = [] stockouts = [] pending = [] response = "" notification = "" # admin must create this user, for holding pending stock transactions nobody = Contact.by_alias("nobody") for code, amount in restock_list: if amount == 0: errors.append(code) if amount == -1 or code == "": self.respond( "Missing product code or amount. Restock messages cannot contain spaces.\nExample: restock dnombo 5ew" ) return True else: current_stock = Stock.get_existing(stocker.alias, code) # make sure the initiator of the transaction has enough stock if current_stock is None or current_stock.stock_amount < amount: stockouts.append(code) else: target_product = Product.by_code(code) s = Stock(seller=nobody, product=target_product, stock_amount=amount) s.save() pending.append(s) current_stock.stock_amount -= amount current_stock.save() if pending: # create the transaction object and add stock to be moved trans = StockTransaction(initiator=stocker, recipient=target, status=2, date_initiated=datetime.now()) trans.save() # need to generate a primary key before adding products for p in pending: trans.to_transfer.add(p) response += "%s %s " % (p.stock_amount, p.product.display_name) notification += "%s %s " % (p.stock_amount, p.product.display_name) trans.save() response += "sent to %s. " % target.alias if stockouts: for out in stockouts: response += "%s " % out response += "out of stock. " if errors: for err in errors: response += "%s " % err response += "not recognized." self.respond(response) if notification: notification += "being sent by %s. Reply 'yes' to accept, 'no' to reject." % stocker.alias target.message(notification)
def registration(req, pk=None, template="registration/dashboard.html", contact_form=CommoditiesContactForm): contact = None connection = None bulk_form = None search = None registration_view = 'registration' registration_edit = 'registration_edit' if hasattr(settings, 'SMS_REGISTRATION_VIEW'): registration_view = settings.SMS_REGISTRATION_VIEW if hasattr(settings, 'SMS_REGISTRATION_EDIT'): registration_edit = settings.SMS_REGISTRATION_EDIT if pk is not None: contact = get_object_or_404(Contact, pk=pk) try: connection = Connection.objects.get(contact=contact) except Connection.DoesNotExist: connection = None if req.method == "POST": if req.POST["submit"] == "Delete Contact": name = unicode(contact) contact.delete() return HttpResponseRedirect("%s?deleted=%s" % (reverse(registration_view), name)) elif "bulk" in req.FILES: # TODO use csv module #reader = csv.reader(open(req.FILES["bulk"].read(), "rb")) #for row in reader: for line in req.FILES["bulk"]: line_list = line.split(',') name = line_list[0].strip() backend_name = line_list[1].strip() identity = line_list[2].strip() contact = Contact(name=name) contact.save() # TODO deal with errors! backend = Backend.objects.get(name=backend_name) connection = Connection(backend=backend, identity=identity,\ contact=contact) connection.save() return HttpResponseRedirect(reverse(registration_view)) else: contact_form = contact_form(instance=contact, data=req.POST) if contact_form.is_valid(): created = False if contact is None: created = True contact = contact_form.save() if created: response = "Dear %(name)s, you have been registered on %(site)s" % \ {'name': contact.name, 'site': Site.objects.get(id=settings.SITE_ID).domain } send_message(contact.default_connection, response) return HttpResponseRedirect( "%s?created=%s" % (reverse(registration_edit, kwargs={'pk': contact.pk}), unicode(contact))) else: if pk is None: supplypoint = None if "supplypoint" in req.GET and req.GET["supplypoint"]: try: supplypoint = SupplyPoint.objects.get( code=req.GET["supplypoint"]) except SupplyPoint.DoesNotExist, SupplyPoint.MultipleObjectsReturned: pass contact_form = contact_form(instance=contact, initial={'supply_point': supplypoint}) else:
def test_that_retrieves_none_when_contact_do_not_have_a_poll(self): contact = Contact() contact.save() self.assertEqual(None, self.view.get_current_poll_for(contact))
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()
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 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()
def handle(self, text): b = InputCleaner() if is_eligible_for_results(self.msg.connection): # refuse re-registration if they're still active and eligible self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=self.msg.connection.contact.location) return text = text.strip() text = b.remove_double_spaces(text) if len(text) < (self.PIN_LENGTH + self.MIN_CLINIC_CODE_LENGTH + self.MIN_NAME_LENGTH + 1): self.mulformed_msg_help() return #signed pin if text[-5:-4] == '-' or text[-5:-4] == '+': self.invalid_pin(text[-5:]) return #too long pin if ' ' in text and text[1 + text.rindex(' '):].isdigit() and len(text[1 + text.rindex(' '):]) > self.PIN_LENGTH: self.invalid_pin(text[1 + text.rindex(' '):]) return #non-white space before pin if text[-5:-4] != ' ' and text[-4:-3] != ' ': self.respond("Sorry, you should put a space before your pin. " "Please make sure your code is a %s-digit number like %s. " "Send JOIN <CLINIC CODE> <YOUR NAME> <SECURITY CODE>." % ( self.PIN_LENGTH, ''.join(str(i) for i in range(1, int(self.PIN_LENGTH) + 1)))) return #reject invalid pin user_pin = text[-4:] if not user_pin: self.help() return elif len(user_pin) < 4: self.invalid_pin(user_pin) return elif not user_pin.isdigit(): self.invalid_pin(user_pin) return group = self.PATTERN.search(text) if group is None: self.mulformed_msg_help() return tokens = group.groups() if not tokens: self.mulformed_msg_help() return clinic_code = tokens[0].strip() clinic_code = b.try_replace_oil_with_011(clinic_code) #we expect all codes have format PPDDFF or PPDDFFS clinic_code = clinic_code[0:6] name = tokens[2] name = name.title().strip() pin = tokens[4].strip() if len(pin) != self.PIN_LENGTH: self.respond(self.INVALID_PIN) return if not name: self.respond("Sorry, you must provide a name to register. %s" % self.HELP_TEXT) return elif len(name) < self.MIN_NAME_LENGTH: self.respond("Sorry, you must provide a valid name to register. %s" % self.HELP_TEXT) return try: location = Location.objects.get(slug__iexact=clinic_code, type__slug__in=const.CLINIC_SLUGS) if self.msg.connection.contact is not None \ and self.msg.connection.contact.is_active: # this means they were already registered and active, but not yet # receiving results. clinic = get_clinic_or_default(self.msg.connection.contact) if clinic != location: self.respond(self.ALREADY_REGISTERED, name=self.msg.connection.contact.name, location=clinic) return True else: contact = self.msg.contact else: contact = Contact(location=location) clinic = get_clinic_or_default(contact) contact.name = name contact.pin = pin contact.save() contact.types.add(const.get_clinic_worker_type()) self.msg.connection.contact = contact self.msg.connection.save() self.respond("Hi %(name)s, thanks for registering for " "Results160 from %(location)s. " "Your PIN is %(pin)s. " "Reply with keyword 'HELP' if this is " "incorrect", name=contact.name, location=clinic.name, pin=pin) except Location.DoesNotExist: self.respond("Sorry, I don't know about a location with code %(code)s. Please check your code and try again.", code=clinic_code)
def testEmptyInstance(self): NAME = "newuser" PHONE = "+233123" contact = Contact(name=NAME) form = CommoditiesContactForm({'name': NAME}, instance=None) self.assertFalse(form.is_valid())
def if_exists_delete_contact(name): try: contact = Contact.objects.get(name=name) Contact.delete(contact) except Contact.DoesNotExist: pass
def populate_user(row): for k, v in row.items(): if v == "": del row[k] NON_REQUIRED_FIELDS = ["email", "perm"] 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 if "perm" in row and not row["perm"] in ALLOWED_PERMS: print "perm must be one of: %s" % ", ".join(ALLOWED_PERMS) return if "perm" in row: perm = Permission.objects.get(codename=row["perm"]) else: perm = None 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() if perm: u.user_permissions.add(perm) 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()
""" Manager to filter by a location looking in both the location and location parent field. Call it like: objects.location(my_loc).filter(name="mary") """ def location(self, location): return self.get_query_set().location(location) def get_query_set(self): return SelfOrParentLocationQuerySet(self.model) # override the Contacts manager so you can do location aware queries Contact.add_to_class("objects", SelfOrParentLocationContactManager()) class ActiveContactManager(SelfOrParentLocationContactManager): """Filter contacts by who is active""" def get_query_set(self): return super(ActiveContactManager, self).get_query_set()\ .filter(is_active=True) # add the active manager to the Contact class. You can reference this # instead of objects like: # Contact.active.all() # Contact.active.filter(name="mary") # etc. Contact.add_to_class("active", ActiveContactManager())
def migrate(): for product in old_models.Product.objects.all(): p = new_models.Product(name=product.name, units=product.units, sms_code=product.sms_code, description=product.description) p.save() for p in old_models.ProductReportType.objects.all(): r = new_models.ProductReportType(name=p.name, sms_code=p.sms_code) r.save() # Necessary because there's no slug field types = (("MOHSW", "moh"), ("REGION", "reg"), ("DISTRICT", "dis"), ("FACILITY", "fac")) for t in types: nt = new_models.SupplyPointType(name=t[0], code=t[1]) nt.save() for object in old_models.ServiceDeliveryPoint.objects.all(): if new_models.SupplyPoint.objects.filter(name=object.name).exists(): return l = new_models.Location(point=object.point if object.point else None, type=object.type, parent_type=object.parent_type, parent_id=object.parent_id, parent=object.parent) l.save() sp = new_models.SupplyPoint( name=object.sdp_name, is_active=object.active, location=l, type=new_models.SupplyPointType.objects.get(name=object.type.name)) if new_models.SupplyPoint.objects.filter( name=sp.location.parent.name).exists(): sp.supplied_by = new_models.SupplyPoint.objects.get( name=sp.location.parent.name) sp.save() for a in old_models.ActiveProduct.objects.filter( service_delivery_point=object): ps = new_models.ProductStock( is_active=a.is_active, supply_point=sp, quantity=a.current_quantity, product=new_models.Product.objects.get( sms_code=a.product.sms_code)) ps.save() roles = (("Facility in-charge", "ic"), ("DMO", "dm"), ("RMO", "rm"), ("District Pharmacist", "dp"), ("MOHSW", "mh"), ("MSD", "ms")) for r in roles: c = new_models.ContactRole(name=r[0], code=r[1]) c.save() for oc in old_models.ContactDetail.objects.all(): c = Contact(name=oc.name, role=new_models.ContactRole.objects.get(name=oc.role.name), supply_point=new_models.SupplyPoint.objects.get( name=oc.service_delivery_point.name)) c.save() for cb in ConnectionBase.objects.filter(contact=oc): cb.contact = c cb.save()
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))
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()
def test_that_contact_exists_when_connection_has_contact(self): view = UReporterApiView() connection = Connection(contact=Contact()) self.assertEqual(True, view.contact_exists(connection))
def registration(req, pk=None, template="registration/dashboard.html", contact_form=CommoditiesContactForm): contact = None connection = None bulk_form = None search = None registration_view = 'registration' registration_edit = 'registration_edit' if hasattr(settings, 'SMS_REGISTRATION_VIEW'): registration_view = settings.SMS_REGISTRATION_VIEW if hasattr(settings, 'SMS_REGISTRATION_EDIT'): registration_edit = settings.SMS_REGISTRATION_EDIT if pk is not None: contact = get_object_or_404( Contact, pk=pk) try: connection = Connection.objects.get(contact=contact) except Connection.DoesNotExist: connection = None if req.method == "POST": if req.POST["submit"] == "Delete Contact": name = unicode(contact) contact.delete() return HttpResponseRedirect("%s?deleted=%s" % (reverse(registration_view), name)) elif "bulk" in req.FILES: # TODO use csv module #reader = csv.reader(open(req.FILES["bulk"].read(), "rb")) #for row in reader: for line in req.FILES["bulk"]: line_list = line.split(',') name = line_list[0].strip() backend_name = line_list[1].strip() identity = line_list[2].strip() contact = Contact(name=name) contact.save() # TODO deal with errors! backend = Backend.objects.get(name=backend_name) connection = Connection(backend=backend, identity=identity,\ contact=contact) connection.save() return HttpResponseRedirect( reverse(registration_view)) else: contact_form = contact_form( instance=contact, data=req.POST) if contact_form.is_valid(): created = False if contact is None: created = True contact = contact_form.save() if created: response = "Dear %(name)s, you have been registered on %(site)s" % \ {'name': contact.name, 'site': Site.objects.get(id=settings.SITE_ID).domain } send_message(contact.default_connection, response) return HttpResponseRedirect("%s?created=%s" % (reverse(registration_edit, kwargs={'pk':contact.pk}), unicode(contact))) else: if pk is None: supplypoint = None if "supplypoint" in req.GET and req.GET["supplypoint"]: try: supplypoint = SupplyPoint.objects.get(code=req.GET["supplypoint"]) except SupplyPoint.DoesNotExist, SupplyPoint.MultipleObjectsReturned: pass contact_form = contact_form( instance=contact, initial={'supply_point':supplypoint}) else:
def 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) )
def migrate(): for product in old_models.Product.objects.all(): p = new_models.Product( name=product.name, units=product.units, sms_code=product.sms_code, description=product.description ) p.save() for p in old_models.ProductReportType.objects.all(): r = new_models.ProductReportType(name=p.name,sms_code=p.sms_code) r.save() # Necessary because there's no slug field types = ( ("MOHSW", "moh"), ("REGION", "reg"), ("DISTRICT", "dis"), ("FACILITY", "fac") ) for t in types: nt = new_models.SupplyPointType( name = t[0], code = t[1] ) nt.save() for object in old_models.ServiceDeliveryPoint.objects.all(): if new_models.SupplyPoint.objects.filter(name=object.name).exists(): return l = new_models.Location(point=object.point if object.point else None, type=object.type, parent_type=object.parent_type, parent_id=object.parent_id, parent=object.parent) l.save() sp = new_models.SupplyPoint( name = object.sdp_name, is_active = object.active, location = l, type = new_models.SupplyPointType.objects.get(name=object.type.name)) if new_models.SupplyPoint.objects.filter(name = sp.location.parent.name).exists(): sp.supplied_by = new_models.SupplyPoint.objects.get(name = sp.location.parent.name) sp.save() for a in old_models.ActiveProduct.objects.filter(service_delivery_point=object): ps = new_models.ProductStock(is_active = a.is_active, supply_point = sp, quantity = a.current_quantity, product = new_models.Product.objects.get(sms_code=a.product.sms_code)) ps.save() roles = ( ("Facility in-charge", "ic"), ("DMO", "dm"), ("RMO", "rm"), ("District Pharmacist", "dp"), ("MOHSW", "mh"), ("MSD", "ms") ) for r in roles: c = new_models.ContactRole(name=r[0], code=r[1]) c.save() for oc in old_models.ContactDetail.objects.all(): c = Contact( name = oc.name, role = new_models.ContactRole.objects.get(name=oc.role.name), supply_point=new_models.SupplyPoint.objects.get(name=oc.service_delivery_point.name) ) c.save() for cb in ConnectionBase.objects.filter(contact=oc): cb.contact = c cb.save()
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))
class CreateUserHandler(RecordResponseHandler): """ Registration for HSAs """ keyword = "hsa" def help(self): self.respond(config.Messages.HSA_HELP) @logistics_contact_and_permission_required(config.Operations.ADD_USER) def handle(self, text): words = text.split() if len(words) < 3: self.help() else: self.contact_name = " ".join(words[:-2]) self.extra = words[-2] code = words[-1] try: self.supply_point = SupplyPoint.objects.get(code__iexact=code) except SupplyPoint.DoesNotExist: self.respond(_(config.Messages.UNKNOWN_LOCATION), code=code ) # default to HSA role = ContactRole.objects.get(code=config.Roles.HSA) def format_id(code, id): try: id_num = int(id) if id_num < 1 or id_num >= 100: raise IdFormatException("id must be a number between 1 and 99. %s is out of range" % id) return "%s%02d" % (code, id_num) except ValueError: raise IdFormatException("id must be a number between 1 and 99. %s is not a number" % id) try: hsa_id = format_id(self.supply_point.code, self.extra) except IdFormatException, e: self.respond(str(e)) return if Location.objects.filter(code=hsa_id).exists(): self.respond("Sorry, a location with %(code)s already exists. Another HSA may have already registered this ID", code=hsa_id) return if SupplyPoint.objects.filter(code=hsa_id, contact__is_active=True).exists(): self.respond("Sorry, a supply point with %(code)s already exists. Another HSA may have already registered this ID", code=hsa_id) return # create a location and supply point for the HSA hsa_loc = Location.objects.create(name=self.contact_name, type=config.hsa_location_type(), code=hsa_id, parent=self.supply_point.location) sp = SupplyPoint.objects.create(name=self.contact_name, code=hsa_id, type=config.hsa_supply_point_type(), location=hsa_loc, supplied_by=self.supply_point) # overwrite the existing contact data if it was already there # we know at least they were not active since we checked above contact = Contact() contact.name = self.contact_name contact.supply_point = sp contact.role = role contact.is_active = True contact.save() self.respond(_(config.Messages.REGISTRATION_CONFIRM), sp_name=self.supply_point.name, contact_name=contact.name, role=contact.role.name)
def handle(self, text): sp_name = None msd_code = None if text.find(config.DISTRICT_REG_DELIMITER) != -1: phrases = [x.strip() for x in text.split(":")] if len(phrases) != 2: self.respond_error(_(config.Messages.REGISTER_HELP)) return True name = phrases[0] sp_name = phrases[1] try: sdp = SupplyPoint.objects.get(type__code="district", name__istartswith=sp_name) except SupplyPoint.DoesNotExist: kwargs = {'name': sp_name} self.respond_error( _(config.Messages.REGISTER_UNKNOWN_DISTRICT), **kwargs) return True except SupplyPoint.MultipleObjectsReturned: kwargs = {'name': sp_name} self.respond_error( _(config.Messages.REGISTER_UNKNOWN_DISTRICT), **kwargs) return True else: words = text.split() names = [] msd_codes = [] for the_string in words: if re.match('^d\d+', the_string.strip().lower()): msd_codes.append(the_string.strip().lower()) else: names.append(the_string) name = " ".join(names) if len(msd_codes) != 1: self.respond_error(_(config.Messages.REGISTER_HELP)) return True else: [msd_code] = msd_codes try: sdp = SupplyPoint.objects.get(code__iexact=msd_code) except SupplyPoint.DoesNotExist: kwargs = {'msd_code': msd_code} self.respond_error( _(config.Messages.REGISTER_UNKNOWN_CODE), **kwargs) return True # Default to Facility in-charge or District Pharmacist for now if sdp.type.code.lower() == config.SupplyPointCodes.DISTRICT: role = ContactRole.objects.get( code__iexact=config.Roles.DISTRICT_PHARMACIST) elif sdp.type.code.lower() == config.SupplyPointCodes.FACILITY: role = ContactRole.objects.get(code__iexact=config.Roles.IN_CHARGE) else: # TODO be graceful self.add_tag("Error") raise Exception("bad location type: %s" % sdp.type.name) contact = self.msg.logistics_contact if hasattr( self.msg, 'logistics_contact') else Contact() contact.name = name contact.supply_point = sdp contact.role = role contact.is_active = True contact.is_approved = True contact.language = config.Languages.DEFAULT contact.save() self.msg.connection.contact = contact self.msg.connection.save() if sp_name: kwargs = {'sdp_name': sdp.name, 'contact_name': contact.name} self.respond(_(config.Messages.REGISTRATION_CONFIRM_DISTRICT), **kwargs) else: kwargs = { 'sdp_name': sdp.name, 'msd_code': msd_code, 'contact_name': contact.name } self.respond(_(config.Messages.REGISTRATION_CONFIRM), **kwargs)