Ejemplo n.º 1
1
def run():
    from django.contrib.auth.models import Group


    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'testadmin'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u'*****@*****.**'
    auth_user_1.password = u'sha1$f8636$9ce2327b480195f1c764ac05aad10dc1a106a58e'
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.last_login = datetime.datetime(2009, 8, 6, 10, 37, 54)
    auth_user_1.date_joined = datetime.datetime(2009, 4, 15, 10, 30, 52)
    auth_user_1.save()

    from django.contrib.auth.models import Message


    from hq.models import Domain

    hq_domain_1 = Domain()
    hq_domain_1.name = u'Pathfinder'
    hq_domain_1.description = u''
    hq_domain_1.timezone = None
    hq_domain_1.save()

    hq_domain_2 = Domain()
    hq_domain_2.name = u'BRAC'
    hq_domain_2.description = u''
    hq_domain_2.timezone = None
    hq_domain_2.save()

    hq_domain_3 = Domain()
    hq_domain_3.name = u'Grameen'
    hq_domain_3.description = u''
    hq_domain_3.timezone = None
    hq_domain_3.save()

    hq_domain_4 = Domain()
    hq_domain_4.name = u'MVP'
    hq_domain_4.description = u''
    hq_domain_4.timezone = None
    hq_domain_4.save()

    from hq.models import OrganizationType

    hq_organizationtype_1 = OrganizationType()
    hq_organizationtype_1.name = u'NGO'
    hq_organizationtype_1.domain = hq_domain_1
    hq_organizationtype_1.description = u''
    hq_organizationtype_1.save()

    hq_organizationtype_2 = OrganizationType()
    hq_organizationtype_2.name = u'BRAC-Org'
    hq_organizationtype_2.domain = hq_domain_2
    hq_organizationtype_2.description = u''
    hq_organizationtype_2.save()

    hq_organizationtype_3 = OrganizationType()
    hq_organizationtype_3.name = u'Grameen-Intel'
    hq_organizationtype_3.domain = hq_domain_3
    hq_organizationtype_3.description = u''
    hq_organizationtype_3.save()

    hq_organizationtype_4 = OrganizationType()
    hq_organizationtype_4.name = u'MVP-Org'
    hq_organizationtype_4.domain = hq_domain_4
    hq_organizationtype_4.description = u''
    hq_organizationtype_4.save()

    from httptester.models import Permissions


    from locations.models import LocationType


    from locations.models import Location


    from reports.models import Case


    from patterns.models import Pattern




    from receiver.models import Submission


    from receiver.models import Attachment


    from receiver.models import SubmissionHandlingType


    from receiver.models import SubmissionHandlingOccurrence


    from reporters.models import Role


    from reporters.models import ReporterGroup

    reporters_reportergroup_1 = ReporterGroup()
    reporters_reportergroup_1.title = u'brac-chw-supervisors'
    reporters_reportergroup_1.parent = None
    reporters_reportergroup_1.description = u'BRAC CHW supervisors'
    reporters_reportergroup_1.save()

    reporters_reportergroup_2 = ReporterGroup()
    reporters_reportergroup_2.title = u'brac-chw-members'
    reporters_reportergroup_2.parent = None
    reporters_reportergroup_2.description = u'BRAC CHW members'
    reporters_reportergroup_2.save()

    from reporters.models import Reporter

    reporters_reporter_1 = Reporter()
    reporters_reporter_1.alias = u'bderenzi'
    reporters_reporter_1.first_name = u''
    reporters_reporter_1.last_name = u''
    reporters_reporter_1.location = None
    reporters_reporter_1.role = None
    reporters_reporter_1.language = u'en'
    reporters_reporter_1.registered_self = False
    reporters_reporter_1.save()

    reporters_reporter_1.groups.add(reporters_reportergroup_1)

    reporters_reporter_2 = Reporter()
    reporters_reporter_2.alias = u'njowine'
    reporters_reporter_2.first_name = u''
    reporters_reporter_2.last_name = u''
    reporters_reporter_2.location = None
    reporters_reporter_2.role = None
    reporters_reporter_2.language = u''
    reporters_reporter_2.registered_self = False
    reporters_reporter_2.save()

    reporters_reporter_3 = Reporter()
    reporters_reporter_3.alias = u'husseini'
    reporters_reporter_3.first_name = u''
    reporters_reporter_3.last_name = u''
    reporters_reporter_3.location = None
    reporters_reporter_3.role = None
    reporters_reporter_3.language = u''
    reporters_reporter_3.registered_self = False
    reporters_reporter_3.save()

    reporters_reporter_4 = Reporter()
    reporters_reporter_4.alias = u'joachim'
    reporters_reporter_4.first_name = u''
    reporters_reporter_4.last_name = u''
    reporters_reporter_4.location = None
    reporters_reporter_4.role = None
    reporters_reporter_4.language = u''
    reporters_reporter_4.registered_self = False
    reporters_reporter_4.save()

    reporters_reporter_5 = Reporter()
    reporters_reporter_5.alias = u'demo_user'
    reporters_reporter_5.first_name = u''
    reporters_reporter_5.last_name = u''
    reporters_reporter_5.location = None
    reporters_reporter_5.role = None
    reporters_reporter_5.language = u''
    reporters_reporter_5.registered_self = False
    reporters_reporter_5.save()

    from reporters.models import PersistantBackend

    reporters_persistantbackend_1 = PersistantBackend()
    reporters_persistantbackend_1.slug = u'http'
    reporters_persistantbackend_1.title = u'http'
    reporters_persistantbackend_1.save()

    from reporters.models import PersistantConnection

    reporters_persistantconnection_1 = PersistantConnection()
    reporters_persistantconnection_1.backend = reporters_persistantbackend_1
    reporters_persistantconnection_1.identity = u'13'
    reporters_persistantconnection_1.reporter = reporters_reporter_1
    reporters_persistantconnection_1.last_seen = None
    reporters_persistantconnection_1.save()

    from hq.models import Organization

    hq_organization_1 = Organization()
    hq_organization_1.name = u'Pathfinder'
    hq_organization_1.domain = hq_domain_1
    hq_organization_1.description = u'TZ'
    hq_organization_1.parent = None
    hq_organization_1.members = None
    hq_organization_1.supervisors = None
    hq_organization_1.save()

    hq_organization_1.organization_type.add(hq_organizationtype_1)

    hq_organization_2 = Organization()
    hq_organization_2.name = u'BRAC'
    hq_organization_2.domain = hq_domain_2
    hq_organization_2.description = u''
    hq_organization_2.parent = None
    hq_organization_2.members = None
    hq_organization_2.supervisors = None
    hq_organization_2.save()

    hq_organization_2.organization_type.add(hq_organizationtype_2)

    hq_organization_3 = Organization()
    hq_organization_3.name = u'BRAC-CHP'
    hq_organization_3.domain = hq_domain_2
    hq_organization_3.description = u''
    hq_organization_3.parent = hq_organization_2
    hq_organization_3.members = reporters_reportergroup_2
    hq_organization_3.supervisors = reporters_reportergroup_1
    hq_organization_3.save()

    hq_organization_3.organization_type.add(hq_organizationtype_2)

    hq_organization_4 = Organization()
    hq_organization_4.name = u'BRAC-CHW'
    hq_organization_4.domain = hq_domain_2
    hq_organization_4.description = u''
    hq_organization_4.parent = hq_organization_2
    hq_organization_4.members = None
    hq_organization_4.supervisors = None
    hq_organization_4.save()

    hq_organization_4.organization_type.add(hq_organizationtype_2)

    hq_organization_5 = Organization()
    hq_organization_5.name = u'Grameen-Intel'
    hq_organization_5.domain = hq_domain_3
    hq_organization_5.description = u''
    hq_organization_5.parent = None
    hq_organization_5.members = None
    hq_organization_5.supervisors = None
    hq_organization_5.save()

    hq_organization_5.organization_type.add(hq_organizationtype_3)

    hq_organization_6 = Organization()
    hq_organization_6.name = u'MVP'
    hq_organization_6.domain = hq_domain_4
    hq_organization_6.description = u'MVP root organization'
    hq_organization_6.parent = None
    hq_organization_6.members = None
    hq_organization_6.supervisors = None
    hq_organization_6.save()

    hq_organization_6.organization_type.add(hq_organizationtype_4)

    from hq.models import ReportSchedule

    hq_reportschedule_1 = ReportSchedule()
    hq_reportschedule_1.name = u'Direct to bracadmin'
    hq_reportschedule_1.description = u'Direct email to bracadmin'
    hq_reportschedule_1.report_class = u'siteadmin'
    hq_reportschedule_1.report_frequency = u'daily'
    hq_reportschedule_1.report_delivery = u'email'
    hq_reportschedule_1.organization = hq_organization_2
    hq_reportschedule_1.report_function = u''
    hq_reportschedule_1.active = True
    hq_reportschedule_1.save()

    hq_reportschedule_2 = ReportSchedule()
    hq_reportschedule_2.name = u'Brian Weekly Email'
    hq_reportschedule_2.description = u"Brian's Weekly Email"
    hq_reportschedule_2.report_class = u'supervisor'
    hq_reportschedule_2.report_frequency = u'weekly'
    hq_reportschedule_2.report_delivery = u'email'
    hq_reportschedule_2.recipient_user = None
    hq_reportschedule_2.organization = hq_organization_3
    hq_reportschedule_2.report_function = u''
    hq_reportschedule_2.active = True
    hq_reportschedule_2.save()

    hq_reportschedule_3 = ReportSchedule()
    hq_reportschedule_3.name = u'Brian Daily SMS'
    hq_reportschedule_3.description = u"Brian's Daily SMS as CHP Supervisor"
    hq_reportschedule_3.report_class = u'supervisor'
    hq_reportschedule_3.report_frequency = u'daily'
    hq_reportschedule_3.report_delivery = u'sms'
    hq_reportschedule_3.recipient_user = None
    hq_reportschedule_3.organization = hq_organization_3
    hq_reportschedule_3.report_function = u''
    hq_reportschedule_3.active = True
    hq_reportschedule_3.save()

    hq_reportschedule_4 = ReportSchedule()
    hq_reportschedule_4.name = u'Daily report to BRAC-CHW'
    hq_reportschedule_4.description = u'Daily SMS as CHW Member'
    hq_reportschedule_4.report_class = u'member'
    hq_reportschedule_4.report_frequency = u'daily'
    hq_reportschedule_4.report_delivery = u'sms'
    hq_reportschedule_4.recipient_user = None
    hq_reportschedule_4.organization = hq_organization_4
    hq_reportschedule_4.report_function = u''
    hq_reportschedule_4.active = True
    hq_reportschedule_4.save()

    hq_reportschedule_5 = ReportSchedule()
    hq_reportschedule_5.name = u'Supervisor weekly SMS CHP'
    hq_reportschedule_5.description = u'Supervisor weekly SMS CHP'
    hq_reportschedule_5.report_class = u'supervisor'
    hq_reportschedule_5.report_frequency = u'weekly'
    hq_reportschedule_5.report_delivery = u'sms'
    hq_reportschedule_5.recipient_user = None
    hq_reportschedule_5.organization = hq_organization_3
    hq_reportschedule_5.report_function = u''
    hq_reportschedule_5.active = True
    hq_reportschedule_5.save()

    from reports.models import FormIdentifier


    from reports.models import CaseFormIdentifier


    from xformmanager.models import ElementDefModel


    from xformmanager.models import FormDefModel


    from xformmanager.models import Metadata


    from hq.models import ReporterProfile

    hq_reporterprofile_1 = ReporterProfile()
    hq_reporterprofile_1.reporter = reporters_reporter_4
    hq_reporterprofile_1.chw_id = u'-1'
    hq_reporterprofile_1.chw_username = u'joachim'
    hq_reporterprofile_1.domain = hq_domain_1
    hq_reporterprofile_1.organization = hq_organization_1
    hq_reporterprofile_1.guid = u'-1'
    hq_reporterprofile_1.approved = True
    hq_reporterprofile_1.active = True
    hq_reporterprofile_1.save()

    hq_reporterprofile_2 = ReporterProfile()
    hq_reporterprofile_2.reporter = reporters_reporter_3
    hq_reporterprofile_2.chw_id = u'11'
    hq_reporterprofile_2.chw_username = u'husseini'
    hq_reporterprofile_2.domain = hq_domain_1
    hq_reporterprofile_2.organization = hq_organization_1
    hq_reporterprofile_2.guid = u'11'
    hq_reporterprofile_2.approved = True
    hq_reporterprofile_2.active = True
    hq_reporterprofile_2.save()

    hq_reporterprofile_3 = ReporterProfile()
    hq_reporterprofile_3.reporter = reporters_reporter_5
    hq_reporterprofile_3.chw_id = u'0'
    hq_reporterprofile_3.chw_username = u'demo_user'
    hq_reporterprofile_3.domain = hq_domain_1
    hq_reporterprofile_3.organization = hq_organization_1
    hq_reporterprofile_3.guid = u'0'
    hq_reporterprofile_3.approved = True
    hq_reporterprofile_3.active = True
    hq_reporterprofile_3.save()

    hq_reporterprofile_4 = ReporterProfile()
    hq_reporterprofile_4.reporter = reporters_reporter_2
    hq_reporterprofile_4.chw_id = u'13'
    hq_reporterprofile_4.chw_username = u'njowine'
    hq_reporterprofile_4.domain = hq_domain_1
    hq_reporterprofile_4.organization = hq_organization_1
    hq_reporterprofile_4.guid = u'13'
    hq_reporterprofile_4.approved = True
    hq_reporterprofile_4.active = True
    hq_reporterprofile_4.save()

    from hq.models import ExtUser

    hq_extuser_1 = ExtUser()
    hq_extuser_1.username = u'bracadmin'
    hq_extuser_1.first_name = u''
    hq_extuser_1.last_name = u''
    hq_extuser_1.email = u'*****@*****.**'
    hq_extuser_1.password = u'sha1$25e8d$45cfe119a9429d066168a20255f737dbffef6488'
    hq_extuser_1.is_staff = False
    hq_extuser_1.is_active = True
    hq_extuser_1.is_superuser = True
    hq_extuser_1.last_login = datetime.datetime(2009, 4, 15, 10, 33, 29)
    hq_extuser_1.date_joined = datetime.datetime(2009, 4, 15, 10, 33, 29)
    hq_extuser_1.chw_id = None
    hq_extuser_1.chw_username = None
    hq_extuser_1.primary_phone = u'+16176453236'
    hq_extuser_1.domain = hq_domain_2
    hq_extuser_1.organization = None
    hq_extuser_1.reporter = None
    hq_extuser_1.save()

    hq_extuser_2 = ExtUser()
    hq_extuser_2.username = u'pfadmin'
    hq_extuser_2.first_name = u''
    hq_extuser_2.last_name = u''
    hq_extuser_2.email = u''
    hq_extuser_2.password = u'sha1$223b5$7e92dfc51c7ae3ad5b0fd4df4b52396630e72406'
    hq_extuser_2.is_staff = False
    hq_extuser_2.is_active = True
    hq_extuser_2.is_superuser = True
    hq_extuser_2.last_login = datetime.datetime(2009, 4, 24, 16, 53, 39)
    hq_extuser_2.date_joined = datetime.datetime(2009, 4, 15, 10, 34, 6)
    hq_extuser_2.chw_id = None
    hq_extuser_2.chw_username = None
    hq_extuser_2.primary_phone = u''
    hq_extuser_2.domain = hq_domain_1
    hq_extuser_2.organization = None
    hq_extuser_2.reporter = None
    hq_extuser_2.save()

    hq_extuser_3 = ExtUser()
    hq_extuser_3.username = u'gradmin'
    hq_extuser_3.first_name = u''
    hq_extuser_3.last_name = u''
    hq_extuser_3.email = u''
    hq_extuser_3.password = u'sha1$f8df4$5339016289f029e23e14466e735a3e8cf016b57f'
    hq_extuser_3.is_staff = False
    hq_extuser_3.is_active = True
    hq_extuser_3.is_superuser = True
    hq_extuser_3.last_login = datetime.datetime(2009, 4, 24, 16, 55, 24)
    hq_extuser_3.date_joined = datetime.datetime(2009, 4, 15, 10, 34, 38)
    hq_extuser_3.chw_id = None
    hq_extuser_3.chw_username = None
    hq_extuser_3.primary_phone = u''
    hq_extuser_3.domain = hq_domain_3
    hq_extuser_3.organization = None
    hq_extuser_3.reporter = None
    hq_extuser_3.save()

    hq_extuser_4 = ExtUser()
    hq_extuser_4.username = u'brian'
    hq_extuser_4.first_name = u''
    hq_extuser_4.last_name = u''
    hq_extuser_4.email = u'*****@*****.**'
    hq_extuser_4.password = u'sha1$245de$137d06d752eee1885a6bbd1e40cbe9150043dd5e'
    hq_extuser_4.is_staff = False
    hq_extuser_4.is_active = True
    hq_extuser_4.is_superuser = True
    hq_extuser_4.last_login = datetime.datetime(2009, 4, 24, 17, 1, 40)
    hq_extuser_4.date_joined = datetime.datetime(2009, 4, 15, 10, 35, 1)
    hq_extuser_4.chw_id = None
    hq_extuser_4.chw_username = None
    hq_extuser_4.primary_phone = u'+16174016544'
    hq_extuser_4.domain = hq_domain_2
    hq_extuser_4.organization = None
    hq_extuser_4.reporter = None
    hq_extuser_4.save()

    hq_extuser_5 = ExtUser()
    hq_extuser_5.username = u'gayo'
    hq_extuser_5.first_name = u''
    hq_extuser_5.last_name = u''
    hq_extuser_5.email = u'*****@*****.**'
    hq_extuser_5.password = u'sha1$2aa9b$f8ce3e507b719c97d8442e518f8632c4454e686f'
    hq_extuser_5.is_staff = False
    hq_extuser_5.is_active = True
    hq_extuser_5.is_superuser = False
    hq_extuser_5.last_login = datetime.datetime(2009, 4, 15, 10, 35, 25)
    hq_extuser_5.date_joined = datetime.datetime(2009, 4, 15, 10, 35, 25)
    hq_extuser_5.chw_id = None
    hq_extuser_5.chw_username = None
    hq_extuser_5.primary_phone = u'+16174016544'
    hq_extuser_5.domain = hq_domain_2
    hq_extuser_5.organization = None
    hq_extuser_5.reporter = None
    hq_extuser_5.save()

    hq_extuser_6 = ExtUser()
    hq_extuser_6.username = u'pf1'
    hq_extuser_6.first_name = u''
    hq_extuser_6.last_name = u''
    hq_extuser_6.email = u''
    hq_extuser_6.password = u'sha1$245de$137d06d752eee1885a6bbd1e40cbe9150043dd5e'
    hq_extuser_6.is_staff = False
    hq_extuser_6.is_active = True
    hq_extuser_6.is_superuser = False
    hq_extuser_6.last_login = datetime.datetime(2009, 4, 15, 10, 57, 13)
    hq_extuser_6.date_joined = datetime.datetime(2009, 4, 15, 10, 57, 13)
    hq_extuser_6.chw_id = None
    hq_extuser_6.chw_username = None
    hq_extuser_6.primary_phone = u''
    hq_extuser_6.domain = hq_domain_1
    hq_extuser_6.organization = None
    hq_extuser_6.reporter = None
    hq_extuser_6.save()

    hq_extuser_7 = ExtUser()
    hq_extuser_7.username = u'pf2'
    hq_extuser_7.first_name = u''
    hq_extuser_7.last_name = u''
    hq_extuser_7.email = u''
    hq_extuser_7.password = u'sha1$245de$137d06d752eee1885a6bbd1e40cbe9150043dd5e'
    hq_extuser_7.is_staff = False
    hq_extuser_7.is_active = True
    hq_extuser_7.is_superuser = False
    hq_extuser_7.last_login = datetime.datetime(2009, 4, 15, 10, 57, 31)
    hq_extuser_7.date_joined = datetime.datetime(2009, 4, 15, 10, 57, 31)
    hq_extuser_7.chw_id = None
    hq_extuser_7.chw_username = None
    hq_extuser_7.primary_phone = u''
    hq_extuser_7.domain = hq_domain_1
    hq_extuser_7.organization = None
    hq_extuser_7.reporter = None
    hq_extuser_7.save()

    hq_extuser_8 = ExtUser()
    hq_extuser_8.username = u'br1'
    hq_extuser_8.first_name = u''
    hq_extuser_8.last_name = u''
    hq_extuser_8.email = u''
    hq_extuser_8.password = u'sha1$f0e70$8d5487476afde09a4a35de8d6ef3b39fba0b4405'
    hq_extuser_8.is_staff = False
    hq_extuser_8.is_active = True
    hq_extuser_8.is_superuser = False
    hq_extuser_8.last_login = datetime.datetime(2009, 4, 15, 10, 57, 52)
    hq_extuser_8.date_joined = datetime.datetime(2009, 4, 15, 10, 57, 52)
    hq_extuser_8.chw_id = None
    hq_extuser_8.chw_username = None
    hq_extuser_8.primary_phone = u'+16176453236'
    hq_extuser_8.domain = hq_domain_2
    hq_extuser_8.organization = None
    hq_extuser_8.reporter = None
    hq_extuser_8.save()

    hq_extuser_9 = ExtUser()
    hq_extuser_9.username = u'br2'
    hq_extuser_9.first_name = u''
    hq_extuser_9.last_name = u''
    hq_extuser_9.email = u''
    hq_extuser_9.password = u'sha1$a4c05$da3d0998c0d01ded87ffcd26cefdd5db619c6927'
    hq_extuser_9.is_staff = False
    hq_extuser_9.is_active = True
    hq_extuser_9.is_superuser = False
    hq_extuser_9.last_login = datetime.datetime(2009, 4, 15, 10, 58, 7)
    hq_extuser_9.date_joined = datetime.datetime(2009, 4, 15, 10, 58, 7)
    hq_extuser_9.chw_id = None
    hq_extuser_9.chw_username = None
    hq_extuser_9.primary_phone = u'+16174016544'
    hq_extuser_9.domain = hq_domain_2
    hq_extuser_9.organization = None
    hq_extuser_9.reporter = None
    hq_extuser_9.save()

    hq_extuser_10 = ExtUser()
    hq_extuser_10.username = u'grdoc'
    hq_extuser_10.first_name = u''
    hq_extuser_10.last_name = u''
    hq_extuser_10.email = u''
    hq_extuser_10.password = u'sha1$9df33$4bb013b189b71d3cfefa6f8b867c7a500ea46f68'
    hq_extuser_10.is_staff = False
    hq_extuser_10.is_active = True
    hq_extuser_10.is_superuser = False
    hq_extuser_10.last_login = datetime.datetime(2009, 4, 22, 14, 45, 11)
    hq_extuser_10.date_joined = datetime.datetime(2009, 4, 22, 14, 45, 11)
    hq_extuser_10.chw_id = None
    hq_extuser_10.chw_username = None
    hq_extuser_10.primary_phone = u''
    hq_extuser_10.domain = hq_domain_3
    hq_extuser_10.organization = None
    hq_extuser_10.reporter = None
    hq_extuser_10.save()

    hq_extuser_11 = ExtUser()
    hq_extuser_11.username = u'grsupervisor'
    hq_extuser_11.first_name = u''
    hq_extuser_11.last_name = u''
    hq_extuser_11.email = u'*****@*****.**'
    hq_extuser_11.password = u'sha1$4c2a2$cec32be6824786e76488aea338f350c6bbceb8eb'
    hq_extuser_11.is_staff = False
    hq_extuser_11.is_active = True
    hq_extuser_11.is_superuser = False
    hq_extuser_11.last_login = datetime.datetime(2009, 4, 22, 14, 45, 36)
    hq_extuser_11.date_joined = datetime.datetime(2009, 4, 22, 14, 45, 36)
    hq_extuser_11.chw_id = None
    hq_extuser_11.chw_username = None
    hq_extuser_11.primary_phone = u'+16174016544'
    hq_extuser_11.domain = hq_domain_3
    hq_extuser_11.organization = None
    hq_extuser_11.reporter = None
    hq_extuser_11.save()

    hq_extuser_12 = ExtUser()
    hq_extuser_12.username = u'grmobile1'
    hq_extuser_12.first_name = u''
    hq_extuser_12.last_name = u''
    hq_extuser_12.email = u''
    hq_extuser_12.password = u'sha1$ecda0$0728c9c311d4308333bb62058c1f2e979d2899ea'
    hq_extuser_12.is_staff = False
    hq_extuser_12.is_active = True
    hq_extuser_12.is_superuser = False
    hq_extuser_12.last_login = datetime.datetime(2009, 4, 22, 14, 45, 55)
    hq_extuser_12.date_joined = datetime.datetime(2009, 4, 22, 14, 45, 55)
    hq_extuser_12.chw_id = None
    hq_extuser_12.chw_username = None
    hq_extuser_12.primary_phone = u''
    hq_extuser_12.domain = hq_domain_3
    hq_extuser_12.organization = None
    hq_extuser_12.reporter = None
    hq_extuser_12.save()

    hq_extuser_13 = ExtUser()
    hq_extuser_13.username = u'grmobile2'
    hq_extuser_13.first_name = u''
    hq_extuser_13.last_name = u''
    hq_extuser_13.email = u''
    hq_extuser_13.password = u'sha1$6b5c2$12023bfbeb8ac8614d9d7800444f4b2053c67f3e'
    hq_extuser_13.is_staff = False
    hq_extuser_13.is_active = True
    hq_extuser_13.is_superuser = False
    hq_extuser_13.last_login = datetime.datetime(2009, 4, 22, 14, 46, 11)
    hq_extuser_13.date_joined = datetime.datetime(2009, 4, 22, 14, 46, 11)
    hq_extuser_13.chw_id = None
    hq_extuser_13.chw_username = None
    hq_extuser_13.primary_phone = u''
    hq_extuser_13.domain = hq_domain_3
    hq_extuser_13.organization = None
    hq_extuser_13.reporter = None
    hq_extuser_13.save()

    hq_extuser_14 = ExtUser()
    hq_extuser_14.username = u'mvpadmin'
    hq_extuser_14.first_name = u''
    hq_extuser_14.last_name = u''
    hq_extuser_14.email = u''
    hq_extuser_14.password = u'sha1$65d24$447a3770156eb7d91381819b14fb9c7a07ce15eb'
    hq_extuser_14.is_staff = False
    hq_extuser_14.is_active = True
    hq_extuser_14.is_superuser = True
    hq_extuser_14.last_login = datetime.datetime(2009, 4, 30, 13, 49, 20)
    hq_extuser_14.date_joined = datetime.datetime(2009, 4, 30, 13, 20, 36)
    hq_extuser_14.chw_id = u'000'
    hq_extuser_14.chw_username = None
    hq_extuser_14.primary_phone = u''
    hq_extuser_14.domain = hq_domain_4
    hq_extuser_14.organization = None
    hq_extuser_14.reporter = None
    hq_extuser_14.save()

    hq_extuser_15 = ExtUser()
    hq_extuser_15.username = u'mvpuser1'
    hq_extuser_15.first_name = u''
    hq_extuser_15.last_name = u''
    hq_extuser_15.email = u''
    hq_extuser_15.password = u'resetme'
    hq_extuser_15.is_staff = False
    hq_extuser_15.is_active = True
    hq_extuser_15.is_superuser = False
    hq_extuser_15.last_login = datetime.datetime(2009, 4, 30, 13, 21, 57)
    hq_extuser_15.date_joined = datetime.datetime(2009, 4, 30, 13, 21, 57)
    hq_extuser_15.chw_id = u'001'
    hq_extuser_15.chw_username = None
    hq_extuser_15.primary_phone = u''
    hq_extuser_15.domain = hq_domain_4
    hq_extuser_15.organization = None
    hq_extuser_15.reporter = None
    hq_extuser_15.save()







    hq_reportschedule_1.recipient_user = hq_extuser_1
    hq_reportschedule_1.save()
















    from graphing.models import GraphPref, GraphGroup

    graphing_graphpref_1 = GraphPref()
    graphing_graphpref_1.user = hq_extuser_4
    graphing_graphpref_1.save()
    graphing_graphpref_1.root_graphs = [GraphGroup.objects.get(id=5)]
    graphing_graphpref_1.save()
    
    graphing_graphpref_2 = GraphPref()
    graphing_graphpref_2.user = hq_extuser_3
    graphing_graphpref_2.save()
    graphing_graphpref_2.root_graphs = [GraphGroup.objects.get(id=1)]
    graphing_graphpref_2.save()
