Esempio 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),
    )
Esempio n. 2
0
def edtrac_autoreg(**kwargs):
    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'edtrac_autoreg':
        return
    session = ScriptSession.objects.filter(
        script=progress.script, connection=connection).order_by('-end_time')[0]
    script = progress.script
    role_poll = script.steps.get(poll__name='edtrac_role').poll
    gender_poll = script.steps.get(poll__name='edtrac_gender').poll
    class_poll = script.steps.get(poll__name='edtrac_class').poll
    district_poll = script.steps.get(poll__name='edtrac_district').poll
    subcounty_poll = script.steps.get(poll__name='edtrac_subcounty').poll
    school_poll = script.steps.get(poll__name='edtrac_school').poll
    name_poll = script.steps.get(poll__name='edtrac_name').poll

    name = find_best_response(session, name_poll)
    role = find_best_response(session, role_poll)
    gender = find_best_response(session, gender_poll)
    grade = find_best_response(session, class_poll)
    subcounty = find_best_response(session, subcounty_poll)
    district = find_best_response(session, district_poll)

    if name:
        name = ' '.join([n.capitalize() for n in name.lower().split()])[:100]
    if district:
        district = find_closest_match(district,
                                      Location.objects.filter(type='district'))

    if subcounty:
        if district:
            subcounty = find_closest_match(
                subcounty,
                district.get_descendants().filter(type='sub_county'))
        else:
            subcounty = find_closest_match(
                subcounty, Location.objects.filter(type='sub_county'))

    grp = match_group_response(session, role, role_poll)

    if subcounty:
        rep_location = subcounty
    elif district:
        rep_location = district
    else:
        rep_location = Location.tree.root_nodes()[0]
    try:
        contact = connection.contact or EmisReporter.objects.get(
            name=name,
            reporting_location=rep_location,
            groups=grp,
            connection=connection)
        if connection.contact:
            contact = EmisReporter.objects.get(pk=connection.contact.pk)
    except EmisReporter.DoesNotExist, EmisReporter.MultipleObectsReturned:
        contact = EmisReporter.objects.create()
Esempio n. 3
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()
Esempio n. 4
0
def do_autoreg(**kwargs):
    ''' 
    Kenya autoreg post registration particulars handling. 
    This method responds to a signal sent by the Script module on completion of the cvs_autoreg script
    '''
    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'autoreg':
        return
    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
    script = progress.script

    contact = connection.contact if connection.contact else Contact.objects.create()
    connection.contact = contact
    connection.save()

    name_poll = script.steps.get(poll__name='autoreg_name').poll
    org_poll = script.steps.get(poll__name='autoreg_org').poll
    field_poll = script.steps.get(poll__name='autoreg_field').poll
    division_poll = script.steps.get(poll__name='autoreg_division').poll
    building_poll = script.steps.get(poll__name='autoreg_building').poll

    org = find_best_response(session, org_poll)
    org = find_closest_match(org, Group.objects) if org else None
    contact.groups.add(org or Group.objects.get(name='Other Organizations'))

    field = find_best_response(session, field_poll)
    field = find_closest_match(field, Group.objects) if field else None
    contact.groups.add(field or Group.objects.get(name='Other Fields'))

    contact.name = find_best_response(session, name_poll) or 'Anonymous User'
    contact.name = ' '.join([n.capitalize() for n in contact.name.lower().split()])
    contact.name = contact.name[:100]

    division = find_best_response(session, division_poll)
    schools = School.objects
    facilities = HealthFacility.objects
    if division:
        division = find_closest_match(division, Location.objects.filter(type__name='division'))
        if division:
            contact.reporting_location = division
            schools = School.objects.filter(location__in=division.get_descendants(include_self=True))
            facilities = HealthFacility.objects.filter(catchment_areas__in=division.get_descendants(include_self=True))

    building = find_best_response(session, building_poll)
    if building:
        contact.school = find_closest_match(building, schools)
        contact.health_facility = find_closest_match(building, facilities)

    contact.save()
def parse_location_value(value):
    location_value = find_closest_match(value, Location.objects.exclude(type='district'))
    if not location_value:
        message = _(getattr(settings, 'UNRECOGNIZED_LOCATION_RESPONSE_TEXT', ''))
        raise ValidationError(message)
    else:
        return location_value
Esempio n. 6
0
def emis_autoreg_transition(**kwargs):

    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'emis_autoreg':
        return
    script = progress.script
    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
    role_poll = script.steps.get(order=1).poll
    role = find_best_response(session, role_poll)
    group = None
    if role:
        group = find_closest_match(role, Group.objects)
    skipsteps = {
        'emis_subcounty':['Teachers', 'Head Teachers', 'SMC', 'GEM'],
        'emis_one_school':['Teachers', 'Head Teachers', 'SMC'],
        'emis_many_school':['GEM'],
    }
    skipped = True
    while group and skipped:
        skipped = False
        for step_name, roles in skipsteps.items():
            if  progress.step.poll and \
                progress.step.poll.name == step_name and group.name not in roles:
                skipped = True
                progress.step = progress.script.steps.get(order=progress.step.order + 1)
                progress.save()
                break
