def test_agency_user_case_from_voucher_fulfilled_by_id(self):
        prescription = self.create_prescription_case()
        voucher = self.create_voucher_case(prescription.case_id)

        self.assertIsNone(
            agency_user_case_from_voucher_fulfilled_by_id(
                None,
                CaseReminder(domain=self.domain)
            )
        )

        self.assertIsNone(
            agency_user_case_from_voucher_fulfilled_by_id(
                None,
                CaseReminder(domain=self.domain, case_id=voucher.case_id)
            )
        )

        user = CommCareUser.create(self.domain, 'mobile', 'password')
        update_case(self.domain, voucher.case_id, case_properties={'voucher_fulfilled_by_id': user.get_id})

        with create_user_case(user) as user_case:
            self.assertEqual(
                agency_user_case_from_voucher_fulfilled_by_id(
                    None,
                    CaseReminder(domain=self.domain, case_id=voucher.case_id)
                ).case_id,
                user_case.case_id
            )
Beispiel #2
0
def reminders_in_error(request, domain):
    handler_map = {}
    if request.method == "POST":
        form = RemindersInErrorForm(request.POST)
        if form.is_valid():
            kwargs = {}
            if is_bigcouch():
                # Force a write to all nodes before returning
                kwargs["w"] = bigcouch_quorum_count()
            current_timestamp = datetime.utcnow()
            for reminder_id in form.cleaned_data.get("selected_reminders"):
                reminder = CaseReminder.get(reminder_id)
                if reminder.domain != domain:
                    continue
                if reminder.handler_id in handler_map:
                    handler = handler_map[reminder.handler_id]
                else:
                    handler = reminder.handler
                    handler_map[reminder.handler_id] = handler
                reminder.error = False
                reminder.error_msg = None
                handler.set_next_fire(reminder, current_timestamp)
                reminder.save(**kwargs)

    timezone = report_utils.get_timezone(request.couch_user.user_id, domain)
    reminders = []
    for reminder in CaseReminder.view("reminders/reminders_in_error",
                                      startkey=[domain],
                                      endkey=[domain, {}],
                                      include_docs=True).all():
        if reminder.handler_id in handler_map:
            handler = handler_map[reminder.handler_id]
        else:
            handler = reminder.handler
            handler_map[reminder.handler_id] = handler
        recipient = reminder.recipient
        case = reminder.case
        reminders.append({
            "reminder_id":
            reminder._id,
            "handler_id":
            reminder.handler_id,
            "handler_name":
            handler.nickname,
            "case_id":
            case.get_id if case is not None else None,
            "case_name":
            case.name if case is not None else None,
            "next_fire":
            tz_utils.adjust_datetime_to_timezone(
                reminder.next_fire, pytz.utc.zone,
                timezone.zone).strftime("%Y-%m-%d %H:%M:%S"),
            "error_msg":
            reminder.error_msg,
            "recipient_name":
            get_recipient_name(recipient),
        })
Beispiel #3
0
def reminders_in_error(request, domain):
    handler_map = {}
    if request.method == "POST":
        form = RemindersInErrorForm(request.POST)
        if form.is_valid():
            kwargs = {}
            if is_bigcouch():
                # Force a write to all nodes before returning
                kwargs["w"] = bigcouch_quorum_count()
            current_timestamp = datetime.utcnow()
            for reminder_id in form.cleaned_data.get("selected_reminders"):
                reminder = CaseReminder.get(reminder_id)
                if reminder.domain != domain:
                    continue
                if reminder.handler_id in handler_map:
                    handler = handler_map[reminder.handler_id]
                else:
                    handler = reminder.handler
                    handler_map[reminder.handler_id] = handler
                reminder.error = False
                reminder.error_msg = None
                handler.set_next_fire(reminder, current_timestamp)
                reminder.save(**kwargs)
    
    timezone = report_utils.get_timezone(request.couch_user.user_id, domain)
    reminders = []
    for reminder in CaseReminder.view("reminders/reminders_in_error", startkey=[domain], endkey=[domain, {}], include_docs=True).all():
        if reminder.handler_id in handler_map:
            handler = handler_map[reminder.handler_id]
        else:
            handler = reminder.handler
            handler_map[reminder.handler_id] = handler
        recipient = reminder.recipient
        case = reminder.case
        reminders.append({
            "reminder_id" : reminder._id,
            "handler_id" : reminder.handler_id,
            "handler_name" : handler.nickname,
            "case_id" : case.get_id if case is not None else None,
            "case_name" : case.name if case is not None else None,
            "next_fire" : tz_utils.adjust_datetime_to_timezone(reminder.next_fire, pytz.utc.zone, timezone.zone).strftime("%Y-%m-%d %H:%M:%S"),
            "error_msg" : reminder.error_msg,
            "recipient_name" : get_recipient_name(recipient),
        })
    context = {
        "domain" : domain,
        "reminders" : reminders,
        "timezone" : timezone,
        "timezone_now" : datetime.now(tz=timezone),
    }
    return render(request, "reminders/partial/reminders_in_error.html", context)
