Exemplo n.º 1
0
 def recipient(self):
     handler = self.handler
     if handler.recipient == RECIPIENT_USER:
         return self.user
     elif handler.recipient == RECIPIENT_CASE:
         return CommConnectCase.get(self.case_id)
     elif handler.recipient == RECIPIENT_SURVEY_SAMPLE:
         return SurveySample.get(self.sample_id)
     elif handler.recipient == RECIPIENT_OWNER:
         return get_wrapped_owner(get_owner_id(self.case))
     elif handler.recipient == RECIPIENT_PARENT_CASE:
         indices = self.case.indices
         for index in indices:
             # TODO: The data model allows for more than one parent.
             # For now, send to the first parent, but need to decide how to handle multiple ones.
             if index.identifier == "parent":
                 return CommConnectCase.get(index.referenced_id)
         return None
     elif handler.recipient == RECIPIENT_SUBCASE:
         indices = self.case.reverse_indices
         recipients = []
         for index in indices:
             if index.identifier == "parent":
                 subcase = CommConnectCase.get(index.referenced_id)
                 if case_matches_criteria(subcase, handler.recipient_case_match_type, handler.recipient_case_match_property, handler.recipient_case_match_value):
                     recipients.append(subcase)
         return recipients
     else:
         return None
Exemplo n.º 2
0
    def setUp(self):
        super(AllBackendTest, self).setUp()
        backend_api.TEST = True

        self.domain_obj = Domain(name='all-backend-test')
        self.domain_obj.save()
        self.create_account_and_subscription(self.domain_obj.name)
        self.domain_obj = Domain.get(self.domain_obj._id)

        self.test_phone_number = '99912345'
        self.contact1 = CommCareCase(domain=self.domain_obj.name)
        self.contact1.set_case_property('contact_phone_number', self.test_phone_number)
        self.contact1.set_case_property('contact_phone_number_is_verified', '1')
        self.contact1.save()
        self.contact1 = CommConnectCase.wrap(self.contact1.to_json())

        # For use with megamobile only
        self.contact2 = CommCareCase(domain=self.domain_obj.name)
        self.contact2.set_case_property('contact_phone_number', '63%s' % self.test_phone_number)
        self.contact2.set_case_property('contact_phone_number_is_verified', '1')
        self.contact2.save()
        self.contact2 = CommConnectCase.wrap(self.contact2.to_json())

        self.unicel_backend = UnicelBackend(name='UNICEL', is_global=True)
        self.unicel_backend.save()

        self.mach_backend = MachBackend(name='MACH', is_global=True)
        self.mach_backend.save()

        self.tropo_backend = TropoBackend(name='TROPO', is_global=True)
        self.tropo_backend.save()

        self.http_backend = HttpBackend(name='HTTP', is_global=True)
        self.http_backend.save()

        self.telerivet_backend = TelerivetBackend(name='TELERIVET', is_global=True,
            webhook_secret='telerivet-webhook-secret')
        self.telerivet_backend.save()

        self.test_backend = TestSMSBackend(name='TEST', is_global=True)
        self.test_backend.save()

        self.grapevine_backend = GrapevineBackend(name='GRAPEVINE', is_global=True)
        self.grapevine_backend.save()

        self.twilio_backend = TwilioBackend(name='TWILIO', is_global=True)
        self.twilio_backend.save()

        self.megamobile_backend = MegamobileBackend(name='MEGAMOBILE', is_global=True)
        self.megamobile_backend.save()

        self.smsgh_backend = SMSGHBackend(name='SMSGH', is_global=True)
        self.smsgh_backend.save()

        if not hasattr(settings, 'SIMPLE_API_KEYS'):
            settings.SIMPLE_API_KEYS = {}

        settings.SIMPLE_API_KEYS['grapevine-test'] = 'grapevine-api-key'
Exemplo n.º 3
0
def device_data(request):
    if "data" not in request.POST:
        return HttpResponseBadRequest("Missing 'data' POST parameter.")

    data = request.POST.get("data")
    data = data.strip()
    data_points = data.split(",")
    device_id = None
    for data_point in data_points:
        key_value = data_point.partition("=")
        key = key_value[0].strip().upper()
        value = key_value[2].strip()
        if key == "SN":
            device_id = value
            break

    if device_id is None:
        return HttpResponseBadRequest("Missing 'SN' in data string.")

    # This view lookup is an implicit assert that either one device exists
    # with the given device_id, or no devices exist with this device_id.
    case = CommConnectCase.view("wisepill/device",
                                key=[device_id],
                                include_docs=True).one()

    event = WisePillDeviceEvent(
        domain=case.domain if case is not None else None,
        data=data,
        received_on=datetime.utcnow(),
        case_id=case._id if case is not None else None,
        processed=False,
    )
    event.save()

    if case is not None:
        survey_keywords = SurveyKeyword.get_all(case.domain)
        for survey_keyword in survey_keywords:
            if survey_keyword.keyword.upper() == "DEVICE_EVENT":
                for survey_keyword_action in survey_keyword.actions:
                    if survey_keyword_action.action == METHOD_STRUCTURED_SMS:
                        handle_structured_sms(survey_keyword,
                                              survey_keyword_action,
                                              case,
                                              None,
                                              "DEVICE_EVENT,%s" % data,
                                              send_response=False)
                        event.processed = True
                        event.save()
                        break