Esempio n. 7
0
def emis_autoreg_transition(**kwargs):

    connection = kwargs["connection"]
    progress = kwargs["sender"]
    if not progress.script.slug == "emis_autoreg":
        return
    script = progress.script
    try:
        session = ScriptSession.objects.filter(script=progress.script, connection=connection, end_time=None).latest(
            "start_time"
        )
    except ScriptSession.DoesNotExist:
        return
    role_poll = script.steps.get(order=1).poll
    role = find_best_response(session, role_poll)
    group = None
    if role:
        group = find_closest_match(role, Group.objects)
    skipsteps = {
        "emis_subcounty": ["Teachers", "Head Teachers", "SMC"],
        "emis_one_school": ["Teachers", "Head Teachers", "SMC"],
        "emis_many_school": ["GEM"],
    }
    skipped = True
    while group and skipped:
        skipped = False
        for step_name, roles in skipsteps.items():
            if progress.step.poll and progress.step.poll.name == step_name and group.name not in roles:
                skipped = True
                progress.step = progress.script.steps.get(order=progress.step.order + 1)
                progress.save()
                break
Esempio n. 8
0
 def testyouthgrouppoll(self):
     groups=[u"GEM",u"gem",u"GEM group",u"it is GEM",u"yes GEM masaka group",u"yes GEM",u"Gem masaka",u"Girls Education Movement(GEM)",u"GEM-Uganda",u"YES GEM?§U",u"Yes Gem's chapter"]
     for gr in groups:
         for g in re.findall(r'\w+', gr):
             group = find_closest_match(g, Group.objects)
             if group:
                 self.assertEqual(self.gem_group,group)
Esempio n. 9
0
def xform_received_handler(sender, **kwargs):
    xform = kwargs['xform']
    submission = kwargs['submission']
    contact = Contact.objects.get(pk=kwargs['message'].connection.contact_id)

    if xform.keyword == 'coffee':
        date = datetime.now()
        customer = Customer.objects.filter(pk=contact.pk)[0]
        if submission.eav.coffee_type:
            coffee_name = find_closest_match(submission.eav.coffee_type, MenuItem.objects)
        else:
            coffee_name = customer.preferences.standard_drink
        if submission.eav.coffee_location:
            deliver_to = submission.eav.coffee_location
        else:
            deliver_to = contact.groups.all()[0].name + ' ' + Department.objects.get(pk=contact.groups.all()[0].pk).floor

        num_cups = submission.eav.coffee_cups if submission.eav.coffee_cups else 1

        CoffeeOrder.objects.create(\
            date=date, \
            customer=customer, \
            coffee_name=coffee_name, \
            num_cups=num_cups, \
            deliver_to=deliver_to, \
            )
        submission.response = str(num_cups) + ' cup(s) of ' + coffee_name.name + ' coming up shortly! We will deliver to ' + deliver_to
        submission.save()
Esempio n. 10
0
def cvs_autoreg(**kwargs):
    '''
    CVS autoreg post registration particulars handling.
    This method responds to a signal sent by the Script module on completion of the cvs_autoreg script
    '''
    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'cvs_autoreg':
        return
    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
    script = progress.script

    rolepoll = script.steps.get(poll__name='cvs_role').poll
    namepoll = script.steps.get(poll__name='cvs_name').poll
    districtpoll = script.steps.get(poll__name='cvs_district').poll
    healthfacilitypoll = script.steps.get(poll__name='cvs_healthfacility').poll
    villagepoll = script.steps.get(poll__name='cvs_village').poll

    role = None
    resps = session.responses.filter(response__poll=rolepoll, response__has_errors=False).order_by('-response__date')
    if resps.count():
        role = resps[0].response

    name = find_best_response(session, namepoll)
    district = find_best_response(session, districtpoll)
    village_name = find_best_response(session, villagepoll)
    village = None
    if village_name:
        if district:
            village = find_closest_match(village_name, district.get_descendants(include_self=True))
        else:
            village = find_closest_match(village_name, Location.objects)

    healthfacility = find_best_response(session, healthfacilitypoll)

    if name:
        name = ' '.join([n.capitalize() for n in name.lower().split()])
        name = name[:100]

    try:
        contact = connection.contact or HealthProvider.objects.get(name=name, \
                                      reporting_location=(village or district), \
                                      village=village, \
                                      village_name=village_name)
    except Contact.DoesNotExist, Contact.MultipleObectsReturned:
        contact = HealthProvider.objects.create()
def parse_district_value(value):
    district_value = find_closest_match(value, Location.objects.filter(type__slug='district'))
    country_specific_tokens = getattr(settings, 'COUNTRY_SPECIFIC_TOKENS', {"district":"district"})
    if not district_value:
        message = _(getattr(settings, 'UNRECOGNIZED_DISTRICT_RESPONSE_TEXT', '')%country_specific_tokens)
        raise ValidationError(message)
    else:
        return district_value
Esempio n. 12
0
def ussd_reg(sender, **kwargs):
    try:
        name = sender.navigations.filter(screen__slug='reg_name').latest('date').response
        facility = sender.navigations.filter(screen__slug='reg_hc').latest('date').response
        district = sender.navigations.filter(screen__slug='reg_dist').latest('date').response
        district = find_closest_match(district, Location.objects.filter(type__name='district'))
        if district:
            sublocs = district.get_descendants(include_self=True).all()
            facility = find_closest_match(facility, HealthFacility.objects.filter(catchment_areas__in=sublocs))
        else:
            facility = find_closest_match(facility, HealthFacility.objects)
        provider = HealthProvider.objects.create(name=name, facility=facility, reporting_location=district, active=False)
        provider.connection_set.add(sender.connection)
        # sender.connection.contact = provider
        # sender.connection.save()
    except Navigation.DoesNotExist:
        pass
Esempio n. 13
0
def parse_district_value(value):
    location_template = STARTSWITH_PATTERN_TEMPLATE % '[a-zA-Z]*'
    regex = re.compile(location_template)
    toret = find_closest_match(value, Location.objects.filter(type__name='district'))
    if not toret:
        raise ValidationError(
            "We didn't recognize your district.  Please carefully type the name of your district and re-send.")
    else:
        return toret
    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()