Beispiel #4
0
    def test_recipient_case_owner_location_parent(self):
        parent_location = SQLLocation.objects.create(
            domain=self.domain,
            name='parent test',
            site_code='parent',
            location_type=self.parent_location_type)

        child_location = SQLLocation.objects.create(
            domain=self.domain,
            name='child test',
            site_code='child',
            location_type=self.child_location_type,
            parent=parent_location)

        self.user.set_location(child_location.couch_location)

        with create_test_case(self.domain,
                              'test-case',
                              'test-name',
                              owner_id=self.user.get_id) as case:
            self.assertEqual(case.owner_id, self.user.get_id)
            handler = CaseReminderHandler(
                domain=self.domain,
                recipient=RECIPIENT_CASE_OWNER_LOCATION_PARENT)
            reminder = CaseReminder(domain=self.domain, case_id=case.case_id)

            # Test the recipient is returned correctly
            with patch('corehq.apps.reminders.models.CaseReminder.handler',
                       new=handler):
                self.assertEqual(reminder.recipient, [parent_location])

            # Remove parent location
            parent_location.delete()
            child_location.parent = None
            child_location.save()
            with patch('corehq.apps.reminders.models.CaseReminder.handler',
                       new=handler):
                self.assertIsNone(reminder.recipient)

            # Remove child location
            self.user.unset_location()
            child_location.delete()
            with patch('corehq.apps.reminders.models.CaseReminder.handler',
                       new=handler):
                self.assertIsNone(reminder.recipient)

            # Remove case
            reminder.case_id = None
            with patch('corehq.apps.reminders.models.CaseReminder.handler',
                       new=handler):
                self.assertIsNone(reminder.recipient)
    def test_person_case_from_voucher_case(self):
        prescription = self.create_prescription_case()
        voucher = self.create_voucher_case(prescription.case_id)

        self.assertIsNone(
            person_case_from_voucher_case(None, CaseReminder(domain=self.domain))
        )

        self.assertIsNone(
            person_case_from_voucher_case(None, CaseReminder(domain=self.domain, case_id=prescription.case_id))
        )

        self.assertEqual(
            person_case_from_voucher_case(None, CaseReminder(domain=self.domain, case_id=voucher.case_id)).case_id,
            self.person_id
        )