Exemplo n.º 4
0
    def setUp(self):
        self.domain = "test-domain"
        self.domain2 = "test-domain2"

        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()
        self.domain_obj = Domain.get(self.domain_obj._id) # Prevent resource conflict

        self.backend1 = TestCaseBackend(name="BACKEND1",is_global=True)
        self.backend1.save()

        self.backend2 = TestCaseBackend(name="BACKEND2",is_global=True)
        self.backend2.save()

        self.backend3 = TestCaseBackend(name="BACKEND3",is_global=True)
        self.backend3.save()

        self.backend4 = TestCaseBackend(name="BACKEND4",is_global=True)
        self.backend4.save()

        self.backend5 = TestCaseBackend(name="BACKEND5",domain=self.domain,is_global=False,authorized_domains=[])
        self.backend5.save()

        self.backend6 = TestCaseBackend(name="BACKEND6",domain=self.domain2,is_global=False,authorized_domains=[self.domain])
        self.backend6.save()

        self.backend7 = TestCaseBackend(name="BACKEND7",domain=self.domain2,is_global=False,authorized_domains=[])
        self.backend7.save()
        
        self.backend8 = TestCaseBackend(name="BACKEND",domain=self.domain,is_global=False,authorized_domains=[])
        self.backend8.save()

        self.backend9 = TestCaseBackend(name="BACKEND",domain=self.domain2,is_global=False,authorized_domains=[self.domain])
        self.backend9.save()

        self.backend10 = TestCaseBackend(name="BACKEND",is_global=True)
        self.backend10.save()

        self.backend_mapping1 = BackendMapping(is_global=True,prefix="*",backend_id=self.backend1._id)
        self.backend_mapping1.save()

        self.backend_mapping2 = BackendMapping(is_global=True,prefix="1",backend_id=self.backend2._id)
        self.backend_mapping2.save()

        self.backend_mapping3 = BackendMapping(is_global=True,prefix="91",backend_id=self.backend3._id)
        self.backend_mapping3.save()

        self.backend_mapping4 = BackendMapping(is_global=True,prefix="265",backend_id=self.backend4._id)
        self.backend_mapping4.save()

        self.case = CommCareCase(domain=self.domain)
        self.case.set_case_property("contact_phone_number","15551234567")
        self.case.set_case_property("contact_phone_number_is_verified", "1")
        self.case.save()

        self.contact = CommConnectCase.wrap(self.case.to_json())

        settings.SMS_LOADED_BACKENDS.append("corehq.apps.sms.tests.TestCaseBackend")
Exemplo n.º 5
0
def get_contact(contact_id):
    from corehq.apps.sms.models import CommConnectCase
    contact = CommConnectCase.get(contact_id)
    if contact.doc_type != "CommCareCase":
        try:
            contact = CouchUser.get_by_user_id(contact_id)
        except CouchUser.AccountTypeError:
            raise Exception("Unkown contact type for contact %s" % contact_id)
    return contact