Ejemplo n.º 2
0
def create_reporter_with_connection(alias, phone_number, backend):
    reporter = Reporter(alias=alias)
    reporter.save()
    conn, c_created = PersistantConnection.objects.get_or_create(identity=phone_number, backend=backend)
    conn.reporter = reporter
    conn.save()
    return reporter
Ejemplo n.º 3
0
 def register_from_message(modelBase, message):
     potential_registrant = Respondent.objects.filter(phone_number=message.connection.identity)
     if potential_registrant:
         return potential_registrant[0]
     else:
         # have to create a Reporter and PersistentConnection
         # TODO: 
         spl = message.text.partition(" ")
         
         reporter = Reporter(alias=message.connection.identity, first_name=spl[0], last_name=spl[2])
         reporter.save()
         
         be = PersistantBackend.from_message(message)
         be.save()
         
         conn = PersistantConnection.from_message(message)
         conn.reporter = reporter
         conn.save()
         conn.seen()
         
         resp = Respondent(
         phone_number=message.connection.identity,
         registered_at=datetime.now(),
         reporter=reporter,
         connection=conn)
         resp.save()
         
         return resp
Ejemplo n.º 4
0
    def test_junk_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, reporter=reporter, identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond("junk"), TRIGGER_INCORRECT_MESSAGE)
