Ejemplo n.º 1
0
def signup(request):
    status_message = None
    if request.method == "POST":
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            mobile = signup_form.cleaned_data["mobile"]
            (number, backend) = assign_backend(mobile)

            # create our connection

            (connection, conn_created) = Connection.objects.get_or_create(backend=backend, identity=number)
            connection.contact = Contact.objects.create(
                name=signup_form.cleaned_data["firstname"] + " " + signup_form.cleaned_data["lastname"]
            )
            contact = connection.contact
            contact.reporting_location = signup_form.cleaned_data["district"]

            contact.gender = signup_form.cleaned_data["gender"]
            if signup_form.cleaned_data["village"]:
                connection.contact.village = find_closest_match(
                    signup_form.cleaned_data["village"], Location.objects.exclude(type="district")
                )
            if signup_form.cleaned_data["age"]:
                contact.birthdate = datetime.datetime.now() - datetime.timedelta(
                    days=365 * int(signup_form.cleaned_data["age"])
                )

            if signup_form.cleaned_data["group"]:
                group_to_match = signup_form.cleaned_data["group"]

                if Group.objects.filter(name="Other uReporters").count():
                    default_group = Group.objects.get(name="Other uReporters")
                    contact.groups.add(default_group)
                if group_to_match:
                    for g in re.findall(r"\w+", group_to_match):
                        if g:
                            group = find_closest_match(str(g), Group.objects)
                            if group:
                                connection.contact.groups.add(group)
                                break
            connection.save()
            contact.save()
            status_message = "You have successfully signed up :)"
            if conn_created:
                Message.objects.create(
                    connection=connection,
                    direction="O",
                    status="Q",
                    text="CONGRATULATIONS!!! You are now a registered member of Ureport! With Ureport, you can make a real difference!  Speak Up and Be Heard! from UNICEF",
                )
        else:
            return render_to_response(
                "ureport/signup.html", dict(signup_form=signup_form), context_instance=RequestContext(request)
            )
    signup_form = SignupForm()
    return render_to_response(
        "ureport/signup.html",
        dict(signup_form=signup_form, status_message=status_message),
        context_instance=RequestContext(request),
    )
Ejemplo n.º 2
0
def send_message(request, template='ureport/partials/forward.html'):
    if not request.method == 'POST':
        send_message_form = SendMessageForm()

        if request.GET.get('forward', None):
            # import pdb; pdb.set_trace()
            msg = request.GET.get('msg')

            template = 'ureport/partials/forward.html'
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                ForwardMessageForm(data={'text': message.text})
            request.session['mesg'] = message
        if request.GET.get('reply', None):
            msg = request.GET.get('msg')
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                SendMessageForm(data={'text': message.text,
                                      'recipients': message.connection.identity})
            template = 'ureport/partials/reply.html'
            request.session['mesg'] = message
    else:
        send_message_form = SendMessageForm(request.POST)
        if request.GET.get('forward'):
            status = 'forwarded'
        else:
            status = 'replied'
        if send_message_form.is_valid():
            recs = send_message_form.cleaned_data.get('recipients').split(',')
            (st, _) = \
                MessageAttribute.objects.get_or_create(name=status)
            (det, _) = \
                MessageDetail.objects.get_or_create(message=request.session['mesg'
                ], attribute=st, value=send_message_form.cleaned_data.get('text'
                ), description='replied')
            for r in recs:
                try:
                    connection = Connection.objects.get(identity=r)
                except Connection.DoesNotExist:
                    number, backend = assign_backend(r)
                    connection = Connection.objects.create(identity=r,
                                                           backend=backend)

                #                rate,_=MessageAttribute.objects.get_or_create(name="forwarded")
                #                det,_=MessageDetail.objects.get_or_create(message=message,attribute=rate,value="1",description="forwarded")

                message = Message.objects.create(
                    direction='O',
                    text=send_message_form.cleaned_data.get('text'),
                    status='Q',
                    connection=connection)

            return HttpResponse('Message Sent :)')
        else:
            return HttpResponse('smothing went wrong')

    return render_to_response(template,
                              {'send_message_form': send_message_form},
                              context_instance=RequestContext(request))
Ejemplo n.º 3
0
def send_message(request, template='ureport/partials/forward.html'):
    if not request.method == 'POST':
        send_message_form = SendMessageForm()

        if request.GET.get('forward', None):
            # import pdb; pdb.set_trace()
            msg = request.GET.get('msg')

            template = 'ureport/partials/forward.html'
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                ForwardMessageForm(data={'text': message.text})
            request.session['mesg'] = message
        if request.GET.get('reply', None):
            msg = request.GET.get('msg')
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                SendMessageForm(data={'text': message.text,
                                      'recipients': message.connection.identity})
            template = 'ureport/partials/reply.html'
            request.session['mesg'] = message
    else:
        send_message_form = SendMessageForm(request.POST)
        if request.GET.get('forward'):
            status = 'forwarded'
        else:
            status = 'replied'
        if send_message_form.is_valid():
            recs = send_message_form.cleaned_data.get('recipients'
            ).split(',')
            (st, _) = \
                MessageAttribute.objects.get_or_create(name=status)
            (det, _) = \
                MessageDetail.objects.get_or_create(message=request.session['mesg'
                ], attribute=st, value=send_message_form.cleaned_data.get('text'
                ), description='replied')
            for r in recs:
                try:
                    connection = Connection.objects.get(identity=r)
                except Connection.DoesNotExist:
                    number, backend = assign_backend(r)
                    connection = Connection.objects.create(identity=r, backend=backend)


                #                rate,_=MessageAttribute.objects.get_or_create(name="forwarded")
                #                det,_=MessageDetail.objects.get_or_create(message=message,attribute=rate,value="1",description="forwarded")

                message = Message.objects.create(direction='O',
                                                 text=send_message_form.cleaned_data.get('text'
                                                 ), status='Q', connection=connection)

            return HttpResponse('Message Sent :)')
        else:
            return HttpResponse('smothing went wrong')

    return render_to_response(template,
                              {'send_message_form': send_message_form},
                              context_instance=RequestContext(request))