Beispiel #6
0
def get_reminder_domain(reminder_id):
    """
    A reminder instance's domain should never change once set, so
    we can use a very long timeout.
    """
    from corehq.apps.reminders.models import CaseReminder
    return CaseReminder.get(reminder_id).domain
 def get_source_instances(self):
     return list(
         CaseReminder.view(
             'reminders/by_domain_handler_case',
             startkey=[self.handler.domain, self.handler._id],
             endkey=[self.handler.domain, self.handler._id, {}],
             include_docs=True).all())
    def get_broadcast_migration_function(self, handler):
        if handler.method not in (METHOD_SMS, METHOD_EMAIL, METHOD_SMS_SURVEY):
            return None

        if len(handler.events) != 1:
            return None

        if handler.method in (METHOD_SMS, METHOD_EMAIL) and len(
                handler.events[0].message) != 1:
            return None

        if handler.method == METHOD_EMAIL and len(
                handler.events[0].subject) != 1:
            return None

        if handler.recipient not in (
                RECIPIENT_SURVEY_SAMPLE,
                RECIPIENT_USER_GROUP,
                RECIPIENT_LOCATION,
        ):
            return None

        if handler.recipient == RECIPIENT_SURVEY_SAMPLE and not handler.sample_id:
            return None

        if handler.recipient == RECIPIENT_USER_GROUP and not handler.user_group_id:
            return None

        if handler.recipient == RECIPIENT_LOCATION and len(
                handler.location_ids) != 1:
            return None

        if handler.locked:
            return None

        if handler.start_condition_type != ON_DATETIME:
            return None

        if handler.user_data_filter:
            return None

        reminder_result = list(
            CaseReminder.view('reminders/by_domain_handler_case',
                              startkey=[handler.domain, handler._id],
                              endkey=[handler.domain, handler._id, {}],
                              include_docs=True).all())

        if len(reminder_result) > 1:
            return None

        if ((len(reminder_result) == 0 or not reminder_result[0].active)
                and handler.start_datetime
                and handler.start_datetime < datetime.utcnow()
                and handler.event_interpretation == EVENT_AS_OFFSET
                and handler.max_iteration_count == 1
                and handler.events[0].day_num == 0
                and handler.events[0].fire_time == time(0, 0)):
            return migrate_past_immediate_broadcast

        return None
Beispiel #9
0
def get_reminder_domain(reminder_id):
    """
    A reminder instance's domain should never change once set, so
    we can use a very long timeout.
    """
    from corehq.apps.reminders.models import CaseReminder
    return CaseReminder.get(reminder_id).domain
Beispiel #10
0
def _fire_reminder(reminder_id):
    utcnow = datetime.utcnow()
    reminder = CaseReminder.get(reminder_id)
    # This key prevents doc update conflicts with rule running
    key = "rule-update-definition-%s-case-%s" % (reminder.handler_id, reminder.case_id)
    with CriticalSection([key], timeout=(settings.REMINDERS_QUEUE_PROCESSING_LOCK_TIMEOUT * 60)):
        # Refresh the reminder
        reminder = CaseReminder.get(reminder_id)
        if not reminder.retired and reminder.active and utcnow >= reminder.next_fire:
            handler = reminder.handler
            if reminder_is_stale(reminder, utcnow):
                handler.set_next_fire(reminder, utcnow)
                reminder.save()
                return
            if handler.fire(reminder):
                handler.set_next_fire(reminder, utcnow)
                reminder.save()
 def _test_prescription_voucher_alert_with_language(self, voucher,
                                                    language_code,
                                                    expected_message):
     self.assertEqual(
         prescription_voucher_alert(CaseReminder(case_id=voucher.case_id),
                                    CaseReminderHandler(default_lang='en'),
                                    FakeRecipient(language_code)),
         expected_message)
Beispiel #12
0
    def handle(self, **options):
        num_dups = 0
        make_fixes = options["fix"]
        ids = {}
        rows = CaseReminder.view("reminders/by_domain_handler_case",
                                 include_docs=False).all()

        for row in rows:
            row_key = row["key"]
            if row_key[2]:
                ids_key = "|".join(row_key)
                if ids_key in ids:
                    ids[ids_key].append(row["id"])
                else:
                    ids[ids_key] = [row["id"]]

        for k, v in ids.items():
            if len(v) > 1:
                num_dups += 1
                split_key = k.split("|")
                print("Duplicate found: ", split_key)

                handler = CaseReminderHandler.get(split_key[1])
                if handler.start_condition_type != CASE_CRITERIA:
                    print("ERROR: Duplicate with the above key is not a case "
                          "criteria reminder")
                    continue

                all_match = True
                reminders = [CaseReminder.get(i) for i in v]
                for r in reminders[1:]:
                    all_match = all_match and self.reminders_match(
                        reminders[0], r)
                if all_match:
                    if make_fixes:
                        print("Removing duplicate(s)...")
                        for r in reminders[1:]:
                            r.retire()
                        c = CommCareCase.get(split_key[2])
                        messaging_case_changed_receiver(None, c)
                else:
                    print(
                        "ERROR: Not all of the reminders with the above key match"
                    )

        print("%s Duplicate(s) were found" % num_dups)