Exemplo n.º 6
0
def get_contact(contact_id):
    from corehq.apps.sms.models import CommConnectCase
    contact = CommConnectCase.get(contact_id)
    if contact.doc_type != "CommCareCase":
        try:
            contact = CouchUser.get_by_user_id(contact_id)
        except CouchUser.AccountTypeError:
            raise Exception("Unkown contact type for contact %s" % contact_id)
    return contact
    def handle(self, *args, **options):
        if len(args) == 0:
            raise CommandError("Usage: python manage.py check_case_verified_numbers <domain1 domain2 ...>")

        make_fixes = options["fix"]

        for domain in args:
            print "*** Processing Domain %s ***" % domain
            for case in get_cases_in_domain(domain):
                contact_phone_number = case.get_case_property("contact_phone_number")
                contact_phone_number_is_verified = case.get_case_property("contact_phone_number_is_verified")
                contact_backend_id = case.get_case_property("contact_backend_id")
                contact_ivr_backend_id = case.get_case_property("contact_ivr_backend_id")
                
                contact = CommConnectCase.wrap(case.to_json())
                verified_numbers = contact.get_verified_numbers(include_pending=True)
                
                should_have_entry = contact_phone_number_is_verified and contact_phone_number is not None and contact_phone_number != "" and str(contact_phone_number) != "0" and not case.closed
                has_entry = len(verified_numbers) > 0
                
                if len(verified_numbers) > 1:
                    print "skipping case %s, multiple verified number entries found" % case._id
                    continue
                
                if has_entry:
                    verified_number = sorted(verified_numbers.iteritems())[0][1]
                    if not verified_number.verified:
                        print "skipping case %s, unverified number found" % case._id
                        continue
                
                if has_entry and should_have_entry:
                    if verified_number.phone_number != contact_phone_number or verified_number.backend_id != contact_backend_id or verified_number.ivr_backend_id != contact_ivr_backend_id:
                        print "DISCREPANCY: case %s case properties don't match the verified number entry" % case._id
                        if make_fixes:
                            try:
                                contact.save_verified_number(contact.domain, contact_phone_number, True, contact_backend_id, ivr_backend_id=contact_ivr_backend_id, only_one_number_allowed=True)
                            except (InvalidFormatException, PhoneNumberInUseException):
                                contact.delete_verified_number()
                elif has_entry and not should_have_entry:
                    print "DISCREPANCY: case %s has a verified number but should not" % case._id
                    if make_fixes:
                        contact.delete_verified_number()
                elif not has_entry and should_have_entry:
                    try:
                        contact.verify_unique_number(contact_phone_number)
                    except InvalidFormatException:
                        print "DISCREPANCY: case %s does not have a verified number because number format is invalid" % case._id
                    except PhoneNumberInUseException:
                        print "DISCREPANCY: case %s does not have a verified number because number is already in use" % case._id
                    else:
                        print "DISCREPANCY: case %s does not have a verified number but should" % case._id
                        if make_fixes:
                            contact.save_verified_number(contact.domain, contact_phone_number, True, contact_backend_id, ivr_backend_id=contact_ivr_backend_id, only_one_number_allowed=True)
                else:
                    # Doesn't have an entry, and shouldn't have an entry
                    pass
Exemplo n.º 8
0
 def owner(self):
     if self.owner_doc_type == "CommCareCase":
         # Circular import
         from corehq.apps.sms.models import CommConnectCase
         return CommConnectCase.get(self.owner_id)
     elif self.owner_doc_type == "CommCareUser":
         # Circular import
         from corehq.apps.users.models import CommCareUser
         return CommCareUser.get(self.owner_id)
     else:
         return None
Exemplo n.º 9
0
 def owner(self):
     if self.owner_doc_type == "CommCareCase":
         # Circular import
         from corehq.apps.sms.models import CommConnectCase
         return CommConnectCase.get(self.owner_id)
     elif self.owner_doc_type == "CommCareUser":
         # Circular import
         from corehq.apps.users.models import CommCareUser
         return CommCareUser.get(self.owner_id)
     else:
         return None
Exemplo n.º 10
0
def device_data(request):
    if "data" not in request.POST:
        return HttpResponseBadRequest("Missing 'data' POST parameter.")

    data = request.POST.get("data")
    data = data.strip()
    data_points = data.split(",")
    device_id = None
    for data_point in data_points:
        key_value = data_point.partition("=")
        key = key_value[0].strip().upper()
        value = key_value[2].strip()
        if key == "SN":
            device_id = value
            break

    if device_id is None:
        return HttpResponseBadRequest("Missing 'SN' in data string.")

    # This view lookup is an implicit assert that either one device exists
    # with the given device_id, or no devices exist with this device_id.
    case = CommConnectCase.view("wisepill/device", key=[device_id], include_docs=True).one()

    event = WisePillDeviceEvent(
        domain=case.domain if case is not None else None,
        data=data,
        received_on=datetime.utcnow(),
        case_id=case._id if case is not None else None,
        processed=False,
    )
    event.save()

    if case is not None:
        survey_keywords = SurveyKeyword.get_all(case.domain)
        for survey_keyword in survey_keywords:
            if survey_keyword.keyword.upper() == "DEVICE_EVENT":
                for survey_keyword_action in survey_keyword.actions:
                    if survey_keyword_action.action == METHOD_STRUCTURED_SMS:
                        handle_structured_sms(
                            survey_keyword,
                            survey_keyword_action,
                            case,
                            None,
                            "DEVICE_EVENT,%s" % data,
                            send_response=False,
                        )
                        event.processed = True
                        event.save()
                        break

    return HttpResponse("")