Ejemplo n.º 4
0
    def handle(self, **options):
        path = options["path"]
        group = Group.objects.get(name="CODES Bukango")
        district = Location.objects.get(name='Bukomansimbi',
                                        type__name='district')
        print "Groups ===============>", group.name
        csv_rows = csv.reader(open(path, 'rU'), delimiter=",")
        rnum = 0
        for row in csv_rows:
            print row
            rnum += 1
            try:
                name, number, gender, age, village, dist, g = tuple(row)
                num = number.replace('-', '').strip()
                name = name.strip().replace("\"",
                                            '').replace('\'',
                                                        "").replace("  ", " ")
            except:
                print 'Row Error:', row
                continue

            num = self.clean_number(num)
            if num:
                number, backend = assign_backend(num)

                connection, created = Connection.objects.get_or_create(
                    identity=number, backend=backend)

                if not created:
                    contact = connection.contact
                    contact.name = name
                    if not contact:
                        contact = Contact.objects.create(name=name)
                else:
                    contact = Contact.objects.create(name=name)

                print "Contact ===>", contact.name
                contact.save()
                if group:
                    contact.groups.add(group)
                contact.village_name = village
                contact.reporting_location = district
                print "Village: District===>", village, district
                if gender.lower().startswith('m'):
                    gender = 'm'
                else:
                    gender = 'f'
                contact.gender = gender
                print "Gender===>", gender
                contact.birthdate = self.birth_date(int(age))
                print "Birth date====>", contact.birthdate

                connection.contact = contact
                connection.save()
                contact.save()
            else:
                print 'Number Error:', row
        print rnum, "================>", group.name
Ejemplo n.º 5
0
 def clean(self):
     cleaned_data = self.cleaned_data
     cleaned_data['district'] = \
         Location.objects.get(pk=int(cleaned_data.get('district', '1'
         )))
     try:
         phone = cleaned_data.get('mobile')
         p, b = assign_backend(phone)
     except Exception as e:
         raise ValidationError(str(e))
     return cleaned_data
Ejemplo n.º 6
0
 def clean(self):
     cleaned_data = self.cleaned_data
     cleaned_data['district'] = \
         Location.objects.get(pk=int(cleaned_data.get('district', '1'
         )))
     try:
         phone = cleaned_data.get('mobile')
         p, b = assign_backend(phone)
     except Exception as e:
         raise ValidationError(str(e))
     return cleaned_data
Ejemplo n.º 7
0
    def handle(self, **options):
        path = options["path"]
        group = Group.objects.get(name="CODES Bukango")
        district = Location.objects.get(name='Bukomansimbi', type__name='district')
        print "Groups ===============>", group.name
        csv_rows = csv.reader(open(path, 'rU'), delimiter=",")
        rnum = 0
        for row in csv_rows:
            print row
            rnum += 1
            try:
                name, number, gender, age, village, dist, g = tuple(row)
                num = number.replace('-', '').strip()
                name = name.strip().replace("\"", '').replace('\'', "").replace("  ", " ")
            except:
                print 'Row Error:', row
                continue

            num = self.clean_number(num)
            if num:
                number, backend = assign_backend(num)

                connection, created = Connection.objects.get_or_create(identity=number, backend=backend)

                if not created:
                    contact = connection.contact
                    contact.name = name
                    if not contact:
                        contact = Contact.objects.create(name=name)
                else:
                    contact = Contact.objects.create(name=name)

                print "Contact ===>", contact.name
                contact.save()
                if group:
                    contact.groups.add(group)
                contact.village_name = village
                contact.reporting_location = district
                print "Village: District===>", village, district
                if gender.lower().startswith('m'):
                    gender = 'm'
                else:
                    gender = 'f'
                contact.gender = gender
                print "Gender===>", gender
                contact.birthdate = self.birth_date(int(age))
                print "Birth date====>", contact.birthdate

                connection.contact = contact
                connection.save()
                contact.save()
            else:
                print 'Number Error:', row
        print rnum, "================>", group.name
Ejemplo n.º 8
0
def create_reporter(mobile, name, parish):
    role, _ = Group.objects.get_or_create(name='Ntds')
    msisdn, backend = assign_backend(mobile)
    connection, created = Connection.objects.get_or_create(identity=mobile, backend=backend)
    provider = HealthProvider.objects.create(name=name, location=parish)
    provider.groups.add(role)
    connection.contact = provider
    connection.save()
    rep = Reporter(healthprovider_ptr=provider)
    rep.__dict__.update(provider.__dict__)
    rep.save()
    # reporter=Reporter.objects.create(healthprovider_ptr=provider)
    return rep
Ejemplo n.º 9
0
    def handle(self, **options):
        path = options["path"]
        gr = options["group"]

        group = find_closest_match(gr, Group.objects)
        print group
        csv_rows = csv.reader(open(path), delimiter=",")
        rnum = 0
        for row in csv_rows:

            name, mobile, sex, birthdate, district, village, sub_county, gr = tuple(
                row)
            if name == "name":
                continue

            number, backend = assign_backend(mobile.replace('-', '').strip())
            connection, created = Connection.objects.get_or_create(
                identity=number, backend=backend)
            if not created:
                contact = connection.contact
                if not contact:
                    contact = Contact.objects.create(name=name)
            else:
                contact = Contact.objects.create(name=name)

            if group:
                contact.groups.add(group)
            if district:
                try:
                    contact.reporting_location = find_closest_match(
                        district,
                        Location.objects.filter(type__name='district'))
                except:
                    contact.reporting_location = Location.objects.filter(
                        type__name="district", name=district)[0]

            if village:
                contact.village = find_closest_match(
                    village, Location.objects.filter(type__name='village'))
            if birthdate:

                contact.birthdate = datetime.datetime.strptime(
                    birthdate.strip(), '%d/%m/%Y')
            if sex == "Male":
                contact.gender = "M"
            elif sex == "Female":
                contact.gender = "F"
            contact.save()

            connection.contact = contact
            connection.save()