Beispiel #13
0
 def get_items_to_be_processed(self, utcnow):
     utcnow_json = json_format_datetime(utcnow)
     result = CaseReminder.view('reminders/by_next_fire',
         startkey=[None],
         endkey=[None, utcnow_json],
         include_docs=False,
     ).all()
     return [{"id": e["id"], "key": e["key"][1]} for e in result]
 def get_items_to_be_processed(self, utcnow):
     utcnow_json = json_format_datetime(utcnow)
     result = CaseReminder.view('reminders/by_next_fire',
         startkey=[None],
         endkey=[None, utcnow_json],
         include_docs=False,
     ).all()
     return [QueueItem(e['id'], e['key'], e) for e in result]
 def get_items_to_be_processed(self, utcnow):
     utcnow_json = json_format_datetime(utcnow)
     result = CaseReminder.view('reminders/by_next_fire',
         startkey=[None],
         endkey=[None, utcnow_json],
         include_docs=False,
     ).all()
     return [{"id": e["id"], "key": e["key"][1]} for e in result]
Beispiel #16
0
def delete_reminders_for_cases(domain, case_ids):
    handler_ids = CaseReminderHandler.get_handler_ids(
        domain, reminder_type_filter=REMINDER_TYPE_DEFAULT)
    for ids in chunked(case_ids, 50):
        keys = [[domain, handler_id, case_id] for handler_id in handler_ids
                for case_id in ids]
        results = CaseReminder.get_db().view(
            'reminders/by_domain_handler_case', keys=keys, include_docs=True)
        soft_delete_docs([row['doc'] for row in results], CaseReminder)
    def test_recipient_case_owner_location_parent(self):
        parent_location = SQLLocation.objects.create(
            domain=self.domain,
            name='parent test',
            site_code='parent',
            location_type=self.parent_location_type
        )

        child_location = SQLLocation.objects.create(
            domain=self.domain,
            name='child test',
            site_code='child',
            location_type=self.child_location_type,
            parent=parent_location
        )

        self.user.set_location(child_location.couch_location)

        with create_test_case(self.domain, 'test-case', 'test-name', owner_id=self.user.get_id) as case:
            self.assertEqual(case.owner_id, self.user.get_id)
            handler = CaseReminderHandler(domain=self.domain, recipient=RECIPIENT_CASE_OWNER_LOCATION_PARENT)
            reminder = CaseReminder(domain=self.domain, case_id=case.case_id)

            # Test the recipient is returned correctly
            with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler):
                self.assertEqual(reminder.recipient, [parent_location])

            # Remove parent location
            parent_location.delete()
            child_location.parent = None
            child_location.save()
            with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler):
                self.assertIsNone(reminder.recipient)

            # Remove child location
            self.user.unset_location()
            child_location.delete()
            with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler):
                self.assertIsNone(reminder.recipient)

            # Remove case
            reminder.case_id = None
            with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler):
                self.assertIsNone(reminder.recipient)