Ejemplo n.º 5
0
 def save(self, *args, **kwargs):
     is_reporter_created = False
     if not hasattr(self, "reporter"):
         is_reporter_created = True
         r = Reporter(alias="temp")
         r.save()
         self.reporter = r
     self.reporter.save()
     super(Contact, self).save(*args, **kwargs)
     if is_reporter_created:
         self.reporter.alias = self.pk
         self.reporter.save()
Ejemplo n.º 6
0
    def testBasicViews(self):
        reporter = Reporter(alias="rapporteur")
        reporter.save()
        domain = Domain.objects.get(name='mockdomain')
        profile = ReporterProfile(reporter=reporter, domain=domain)
        profile.save()

        response = self.client.get('/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/serverup.txt')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/change_password/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/report/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/report/email/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)
        
        response = self.client.get('/report/sms/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/reporters/add/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)
        
        response = self.client.get('/reporters/%s/' % reporter.id)
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/charts/default/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/charts/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)

        response = self.client.get('/stats/')
        self.assertNotContains(response,"Error", status_code=200)
        self.assertNotContains(response,"Exception", status_code=200)
        
        # TODO - fix
        """
Ejemplo n.º 7
0
class RegistrationTest(TestCase):
    fixtures = ['registration']
    
    def setUp(self):
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.connection = Connection(backend=self.backend, identity="1000")
        self.pconnection = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="1000")
        self.pconnection.save()
        self.reporter.connections.add(self.pconnection)
        
        self. message = Message(text='register poll 100 1001', connection=self.connection)
        self.message.persistant_connection = self.pconnection

        self.message_with_correct_geo_codes = Message(text='register poll 1 3', connection=self.connection)
        self.message_with_correct_geo_codes.persistant_connection = self.pconnection

    
    def test_parse(self):
        self.reg = Registration()
        registration_info = self.reg._parse(self.message)
        self.assertEquals(registration_info.public_identifier, 'poll')

    def test_load_by_mobile_number(self):
        query_result = Registration.objects.filter(phone__identity = '100')
        self.assertEquals(query_result.count(), 0)

        query_result = Registration.objects.filter(phone__identity = '1000')
        self.assertEquals(query_result.count(), 1)
        r = query_result.iterator().next()
        self.assertNotEquals(r, None)

    def test_to_string(self):
        r = Registration()
        r.public_identifier = "Poll"
        r.governorate = "12"
        r.district = "8"
        r.phone = self.pconnection
        self.assertEquals(str(r), "1000 Poll")

    def test_valid_location(self):
        r = Registration()
        self.assertEquals(r.respond(self.message_with_correct_geo_codes), "initiate_poll_message")

    def test_invalid_location(self):
        r = Registration()
        self.assertEquals(r.respond(self.message), "location_does_not_exist")
Ejemplo n.º 8
0
def run():
    print "starting"
    from hq.models import ExtUser, ReporterProfile
    from reporters.models import Reporter, PersistantBackend, PersistantConnection

    all_users = ExtUser.objects.all()
    for user in all_users:
        print "processing user %s" % user
        rep = user.reporter
        if rep:
            print "%s already has attached reporter object!  %s" % (user,
                                                                    reporter)
        else:
            rep = Reporter()
            # if they have a first and last name set, use those,
            # otherwise just use the login
            if user.first_name and user.last_name:

                alias, fn, ln = Reporter.parse_name(
                    "%s %s" % (user.first_name, user.last_name))
            else:
                alias, fn, ln = Reporter.parse_name(user.username)
            print "Chose alias: %s first last: %s %s" % (alias, fn, ln)
            rep.first_name = fn
            rep.last_name = ln
            rep.alias = alias
            rep.save()

        profile = ReporterProfile()
        profile.reporter = rep
        profile.chw_id = user.chw_id
        profile.chw_username = user.chw_username
        profile.domain = user.domain
        profile.save()
        print "Saved profile %s for %s" % (profile, user)
        if user.primary_phone:
            # create a backend / connection for them.  This is
            # still a little hazy as it's not clear how the
            # backend is properly chosen

            # this will create an arbitrary backend if none is
            # found
            if len(PersistantBackend.objects.all()) == 0:
                PersistantBackend.objects.create(
                    slug="data_migration", title="Data Migration Backend")
            backend = PersistantBackend.objects.all()[0]
            try:
                conn = PersistantConnection.objects.create(
                    backend=backend, identity=user.primary_phone, reporter=rep)
                print "created connection %s for %s" % (conn, user)
            except Exception, e:
                print "Error creating connection for %s for number %s.  Is it possible you have duplicate phone numbers?" % (
                    user, user.primary_phone)
Ejemplo n.º 9
0
class RegistrationTest(TestCase):
    fixtures = ['registration']
    
    def setUp(self):
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.connection = Connection(backend=self.backend, identity="1000")
        self.pconnection = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="1000")
        self.pconnection.save()
        self.reporter.connections.add(self.pconnection)
        
        message = Message(text='register poll 100 1001', connection=self.connection)
        message.persistant_connection = self.pconnection

    
    def test_parse(self):
        # there should only be one registration object in this fixture
        self.reg = Registration.objects.get()
        self.assertEquals(self.reg.public_identifier, 'poll')
        self.assertEquals(self.reg.governorate, "10")
        self.assertEquals(self.reg.district, "8")
        self.assertEquals(self.reg.phone.identity, "1000")

    def test_load_by_mobile_number(self):
        query_result = Registration.objects.filter(phone__identity = '100')
        self.assertEquals(query_result.count(), 0)

        query_result = Registration.objects.filter(phone__identity = '1000')
        self.assertEquals(query_result.count(), 1)
        r = query_result.iterator().next()
        self.assertNotEquals(r, None)

    def test_to_string(self):
        r = Registration()
        r.public_identifier = "Poll"
        r.governorate = "12"
        r.district = "8"
        r.phone = self.pconnection
        self.assertEquals(str(r), "1000 Poll 12 8")
Ejemplo n.º 10
0
def run():
    print "starting"
    from hq.models import ExtUser, ReporterProfile
    from reporters.models import Reporter, PersistantBackend, PersistantConnection
    
    all_users = ExtUser.objects.all()
    for user in all_users:
        print "processing user %s" % user
        rep = user.reporter
        if rep:
            print "%s already has attached reporter object!  %s" % (user, reporter)
        else:
            rep = Reporter()
            # if they have a first and last name set, use those, 
            # otherwise just use the login
            if user.first_name and user.last_name:
                
                alias, fn, ln = Reporter.parse_name("%s %s" % (user.first_name, user.last_name))
            else:
                alias, fn, ln = Reporter.parse_name(user.username)
            print "Chose alias: %s first last: %s %s" % (alias, fn, ln) 
            rep.first_name = fn
            rep.last_name = ln
            rep.alias = alias
            rep.save()
        
        profile = ReporterProfile()
        profile.reporter = rep
        profile.chw_id = user.chw_id
        profile.chw_username = user.chw_username
        profile.domain = user.domain 
        profile.save()
        print "Saved profile %s for %s" % (profile, user)
        if user.primary_phone:
            # create a backend / connection for them.  This is 
            # still a little hazy as it's not clear how the 
            # backend is properly chosen
            
            # this will create an arbitrary backend if none is 
            # found 
            if len(PersistantBackend.objects.all()) == 0:
                PersistantBackend.objects.create(slug="data_migration", 
                                                 title="Data Migration Backend")
            backend = PersistantBackend.objects.all()[0]
            try:
                conn = PersistantConnection.objects.create(backend=backend, 
                                                           identity=user.primary_phone, 
                                                           reporter=rep)
                print "created connection %s for %s" % (conn, user)
            except Exception, e:
                print "Error creating connection for %s for number %s.  Is it possible you have duplicate phone numbers?" % (user, user.primary_phone)
Ejemplo n.º 11
0
    def handle_register(self, message, msg_text):
        connection, unused = getConnectionAndReporter(message,
                                                      self.ALLOWED_ROLE_CODES)

        text = msg_text.strip()

        if text == u'':
            message.respond(self.HELP_MESSAGES[u'register'])
            return

        try:
            location_code, role_code, full_name = grammar(text).register()
        except parsley.ParseError:
            message.respond(self.ERROR_MESSAGES[u'invalid_message'] %
                            {u'text': message.text})
            return

        location = Location.get_by_code(location_code)
        if location is None:
            message.respond(self.ERROR_MESSAGES[u'invalid_location'] % {
                u'location_code': location_code,
                u'text': message.text
            })
            return

        role = Role.get_by_code(role_code)
        if role is None or role.code.lower() not in self.ALLOWED_ROLE_CODES:
            message.respond(self.ERROR_MESSAGES[u'invalid_role'] % {
                u'role_code': role_code,
                u'text': message.text
            })
            return

        kwargs = {u'location': location, u'role': role}
        kwargs[u'alias'], kwargs[u'first_name'], kwargs[
            u'last_name'] = Reporter.parse_name(full_name)
        rep = Reporter(**kwargs)

        if Reporter.exists(rep, connection):
            message.respond(
                self.RESPONSE_MESSAGES[u'already_registered'] % {
                    u'name': rep.first_name,
                    u'role': rep.role.name,
                    u'location': rep.location.name,
                    u'location_type': rep.location.type.name
                })
            return

        rep.save()
        connection.reporters.add(rep)

        message.respond(
            self.RESPONSE_MESSAGES[u'register'] % {
                u'name': rep.first_name,
                u'role': rep.role.code,
                u'location': rep.location.name,
                u'location_type': rep.location.type.name
            })
Ejemplo n.º 12
0
 def setUp(self):
     self.backend = PersistantBackend(slug="MockBackend")
     self.backend.save()
     self.reporter = Reporter(alias="ReporterName")
     self.reporter.save()
     self.connection = Connection(backend=self.backend, identity="1000")
     self.pconnection = PersistantConnection(backend=self.backend, 
                                             reporter=self.reporter, 
                                             identity="1000")
     self.pconnection.save()
     self.reporter.connections.add(self.pconnection)
     
     message = Message(text='register poll 100 1001', connection=self.connection)
     message.persistant_connection = self.pconnection
Ejemplo n.º 13
0
    def setUp(self):
        Question.objects.all().delete()
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.pconnection = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="1000", governorate = 2, district = 4)
        self.pconnection.save()

        self.pconnection1 = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="10001", governorate = 7, district = 8)
        self.pconnection1.save()

        self.reporter.connections.add(self.pconnection)
        
        self.question1 = Question(text = "question1")
        self.question1.is_first = True
        self.question1.save()
        self.question2 = Question(text = "question2")
        self.question2.save()
        self.question3 = Question(text = "question3")
        self.question3.save()
        
        self.question1.next_question = self.question2
        self.question2.next_question = self.question3

        self.question1.save()
        self.question2.save()
        self.question3.save()

        self.setup_choices(self.question1)
        self.setup_choices(self.question2)
        self.setup_choices(self.question3)

        q = Questionnaire(trigger = "trigger", max_retries=3)
        q.save()
        DemographicParser(questionnaire=q, name='age', regex='[0-9]+', 
                        order=1, type='i').save()
        DemographicParser(questionnaire=q, name='gender', 
                        regex='m|f|male|female', order=2, type='c').save()

        r = Registration(phone = self.pconnection)
        r.save()
        
        r1 = Registration(phone = self.pconnection)
        r1.save()
Ejemplo n.º 14
0
def autoregister_reporters(domain):
    """Scan the metadata to see all submissions and autoregister Reporter 
       and ReporterProfile for pending approval for the domain"""

    # for a given domain, get all the formdefs
    fdefs = FormDefModel.objects.filter(domain=domain)

    # for all those formdefs, scan the metadata for parsed submissions
    allmetas_for_domain = Metadata.objects.filter(formdefmodel__in=fdefs)

    username_tuples = allmetas_for_domain.values_list("username").distinct()

    # the values_list returns a list of tuples, so we need to flip it into a list
    # from [(),()...] to [...]
    usernames = []
    for uname in username_tuples:
        usernames.append(uname[0])

    seen_profiles = ReporterProfile.objects.filter(domain=domain).filter(chw_username__in=usernames)

    new_profiles = []
    for uname in usernames:
        if seen_profiles.filter(chw_username=uname).count() == 0:
            new_profiles.append(uname)

    for prof in new_profiles:
        # create a new ReporterProfile
        chw_id = allmetas_for_domain.filter(username=prof)[0].chw_id

        newProf = ReporterProfile(
            chw_id=chw_id, chw_username=prof, domain=domain, guid=str(uuid.uuid1()).replace("-", "")
        )

        # create a new Reporter
        rep = Reporter()
        alias, fn, ln = Reporter.parse_name("%s %s" % ("chw", prof))
        rep.first_name = fn
        rep.last_name = ln
        rep.alias = alias
        rep.save()

        newProf.reporter = rep
        newProf.save()
Ejemplo n.º 15
0
def __combined_message_log_row(row):
    reporter = None
    connection = None

    # order of fields output by combined_message_log:
    #   [0] direction           [1] message_id      [2] message_date
    #   [3] message_text        [4] reporter_id     [5] reporter_first_name
    #   [6] reporter_last_name  [7] backend_id      [8] backend_title
    #   [9] backend_slug       [10] connection_id  [11] connection_identity

    # if this message is linked to a reporter, create a Reporter object
    # (so we can call the  methods like full_name) without hitting the
    # database each time. note that not all fields were fetched, so the
    # object won't work fully, but enough to display it
    if row[4] is not None:
        reporter = Reporter(first_name=row[5], last_name=row[6], pk=row[4])

    # likewise for a backend+connection, if this message isn't
    # linked to a reporter. combined_message_log can't filter
    # by connections (yet), but they must be displayed
    if row[7] is not None:
        backend = PersistantBackend(title=row[8], slug=row[9], id=row[7])

        connection = PersistantConnection(backend=backend,
                                          identity=row[11],
                                          id=row[10])

    # If the date object is already a datetime, don't bother
    # casting it.  Otherwise do.
    casted_date = row[2]
    if not isinstance(casted_date, datetime):
        casted_date = typecast_timestamp(row[2])
    return {
        "direction": row[0],
        "pk": row[1],
        "date": casted_date,
        "text": row[3],
        "reporter": reporter,
        "connection": connection
    }
Ejemplo n.º 16
0
    def handle(self, text):

        # extract the optional fields early, if they were
        # provided, to avoid them ending up in the name
        languages, text = extract_objects(text, [Language])
        locations, text = extract_objects(text, [Location])

        resp = "Thank you for registering"

        # REMOVE THE VILLAGE NAME! :O
        text = re.sub("\s+\S+$", "", text, re.I)

        # create the new reporter
        alias, fn, ln = Reporter.parse_name(text)
        rep = Reporter.objects.create(
            alias=alias,
            first_name=fn,
            last_name=ln,
            registered_self=True)

        # set the optional fields, if they were provided
        if languages:
            rep.language = languages[0]
            resp += " in %s" % (rep.language)

        if locations:
            rep.location = locations[0]
            resp += " at %s" % (rep.location)

        rep.save()

        # attach the reporter to the current connection
        self.msg.persistant_connection.reporter = rep
        self.msg.persistant_connection.save()

        self.respond("%s." % resp)
Ejemplo n.º 17
0
    def register(self, message, location_code, role, name=''):
        conn, unused = getConnectionAndReporter(message, ALLOWED_ROLE_CODES)

        data = {}
        try:
            data['location'] = Location.objects.get(code=location_code,
                                                    type__name=u'RC',
                                                    active=True)
            data['role'] = Role.objects.get(code__iexact=role)
            data['alias'], data['first_name'], data[
                'last_name'] = Reporter.parse_name(name.strip())
            rep = Reporter(**data)

            if Reporter.exists(rep, conn):
                message.respond(self.response_messages['already_registered'] %
                                dict(name=rep.first_name,
                                     role=rep.role,
                                     location_name=rep.location))
                return True

            rep.save()
            conn.reporters.add(rep)

            message.respond(self.response_messages['registered'] %
                            dict(name=rep.first_name,
                                 role=rep.role,
                                 location_name=rep.location,
                                 location_type=rep.location.type))
        except Role.DoesNotExist:
            message.respond(self.error_messages['invalid_role'] %
                            dict(role_code=role, text=message.text))
        except Location.DoesNotExist:
            message.respond(
                self.error_messages['invalid_location'] %
                dict(location_code=location_code, text=message.text))

        return True
Ejemplo n.º 18
0
class UserSessionTest(TestCase):
    apps = (poll_App,)

    def setUp(self):
        Question.objects.all().delete()
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.pconnection = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="1000", governorate = 2, district = 4)
        self.pconnection.save()

        self.pconnection1 = PersistantConnection(backend=self.backend, 
                                                reporter=self.reporter, 
                                                identity="10001", governorate = 7, district = 8)
        self.pconnection1.save()

        self.reporter.connections.add(self.pconnection)
        
        self.question1 = Question(text = "question1")
        self.question1.is_first = True
        self.question1.save()
        self.question2 = Question(text = "question2")
        self.question2.save()
        self.question3 = Question(text = "question3")
        self.question3.save()
        
        self.question1.next_question = self.question2
        self.question2.next_question = self.question3

        self.question1.save()
        self.question2.save()
        self.question3.save()

        self.setup_choices(self.question1)
        self.setup_choices(self.question2)
        self.setup_choices(self.question3)

        q = Questionnaire(trigger = "trigger", max_retries=3)
        q.save()
        DemographicParser(questionnaire=q, name='age', regex='[0-9]+', 
                        order=1, type='i').save()
        DemographicParser(questionnaire=q, name='gender', 
                        regex='m|f|male|female', order=2, type='c').save()

        r = Registration(phone = self.pconnection)
        r.save()
        
        r1 = Registration(phone = self.pconnection)
        r1.save()

    def setup_choices(self,question):
        choice1 = Choice(code= 'a',question=question, text="a")
        choice2 = Choice(code= 'b',question=question, text="a")
        choice3 = Choice(code= 'c',question=question, text="a")
        choice1.save()
        choice2.save()
        choice3.save()

    def test_open_new_session(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        self.assertEquals(session.question, None)
        
    def test_respond_with_first_question_on_new_session_for_any_message(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        self.assertEquals(session.respond("trigger m 16"), str(self.question1))

    def test_correct_response_to_question_sends_next_question(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        self.assertEquals(session.question, None)
        response1 = session.respond("trigger m 16")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("a")
        self.assertEquals(response2, str(self.question2))
        self.assertEquals(session.question, self.question2)

    def test_wrong_response_to_question_sends_error(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        self.assertEquals(session.question, None)
        response1 = session.respond("trigger f 16")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("django")
        self.assertEquals(response2, "error_parsing_response")
        self.assertEquals(session.question, self.question1)

    def test_retrieve_ongoing_session_at_question2(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        session.user = user
        session.question = self.question2
        session.save()

        session = UserSession.open(self.pconnection)

        self.assertEquals(session.respond("b"), str(self.question3))
        self.assertEquals(session.question, self.question3)
        
    def test_close_ongoing_session_at_trigger(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        session.user = user
        session.question = self.question2
        self.assertEquals(session.respond("c"), str(self.question3))
        self.assertEquals(session.question, self.question3)
        
        self.assertEquals(session.respond("trigger 13 m"), str(self.question1))
        self.assertEquals(session.question, self.question1)


    def test_close_session_on_last_answer(self):
        session = UserSession.open(self.pconnection)
        user = session.user
        user.save()
        session.user = user
        session.question = self.question3
        self.assertEquals(session.respond("c"), "thanks")
        self.assertEquals(session.question, None)
        self.assertEquals(session.user, None)

    def test_user_interaction_is_saved_when_successful(self):
        initial_number_of_responses = len(UserResponse.objects.all())
        initial_number_of_users = len(User.objects.all())
        
        session = UserSession.open(self.pconnection1)
        session.respond('trigger 14 f')
        self.assertEquals(len(User.objects.all()), initial_number_of_users + 1)
        session.respond('a')
        self.assertEquals(len(UserResponse.objects.all()), initial_number_of_responses + 1)

    def test_end_session_on_reaching_max_num_allowed_retries(self):
        session = UserSession.open(self.pconnection1)
        user = session.user
        user.save()
        session.user = user
        session.question = self.question1
        session.respond('t')
        session.respond('t')
        session.respond('t')
        self.assertEquals(session.question, None)

    def test_user_demographics_saved_when_present(self):
        session = UserSession.open(self.pconnection1)
        session.respond('trigger 13 f')
        latest_user = User.objects.all().order_by('-id')[0]
        self.assertEquals(latest_user.age, 13)
        self.assertEquals(latest_user.gender, 'f')
        
        
    def test_user_location_from_registration(self):
        session = UserSession.open(self.pconnection)
        session.respond('trigger 14 f')
        latest_user = User.objects.all().order_by('-id')[0]
        self.assertEquals(latest_user.governorate, 2)
        self.assertEquals(latest_user.district, 4)
        
    def test_junk_trigger_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, 
                                                reporter=reporter, 
                                                identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond('trigger junk'), TRIGGER_INCORRECT_MESSAGE )

    def test_junk_message(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond('junk'), TRIGGER_INCORRECT_MESSAGE )

    def test_recreate_user_if_demographic_data_changes(self):
        session = UserSession.open(self.pconnection)
        session.respond("trigger m 16")
        session.respond("trigger m 12")
        self.assertEquals(len(User.objects.all()), 2)

    def test_reset_session_on_sending_trigger(self):
        session = UserSession.open(self.pconnection)
        session.respond("trigger m 16")
        
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, self.question1)
        session.respond("trigger f 12")

        self.assertEquals(session.question, self.question1)
        session = UserSession.open(self.pconnection)
        session.respond("a")

        self.assertEquals(session.question, self.question2)
        
    def test_less_than_required_choices_reminds_user(self):
        self.question1.max_choices = 2
        self.question1.save()
        session = UserSession.open(self.pconnection)
        session.respond("trigger m 16")
        self.assertEquals(session.question.max_choices, 2)
        error = session.respond("a")
        self.assertEquals(error, "err_less_thank_expected_choices")
Ejemplo n.º 19
0
class UserSessionTest(TestCase):
    apps = (poll_App,)

    def setUp(self):
        Question.objects.all().delete()
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.pconnection = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="1000")
        self.pconnection.save()

        self.pconnection1 = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="10001")
        self.pconnection1.save()

        self.reporter.connections.add(self.pconnection)

        self.question1 = Question(text="question1")
        self.question1.is_first = True
        self.question1.save()
        self.question2 = Question(text="question2")
        self.question2.save()
        self.question3 = Question(text="question3")
        self.question3.save()

        self.question1.next_question = self.question2
        self.question2.next_question = self.question3

        self.question1.save()
        self.question2.save()
        self.question3.save()

        self.setup_choices(self.question1)
        self.setup_choices(self.question2)
        self.setup_choices(self.question3)

        q = Questionnaire(trigger="trigger", max_retries=3)
        q.save()
        DemographicParser(questionnaire=q, name="age", regex="[0-9]+", order=1, type="i").save()
        DemographicParser(questionnaire=q, name="gender", regex="m|f|male|female", order=2, type="c").save()
        self.user = User(connection=self.pconnection)
        self.user.save()

        r = Registration(governorate=3, district=4, phone=self.pconnection)
        r.save()

    def setup_choices(self, question):
        choice1 = Choice(code="a", question=question, text="a")
        choice2 = Choice(code="b", question=question, text="a")
        choice3 = Choice(code="c", question=question, text="a")
        choice1.save()
        choice2.save()
        choice3.save()

    def test_open_new_session(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)

    def test_respond_with_first_question_on_new_session_for_any_message(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("text"), str(self.question1))

    def test_correct_response_to_question_sends_next_question(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)
        response1 = session.respond("text")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("a")
        self.assertEquals(response2, str(self.question2))
        self.assertEquals(session.question, self.question2)

    def test_wrong_response_to_question_sends_error(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)
        response1 = session.respond("text")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("django")
        self.assertEquals(response2, "error_parsing_response")
        self.assertEquals(session.question, self.question1)

    def test_retrieve_ongoing_session_at_question2(self):
        session = UserSession.open(self.pconnection)
        session.user = self.user
        session.question = self.question2
        session.save()
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("b"), str(self.question3))
        self.assertEquals(session.question, self.question3)

    def test_close_ongoing_session_at_trigger(self):
        session = UserSession.open(self.pconnection)
        session.user = self.user
        session.question = self.question2
        session.save()
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("c"), str(self.question3))
        self.assertEquals(session.question, self.question3)

        self.assertEquals(session.respond("trigger 13 m"), str(self.question1))
        self.assertEquals(session.question, self.question1)

    def test_close_session_on_last_answer(self):
        session = UserSession.open(self.pconnection)
        session.question = self.question3
        session.user = self.user
        self.assertEquals(session.respond("c"), "thanks")
        self.assertEquals(session.question, None)

    def test_user_interaction_is_saved_when_successful(self):
        initial_number_of_responses = len(UserResponse.objects.all())
        initial_number_of_users = len(User.objects.all())

        session = UserSession.open(self.pconnection1)
        session.respond("trigger 14 f")
        self.assertEquals(len(User.objects.all()), initial_number_of_users + 1)
        session.respond("a")
        self.assertEquals(len(UserResponse.objects.all()), initial_number_of_responses + 1)

    def test_end_session_on_reaching_max_num_allowed_retries(self):
        session = UserSession.open(self.pconnection1)
        session.question = self.question1
        session.user = self.user
        session.respond("t")
        session.respond("t")
        session.respond("t")
        self.assertEquals(session.question, None)

    def test_user_demographics_saved_when_present(self):
        session = UserSession.open(self.pconnection1)
        session.respond("trigger 13 f")
        latest_user = User.objects.all().order_by("-id")[0]
        self.assertEquals(latest_user.age, 13)
        self.assertEquals(latest_user.gender, "f")

    def test_user_location_from_registration(self):
        session = UserSession.open(self.pconnection)
        session.respond("trigger 14 f")
        latest_user = User.objects.all().order_by("-id")[0]
        self.assertEquals(latest_user.governorate, 3)
        self.assertEquals(latest_user.district, 4)

    def test_junk_trigger_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, reporter=reporter, identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond("trigger junk"), TRIGGER_INCORRECT_MESSAGE)

    def test_junk_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, reporter=reporter, identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond("junk"), TRIGGER_INCORRECT_MESSAGE)
Ejemplo n.º 20
0
       translation came from the database or a locale dict.
       
       It is created and returned by the Token.translate method when no "real"
       String instance exists, but a translation was found in a locale dict."""

    def __init__(self, language, token, string):
        self.language = language
        self.token = token
        self.string = string

    def __unicode__(self):
        return self.string

    def __repr__(self):
        return '<%s: %s>' %\
            (type(self).__name__, self.token)