def handle_excel_file(file):
    contacts = []
    invalid = []
    duplicates = []
    info = ''
    try:
        group = Group.objects.get(name=settings.BEDNETS_GROUP_NAME)
        parsed_values = XlsParser().parse(file.read())
        for values in parsed_values:
            raw_number = values.get('telephone number')
            if raw_number is None:
                invalid.append(values)
                continue
            raw_number = _clean_telephone_number(raw_number)
            if len(raw_number) < 9:
                invalid.append(raw_number)
                continue
            phone_number, backend = assign_backend(raw_number)
            if phone_number not in contacts and backend is not None:
                connection, created = Connection.objects.get_or_create(identity=phone_number, backend=backend)
                if not created and connection.contact is not None:
                    duplicates.append(phone_number)
                contact = connection.contact or Contact()
                contact.name = _parse_name(values.get('name'))
                _set_reporting_location(values.get('district'), contact)
                contact.save()
                contact.groups.add(group)
                _assign_user_to_contact(contact, group, values)
                connection.contact = contact
                connection.save()
                contacts.append(phone_number)
            elif backend is None:
                invalid.append(phone_number)
    except XlsParsingException:
        return "Invalid file"
    if len(contacts) > 0:
        info = 'Contacts with numbers... '\
               + ' ,'.join(contacts)\
        + ' have been uploaded ! '

    if len(duplicates) > 0:
        info = info\
               + 'The following numbers already exist in the system and have been updated: '\
        + ' ,'.join(duplicates)
    if len(invalid) > 0:
        info = info\
               + 'The following numbers may be invalid and thus have not been added to the system: '\
        + ' ,'.join(invalid)
    return info
Ejemplo n.º 11
0
 def setUp(self):
     user = User.objects.create_user("test", "*****@*****.**", password="******")
     number, backend = assign_backend("256798288221")
     connection = Connection.objects.create(identity=number, backend=backend)
     contact = Contact.objects.create(name="Test Contact")
     connection.contact = contact
     connection.save()
     poll = Poll.objects.create(
         name="Test Poll for poll attribute", question="Test question for test poll", user=user
     )
     poll.contacts.add(contact)
     poll.save()
     self.attr = PollAttribute.objects.create(key="viewable", key_type="bool", default=True)
     self.value = PollAttributeValue.objects.create(poll=poll, value=False)
     self.attr.values.add(self.value)
Ejemplo n.º 12
0
    def handle(self, **options):
        path = options["path"]
        gr = options["group"]

        group = find_closest_match(gr, Group.objects)
        print group
        csv_rows = csv.reader(open(path), delimiter=",")
        rnum = 0
        for row in csv_rows:

            name,mobile,sex,birthdate,district,village,sub_county,gr = tuple(row)
            if name=="name":
                continue

            number, backend = assign_backend(mobile.replace('-', '').strip())
            connection, created = Connection.objects.get_or_create(identity=number, backend=backend)
            if not created:
                contact = connection.contact
                if not contact:
                    contact = Contact.objects.create(name=name)
            else:
                contact = Contact.objects.create(name=name)

            if group:
                contact.groups.add(group)
            if district:
                try:
                    contact.reporting_location = find_closest_match(district, Location.objects.filter(type__name='district'))
                except:
                    contact.reporting_location = Location.objects.filter(type__name="district",name=district)[0]

            if village:
                contact.village = find_closest_match(village, Location.objects.filter(type__name='village'))
            if birthdate:

                contact.birthdate = datetime.datetime.strptime(birthdate.strip(), '%d/%m/%Y')
            if sex == "Male":
                contact.gender = "M"
            elif sex == "Female":
                contact.gender ="F"
            contact.save()

            connection.contact = contact
            connection.save()
Ejemplo n.º 13
0
 def setUp(self):
     user = User.objects.create_user('test',
                                     '*****@*****.**',
                                     password='******')
     number, backend = assign_backend('256798288221')
     connection = Connection.objects.create(identity=number,
                                            backend=backend)
     contact = Contact.objects.create(name='Test Contact')
     connection.contact = contact
     connection.save()
     poll = Poll.objects.create(name='Test Poll for poll attribute',
                                question='Test question for test poll',
                                user=user)
     poll.contacts.add(contact)
     poll.save()
     self.attr = PollAttribute.objects.create(key='viewable',
                                              key_type='bool',
                                              default=True)
     self.value = PollAttributeValue.objects.create(poll=poll, value=False)
     self.attr.values.add(self.value)
Ejemplo n.º 14
0
    def process(self):
        excel = reader.excel.load_workbook(self.excel_file.path)
        rows = []
        for sheet in excel.worksheets:
            for row in sheet.rows:
                r = []
                for cell in row:
                    r.append(cell.value)
                rows.append(tuple(r))
        with_error = []
        for row in rows:
            try:
                phone, group, name, language, gender, age, occupation, district, village_name, subcounty, health_facility = tuple(
                    row[:11])
                district = self._get_district(str(district))
                phone = self._clean_phone(str(phone))
                birth_date = self._birth_date(str(age))
                gender = self._get_gender(str(gender))
                group = self._get_group(group)
                language = language if language else 'en'

                connection, created = Connection.objects.get_or_create(
                    identity=phone, backend=assign_backend(phone)[1])
                if connection.contact is not None:
                    contact = connection.contact
                else:
                    contact = Contact.objects.create(name=" ")
                connection.contact = contact
                connection.save()

                contact.language = language
                contact.gender = gender
                contact.birthdate = birth_date
                contact.reporting_location = district
                contact.occupation = occupation
                contact.village_name = village_name
                contact.groups.add(group)
                contact.save()
            except UploadContactException, e:
                with_error.append((row, e))
                continue