Esempio n. 15
0
def emis_autoreg(**kwargs):

    connection = kwargs["connection"]
    progress = kwargs["sender"]
    if not progress.script.slug == "emis_autoreg":
        return

    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by("-end_time")[0]
    script = progress.script

    role_poll = script.steps.get(order=1).poll
    district_poll = script.steps.get(order=2).poll
    subcounty_poll = script.steps.get(order=3).poll
    school_poll = script.steps.get(order=4).poll
    schools_poll = script.steps.get(order=5).poll
    name_poll = script.steps.get(order=6).poll

    name = find_best_response(session, name_poll)
    role = find_best_response(session, role_poll)
    default_group = Group.objects.get(name="Other EMIS Reporters")
    subcounty = find_best_response(session, subcounty_poll)
    district = find_best_response(session, district_poll)

    if name:
        name = " ".join([n.capitalize() for n in name.lower().split()])[:100]

    if subcounty:
        subcounty = find_closest_match(subcounty, Location.objects.filter(type__name="sub_county"))

    grp = find_closest_match(role, Group.objects)
    grp = grp if grp else default_group

    if subcounty:
        rep_location = subcounty
    elif district:
        rep_location = district
    else:
        rep_location = Location.tree.root_nodes()[0]
    try:
        contact = connection.contact or EmisReporter.objects.get(name=name, reporting_location=rep_location, groups=grp)
        if connection.contact:
            contact = EmisReporter.objects.get(pk=connection.contact.pk)
    except EmisReporter.DoesNotExist, EmisReporter.MultipleObectsReturned:
        contact = EmisReporter.objects.create()
Esempio n. 16
0
 def testyouthgrouppoll(self):
     groups = [
         u"GEM", u"gem", u"GEM group", u"it is GEM",
         u"yes GEM masaka group", u"yes GEM", u"Gem masaka",
         u"Girls Education Movement(GEM)", u"GEM-Uganda", u"YES GEM?§U",
         u"Yes Gem's chapter"
     ]
     for gr in groups:
         for g in re.findall(r'\w+', gr):
             group = find_closest_match(g, Group.objects)
             if group:
                 self.assertEqual(self.gem_group, group)
Esempio n. 17
0
def parse_district_value(value):
    """
    This function confirms whether your district does exist in a predefined list of districts.
    """
    location_template = STARTSWITH_PATTERN_TEMPLATE % '[a-zA-Z]*'
    regex = re.compile(location_template)
    toret = find_closest_match(value, Location.objects.filter(type__name='district'))
    if not toret:
        country_specific_tokens = getattr(settings, 'COUNTRY_SPECIFIC_TOKENS', {"district":"district"})
        message = _(getattr(settings, 'UNRECOGNIZED_DISTRICT_RESPONSE_TEXT', '') % {"district": country_specific_tokens['district']})
        raise ValidationError(message)
    else:
        return toret
Esempio n. 18
0
    def handle(self, **options):
        try:
            group_poll_responses = Script.objects.get(
                pk="ureport_autoreg").steps.get(order=1).poll.responses.all()
            gem = Group.objects.get(name="GEM")
            world_vision = Group.objects.get(name="World Vision")
            bosco = Group.objects.get(name="BOSCO")
            msc = Group.objects.get(name="MSC")
            cou = Group.objects.get(name="Church of Uganda")
            catholic_secritariat = Group.objects.get(
                name="Catholic secretariat")
            groups = {
                catholic_secritariat: ["catholic", 'secritariat'],
                world_vision: ["world", "vision"],
                gem: ["gem", "eduction movement"],
                bosco: ["bosco"],
                msc: ["muslim", "supreme"],
                cou: ["church"],
            }
            for response in group_poll_responses:
                txt = response.message.text.strip().lower()

                matched = False

                for group, word_list in groups.items():
                    for word in word_list:
                        if word in txt.split():
                            if response.contact and group not in response.contact.groups.all(
                            ):
                                response.contact.groups.add(group)
                                print "handled"
                                print txt
                                print response.contact.groups.all()
                                matched = True
                #get fuzzier
                if not matched:
                    for g in re.findall(r'\w+', txt):
                        group = find_closest_match(g, Group.objects)
                        if group and group in User.objects.get(
                                username="******").groups.all():
                            if response.contact and group not in response.contact.groups.all(
                            ):
                                response.contact.groups.add(group)
                                print "handled"
                                print txt
                                print response.contact.groups.all()

        except Exception, exc:
            print traceback.format_exc(exc)