Exemplo n.º 11
0
    def __test_contact_level_backend(self):
        # Test sending to verified number with a contact-level backend owned by the domain
        self.case.set_case_property('contact_backend_id', 'BACKEND')
        self.case.save()
        self.contact = CommConnectCase.wrap(self.case.to_json())
        verified_number = self.contact.get_verified_number()
        self.assertTrue(verified_number is not None)
        self.assertEqual(verified_number.backend_id, 'BACKEND')
        self.assertEqual(verified_number.phone_number, '15551234567')

        with patch(
            'corehq.messaging.smsbackends.test.models.SQLTestSMSBackend.send',
            autospec=True
        ) as mock_send:
            self.assertTrue(send_sms_to_verified_number(verified_number, 'Test for domain BACKEND'))
        self.assertEqual(mock_send.call_count, 1)
        self.assertEqual(mock_send.call_args[0][0].pk, self.backend8.pk)

        # Test sending to verified number with a contact-level backend granted to the domain by another domain
        self.backend8.name = 'BACKEND8'
        self.backend8.save()

        with patch(
            'corehq.messaging.smsbackends.test.models.SQLTestSMSBackend.send',
            autospec=True
        ) as mock_send:
            self.assertTrue(send_sms_to_verified_number(verified_number, 'Test for shared domain BACKEND'))
        self.assertEqual(mock_send.call_count, 1)
        self.assertEqual(mock_send.call_args[0][0].pk, self.backend9.pk)

        # Test sending to verified number with a contact-level global backend
        self.backend9.name = 'BACKEND9'
        self.backend9.save()

        with patch(
            'corehq.messaging.smsbackends.test.models.SQLTestSMSBackend.send',
            autospec=True
        ) as mock_send:
            self.assertTrue(send_sms_to_verified_number(verified_number, 'Test for global BACKEND'))
        self.assertEqual(mock_send.call_count, 1)
        self.assertEqual(mock_send.call_args[0][0].pk, self.backend10.pk)

        # Test raising exception if contact-level backend is not found
        self.backend10.name = 'BACKEND10'
        self.backend10.save()

        with self.assertRaises(BadSMSConfigException):
            send_sms_to_verified_number(verified_number, 'Test for unknown BACKEND')
Exemplo n.º 12
0
 def fire(self, reminder):
     """
     Sends the message associated with the given CaseReminder's current event.
     
     reminder    The CaseReminder which to fire.
     
     return      True on success, False on failure
     """
     # Prevent circular import
     from .event_handlers import EVENT_HANDLER_MAP
     
     # Retrieve the list of individual recipients
     recipient = reminder.recipient
     
     if isinstance(recipient, list) and len(recipient) > 0:
         recipients = recipient
     elif isinstance(recipient, CouchUser) or isinstance(recipient, CommCareCase):
         recipients = [recipient]
     elif isinstance(recipient, Group):
         recipients = recipient.get_users(is_active=True, only_commcare=False)
     elif isinstance(recipient, SurveySample):
         recipients = [CommConnectCase.get(case_id) for case_id in recipient.contacts]
     else:
         return False
     
     # Retrieve the corresponding verified number entries for all individual recipients
     verified_numbers = {}
     for r in recipients:
         try:
             contact_verified_numbers = r.get_verified_numbers(False)
             if len(contact_verified_numbers) > 0:
                 verified_number = sorted(contact_verified_numbers.iteritems())[0][1]
             else:
                 verified_number = None
         except Exception:
             verified_number = None
         verified_numbers[r.get_id] = verified_number
     
     # Set the event initiation timestamp if we're not on any timeouts
     if reminder.callback_try_count == 0:
         reminder.event_initiation_timestamp = self.get_now()
     
     # Call the appropriate event handler
     event_handler = EVENT_HANDLER_MAP.get(self.method)
     last_fired = self.get_now() # Store the timestamp right before firing to ensure continuity in the callback lookups
     result = event_handler(reminder, self, recipients, verified_numbers)
     reminder.last_fired = last_fired
     return result
Exemplo n.º 13
0
 def spawn_reminder(self, case, now, recipient=None):
     """
     Creates a CaseReminder.
     
     case    The CommCareCase for which to create the CaseReminder.
     now     The date and time to kick off the CaseReminder. This is the date and time from which all
             offsets are calculated.
     
     return  The CaseReminder
     """
     if recipient is None:
         if self.recipient == RECIPIENT_USER:
             recipient = CommCareUser.get_by_user_id(case.user_id)
         elif self.recipient == RECIPIENT_CASE:
             recipient = CommConnectCase.get(case._id)
     local_now = CaseReminderHandler.utc_to_local(recipient, now)
     
     case_id = case._id if case is not None else None
     user_id = case.user_id if case is not None else None
     sample_id = recipient._id if self.recipient == RECIPIENT_SURVEY_SAMPLE else None
     
     reminder = CaseReminder(
         domain=self.domain,
         case_id=case_id,
         handler_id=self._id,
         user_id=user_id,
         method=self.method,
         active=True,
         start_date=date(now.year, now.month, now.day) if (now.hour == 0 and now.minute == 0 and now.second == 0 and now.microsecond == 0) else date(local_now.year,local_now.month,local_now.day),
         schedule_iteration_num=1,
         current_event_sequence_num=0,
         callback_try_count=0,
         skip_remaining_timeouts=False,
         sample_id=sample_id,
         xforms_session_ids=[],
     )
     # Set the first fire time appropriately
     if self.event_interpretation == EVENT_AS_OFFSET:
         # EVENT_AS_OFFSET
         day_offset = self.start_offset + self.events[0].day_num
         time_offset = self.events[0].fire_time
         reminder.next_fire = now + timedelta(days=day_offset, hours=time_offset.hour, minutes=time_offset.minute, seconds=time_offset.second)
     else:
         # EVENT_AS_SCHEDULE
         reminder.next_fire = self.get_current_reminder_event_timestamp(reminder, recipient, case)
     return reminder