Ejemplo n.º 15
0
    def handle(self, **options):
        path = options["path"]
        group = Group.objects.get(name="UNITED NATIONS ALL STAFF")
        csv_rows = csv.reader(open(path, 'rU'), delimiter=",")
        rnum = 0
        for row in csv_rows:

            try:
                org, title, name, designation, mobile = tuple(row)
                mobiles = mobile.replace('-', '').strip().split('/')
                name = name.strip().replace("\"", '').replace('\'', "").replace("  ", " ")
            except:
                print 'Row Error:', row
                continue

            for num in mobiles:
                num = self.clean_number(num)
                if num:
                    number, backend = assign_backend(num)

                    connection, created = Connection.objects.get_or_create(identity=number, backend=backend)

                    if not created:
                        contact = connection.contact
                        if not contact:
                            contact = Contact.objects.create(name=name)
                    else:
                        contact = Contact.objects.create(name=name)

                    if group:
                        contact.groups.add(group)

                    contact.occupation = "%s/%s" % (org.strip().replace("\"", '').replace('\'', "").replace("  ", " "),
                                                    designation.strip().replace("\"", '').replace('\'', "").replace(
                                                        "  ", " "))

                    connection.contact = contact
                    connection.save()
                else:
                    print 'Number Error:', row
Ejemplo n.º 16
0
 def save(self):
     cleaned_data = self.cleaned_data
     district = cleaned_data.get('reporter_district')
     location = cleaned_data.get('reporting_location')
     connection = cleaned_data.get('connection')
     if connection:
         (identity, backend) = assign_backend(connection)
         connection, _x = Connection.objects.get_or_create(identity=identity, backend=backend)
         self.reporter.connection_set.add(connection)
     if district and location and \
         not district.get_descendants(include_self=True).filter(pk=location.pk).count():
         location = None
     self.reporter.location = self.reporter.reporting_location = location or district
     self.reporter.name = cleaned_data.get('name')
     self.reporter.groups.clear()
     for g in cleaned_data.get('roles'):
         self.reporter.groups.add(g)
     self.reporter.facility = cleaned_data.get('facility')
     if not location:
         self.reporter.village_name = cleaned_data.get('village_name')
     self.reporter.save()
     return
Ejemplo n.º 17
0
 def clean_msisdn(self):
     cleaned_data = self.cleaned_data
     identity, backend = assign_backend(cleaned_data['msisdn'])
     c, created = Connection.objects.get_or_create(identity=identity, backend=backend)
     return c
Ejemplo n.º 18
0
    def load_reporters(self, data):
        IGNORED_ENTRIES = []
        for d in data:
            if not d[self.order['name']] or not d[self.order['phone']]:
                print "no name"
                IGNORED_ENTRIES.append(d)
                continue
            print d
            _name = d[self.order['name']].strip()
            _name = ' '.join([pname.capitalize() for pname in _name.split(' ')])
            _phone = '%s' % (str(int(d[self.order['phone']])) if '/' not in '%s' % \
                    d[self.order['phone']]  else d[self.order['phone']])
            #print "=====================>", _phone
            _district = d[self.order['district']].strip().capitalize()
            _role = d[self.order['role']].strip()
            _fac = d[self.order['facility']].strip()
            _fac_type = d[self.order['facility_type']].replace(' ','').lower()
            _village = d[self.order['village']].strip().capitalize()
            _village_type = d[self.order['village_type']].strip().lower()
#            _pvht = d[self.order['pvht']]
            #_phone = _phone.strip().replace('.','').split('e')[0].split('.')[0].replace('-', '')
            nums = _phone.split('/')
            _phone2 = ''
#            _village_name = d[self.order['village_name']].capitalize()
            already_exists = False
            #print nums
            if len(nums) > 1:
                _phone = nums[0]
                _phone2 = nums[1]

            #print _name, _phone, _role
            district = find_closest_match(_district, Location.objects.filter(\
                    type='district'), match_exact=True)
            #roles = list(Group.objects.filter(name__in=_role.split(',')))
            if not district:
                print "WARNING: District Not Found (%s)" % _district
                IGNORED_ENTRIES.append(d)
                continue
                print "============================================================================="
            facility = ''

            if not facility:
                xx = HealthFacility.objects.filter(name__iexact="%s" % _fac, type__slug=_fac_type).\
                        filter(catchment_areas__in=district.get_descendants(include_self=True))
                facility = xx[0] if xx else ''
                #print 'facility count  on 1st search',xx.count()
                if not facility:
                    facility = HealthFacility.objects.filter(name__iexact=_fac).filter(\
                            catchment_areas__in=district.get_descendants(include_self=True))
                    #print 'facility count on 2nd search',facility.count()
                    if facility.exists(): facility = facility[0]
                if not facility:
                    try:
                        facility = find_closest_match(_fac, HealthFacility.objects.filter(\
                                type__slug__in=[_fac_type]).filter(catchment_areas__in=\
                                district.get_descendants(include_self=True)), match_exact=True)
                    except HealthFacility.MultipleObjectsReturned:
                        xx = HealthFacility.objects.filter(name=_fac,type__slug=_fac_type).\
                                filter(catchment_areas__in=district.get_descendants(include_self=True))
                        facility = xx[0] if xx else ''
                if not facility:
                    print "WARNING: Facility Not Found (%s %s)" % (_fac, _fac_type)
                    IGNORED_ENTRIES.append(d)
                    print "============================================================================="
                    continue
            print "INFO: Facility Found: (%s)" % facility.name
            village = None
            if _village:
                if district:
                    #village = find_closest_match(_village, Location.objects.filter(type__in=[_village_type]))
                    if facility.catchment_areas.all():
                        village = facility.catchment_areas.all()[0]
                    else:
                        village = find_closest_match(_village, district.get_descendants(include_self=True).\
                                filter(type__in=[_village_type]), match_exact=True)
                    #print 'at village'
            else:
                    if facility.catchment_areas.all():
                        village = facility.catchment_areas.all()[0]