Esempio n. 19
0
    def handle(self, **options):
        try:
            group_poll_responses=Script.objects.get(pk="ureport_autoreg").steps.get(order=1).poll.responses.all()
            gem=Group.objects.get(name="GEM")
            world_vision=Group.objects.get(name="World Vision")
            bosco=Group.objects.get(name="BOSCO")
            msc=Group.objects.get(name="MSC")
            cou=Group.objects.get(name="Church of Uganda")
            catholic_secritariat=Group.objects.get(name="Catholic secretariat")
            groups={
                catholic_secritariat:["catholic",'secritariat'],
                world_vision:["world","vision"],
                gem:["gem","eduction movement"],
                bosco:["bosco"],
                msc:["muslim","supreme"],
                cou:["church"],
            }
            for response in group_poll_responses:
                txt=response.message.text.strip().lower()

                matched=False

                for group, word_list in groups.items():
                    for word in word_list:
                        if word in txt.split():
                            if response.contact and group not in response.contact.groups.all():
                                response.contact.groups.add(group)
                                print "handled"
                                print txt
                                print response.contact.groups.all()
                                matched=True
                #get fuzzier
                if not matched:
                    for g in re.findall(r'\w+', txt):
                        group = find_closest_match(g, Group.objects)
                        if group and group in User.objects.get(username="******").groups.all():
                            if response.contact and  group not in response.contact.groups.all():
                                response.contact.groups.add(group)
                                print "handled"
                                print txt
                                print response.contact.groups.all()

                        


                            
        except Exception, exc:
            print traceback.format_exc(exc)
    def handle(self, **options):
        auto_reg_conns=ScriptSession.objects.values_list('connection',flat=True)
        no_district_connections=Connection.objects.filter(contact__reporting_location=None).filter(pk__in=auto_reg_conns).values_list('pk',flat=True)
        sic="|".join(Location.objects.filter(type__name='district').values_list('name',flat=True))

        messages=Message.objects.filter(connection__pk__in=no_district_connections,direction="I").filter(text__iregex=".*\m(%s)\y.*"%sic).order_by('date')
        try:
            for message in messages:
                if message.connection.contact:
                    msg=message.text.split()
                    for m in msg:
                        district=find_closest_match(m, Location.objects.filter(type__name='district'))
                        if district:
                            conn=message.connection
                            if not conn.contact.reporting_location:
                                conn.contact.reporting_location=district
                                conn.contact.save()

        except Exception, exc:
            print traceback.format_exc(exc)
Esempio 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'])
            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))
Esempio n. 22
0
def autoreg(**kwargs):
    connection = kwargs["connection"]
    progress = kwargs["sender"]
    if progress.script.slug and progress.script.slug in ["ureport_autoreg2", "ureport_autoreg_luo2"]:
        connection.contact = Contact.objects.create(name="Anonymous User")
        connection.save()
        session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by("-end_time")[0]
        script = progress.script
        youthgrouppoll = script.steps.get(order=1).poll
        districtpoll = script.steps.get(order=2).poll
        agepoll = script.steps.get(order=4).poll
        genderpoll = script.steps.get(order=5).poll
        villagepoll = script.steps.get(order=6).poll
        contact = connection.contact
        word_dict = dict(
            AutoregGroupRules.objects.exclude(values=None).exclude(closed=True).values_list("group__name", "values")
        )

        contact.reporting_location = find_best_response(session, districtpoll)

        age = find_best_response(session, agepoll)
        if age and age < 100:
            contact.birthdate = datetime.datetime.now() - datetime.timedelta(days=(365 * int(age)))

        gresps = session.responses.filter(response__poll=genderpoll, response__has_errors=False).order_by(
            "-response__date"
        )
        if gresps.exists():
            gender = gresps[0].response
            if gender.categories.filter(category__name="male").exists():
                contact.gender = "M"
            elif gender.categories.filter(category__name="female").exists():
                contact.gender = "F"

        village = find_best_response(session, villagepoll)
        if village:
            contact.village = village

        group_to_match = find_best_response(session, youthgrouppoll)
        gr_matched = False

        # to avoid an attempt to None.split()
        if group_to_match:
            try:
                for group_pk, word_list in word_dict.items():
                    for word in word_list.split(","):
                        if word in group_to_match.split():
                            try:
                                contact.groups.add(Group.objects.get(name=group_pk))
                            except (ValueError, Group.DoesNotExist):
                                try:
                                    contact.groups.add(Group.objects.get(pk=group_pk))
                                except (ValueError, Group.DoesNotExist):
                                    pass
                            gr_matched = True
            except AssertionError:
                pass
        default_group = None
        if progress.language:
            contact.language = progress.language
        if Group.objects.filter(name="Other uReporters").exists():
            default_group = Group.objects.get(name="Other uReporters")
        if group_to_match and not gr_matched:

            for g in re.findall(r"\w+", group_to_match):
                if g:
                    excluded = AutoregGroupRules.objects.filter(closed=True).values("group__pk")
                    group = find_closest_match(str(g), Group.objects.exclude(pk__in=excluded))
                    if group:
                        contact.groups.add(group)
                        break

            if default_group:
                contact.groups.add(default_group)
        elif default_group:
            contact.groups.add(default_group)

        if not contact.name:
            contact.name = "Anonymous User"
        contact.save()

        total_ureporters = Contact.objects.exclude(
            connection__identity__in=Blacklist.objects.values_list("connection__identity")
        ).count()
        if total_ureporters % getattr(settings, "USER_MILESTONE", 500) == 0:
            recipients = getattr(settings, "ADMINS", None)
            if recipients:
                recipients = [email for name, email in recipients]
            mgr = getattr(settings, "MANAGERS", None)
            if mgr:
                for email in mgr:
                    recipients.append(email)
            send_mail(
                "UReport now %d voices strong!" % total_ureporters,
                "%s (%s) was the %dth member to finish the sign-up.  Let's welcome them!"
                % (contact.name, connection.identity, total_ureporters),
                "*****@*****.**",
                recipients,
                fail_silently=True,
            )