Exemplo n.º 14
0
def get_contact(contact_id):
    from corehq.apps.sms.models import CommConnectCase
    contact = None
    try:
        contact = CommConnectCase.get(contact_id)
    except ResourceNotFound:
        pass

    if contact and contact.doc_type == 'CommCareCase':
        return contact

    contact = None
    try:
        contact = CouchUser.get_by_user_id(contact_id)
    except CouchUser.AccountTypeError:
        pass

    if not contact:
        raise ContactNotFoundException("Contact not found")

    return contact
Exemplo n.º 15
0
 def spawn_reminder(self, case, now):
     """
     Creates a CaseReminder.
     
     case    The CommCareCase for which to create the CaseReminder.
     now     The date and time to kick off the CaseReminder. This is the date and time from which all
             offsets are calculated.
     
     return  The CaseReminder
     """
     if self.recipient == RECIPIENT_USER:
         recipient = CommCareUser.get_by_user_id(case.user_id)
     else:
         recipient = CommConnectCase.get(case._id)
     local_now = CaseReminderHandler.utc_to_local(recipient, now)
     reminder = CaseReminder(
         domain=self.domain,
         case_id=case._id,
         handler_id=self._id,
         user_id=case.user_id,
         method=self.method,
         active=True,
         start_date=date(now.year, now.month, now.day) if (now.hour == 0 and now.minute == 0 and now.second == 0 and now.microsecond == 0) else date(local_now.year,local_now.month,local_now.day),
         schedule_iteration_num=1,
         current_event_sequence_num=0,
         callback_try_count=0,
         callback_received=False
     )
     # Set the first fire time appropriately
     if self.event_interpretation == EVENT_AS_OFFSET:
         # EVENT_AS_OFFSET
         day_offset = self.start_offset + self.events[0].day_num
         time_offset = self.events[0].fire_time
         reminder.next_fire = now + timedelta(days=day_offset, hours=time_offset.hour, minutes=time_offset.minute, seconds=time_offset.second)
     else:
         # EVENT_AS_SCHEDULE
         local_tmsp = datetime.combine(reminder.start_date, self.events[0].fire_time) + timedelta(days = (self.start_offset + self.events[0].day_num))
         reminder.next_fire = CaseReminderHandler.timestamp_to_utc(recipient, local_tmsp)
     return reminder
Exemplo n.º 16
0
 def recipient(self):
     handler = self.handler
     if handler.recipient == RECIPIENT_USER:
         return self.user
     elif handler.recipient == RECIPIENT_CASE:
         return CommConnectCase.get(self.case_id)
     elif handler.recipient == RECIPIENT_SURVEY_SAMPLE:
         return SurveySample.get(self.sample_id)
     elif handler.recipient == RECIPIENT_OWNER:
         case = self.case
         
         owner_id = case.owner_id
         if owner_id is None:
             owner_id = case.user_id
         owner_doc = get_db().get(owner_id)
         
         if owner_doc["doc_type"] == "CommCareUser":
             return CommCareUser.get_by_user_id(owner_id)
         elif owner_doc["doc_type"] == "Group":
             return Group.get(owner_id)
         else:
             return None
     else:
         return None