#            if _name:
#                _name = ' '.join([n.capitalize() for n in _name.lower().split()])
            if len(_phone) > 12:
                print "WARINIG: Invalid Number (%s) -skipped" % _phone
                IGNORED_ENTRIES.append(d)
                print "============================================================================="
                continue
            try:
                msisdn, backend = assign_backend(_phone)
            except:
                print "WARINIG: Invalid Number (%s) -skipped" % _phone
                IGNORED_ENTRIES.append(d)
                print "============================================================================="
                continue
            #print msisdn, village

            if _phone2:
                try:
                    msisdn2, backend2 = assign_backend(_phone2)
                except:
                    print "WARNING: PhoneNumber Ignored (%s)" % _phone2

            connection2 = None
            try:
                connection = Connection.objects.get(identity=msisdn, backend=backend)
            except Connection.DoesNotExist:
                connection = Connection.objects.create(identity=msisdn, backend=backend)
                transaction.commit()
            except Connection.MultipleObjectsReturned:
                connection = Connection.objects.filter(identity=msisdn, backend=backend)[0]
            # a second phone number
            if _phone2:
                try:
                    connection2 = Connection.objects.get(identity=msisdn2, backend=backend2)
                except Connection.DoesNotExist:
                    connection2 = Connection.objects.create(identity=msisdn2, backend=backend2)
                except Connection.MultipleObjectsReturned:
                    connection2 = Connection.objects.filter(identity=msisdn2, backend=backend2)[0]

            try:
                contact = connection.contact or HealthProvider.objects.get(name=_name, \
                                      reporting_location=(village or  district), \
                                      village=village, \
                                      village_name=_village)
                already_exists = True
            except Contact.DoesNotExist, Contact.MultipleObjectsReturned:
                contact = HealthProvider.objects.create()
                #transaction.commit()

            connection.contact = contact
            connection.save()
            if _name:
                contact.name = _name

            if facility:
                contact.facility = facility
            if village:
                contact.reporting_location = village
                contact.village = village
                contact.village_name = None
            else:
                if district:
                    contact.reporting_location = district
                else:
                    contact.reporting_location = Location.tree.root_nodes()[0]
                contact.village_name = _village
                contact.village = None
            current_groups = list(contact.groups.all().values_list('name', flat=True))
            new_roles = list(set(_role.split(',') + current_groups))
            roles = list(Group.objects.filter(name__in=new_roles))

            contact.groups.clear()
            for role in roles:
                contact.groups.add(role)

            if connection2:
                contact.connection_set.add(connection2)
            contact.save()
            print "INFO: HealthProvider Created[contact_id:%s, identity:(%s,%s)]" % (contact.id, \
                    '%s' % connection.identity if connection else '', connection2.identity if connection2 else '')
            print "============================================================================="
Ejemplo n.º 19
0
    def handle(self, **options):
        import pdb;pdb.set_trace()

        file = options['file']
        wb = load_workbook(filename=file)
        ws=wb.get_sheet_by_name("Community and Schools")
        for row in ws.rows[1:]:
            try:

                role, _ = Group.objects.get_or_create(name='Ntds')
                mobile_is_valid,cleaned_mobile=validate_number("0"+str(row[10].value))
                try:
                    msisdn, backend = assign_backend(cleaned_mobile)
                except ValidationError:
                    msisdn, backend = assign_backend(str(row[10].value).split("/")[0])

                backend,_=Backend.objects.get_or_create(name="yo")


                connection, conn_created = Connection.objects.get_or_create(identity=cleaned_mobile, backend=backend)
                try:
                    district=Location.objects.filter(type="district",name__icontains= row[2].value.strip())[0]
                except IndexError:
                    district=None
                try:
                    subcounty=Location.objects.filter(type="sub_county",name__icontains= row[5].value.strip())[0]
                except IndexError:
                    subcounty=None
                try:
                    pr=row[8].value.strip()
                    if pr=="Aria":
                        pr="Ariya"
                    parish=district.get_descendants().filter(type="parish",name__icontains=row[8].value.strip())[0]
                except IndexError:
                    parish=None
                    print "index error  %s"%row[8].value

                if conn_created:
                    provider = HealthProvider.objects.create(name=row[9].value.strip(), location=parish)
                    provider.groups.add(role)
                    connection.contact = provider
                    connection.save()
             


                
                    rep = Reporter(healthprovider_ptr=provider)
                    rep.__dict__.update(provider.__dict__)
                    rep.district=district
                    rep.subcounty=subcounty
                    rep.parish=parish


                    rep.community=row[11].value.strip()
                    rep.id_number=str(row[0].value)
                    rep.county=row[3].value.strip()
                    rep.subcounty_supervisor=row[6].value.strip()
                    _,s_mobile=validate_number(str(row[7].value))
                    rep.subcounty_supervisor_mobile=s_mobile
                    rep.region=row[1].value.strip()
                    rep.health_subcounty=row[4].value.strip()
                    rep.subcounty_name = row[5].value.strip()
                    rep.parish_name = row[8].value.strip()
                    rep.save()
            except ValidationError:
                pass