Esempio n. 23
0
def autoreg(**kwargs):
    connection = kwargs['connection']
    progress = kwargs['sender']
    if progress.script.slug in progress.script.slug in ['ureport_autoreg2', 'ureport_autoreg_luo2']:
        connection.contact = Contact.objects.create(name='Anonymous User')
        connection.save()
        session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
        script = progress.script
        youthgrouppoll = script.steps.get(order=1).poll
        districtpoll = script.steps.get(order=2).poll
        namepoll = script.steps.get(order=3).poll
        agepoll = script.steps.get(order=4).poll
        genderpoll = script.steps.get(order=5).poll
        villagepoll = script.steps.get(order=6).poll
        contact = connection.contact
        word_dict=dict(AutoregGroupRules.objects.exclude(values=None).values_list('group__name','values'))
        name = find_best_response(session, namepoll)
        if name:
            contact.name = name[:100]

        contact.reporting_location = find_best_response(session, districtpoll)

        age = find_best_response(session, agepoll)
        if age and age < 100:
            contact.birthdate = datetime.datetime.now() - datetime.timedelta(days=(365 * int(age)))

        gresps = session.responses.filter(response__poll=genderpoll, response__has_errors=False).order_by('-response__date')
        if gresps.count():
            gender = gresps[0].response
            if gender.categories.filter(category__name='male').count():
                contact.gender = 'M'
            elif gender.categories.filter(category__name='female').exists():
                contact.gender = 'F'

        village = find_best_response(session, villagepoll)
        if village:
            contact.village = village

        group_to_match = find_best_response(session, youthgrouppoll)
        gr_matched=False
        
        #to avoid an attempt to None.split()
        if group_to_match:
            try:
                for group_pk, word_list in word_dict.items():
                    for word in word_list.split(","):
                        if word in group_to_match.split():
                            contact.groups.add(Group.objects.get(pk=group_pk))
                            gr_matched=True
            except AssertionError:
                pass
        default_group = None
        if progress.language:
            contact.language = progress.language
        if Group.objects.filter(name='Other uReporters').count():
            default_group = Group.objects.get(name='Other uReporters')
        if group_to_match and not gr_matched:

            for g in re.findall(r'\w+', group_to_match):
                if g:
                    group = find_closest_match(str(g), Group.objects.exclude(name__in=["MP","CODES Lugazi","delegate","CAO"]))
                    if group:
                        contact.groups.add(group)
                        break

            if default_group:
                contact.groups.add(default_group)
        elif default_group:
            contact.groups.add(default_group)

        if not contact.name:
            contact.name = 'Anonymous User'
        contact.save()

        total_ureporters = Contact.objects.exclude(connection__identity__in=Blacklist.objects.values_list('connection__identity')).count()
        if total_ureporters % getattr(settings, 'USER_MILESTONE', 500) == 0:
            recipients = getattr(settings, 'ADMINS', None)
            if recipients:
                recipients = [email for name, email in recipients]
            mgr = getattr(settings, 'MANAGERS', None)
            if mgr:
                for email in mgr:
                    recipients.append(email)
            send_mail("UReport now %d voices strong!" % total_ureporters, "%s (%s) was the %dth member to finish the sign-up.  Let's welcome them!" % (contact.name, connection.identity, total_ureporters), '*****@*****.**', recipients, fail_silently=True)
Esempio n. 24
0
    else:
        rep_location = Location.tree.root_nodes()[0]
    try:
        contact = connection.contact or EmisReporter.objects.get(name=name, reporting_location=rep_location, groups=grp)
        if connection.contact:
            contact = EmisReporter.objects.get(pk=connection.contact.pk)
    except EmisReporter.DoesNotExist, EmisReporter.MultipleObectsReturned:
        contact = EmisReporter.objects.create()

    connection.contact = contact
    connection.save()

    group = Group.objects.get(name="Other EMIS Reporters")
    default_group = group
    if role:
        group = find_closest_match(role, Group.objects)
        if not group:
            group = default_group
    contact.groups.add(group)

    if subcounty:
        contact.reporting_location = subcounty
    elif district:
        contact.reporting_location = district
    else:
        contact.reporting_location = Location.tree.root_nodes()[0]

    if name:
        contact.name = name

    if not contact.name:
Esempio n. 25
0
def edtrac_autoreg(**kwargs):
    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'edtrac_autoreg':
        return
    session = ScriptSession.objects.filter(
        script=progress.script,
        connection=connection
    ).order_by('-end_time')[0]
    script = progress.script
    role_poll = script.steps.get(poll__name='edtrac_role').poll
    gender_poll = script.steps.get(poll__name='edtrac_gender').poll
    class_poll = script.steps.get(poll__name='edtrac_class').poll
    district_poll = script.steps.get(poll__name='edtrac_district').poll
    subcounty_poll = script.steps.get(poll__name='edtrac_subcounty').poll
    school_poll = script.steps.get(poll__name='edtrac_school').poll
    name_poll = script.steps.get(poll__name='edtrac_name').poll

    name = find_best_response(session, name_poll)
    role = find_best_response(session, role_poll)
    gender = find_best_response(session, gender_poll)
    grade = find_best_response(session, class_poll)
    subcounty = find_best_response(session, subcounty_poll)
    district = find_best_response(session, district_poll)

    if name:
        name = ' '.join([n.capitalize() for n in name.lower().split()])[:100]
    if district:
        district = find_closest_match(
            district,
            Location.objects.filter(type='district')
        )

    if subcounty:
        if district:
            subcounty = find_closest_match(
                subcounty,
                district.get_descendants().filter(type='sub_county')
            )
        else:
            subcounty = find_closest_match(
                subcounty,
                Location.objects.filter(type='sub_county')
            )

    grp = match_group_response(session, role, role_poll)

    if subcounty:
        rep_location = subcounty
    elif district:
        rep_location = district
    else:
        rep_location = Location.tree.root_nodes()[0]
    try:
        contact = connection.contact or EmisReporter.objects.get(
            name=name,
            reporting_location=rep_location,
            groups=grp,
            connection=connection
        )
        if connection.contact:
            contact = EmisReporter.objects.get(pk=connection.contact.pk)
    except EmisReporter.DoesNotExist, EmisReporter.MultipleObectsReturned:
        contact = EmisReporter.objects.create()