Exemplo n.º 17
0
    def test_backend(self):
        # Test the backend map

        self.assertTrue(send_sms(self.domain, None, "15551234567", "Test for BACKEND2"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertTrue(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend2.delete_invoke_doc()
        self.assertFalse(self.backend2.invoke_doc_exists())

        self.assertTrue(send_sms(self.domain, None, "9100000000", "Test for BACKEND3"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertTrue(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend3.delete_invoke_doc()
        self.assertFalse(self.backend3.invoke_doc_exists())

        self.assertTrue(send_sms(self.domain, None, "26500000000", "Test for BACKEND4"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertTrue(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend4.delete_invoke_doc()
        self.assertFalse(self.backend4.invoke_doc_exists())

        self.assertTrue(send_sms(self.domain, None, "25800000000", "Test for BACKEND1"))
        self.assertTrue(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend1.delete_invoke_doc()
        self.assertFalse(self.backend1.invoke_doc_exists())

        # Test overriding with a domain-level backend

        self.domain_obj = Domain.get(self.domain_obj._id)  # Prevent resource conflict
        self.domain_obj.default_sms_backend_id = self.backend5._id
        self.domain_obj.save()

        self.assertTrue(send_sms(self.domain, None, "15551234567", "Test for BACKEND5"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertTrue(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend5.delete_invoke_doc()
        self.assertFalse(self.backend5.invoke_doc_exists())

        # Test use of backend that another domain owns but has granted access

        self.domain_obj.default_sms_backend_id = self.backend6._id
        self.domain_obj.save()

        self.assertTrue(send_sms(self.domain, None, "25800000000", "Test for BACKEND6"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertTrue(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend6.delete_invoke_doc()
        self.assertFalse(self.backend6.invoke_doc_exists())

        # Test backend access control

        self.domain_obj.default_sms_backend_id = self.backend7._id
        self.domain_obj.save()

        self.assertFalse(send_sms(self.domain, None, "25800000000", "Test for BACKEND7"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())

        # Test sending to verified number with backend map

        self.domain_obj.default_sms_backend_id = None
        self.domain_obj.save()

        verified_number = self.contact.get_verified_number()
        self.assertTrue(verified_number is not None)
        self.assertTrue(verified_number.backend_id is None)
        self.assertEqual(verified_number.phone_number, "15551234567")

        self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND2"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertTrue(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend2.delete_invoke_doc()
        self.assertFalse(self.backend2.invoke_doc_exists())

        # Test sending to verified number with default domain backend

        self.domain_obj.default_sms_backend_id = self.backend5._id
        self.domain_obj.save()

        self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND5"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertTrue(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertFalse(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend5.delete_invoke_doc()
        self.assertFalse(self.backend5.invoke_doc_exists())

        # Test sending to verified number with a contact-level backend owned by the domain

        self.case.set_case_property("contact_backend_id", "BACKEND")
        self.case.save()
        self.contact = CommConnectCase.wrap(self.case.to_json())
        verified_number = self.contact.get_verified_number()
        self.assertTrue(verified_number is not None)
        self.assertEqual(verified_number.backend_id, "BACKEND")
        self.assertEqual(verified_number.phone_number, "15551234567")

        self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertTrue(self.backend8.invoke_doc_exists())
        self.assertFalse(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend8.delete_invoke_doc()
        self.assertFalse(self.backend8.invoke_doc_exists())

        # Test sending to verified number with a contact-level backend granted to the domain by another domain

        self.backend8.delete()

        self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertTrue(self.backend9.invoke_doc_exists())
        self.assertFalse(self.backend10.invoke_doc_exists())
        self.backend9.delete_invoke_doc()
        self.assertFalse(self.backend9.invoke_doc_exists())

        # Test sending to verified number with a contact-level global backend

        self.backend9.delete()

        self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertFalse(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.assertTrue(self.backend10.invoke_doc_exists())
        self.backend10.delete_invoke_doc()
        self.assertFalse(self.backend10.invoke_doc_exists())

        # Test raising exception if contact-level backend is not found

        self.backend10.delete()

        try:
            self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND"))
        except BadSMSConfigException:
            pass
        else:
            self.assertTrue(False)

        # Test send_sms_with_backend

        self.assertTrue(send_sms_with_backend(self.domain, "+15551234567", "Test for BACKEND3", self.backend3._id))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertTrue(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.backend3.delete_invoke_doc()
        self.assertFalse(self.backend3.invoke_doc_exists())

        # Test send_sms_with_backend_name

        self.assertTrue(send_sms_with_backend_name(self.domain, "+15551234567", "Test for BACKEND3", "BACKEND3"))
        self.assertFalse(self.backend1.invoke_doc_exists())
        self.assertFalse(self.backend2.invoke_doc_exists())
        self.assertTrue(self.backend3.invoke_doc_exists())
        self.assertFalse(self.backend4.invoke_doc_exists())
        self.assertFalse(self.backend5.invoke_doc_exists())
        self.assertFalse(self.backend6.invoke_doc_exists())
        self.assertFalse(self.backend7.invoke_doc_exists())
        self.backend3.delete_invoke_doc()
        self.assertFalse(self.backend3.invoke_doc_exists())
Exemplo n.º 18
0
    def setUp(self):
        super(OutgoingFrameworkTestCase, self).setUp()

        self.domain = "test-domain"
        self.domain2 = "test-domain2"

        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()

        self.create_account_and_subscription(self.domain_obj.name)
        self.domain_obj = Domain.get(self.domain_obj._id)

        self.backend1 = SQLTestSMSBackend.objects.create(
            name='BACKEND1',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend2 = SQLTestSMSBackend.objects.create(
            name='BACKEND2',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend3 = SQLTestSMSBackend.objects.create(
            name='BACKEND3',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend4 = SQLTestSMSBackend.objects.create(
            name='BACKEND4',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend5 = SQLTestSMSBackend.objects.create(
            name='BACKEND5',
            domain=self.domain,
            is_global=False,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend6 = SQLTestSMSBackend.objects.create(
            name='BACKEND6',
            domain=self.domain2,
            is_global=False,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )
        self.backend6.set_shared_domains([self.domain])

        self.backend7 = SQLTestSMSBackend.objects.create(
            name='BACKEND7',
            domain=self.domain2,
            is_global=False,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend8 = SQLTestSMSBackend.objects.create(
            name='BACKEND',
            domain=self.domain,
            is_global=False,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend9 = SQLTestSMSBackend.objects.create(
            name='BACKEND',
            domain=self.domain2,
            is_global=False,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )
        self.backend9.set_shared_domains([self.domain])

        self.backend10 = SQLTestSMSBackend.objects.create(
            name='BACKEND',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )

        self.backend_mapping1 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='*',
            backend=self.backend1
        )

        self.backend_mapping2 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='1',
            backend=self.backend2
        )

        self.backend_mapping3 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='91',
            backend=self.backend3
        )

        self.backend_mapping4 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='265',
            backend=self.backend4
        )

        self.backend_mapping5 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='256',
            backend=self.backend5
        )

        self.backend_mapping6 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='25670',
            backend=self.backend6
        )

        self.backend_mapping7 = SQLMobileBackendMapping.objects.create(
            is_global=True,
            backend_type=SQLMobileBackend.SMS,
            prefix='25675',
            backend=self.backend7
        )

        self.case = CommCareCase(domain=self.domain)
        self.case.set_case_property('contact_phone_number', '15551234567')
        self.case.set_case_property('contact_phone_number_is_verified', '1')
        self.case.save()

        self.contact = CommConnectCase.wrap(self.case.to_json())
Exemplo n.º 19
0
    def setUp(self):
        super(AllBackendTest, self).setUp()

        self.domain_obj = Domain(name='all-backend-test')
        self.domain_obj.save()
        self.create_account_and_subscription(self.domain_obj.name)
        self.domain_obj = Domain.get(self.domain_obj._id)

        self.test_phone_number = '99912345'
        self.contact1 = CommCareCase(domain=self.domain_obj.name)
        self.contact1.set_case_property('contact_phone_number', self.test_phone_number)
        self.contact1.set_case_property('contact_phone_number_is_verified', '1')
        self.contact1.save()
        self.contact1 = CommConnectCase.wrap(self.contact1.to_json())

        # For use with megamobile only
        self.contact2 = CommCareCase(domain=self.domain_obj.name)
        self.contact2.set_case_property('contact_phone_number', '63%s' % self.test_phone_number)
        self.contact2.set_case_property('contact_phone_number_is_verified', '1')
        self.contact2.save()
        self.contact2 = CommConnectCase.wrap(self.contact2.to_json())

        self.unicel_backend = SQLUnicelBackend(
            name='UNICEL',
            is_global=True,
            hq_api_id=SQLUnicelBackend.get_api_id()
        )
        self.unicel_backend.save()

        self.mach_backend = SQLMachBackend(
            name='MACH',
            is_global=True,
            hq_api_id=SQLMachBackend.get_api_id()
        )
        self.mach_backend.save()

        self.tropo_backend = SQLTropoBackend(
            name='TROPO',
            is_global=True,
            hq_api_id=SQLTropoBackend.get_api_id()
        )
        self.tropo_backend.save()

        self.http_backend = SQLHttpBackend(
            name='HTTP',
            is_global=True,
            hq_api_id=SQLHttpBackend.get_api_id()
        )
        self.http_backend.save()

        self.telerivet_backend = SQLTelerivetBackend(
            name='TELERIVET',
            is_global=True,
            hq_api_id=SQLTelerivetBackend.get_api_id()
        )
        self.telerivet_backend.set_extra_fields(
            **dict(
                webhook_secret='telerivet-webhook-secret'
            )
        )
        self.telerivet_backend.save()

        self.test_backend = SQLTestSMSBackend(
            name='TEST',
            is_global=True,
            hq_api_id=SQLTestSMSBackend.get_api_id()
        )
        self.test_backend.save()

        self.grapevine_backend = SQLGrapevineBackend(
            name='GRAPEVINE',
            is_global=True,
            hq_api_id=SQLGrapevineBackend.get_api_id()
        )
        self.grapevine_backend.save()

        self.twilio_backend = SQLTwilioBackend(
            name='TWILIO',
            is_global=True,
            hq_api_id=SQLTwilioBackend.get_api_id()
        )
        self.twilio_backend.save()

        self.megamobile_backend = SQLMegamobileBackend(
            name='MEGAMOBILE',
            is_global=True,
            hq_api_id=SQLMegamobileBackend.get_api_id()
        )
        self.megamobile_backend.save()

        self.smsgh_backend = SQLSMSGHBackend(
            name='SMSGH',
            is_global=True,
            hq_api_id=SQLSMSGHBackend.get_api_id()
        )
        self.smsgh_backend.save()

        self.apposit_backend = SQLAppositBackend(
            name='APPOSIT',
            is_global=True,
            hq_api_id=SQLAppositBackend.get_api_id()
        )
        self.apposit_backend.save()

        self.sislog_backend = SQLSislogBackend(
            name='SISLOG',
            is_global=True,
            hq_api_id=SQLSislogBackend.get_api_id()
        )
        self.sislog_backend.save()

        self.yo_backend = SQLYoBackend(
            name='YO',
            is_global=True,
            hq_api_id=SQLYoBackend.get_api_id()
        )
        self.yo_backend.save()
Exemplo n.º 20
0
 def get_case_verified_number(self, case):
     return CommConnectCase.wrap_as_commconnect_case(case).get_verified_number()
Exemplo n.º 21
0
 def test_load_session_data_for_commconnect_case(self):
     user = CommConnectCase(name='A case', _id=uuid.uuid4().hex)
     data = get_user_contributions_to_touchforms_session(user)
     self.assertEqual('A case', data['username'])
     self.assertEqual(user._id, data['user_id'])
     self.assertEqual({}, data['user_data'])
Exemplo n.º 22
0
 def recipient(self):
     if self.handler.recipient == RECIPIENT_USER:
         return self.user
     else:
         return CommConnectCase.get(self.case_id)
Exemplo n.º 23
0
def sync_case_phone_number(self, case):
    try:
        contact = CommConnectCase.wrap_as_commconnect_case(case)
        _sync_case_phone_number(contact)
    except Exception as e:
        self.retry(exc=e)
Exemplo n.º 24
0
    def setUp(self):
        super(BackendTestCase, self).setUp()

        self.domain = "test-domain"
        self.domain2 = "test-domain2"

        self.site, self.site_created = self.get_or_create_site()

        self.domain_obj = Domain(name=self.domain)
        self.domain_obj.save()

        generator.instantiate_accounting_for_tests()
        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain_obj.name, created_by="automated-test"
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(self.domain_obj, edition=SoftwarePlanEdition.ADVANCED)
        self.subscription = Subscription.new_domain_subscription(self.account, self.domain_obj.name, plan)
        self.subscription.is_active = True
        self.subscription.save()
        self.domain_obj = Domain.get(self.domain_obj._id)  # Prevent resource conflict

        self.backend1 = TestCaseBackend(name="BACKEND1", is_global=True)
        self.backend1.save()

        self.backend2 = TestCaseBackend(name="BACKEND2", is_global=True)
        self.backend2.save()

        self.backend3 = TestCaseBackend(name="BACKEND3", is_global=True)
        self.backend3.save()

        self.backend4 = TestCaseBackend(name="BACKEND4", is_global=True)
        self.backend4.save()

        self.backend5 = TestCaseBackend(name="BACKEND5", domain=self.domain, is_global=False, authorized_domains=[])
        self.backend5.save()

        self.backend6 = TestCaseBackend(
            name="BACKEND6", domain=self.domain2, is_global=False, authorized_domains=[self.domain]
        )
        self.backend6.save()

        self.backend7 = TestCaseBackend(name="BACKEND7", domain=self.domain2, is_global=False, authorized_domains=[])
        self.backend7.save()

        self.backend8 = TestCaseBackend(name="BACKEND", domain=self.domain, is_global=False, authorized_domains=[])
        self.backend8.save()

        self.backend9 = TestCaseBackend(
            name="BACKEND", domain=self.domain2, is_global=False, authorized_domains=[self.domain]
        )
        self.backend9.save()

        self.backend10 = TestCaseBackend(name="BACKEND", is_global=True)
        self.backend10.save()

        self.backend_mapping1 = BackendMapping(is_global=True, prefix="*", backend_id=self.backend1._id)
        self.backend_mapping1.save()

        self.backend_mapping2 = BackendMapping(is_global=True, prefix="1", backend_id=self.backend2._id)
        self.backend_mapping2.save()

        self.backend_mapping3 = BackendMapping(is_global=True, prefix="91", backend_id=self.backend3._id)
        self.backend_mapping3.save()

        self.backend_mapping4 = BackendMapping(is_global=True, prefix="265", backend_id=self.backend4._id)
        self.backend_mapping4.save()

        self.backend_mapping5 = BackendMapping(is_global=True, prefix="256", backend_id=self.backend5._id)
        self.backend_mapping5.save()

        self.backend_mapping6 = BackendMapping(is_global=True, prefix="25670", backend_id=self.backend6._id)
        self.backend_mapping6.save()

        self.backend_mapping7 = BackendMapping(is_global=True, prefix="25675", backend_id=self.backend7._id)
        self.backend_mapping7.save()

        self.case = CommCareCase(domain=self.domain)
        self.case.set_case_property("contact_phone_number", "15551234567")
        self.case.set_case_property("contact_phone_number_is_verified", "1")
        self.case.save()

        self.contact = CommConnectCase.wrap(self.case.to_json())

        settings.SMS_LOADED_BACKENDS.append("corehq.apps.sms.tests.TestCaseBackend")