Ejemplo n.º 20
0
def send_message(request, template='ureport/partials/forward.html'):
    if not request.method == 'POST':
        send_message_form = SendMessageForm()

        if request.GET.get('forward', None):
            # import pdb; pdb.set_trace()
            msg = request.GET.get('msg')

            template = 'ureport/partials/forward.html'
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                ForwardMessageForm(data={'text': message.text})
            request.session['mesg'] = message
        if request.GET.get('reply', None):
            msg = request.GET.get('msg')
            message = Message.objects.get(pk=int(msg))
            send_message_form = \
                SendMessageForm(data={'text': message.text,
                                      'recipients': message.connection.identity})
            template = 'ureport/partials/reply.html'
            request.session['mesg'] = message
    else:
        send_message_form = SendMessageForm(request.POST)
        if request.GET.get('forward'):
            status = 'forwarded'
        else:
            status = 'replied'
        if send_message_form.is_valid():
            recs = send_message_form.cleaned_data.get('recipients'
            ).split(',')
            (st, _) = \
                MessageAttribute.objects.get_or_create(name=status)
            (det, _) = \
                MessageDetail.objects.get_or_create(message=request.session['mesg'
                ], attribute=st, value=send_message_form.cleaned_data.get('text'
                ), description='replied')
            for r in recs:
                email_check = re.compile(r"[^@]+@[^@]+\.[^@]+")
                if email_check.match(r):
                    send_mail('Forwarded From Ureport', send_message_form.cleaned_data.get('text'),
                              "Ureport Alerts<*****@*****.**>", [r], fail_silently=True)
                    continue
                try:
                    connection = Connection.objects.get(identity=r)
                except Connection.DoesNotExist:
                    number, backend = assign_backend(r)
                    connection = Connection.objects.create(identity=r, backend=backend)
                message = Message.objects.create(direction='O',
                                                 text=send_message_form.cleaned_data.get('text'
                                                 ), status='Q', connection=connection, priority=8)
                if request.GET.get('flag'):
                    tracker = FlagTracker.objects.create(
                        flag=Flag.objects.get(name__iexact=request.GET.get('flag').replace("-", " ")), reply=message,
                        message=Message.objects.get(pk=request.GET.get('msg')), user=request.user)
                    print tracker

            return HttpResponse('Message Sent :)')
        else:
            return HttpResponse('something went wrong')
    context = {'send_message_form': send_message_form}
    if request.GET.get('flag'):
        context['flag'] = request.GET.get('flag')
        context['msg'] = request.GET.get('msg')
    return render_to_response(template,
                              context,
                              context_instance=RequestContext(request))
Ejemplo n.º 21
0
def signup(request):
    status_message = None
    if request.method == 'POST':
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            mobile = signup_form.cleaned_data['mobile']
            (number, backend) = assign_backend(mobile)

            # create our connection

            (connection, conn_created) = \
                Connection.objects.get_or_create(backend=backend,
                                                 identity=number)
            connection.contact = \
                Contact.objects.create(name=signup_form.cleaned_data['firstname'
                                            ] + ' ' + signup_form.cleaned_data['lastname'])
            contact = connection.contact
            contact.reporting_location = \
                signup_form.cleaned_data['district']

            contact.gender = \
                signup_form.cleaned_data['gender']
            if signup_form.cleaned_data['village']:
                connection.contact.village = \
                    find_closest_match(signup_form.cleaned_data['village'],
                                       Location.objects.exclude(type="district"))
            if signup_form.cleaned_data['age']:
                contact.birthdate = datetime.datetime.now() \
                                    - datetime.timedelta(days=365
                                                              * int(signup_form.cleaned_data['age']))

            if signup_form.cleaned_data['group']:
                group_to_match = signup_form.cleaned_data['group']

                if Group.objects.filter(name='Other uReporters').count():
                    default_group = \
                        Group.objects.get(name='Other uReporters')
                    contact.groups.add(default_group)
                if group_to_match:
                    for g in re.findall(r'\w+', group_to_match):
                        if g:
                            group = find_closest_match(str(g),
                                                       Group.objects)
                            if group:
                                connection.contact.groups.add(group)
                                break
            connection.save()
            contact.save()
            status_message = 'You have successfully signed up :)'
            if conn_created:
                Message.objects.create(connection=connection, direction='O'
                    , status='Q',
                                       text=_(getattr(settings, 'OPT_IN_WEB_CONFIRMATION', ''))
                )
        else:
            return render_to_response('ureport/signup.html',
                                      dict(signup_form=signup_form),
                                      context_instance=RequestContext(request))
    signup_form = SignupForm()
    return render_to_response('ureport/signup.html',
                              dict(signup_form=signup_form,
                                   status_message=status_message),
                              context_instance=RequestContext(request))
Ejemplo n.º 22
0
 def clean_msisdn(self):
     cleaned_data = self.cleaned_data
     identity, backend = assign_backend(cleaned_data['msisdn'])
     c, created = Connection.objects.get_or_create(identity=identity,
                                                   backend=backend)
     return c
Ejemplo n.º 23
0
def signup(request):
    status_message = None
    if request.method == 'POST':
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            mobile = signup_form.cleaned_data['mobile']
            (number, backend) = assign_backend(mobile)

            # create our connection

            (connection, conn_created) =\
            Connection.objects.get_or_create(backend=backend,
                identity=number)
            connection.contact =\
            Contact.objects.create(name=signup_form.cleaned_data['firstname'
                                        ] + ' ' + signup_form.cleaned_data['lastname'])
            connection.contact.reporting_location =\
            signup_form.cleaned_data['district']
            connection.contact.gender =\
            signup_form.cleaned_data['gender']
            if signup_form.cleaned_data['village']:
                connection.contact.village =\
                find_closest_match(signup_form.cleaned_data['village'],
                    Location.objects)
            if signup_form.cleaned_data['age']:
                connection.contact.birthdate = datetime.datetime.now()\
                - datetime.timedelta(days=365
                * int(signup_form.cleaned_data['age']))

            if signup_form.cleaned_data['group']:
                group_to_match = signup_form.cleaned_data['group']

                if Group.objects.filter(name='Other uReporters').count():
                    default_group =\
                    Group.objects.get(name='Other uReporters')
                    connection.contact.groups.add(default_group)
                if group_to_match:
                    for g in re.findall(r'\w+', group_to_match):
                        if g:
                            group = find_closest_match(str(g),
                                Group.objects)
                            if group:
                                connection.contact.groups.add(group)
                                break

            connection.save()
            status_message = 'You have successfully signed up :)'
            if conn_created:
                Message.objects.create(date=datetime.datetime.now(),
                    connection=connection, direction='O'
                    , status='Q',
                    text='CONGRATULATIONS!!! You are now a registered member of Ureport! With Ureport, you can make a real difference!  Speak Up and Be Heard! from UNICEF'
                )
        else:
            return render_to_response('ureport/signup.html',
                dict(signup_form=signup_form),
                context_instance=RequestContext(request))
    signup_form = SignupForm()
    return render_to_response('ureport/signup.html',
        dict(signup_form=signup_form,
            status_message=status_message),
        context_instance=RequestContext(request))