Esempio n. 26
0
        contact.village_name = village_name
        contact.village = None

    contact.groups.clear()
    group = Group.objects.get(name='Other CVS Reporters')
    if role and role.categories.count():
        category = role.categories.all()[0].category
        try:
            group = Group.objects.get(name=category.name)
        except Group.DoesNotExist:
            pass
    contact.groups.add(group)


    if healthfacility:
        facility = find_closest_match(healthfacility, HealthFacility.objects)
        if facility:
            contact.facility = facility

    contact.save()

def ussd_jump_diseases(sender, **kwargs):
    screen = kwargs['screen']
    input = kwargs['input']

    if screen.slug == 'additional':
        try:
            raise TransitionException(screen=Field.objects.get(slug='cases_%s' % input.lower()[:2]))
        except Field.DoesNotExist:
            raise TransitionException(screen=Question.objects.get(slug='additional'))
    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 "============================================================================="
Esempio n. 28
0
        contact.name = 'Anonymous User'
    # activate reporter by default (deactivate when quit)
    contact.active = True
    contact.save()

    reporting_school = None
    school = find_best_response(session, school_poll)
    if school:
        if district:
            reporting_school = School.objects.filter(name__iexact=school)
            if reporting_school.exists():
                reporting_school = reporting_school[0]
            else:
                reporting_school = find_closest_match(
                    school,
                    School.objects.filter(location__name__in=[district],
                                          location__type__name='district'),
                    True)
                contact.has_exact_matched_school = False
                contact.save()
        elif subcounty:
            reporting_school = find_closest_match(
                school,
                School.objects.filter(location__name__in=[subcounty],
                                      location__type__name='sub_county'), True)

    schedule_all(connection)


def edtrac_reschedule_script(**kwargs):
    connection = kwargs['connection']
Esempio n. 29
0
    def handle(self, **options):
        try:

            #get contacts without a connection
            contacts=Contact.objects.filter(connection=None)
            contacts_pks=contacts.values_list('pk')

            #get poll responses which point to these contacts and re align

            responses=Response.objects.filter(contact__pk__in=contacts_pks)

            for response in responses:
                response.contact=response.message.connection.contact
                response.save()

            #get connections without a contact
            
            conns=Connection.objects.filter(contact=None)
            conns_sessions=ScriptSession.objects.filter(connection__in=conns)
            for session in conns_sessions:
                connection=session.connection
                connection.contact = Contact.objects.create(name='Anonymous User')
                connection.save()

                script=session.script

                youthgrouppoll = script.steps.get(order=1).poll
                districtpoll = script.steps.get(order=3).poll
                namepoll = script.steps.get(order=5).poll
                agepoll = script.steps.get(order=6).poll
                genderpoll = script.steps.get(order=7).poll
                villagepoll = script.steps.get(order=8).poll
                contact = connection.contact
                name = find_best_response(session, namepoll)
                if name:
                    contact.name = name[:100]
            
                contact.reporting_location = find_best_response(session, districtpoll)

                age = find_best_response(session, agepoll)
                if age and age < 100:
                    contact.birthdate = datetime.datetime.now() - datetime.timedelta(days=(365 * int(age)))

                gresps = session.responses.filter(response__poll=genderpoll, response__has_errors=False).order_by('-response__date')
                if gresps.count():
                    gender = gresps[0].response
                    if gender.categories.filter(category__name='male').count():
                        contact.gender = 'M'
                    elif gender.categories.filter(category__name='female').exists():
                        contact.gender = 'F'

                village = find_best_response(session, villagepoll)
                if village:
                    contact.village = find_closest_match(village, Location.objects.filter(type__slug="village"))

                group_to_match = find_best_response(session, youthgrouppoll)
                default_group = None

                if Group.objects.filter(name='Other uReporters').count():
                    default_group = Group.objects.get(name='Other uReporters')
                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:
                                contact.groups.add(group)
                                break

                    if default_group:
                        contact.groups.add(default_group)
                elif default_group:
                    contact.groups.add(default_group)


                
            conns2=Connection.objects.filter(contact=None)
            #now delete connection less contacts
            Contact.objects.filter(connection=None).delete()
            #go ahead and create contacts for all connections
            for conn in conns2:
                conn.contact = Contact.objects.create(name='Anonymous User')
                conn.save()

            


        except Exception, exc:
            print traceback.format_exc(exc)
Esempio n. 30
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 = {'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(kind__name='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)
            contact_pks = connections.values_list('contact__pk', flat=True)

            if len(contacts) > 0:
                info = 'Contacts with numbers... ' + ' ,'.join(
                    contacts) + " have been uploaded !\n\n"
            if len(duplicates) > 0:
                info = info + 'The following numbers already exist in the system and thus have not been uploaded: ' + ' ,'.join(
                    duplicates) + '\n\n'
            if len(invalid) > 0:
                info = info + 'The following numbers may be invalid and thus have not been added to the system: ' + ' ,'.join(
                    invalid) + '\n\n'
        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