# if the reporters app happens to also be running, we
# can provide some optional integration (see: app.py)
if "reporters" in settings.RAPIDSMS_APPS:
    from reporters.models import Reporter

    Reporter.add_to_class(
        "language",

        models.ForeignKey(
            Language,
            null=True,
            blank=True))
Ejemplo n.º 21
0
            loc = loc.parent

            # are we at the top?
            if loc is None:
                return locs


    def descendants(self, include_self=False):
        """Returns all of the locations which are descended from this location,
           optionally including itself in the output. This is very inefficient
           (it recurses once for EACH), so consider caching the output."""
        locs = [self] if include_self else []

        for loc in self.children.all():
            locs.extend(loc.descendants(True))

        return locs

# TODO
# WARNING
# OH SHIT
Reporter.add_to_class(
    "location",

    models.ForeignKey(
        Location,
        null=True,
        blank=True
    )
)
Ejemplo n.º 22
0
    def join(self, message, location_code, last_name, first_name, role=None):
        ''' register as a user and join the system

        Format: join [location code] [last name] [first name]
        [role - leave blank for CHEW] '''

        #default alias for everyone until further notice
        username = None
        # do not skip roles for now
        role_code = role
        try:
            name = "%(fname)s %(lname)s" % {'fname': first_name, \
                                            'lname': last_name}
            # parse the name, and create a reporter
            alias, fn, ln = Reporter.parse_name(name)

            if not message.persistant_connection.reporter:
                rep = Reporter(alias=alias, first_name=fn, last_name=ln)
            else:
                rep = message.persistant_connection.reporter
                rep.alias = alias
                rep.first_name = fn
                rep.last_name = ln

            rep.save()

            # attach the reporter to the current connection
            message.persistant_connection.reporter = rep
            message.persistant_connection.save()

            # something went wrong - at the
            # moment, we don't care what
        except:
            message.respond(_("Join Error. Unable to register your account."))

        if role_code == None or role_code.__len__() < 1:
            role_code = Cfg.get('default_chw_role')

        reporter = message.persistant_connection.reporter

        # check location code
        try:
            location = Location.objects.get(code=location_code)
        except models.ObjectDoesNotExist:
            message.forward(reporter.connection().identity, \
                _(u"Join Error. Provided location code (%(loc)s) is wrong.") \
                  % {'loc': location_code})
            return True

        # check that location is a clinic (not sure about that)
        #if not clinic.type in LocationType.objects.filter(name='Clinic'):
        #    message.forward(reporter.connection().identity, \
        #        _(u"Join Error. You must provide a Clinic code."))
        #    return True

        # set location
        reporter.location = location

        # check role code
        try:
            role = Role.objects.get(code=role_code)
        except models.ObjectDoesNotExist:
            message.forward(reporter.connection().identity, \
                _(u"Join Error. Provided Role code (%(role)s) is wrong.") \
                  % {'role': role_code})
            return True

        reporter.role = role

        # set account active
        # /!\ we use registered_self as active
        reporter.registered_self = True

        # save modifications
        reporter.save()

        # inform target
        message.forward(reporter.connection().identity, \
            _("Success. You are now registered as %(role)s at %(loc)s with " \
              "alias @%(alias)s.") \
           % {'loc': location, 'role': reporter.role, 'alias': reporter.alias})

        #inform admin
        if message.persistant_connection.reporter != reporter:
            message.respond(_("Success. %(reporter)s is now registered as " \
                            "%(role)s at %(loc)s with alias @%(alias)s.") \
                            % {'reporter': reporter, 'loc': location, \
                            'role': reporter.role, 'alias': reporter.alias})
        return True