Ejemplo n.º 24
0
def signup(request):
    status_message = None
    if request.method == 'POST':
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            mobile = signup_form.cleaned_data['mobile']
            (number, backend) = assign_backend(mobile)

            # create our connection

            (connection, conn_created) = \
                Connection.objects.get_or_create(backend=backend,
                                                 identity=number)
            connection.contact = \
                Contact.objects.create(name=signup_form.cleaned_data['firstname'
                                            ] + ' ' + signup_form.cleaned_data['lastname'])
            contact = connection.contact
            contact.reporting_location = \
                signup_form.cleaned_data['district']

            contact.gender = \
                signup_form.cleaned_data['gender']
            if signup_form.cleaned_data['village']:
                connection.contact.village = \
                    find_closest_match(signup_form.cleaned_data['village'],
                                       Location.objects.filter(type="village"))
            if signup_form.cleaned_data['age']:
                contact.birthdate = datetime.datetime.now() \
                                    - datetime.timedelta(days=365
                                                              * int(signup_form.cleaned_data['age']))

            if signup_form.cleaned_data['group']:
                group_to_match = signup_form.cleaned_data['group']

                if Group.objects.filter(name='Other uReporters').count():
                    default_group = \
                        Group.objects.get(name='Other uReporters')
                    contact.groups.add(default_group)
                if group_to_match:
                    for g in re.findall(r'\w+', group_to_match):
                        if g:
                            group = find_closest_match(str(g), Group.objects)
                            if group:
                                connection.contact.groups.add(group)
                                break
            contact.save()
            connection.save()
            status_message = 'You have successfully signed up :)'
            if conn_created:
                Message.objects.create(
                    connection=connection,
                    direction='O',
                    status='Q',
                    text=
                    'CONGRATULATIONS!!! You are now a registered member of Ureport! With Ureport, you can make a real difference!  Speak Up and Be Heard! from UNICEF'
                )
        else:
            return render_to_response('ureport/signup.html',
                                      dict(signup_form=signup_form),
                                      context_instance=RequestContext(request))
    signup_form = SignupForm()
    return render_to_response('ureport/signup.html',
                              dict(signup_form=signup_form,
                                   status_message=status_message),
                              context_instance=RequestContext(request))
Ejemplo n.º 25
0
    def process(self):
        excel = reader.excel.load_workbook(self.excel_file.path)
        rows = []
        for sheet in excel.worksheets:
            for row in sheet.rows:
                r = []
                for cell in row:
                    r.append(cell.value)
                rows.append(tuple(r))
        with_error = []
        for row in rows:
            try:
                phone, group, name, language, gender, age, occupation, district, village_name, subcounty, health_facility = tuple(
                    row[:11]
                )
                district = self._get_district(str(district))
                phone = self._clean_phone(str(phone))
                birth_date = self._birth_date(str(age))
                gender = self._get_gender(str(gender))
                group = self._get_group(group)
                language = language if language else "en"

                connection, created = Connection.objects.get_or_create(identity=phone, backend=assign_backend(phone)[1])
                if connection.contact is not None:
                    contact = connection.contact
                else:
                    contact = Contact.objects.create(name=" ")
                connection.contact = contact
                connection.save()

                contact.language = language
                contact.gender = gender
                contact.birthdate = birth_date
                contact.reporting_location = district
                contact.occupation = occupation
                contact.village_name = village_name
                contact.groups.add(group)
                contact.save()
            except UploadContactException, e:
                with_error.append((row, e))
                continue