Beispiel #18
0
def _fire_reminder(reminder_id):
    utcnow = datetime.utcnow()
    reminder = CaseReminder.get(reminder_id)
    # This key prevents doc update conflicts with rule running
    key = "rule-update-definition-%s-case-%s" % (reminder.handler_id, reminder.case_id)
    with CriticalSection([key],
        timeout=(settings.REMINDERS_QUEUE_PROCESSING_LOCK_TIMEOUT*60)):
        # Refresh the reminder
        reminder = CaseReminder.get(reminder_id)
        if (not reminder.retired and reminder.active
            and utcnow >= reminder.next_fire):
            handler = reminder.handler
            if reminder_is_stale(reminder, utcnow):
                handler.set_next_fire(reminder, utcnow)
                reminder.save()
                return
            if handler.fire(reminder):
                handler.set_next_fire(reminder, utcnow)
                reminder.save()
    def handle(self, *args, **options):
        num_dups = 0
        make_fixes = options["fix"]
        ids = {}
        rows = CaseReminder.view("reminders/by_domain_handler_case",
            include_docs=False).all()

        for row in rows:
            row_key = row["key"]
            if row_key[2]:
                ids_key = "|".join(row_key)
                if ids_key in ids:
                    ids[ids_key].append(row["id"])
                else:
                    ids[ids_key] = [row["id"]]

        for k, v in ids.items():
            if len(v) > 1:
                num_dups += 1
                split_key = k.split("|")
                print "Duplicate found: ", split_key

                handler = CaseReminderHandler.get(split_key[1])
                if handler.start_condition_type != CASE_CRITERIA:
                    print ("ERROR: Duplicate with the above key is not a case "
                        "criteria reminder")
                    continue

                all_match = True
                reminders = [CaseReminder.get(i) for i in v]
                for r in reminders[1:]:
                    all_match = all_match and self.reminders_match(reminders[0], r)
                if all_match:
                    if make_fixes:
                        print "Removing duplicate(s)..."
                        for r in reminders[1:]:
                            r.retire()
                        c = CommCareCase.get(split_key[2])
                        case_changed_receiver(None, c)
                else:
                    print "ERROR: Not all of the reminders with the above key match"

        print "%s Duplicate(s) were found" % num_dups
    def test_prescription_voucher_alert_recipients(self):
        located_in_mehsana.clear(self.phi)
        self.dto.site_code = LOCATION_SITE_CODE_MEHSANA
        self.dto.save()
        self.assign_person_to_location(self.phi.location_id)

        prescription = self.create_prescription_case()
        voucher = self.create_voucher_case(prescription.case_id)

        user = CommCareUser.create(self.domain, 'mobile', 'password', location=self.phi)

        # No user case created yet
        result = prescription_voucher_alert_recipients(
            None,
            CaseReminder(domain=self.domain, case_id=voucher.case_id)
        )
        self.assertTrue(isinstance(result, CommCareCaseSQL))
        self.assertEqual(result.case_id, self.person_id)

        # Create user case
        with create_user_case(user) as user_case:
            result = prescription_voucher_alert_recipients(
                None,
                CaseReminder(domain=self.domain, case_id=voucher.case_id)
            )
            self.assertTrue(isinstance(result, list))
            self.assertEqual(
                [case.case_id for case in result],
                [self.person_id, user_case.case_id]
            )

            # Test location outside Mehsana
            located_in_mehsana.clear(self.phi)
            self.dto.site_code = 'dto-other'
            self.dto.save()

            result = prescription_voucher_alert_recipients(
                None,
                CaseReminder(domain=self.domain, case_id=voucher.case_id)
            )
            self.assertTrue(isinstance(result, CommCareCaseSQL))
            self.assertEqual(result.case_id, self.person_id)
Beispiel #21
0
def delete_reminders_for_cases(domain, case_ids):
    handler_ids = CaseReminderHandler.get_handler_ids(
        domain, reminder_type_filter=REMINDER_TYPE_DEFAULT)
    for ids in chunked(case_ids, 50):
        keys = [[domain, handler_id, case_id]
                for handler_id in handler_ids
                for case_id in ids]
        results = CaseReminder.get_db().view(
            'reminders/by_domain_handler_case',
            keys=keys,
            include_docs=True
        )
        soft_delete_docs([row['doc'] for row in results], CaseReminder)