Esempio n. 31
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(kind__name='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)
            contact_pks = connections.values_list('contact__pk', flat=True)

            if len(contacts) > 0:
                info = 'Contacts with numbers... ' + ' ,'.join(contacts) + " have been uploaded !\n\n"
            if len(duplicates) > 0:
                info = info + 'The following numbers already exist in the system and thus have not been uploaded: ' + ' ,'.join(
                    duplicates) + '\n\n'
            if len(invalid) > 0:
                info = info + 'The following numbers may be invalid and thus have not been added to the system: ' + ' ,'.join(
                    invalid) + '\n\n'
        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
Esempio n. 32
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))
Esempio n. 33
0
def coffee_autoreg(**kwargs):

    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'coffee_autoreg':
        return

    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
    script = progress.script

    name_poll = script.steps.get(order=1).poll
    department_poll = script.steps.get(order=2).poll
    extension_poll = script.steps.get(order=3).poll
    email_poll = script.steps.get(order=4).poll
    coffee_standard_poll = script.steps.get(order=5).poll
    milktype_poll = script.steps.get(order=6).poll
    running_order_poll = script.steps.get(order=7).poll
    own_cup_poll = script.steps.get(order=8).poll
    other_notes_poll = script.steps.get(order=9).poll

    name = find_best_response(session, name_poll)
    extension = find_best_response(session, extension_poll)
    department = find_best_response(session, department_poll)
    email = find_best_response(session, email_poll)
    if name:
        name = ' '.join([n.capitalize() for n in name.lower().split()])

    try:
        existing_contact = Customer.objects.get(name=name[:100], \
                                  extension=extension, \
                                  email=email)
        if connection.contact:
            connection.contact.active = True
        else:
            existing_contact.active = True
            existing_contact.save()
            connection.contact = existing_contact
            connection.save()

    except Customer.MultipleObjectsReturned:
        pass

    except Customer.DoesNotExist:

        connection.contact = Customer.objects.create()
        connection.save()
        contact = connection.contact

        if name:
            name = ' '.join([n.capitalize() for n in name.lower().split(' ')])
            contact.name = name[:100]

        if department:
            group = find_closest_match(department, Group.objects)
            if not group:
                group = Group.objects.get(name='Other Coffee People')
        contact.groups.add(group)

        if extension:
            contact.extension = extension

        if email:
            contact.email = email
        contact.save()

        prefs = contact.preferences
        drink = find_best_response(session, coffee_standard_poll)
        if drink:
            prefs.standard_drink = find_closest_match(drink, MenuItem.objects)

        milktype = find_best_response(session, milktype_poll)
        if milktype:
            milktype = ' '.join([n.capitalize() for n in milktype.lower().split(' ')])
            prefs.milk_type = milktype

        own_cup = find_best_response(session, own_cup_poll)
        if own_cup and own_cup in YES_WORDS:
            prefs.own_cup = True

        notes = find_best_response(session, other_notes_poll)
        if notes:
            notes = ' '.join([n.capitalize() for n in notes.lower().split(' ')])
            prefs.notes = notes
        prefs.save()
Esempio n. 34
0
def autoreg(**kwargs):
    connection = kwargs['connection']
    progress = kwargs['sender']
    if progress.script.slug and progress.script.slug in [
            'ureport_autoreg2', 'ureport_autoreg_luo2'
    ]:
        connection.contact = Contact.objects.create(name='Anonymous User')
        connection.save()
        session = ScriptSession.objects.filter(
            script=progress.script,
            connection=connection).order_by('-end_time')[0]
        script = progress.script
        youthgrouppoll = script.steps.get(order=1).poll
        districtpoll = script.steps.get(order=2).poll
        agepoll = script.steps.get(order=4).poll
        genderpoll = script.steps.get(order=5).poll
        villagepoll = script.steps.get(order=6).poll
        contact = connection.contact
        word_dict = dict(
            AutoregGroupRules.objects.exclude(values=None).exclude(
                closed=True).values_list('group__name', 'values'))

        contact.reporting_location = find_best_response(session, districtpoll)

        age = find_best_response(session, agepoll)
        if age and age < 100:
            contact.birthdate = datetime.datetime.now() - datetime.timedelta(
                days=(365 * int(age)))

        gresps = session.responses.filter(
            response__poll=genderpoll,
            response__has_errors=False).order_by('-response__date')
        if gresps.exists():
            gender = gresps[0].response
            if gender.categories.filter(category__name='male').exists():
                contact.gender = 'M'
            elif gender.categories.filter(category__name='female').exists():
                contact.gender = 'F'

        village = find_best_response(session, villagepoll)
        if village:
            contact.village_name = check_location_length(village)

        group_to_match = find_best_response(session, youthgrouppoll)
        gr_matched = False

        #to avoid an attempt to None.split()
        if group_to_match:
            try:
                for group_pk, word_list in word_dict.items():
                    for word in word_list.split(","):
                        if word in group_to_match.split():
                            try:
                                contact.groups.add(
                                    Group.objects.get(name=group_pk))
                            except (ValueError, Group.DoesNotExist):
                                try:
                                    contact.groups.add(
                                        Group.objects.get(pk=group_pk))
                                except (ValueError, Group.DoesNotExist):
                                    pass
                            gr_matched = True
            except AssertionError:
                pass
        default_group = None
        if progress.language:
            contact.language = progress.language
        if Group.objects.filter(name='Other uReporters').exists():
            default_group = Group.objects.get(name='Other uReporters')
        if group_to_match and not gr_matched:

            for g in re.findall(r'\w+', group_to_match):
                if g:
                    excluded = AutoregGroupRules.objects.filter(
                        closed=True).values('group__pk')
                    group = find_closest_match(
                        str(g), Group.objects.exclude(pk__in=excluded))
                    if group:
                        contact.groups.add(group)
                        break

            if default_group:
                contact.groups.add(default_group)
        elif default_group:
            contact.groups.add(default_group)

        if not contact.name:
            contact.name = 'Anonymous User'
        contact.save()

        total_ureporters = Contact.objects.exclude(
            connection__identity__in=Blacklist.objects.values_list(
                'connection__identity')).count()
        if total_ureporters % getattr(settings, 'USER_MILESTONE', 500) == 0:
            recipients = getattr(settings, 'ADMINS', None)
            if recipients:
                recipients = [email for name, email in recipients]
            mgr = getattr(settings, 'MANAGERS', None)
            if mgr:
                for email in mgr:
                    recipients.append(email)
            send_mail(
                "UReport now %d voices strong!" % total_ureporters,
                "%s (%s) was the %dth member to finish the sign-up.  Let's welcome them!"
                % (contact.name, connection.identity, total_ureporters),
                '*****@*****.**',
                recipients,
                fail_silently=True)