Ejemplo n.º 23
0
def check_and_add_reporter(data, domain):
    """
    Checks if xform submitter is registered in application, adds details if not    
    Returns new/matching Reporter object
    """        
        
    chw_username = False # chw_username is the mobile phone number (we don't use traditional users in WQR)
    tester_phone_number = False
    tester_name = False
    
    if data.has_key("meta_username"):
        chw_username = str(data["meta_username"])
    
    # trawl xform data for reporter fields
    match_phone = "phonenumber" # TODO remove eventually, when all forms in the wild have meta_username populated
    match_name = "enteredby"
    
    for key in data.keys():
        if key.find(match_phone) != -1:
            tester_phone_number = str(data[key])
            
        if key.find(match_name) != -1:
            tester_name = data[key]
            
    if tester_phone_number == "None":
        tester_phone_number = None
            
    if tester_phone_number and tester_phone_number[0] != '0':
        tester_phone_number = '0' + tester_phone_number
            
    if (not chw_username) or (chw_username is None) or (chw_username == "None"):
        if tester_phone_number:
            chw_username = tester_phone_number
        else:
            # TODO do we really want to bail if there is no number? could assign a fake number
            return None
            
    # check if reporter exists already    
    rps = ReporterProfile.objects.filter(chw_username=chw_username)     
    
    # check if chw_username is missing a leading 0
    if rps.count() == 0 and chw_username[0] != '0':    
        chw_username = '******' + chw_username
        rps = ReporterProfile.objects.filter(chw_username=chw_username)
    
    if rps.count() > 0:
        rp = rps[0]
        persistant_connection = PersistantConnection.objects.get(reporter=rp.reporter)
        persistant_connection.last_seen = datetime.today()
        persistant_connection.save()
        
        return rp.reporter
    else:
        # add reporter
        reporter = Reporter()
        reporter.alias = tester_name
        reporter.first_name = tester_name.split(" ")[0] # first token after splitting on spaces
        reporter.last_name = " ".join(tester_name.split(" ")[1:]) # all other tokens joined by spaces (even if none)
        reporter.registered_self = 1
        reporter.save()
        reporter.groups.add(ReporterGroup.objects.get(title="Operator"))        
        
        # connection 
        persistant_connection = PersistantConnection()
        persistant_connection.backend = PersistantBackend.objects.get(slug="cellphone")
        persistant_connection.reporter = reporter
        persistant_connection.identity = chw_username
        persistant_connection.preferred = True
        persistant_connection.last_seen = datetime.today()
        persistant_connection.save()
        
        # and finally, reporterprofile
        rp = ReporterProfile()
        rp.reporter = reporter
        rp.chw_username = chw_username
            
        rp.domain = domain
        rp.approved = True
        rp.active = True
        rp.guid = str(uuid.uuid1()).replace('-', '')  
        rp.save()
        
        return reporter
Ejemplo n.º 24
0
 def _create_reporter(self, alias, phone_number):
     reporter = Reporter(alias=alias)
     reporter.save()
     pconnection = self._create_connection(phone_number, reporter)
     reporter.connections.add(pconnection)
     return reporter
Ejemplo n.º 25
0
 def _create_reporter(self, alias, phone_number):
     reporter = Reporter(alias=alias)
     reporter.save()
     pconnection = self._create_connection(phone_number, reporter)
     reporter.connections.add(pconnection)
     return reporter