Beispiel #22
0
    def test_beneficiary_registration_recipients(self):
        located_in_mehsana.clear(self.phi)
        self.dto.site_code = LOCATION_SITE_CODE_MEHSANA
        self.dto.save()
        self.assign_person_to_location(self.phi.location_id)

        update_case(self.domain,
                    self.person_id,
                    case_properties={'fo': self.pcc.location_id})
        user = CommCareUser.create(self.domain,
                                   'mobile',
                                   'password',
                                   location=self.pcc)

        # No user case created yet
        result = beneficiary_registration_recipients(
            None, CaseReminder(domain=self.domain, case_id=self.person_id))
        self.assertTrue(isinstance(result, CommCareCaseSQL))
        self.assertEqual(result.case_id, self.person_id)

        # Create user case
        with self.create_user_case(user) as user_case:
            result = beneficiary_registration_recipients(
                None, CaseReminder(domain=self.domain, case_id=self.person_id))
            self.assertTrue(isinstance(result, list))
            self.assertEqual([case.case_id for case in result],
                             [self.person_id, user_case.case_id])

            # Test location outside Mehsana
            located_in_mehsana.clear(self.phi)
            self.dto.site_code = 'dto-other'
            self.dto.save()

            result = beneficiary_registration_recipients(
                None, CaseReminder(domain=self.domain, case_id=self.person_id))
            self.assertTrue(isinstance(result, CommCareCaseSQL))
            self.assertEqual(result.case_id, self.person_id)
 def get_reminders(self):
     return CaseReminder.view('reminders/by_domain_handler_case',
         start_key=[self.domain],
         end_key=[self.domain, {}],
         include_docs=True).all()
 def get_all_reminders(self):
     return CaseReminder.view('reminders/by_domain_handler_case',
         include_docs=True).all()
    def test_reminder_delete(self):
        reminder = (CaseReminderHandler
            .create(self.domain, 'test')
            .set_case_criteria_start_condition('participant', 'status', MATCH_EXACT, 'green')
            .set_case_criteria_start_date()
            .set_case_recipient()
            .set_sms_content_type('en')
            .set_daily_schedule(fire_time=time(12, 0),
                message={'en': 'Hello {case.name}, your test result was normal.'})
            .set_stop_condition(max_iteration_count=REPEAT_SCHEDULE_INDEFINITELY)
            .set_advanced_options())
        reminder.save()

        r1 = CaseReminder(domain=self.domain, handler_id=reminder.get_id)
        r2 = CaseReminder(domain=self.domain, handler_id='abc')
        r3 = CaseReminder(domain='def', handler_id='ghi')

        r1.save()
        r2.save()
        r3.save()

        self.assertEqual(len(self.get_all_reminders()), 3)
        reminder.retire()
        self.assertEqual(len(self.get_all_reminders()), 2)

        r1 = CaseReminder.get(r1.get_id)
        r2 = CaseReminder.get(r2.get_id)
        r3 = CaseReminder.get(r3.get_id)

        self.assertEqual(r1.doc_type, 'CaseReminder-Deleted')
        self.assertEqual(r2.doc_type, 'CaseReminder')
        self.assertEqual(r3.doc_type, 'CaseReminder')
    def test_ok(self):
        with create_test_case(self.domain,
                              'case_type_a',
                              'test-case',
                              drop_signals=False,
                              user_id=self.user.get_id) as case:

            # Test changing a start condition which is a string
            # Spawn the reminder with an "ok" start condition value
            CaseReminderHandler.now = datetime(year=2012,
                                               month=2,
                                               day=17,
                                               hour=12,
                                               minute=0)
            self.assertIsNone(self.handler1.get_reminder(case))

            update_case(self.domain,
                        case.case_id, {'start_sending1': 'ok'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(
                reminder.next_fire, CaseReminderHandler.now +
                timedelta(days=self.handler1.start_offset))

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'case_property1': 'abc'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Test retiring the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'start_sending1': ''},
                        user_id=self.user.get_id)

            self.assertIsNone(self.handler1.get_reminder(case))
            self.assertEqual(
                CaseReminder.get(old_reminder_id).doc_type,
                "CaseReminder-Deleted")

            # Test changing a start condition which is a date value
            # Spawn the reminder with date start condition value
            update_case(self.domain,
                        case.case_id, {'start_sending1': '2012-02-20'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 20) +
                timedelta(days=self.handler1.start_offset))

            # Reset the date start condition
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'start_sending1': '2012-02-22'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 22) +
                timedelta(days=self.handler1.start_offset))
            self.assertEqual(
                CaseReminder.get(old_reminder_id).doc_type,
                "CaseReminder-Deleted")

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'case_property1': 'abc'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Retire the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'start_sending1': ''},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNone(reminder)
            self.assertEqual(
                CaseReminder.get(old_reminder_id).doc_type,
                "CaseReminder-Deleted")

            # Test changing a start condition which is a string representation of a datetime value
            # Spawn the reminder with datetime start condition value
            update_case(self.domain,
                        case.case_id, {'start_sending1': '2012-02-25 11:15'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 25, 11, 15) +
                timedelta(days=self.handler1.start_offset))

            # Reset the datetime start condition
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'start_sending1': '2012-02-26 11:20'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 26, 11, 20) +
                timedelta(days=self.handler1.start_offset))
            self.assertEqual(
                CaseReminder.get(old_reminder_id).doc_type,
                "CaseReminder-Deleted")

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'case_property1': 'xyz'},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Retire the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain,
                        case.case_id, {'start_sending1': ''},
                        user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNone(reminder)
            self.assertEqual(
                CaseReminder.get(old_reminder_id).doc_type,
                "CaseReminder-Deleted")