def _set_reporting_location(district, contact):
    if is_empty(district):
        contact.reporting_location = Location.tree.root_nodes()[0]
    contact.reporting_location = find_closest_match(district,
            Location.objects.filter(type__slug='district'))
Esempio n. 36
0
    # activate reporter by default (deactivate when quit)
    contact.active = True
    contact.save()

    reporting_school = None
    school = find_best_response(session, school_poll)
    if school:
        if district:
            reporting_school = School.objects.filter(name__iexact=school)
            if reporting_school.exists():
                reporting_school = reporting_school[0]
            else:
                reporting_school = find_closest_match(
                    school,
                    School.objects.filter(
                        location__name__in=[district],
                        location__type__name='district'
                    ),
                    True
                )
                contact.has_exact_matched_school = False
                contact.save()
        elif subcounty:
            reporting_school = find_closest_match(
                school,
                School.objects.filter(
                    location__name__in=[subcounty],
                    location__type__name='sub_county'
                ),
                True
            )
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))
Esempio n. 38
0
def emis_autoreg(**kwargs):

    connection = kwargs['connection']
    progress = kwargs['sender']
    if not progress.script.slug == 'emis_autoreg':
        return

    session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
    script = progress.script

    role_poll = script.steps.get(order=1).poll
    district_poll = script.steps.get(order=2).poll
    subcounty_poll = script.steps.get(order=3).poll
    school_poll = script.steps.get(order=4).poll
    schools_poll = script.steps.get(order=5).poll
    name_poll = script.steps.get(order=6).poll

    if not connection.contact:
#            connection.contact = Contact.objects.create()
            connection.contact = EmisReporter.objects.create()
            connection.save
    contact = connection.contact

    role = find_best_response(session, role_poll)

    group = Group.objects.get(name='Other EMIS Reporters')
    default_group = group
    if role:
        group = find_closest_match(role, Group.objects)
        if not group:
            group = default_group
    contact.groups.add(group)


    subcounty = find_best_response(session, subcounty_poll)
    district = find_best_response(session, district_poll)

    if subcounty:
        subcounty = find_closest_match(subcounty, Location.objects.filter(type__name='sub_county'))

    if subcounty:
        contact.reporting_location = subcounty
    elif district:
        contact.reporting_location = district
    else:
        contact.reporting_location = Location.tree.root_nodes()[0]

    name = find_best_response(session, name_poll)
    if name:
        name = ' '.join([n.capitalize() for n in name.lower().split(' ')])
        contact.name = name[:100]

    if not contact.name:
        contact.name = 'Anonymous User'
    contact.save()

    reporting_school = None
    school = find_best_response(session, school_poll)
    if school:
        if subcounty:
            reporting_school = find_closest_match(school, School.objects.filter(location__name__in=[subcounty], \
                                                                                location__type__name='sub_county'), True)
        elif district:
            reporting_school = find_closest_match(school, School.objects.filter(location__name__in=[district.name], \
                                                                            location__type__name='district'), True)
        else:
            reporting_school = find_closest_match(school, School.objects.filter(location__name=Location.tree.root_nodes()[0].name))
#        e = EmisReporter(pk=contact.pk)
#        e.school = reporting_school
#        e.save()
        contact.school = reporting_school
        contact.save()
    if not getattr(settings, 'TRAINING_MODE', False):
        # Now that you have their roll, they should be signed up for the periodic polling
        _schedule_monthly_script(group, connection, 'emis_abuse', 'last', ['Teachers', 'Head Teachers'])
        _schedule_monthly_script(group, connection, 'emis_meals', 20, ['Teachers', 'Head Teachers'])
        _schedule_monthly_script(group, connection, 'emis_school_administrative', 15, ['Teachers', 'Head Teachers'])

        start_of_term = getattr(settings, 'SCHOOL_TERM_START', datetime.datetime.now())
        if group.name in ['Teachers', 'Head Teachers']:
            sp = ScriptProgress.objects.create(connection=connection, script=Script.objects.get(slug='emis_annual'))
            sp.set_time(start_of_term + datetime.timedelta(14))

        _schedule_monthly_script(group, connection, 'emis_smc_monthly', 28, ['SMC'])

        holidays = getattr(settings, 'SCHOOL_HOLIDAYS', [])
        if group.name in ['SMC']:
            d = datetime.datetime.now()
            # get the date to a wednesday
            d = d + datetime.timedelta((2 - d.weekday()) % 7)
            in_holiday = True
            while in_holiday:
                in_holiday = False
                for start, end in holidays:
                    if d >= start and d <= end:
                        in_holiday = True
                        break
                if in_holiday:
                    d = d + datetime.timedelta(7)
            sp = ScriptProgress.objects.create(connection=connection, script=Script.objects.get(slug='emis_head_teacher_presence'))
            sp.set_time(d)