Ejemplo n.º 26
0
def handle_excel_file(file, group, fields):
    if file:
        excel = file.read()
        workbook = open_workbook(file_contents=excel)
        worksheet = workbook.sheet_by_index(0)
        cols = parse_header_row(worksheet, fields)
        contacts = []
        duplicates = []
        invalid = []
        info = ''

        if not group:
            default_group =\
            Group.objects.filter(name__icontains='ureporters')[0]
            group = default_group

        if worksheet.nrows > 1:
            validated_numbers = []
            for row in range(1, worksheet.nrows):
                numbers = parse_telephone(row, worksheet, cols)
                for raw_num in numbers.split('/'):
                    if raw_num[-2:] == '.0':
                        raw_num = raw_num[:-2]
                    if raw_num[:1] == '+':
                        raw_num = raw_num[1:]
                    if len(raw_num) >= 9:
                        validated_numbers.append(raw_num)
            duplicates =\
            Connection.objects.filter(identity__in=validated_numbers).values_list('identity'
                , flat=True)

            for row in range(1, worksheet.nrows):
                numbers = parse_telephone(row, worksheet, cols)
                if len(numbers) > 0:
                    contact = {}
                    contact['name'] = parse_name(row, worksheet, cols)
                    district = (parse_district(row, worksheet, cols)
                                if 'district' in fields else None)
                    village = (parse_village(row, worksheet, cols)
                               if 'village' in fields else None)
                    birthdate = (parse_birthdate(row, worksheet, cols)
                                 if 'age' in fields else None)
                    gender = (parse_gender(row, worksheet, cols)
                              if 'gender' in fields else None)
                    if district:
                        contact['reporting_location'] =\
                        find_closest_match(district,
                            Location.objects.filter(type__slug='district'
                            ))
                    if village:
                        contact['village'] =\
                        find_closest_match(village,
                            Location.objects)
                    if birthdate:
                        contact['birthdate'] = birthdate
                    if gender:
                        contact['gender'] = gender
                    if group:
                        contact['groups'] = group

                    for raw_num in numbers.split('/'):
                        if raw_num[-2:] == '.0':
                            raw_num = raw_num[:-2]
                        if raw_num[:1] == '+':
                            raw_num = raw_num[1:]
                        if len(raw_num) >= 9:
                            if raw_num not in duplicates:
                                (number, backend) =\
                                assign_backend(raw_num)
                                if number not in contacts and backend\
                                is not None:
                                    Connection.bulk.bulk_insert(
                                        send_pre_save=False,
                                        identity=number,
                                        backend=backend,
                                        contact=contact)
                                    contacts.append(number)
                                elif backend is None:
                                    invalid.append(raw_num)
                        else:
                            invalid.append(raw_num)

            connections =\
            Connection.bulk.bulk_insert_commit(send_post_save=False,
                autoclobber=True)

            #Important to update UreportContact
            for connection in connections:
                connection.contact.save()

            if len(contacts) > 0:
                info = 'Contacts with numbers... '\
                       + ' ,'.join(contacts)\
                + ''' have been uploaded !

'''
            if len(duplicates) > 0:
                info = info\
                       + 'The following numbers already exist in the system and thus have not been uploaded: '\
                       + ' ,'.join(duplicates) + '''

'''
            if len(invalid) > 0:
                info = info\
                       + 'The following numbers may be invalid and thus have not been added to the system: '\
                       + ' ,'.join(invalid) + '''

'''
        else:
            info =\
            'You seem to have uploaded an empty excel file, please fill the excel Contacts Template with contacts and upload again...'
    else:
        info = 'Invalid file'
    return info
Ejemplo n.º 27
0
def handle_excel_file(file, group, fields):
    if file:
        excel = file.read()
        workbook = open_workbook(file_contents=excel)
        worksheet = workbook.sheet_by_index(0)
        cols = parse_header_row(worksheet, fields)
        contacts = []
        duplicates = []
        invalid = []
        info = ''

        if not group:
            default_group =\
            Group.objects.filter(name__icontains='ureporters')[0]
            group = default_group

        if worksheet.nrows > 1:
            validated_numbers = []
            for row in range(1, worksheet.nrows):
                numbers = parse_telephone(row, worksheet, cols)
                for raw_num in numbers.split('/'):
                    if raw_num[-2:] == '.0':
                        raw_num = raw_num[:-2]
                    if raw_num[:1] == '+':
                        raw_num = raw_num[1:]
                    if len(raw_num) >= 9:
                        validated_numbers.append(raw_num)
            duplicates =\
            Connection.objects.filter(identity__in=validated_numbers).values_list('identity'
                , flat=True)

            for row in range(1, worksheet.nrows):
                numbers = parse_telephone(row, worksheet, cols)
                if len(numbers) > 0:
                    contact = {}
                    contact['name'] = parse_name(row, worksheet, cols)
                    district = (parse_district(row, worksheet,
                        cols) if 'district' in fields else None)
                    village = (parse_village(row, worksheet,
                        cols) if 'village' in fields else None)
                    birthdate = (parse_birthdate(row, worksheet,
                        cols) if 'age' in fields else None)
                    gender = (parse_gender(row, worksheet,
                        cols) if 'gender' in fields else None)
                    if district:
                        contact['reporting_location'] =\
                        find_closest_match(district,
                            Location.objects.filter(type__slug='district'
                            ))
                    if village:
                        contact['village'] =\
                        find_closest_match(village,
                            Location.objects)
                    if birthdate:
                        contact['birthdate'] = birthdate
                    if gender:
                        contact['gender'] = gender
                    if group:
                        contact['groups'] = group

                    for raw_num in numbers.split('/'):
                        if raw_num[-2:] == '.0':
                            raw_num = raw_num[:-2]
                        if raw_num[:1] == '+':
                            raw_num = raw_num[1:]
                        if len(raw_num) >= 9:
                            if raw_num not in duplicates:
                                (number, backend) =\
                                assign_backend(raw_num)
                                if number not in contacts and backend\
                                is not None:
                                    Connection.bulk.bulk_insert(send_pre_save=False,
                                        identity=number, backend=backend, contact=contact)
                                    contacts.append(number)
                                elif backend is None:
                                    invalid.append(raw_num)
                        else:
                            invalid.append(raw_num)

            connections =\
            Connection.bulk.bulk_insert_commit(send_post_save=False,
                autoclobber=True)

            #Important to update UreportContact
            for connection in connections:
                connection.contact.save()

            if len(contacts) > 0:
                info = 'Contacts with numbers... '\
                       + ' ,'.join(contacts)\
                + ''' have been uploaded !

'''
            if len(duplicates) > 0:
                info = info\
                       + 'The following numbers already exist in the system and thus have not been uploaded: '\
                       + ' ,'.join(duplicates) + '''

'''
            if len(invalid) > 0:
                info = info\
                       + 'The following numbers may be invalid and thus have not been added to the system: '\
                       + ' ,'.join(invalid) + '''

'''
        else:
            info =\
            'You seem to have uploaded an empty excel file, please fill the excel Contacts Template with contacts and upload again...'
    else:
        info = 'Invalid file'
    return info