Beispiel #27
0
 def get_reminders(self):
     return CaseReminder.view('reminders/by_domain_handler_case',
         startkey=[self.domain],
         endkey=[self.domain, {}],
         include_docs=True).all()
Beispiel #28
0
 def get_all_reminders(self):
     return CaseReminder.view('reminders/by_domain_handler_case',
         include_docs=True).all()
Beispiel #29
0
    def test_reminder_delete(self):
        reminder = (CaseReminderHandler
            .create(self.domain, 'test')
            .set_case_criteria_start_condition('participant', 'status', MATCH_EXACT, 'green')
            .set_case_criteria_start_date()
            .set_case_recipient()
            .set_sms_content_type('en')
            .set_daily_schedule(fire_time=time(12, 0),
                message={'en': 'Hello {case.name}, your test result was normal.'})
            .set_stop_condition(max_iteration_count=REPEAT_SCHEDULE_INDEFINITELY)
            .set_advanced_options())
        reminder.save()

        r1 = CaseReminder(domain=self.domain, handler_id=reminder.get_id)
        r2 = CaseReminder(domain=self.domain, handler_id='abc')
        r3 = CaseReminder(domain='def', handler_id='ghi')

        r1.save()
        r2.save()
        r3.save()

        self.assertEqual(len(self.get_all_reminders()), 3)
        reminder.retire()
        self.assertEqual(len(self.get_all_reminders()), 2)

        r1 = CaseReminder.get(r1.get_id)
        r2 = CaseReminder.get(r2.get_id)
        r3 = CaseReminder.get(r3.get_id)

        self.assertEqual(r1.doc_type, 'CaseReminder-Deleted')
        self.assertEqual(r2.doc_type, 'CaseReminder')
        self.assertEqual(r3.doc_type, 'CaseReminder')
    def test_ok(self):
        with create_test_case(self.domain, 'case_type_a', 'test-case', drop_signals=False,
                user_id=self.user.get_id) as case:

            # Test changing a start condition which is a string
            # Spawn the reminder with an "ok" start condition value
            CaseReminderHandler.now = datetime(year=2012, month=2, day=17, hour=12, minute=0)
            self.assertIsNone(self.handler1.get_reminder(case))

            update_case(self.domain, case.case_id, {'start_sending1': 'ok'}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(
                reminder.next_fire,
                CaseReminderHandler.now + timedelta(days=self.handler1.start_offset)
            )

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'case_property1': 'abc'}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Test retiring the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'start_sending1': ''}, user_id=self.user.get_id)

            self.assertIsNone(self.handler1.get_reminder(case))
            self.assertEqual(CaseReminder.get(old_reminder_id).doc_type, "CaseReminder-Deleted")

            # Test changing a start condition which is a date value
            # Spawn the reminder with date start condition value
            update_case(self.domain, case.case_id, {'start_sending1': '2012-02-20'}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 20) + timedelta(days=self.handler1.start_offset)
            )

            # Reset the date start condition
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'start_sending1': '2012-02-22'}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 22) + timedelta(days=self.handler1.start_offset)
            )
            self.assertEqual(CaseReminder.get(old_reminder_id).doc_type, "CaseReminder-Deleted")

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'case_property1': 'abc'}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Retire the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'start_sending1': ''}, user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNone(reminder)
            self.assertEqual(CaseReminder.get(old_reminder_id).doc_type, "CaseReminder-Deleted")

            # Test changing a start condition which is a string representation of a datetime value
            # Spawn the reminder with datetime start condition value
            update_case(self.domain, case.case_id, {'start_sending1': '2012-02-25 11:15'},
                user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 25, 11, 15) + timedelta(days=self.handler1.start_offset)
            )

            # Reset the datetime start condition
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'start_sending1': '2012-02-26 11:20'},
                user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)

            self.assertEqual(
                reminder.next_fire,
                datetime(2012, 2, 26, 11, 20) + timedelta(days=self.handler1.start_offset)
            )
            self.assertEqual(CaseReminder.get(old_reminder_id).doc_type, "CaseReminder-Deleted")

            # Test that saving the case without changing the start condition has no effect
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'case_property1': 'xyz'},
                user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNotNone(reminder)
            self.assertEqual(reminder.get_id, old_reminder_id)

            # Retire the reminder
            old_reminder_id = reminder.get_id
            update_case(self.domain, case.case_id, {'start_sending1': ''},
                user_id=self.user.get_id)

            reminder = self.handler1.get_reminder(case)
            self.assertIsNone(reminder)
            self.assertEqual(CaseReminder.get(old_reminder_id).doc_type, "CaseReminder-Deleted")
Beispiel #31
0
    def test_host_case_owner_location(self):
        parent_location = SQLLocation.objects.create(
            domain=self.domain,
            name='parent test',
            site_code='parent',
            location_type=self.parent_location_type)
        self.addCleanup(parent_location.delete)

        child_location = SQLLocation.objects.create(
            domain=self.domain,
            name='child test',
            site_code='child',
            location_type=self.child_location_type,
            parent=parent_location)
        self.addCleanup(child_location.delete)

        with create_test_case(self.domain, 'test-extension-case',
                              'name') as extension_case:
            with create_test_case(self.domain, 'test-host-case',
                                  'name') as host_case:

                update_case(
                    self.domain,
                    host_case.case_id,
                    case_properties={'owner_id': child_location.location_id})
                set_parent_case(self.domain,
                                extension_case,
                                host_case,
                                relationship='extension')

                handler1 = CaseReminderHandler(
                    domain=self.domain, recipient='HOST_CASE_OWNER_LOCATION')
                handler2 = CaseReminderHandler(
                    domain=self.domain,
                    recipient='HOST_CASE_OWNER_LOCATION_PARENT')
                reminder = CaseReminder(domain=self.domain,
                                        case_id=extension_case.case_id)

                # Test the recipients are returned correctly
                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler1):
                    self.assertEqual(reminder.recipient, [child_location])

                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler2):
                    self.assertEqual(reminder.recipient, [parent_location])

                # Remove parent location reference
                child_location.parent = None
                child_location.save()
                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler2):
                    self.assertIsNone(reminder.recipient)

                # Test location that does not exist
                update_case(self.domain,
                            host_case.case_id,
                            case_properties={'owner_id': 'does-not-exist'})
                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler1):
                    self.assertIsNone(reminder.recipient)

                # Test on a case that is not an extension case
                reminder.case_id = host_case.case_id
                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler1):
                    self.assertIsNone(reminder.recipient)

                # Test on a blank case id
                reminder.case_id = None
                with patch('corehq.apps.reminders.models.CaseReminder.handler',
                           new=handler1):
                    self.assertIsNone(reminder.recipient)