Example #1
0
def add_complex_reminder_schedule(request, domain, handler_id=None):
    if handler_id:
        h = CaseReminderHandler.get(handler_id)
        if h.doc_type != 'CaseReminderHandler' or h.domain != domain:
            raise Http404
    else:
        h = None
    
    form_list = get_form_list(domain)
    
    if request.method == "POST":
        form = ComplexCaseReminderForm(request.POST)
        if form.is_valid():
            if h is None:
                h = CaseReminderHandler(domain=domain)
                h.ui_type = UI_COMPLEX
            h.case_type = form.cleaned_data["case_type"]
            h.nickname = form.cleaned_data["nickname"]
            h.default_lang = form.cleaned_data["default_lang"]
            h.method = form.cleaned_data["method"]
            h.recipient = form.cleaned_data["recipient"]
            h.start_property = form.cleaned_data["start_property"]
            h.start_value = form.cleaned_data["start_value"]
            h.start_date = form.cleaned_data["start_date"]
            h.start_offset = form.cleaned_data["start_offset"]
            h.start_match_type = form.cleaned_data["start_match_type"]
            h.schedule_length = form.cleaned_data["schedule_length"]
            h.event_interpretation = form.cleaned_data["event_interpretation"]
            h.max_iteration_count = form.cleaned_data["max_iteration_count"]
            h.until = form.cleaned_data["until"]
            h.events = form.cleaned_data["events"]
            h.save()
            return HttpResponseRedirect(reverse('list_reminders', args=[domain]))
    else:
        if h is not None:
            initial = {
                "case_type"             : h.case_type
               ,"nickname"              : h.nickname
               ,"default_lang"          : h.default_lang
               ,"method"                : h.method
               ,"recipient"             : h.recipient
               ,"start_property"        : h.start_property
               ,"start_value"           : h.start_value
               ,"start_date"            : h.start_date
               ,"start_match_type"      : h.start_match_type
               ,"start_offset"          : h.start_offset
               ,"schedule_length"       : h.schedule_length
               ,"event_interpretation"  : h.event_interpretation
               ,"max_iteration_count"   : h.max_iteration_count
               ,"until"                 : h.until
               ,"events"                : h.events
            }
        else:
            initial = {}
        
        form = ComplexCaseReminderForm(initial=initial)
    
    return render_to_response(request, "reminders/partial/add_complex_reminder.html", {
        "domain":       domain
       ,"form":         form
       ,"form_list":    form_list
    })
Example #2
0
def add_survey(request, domain, survey_id=None):
    survey = None
    
    if survey_id is not None:
        survey = Survey.get(survey_id)
    
    if request.method == "POST":
        form = SurveyForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            waves = form.cleaned_data.get("waves")
            followups = form.cleaned_data.get("followups")
            samples = form.cleaned_data.get("samples")
            send_automatically = form.cleaned_data.get("send_automatically")
            send_followup = form.cleaned_data.get("send_followup")
            
            sample_data = {}
            for sample in samples:
                sample_data[sample["sample_id"]] = sample
            
            if send_followup:
                timeout_intervals = [int(followup["interval"]) * 1440 for followup in followups]
            else:
                timeout_intervals = []
            
            timeout_duration = sum(timeout_intervals) / 1440
            final_timeout = lambda wave : [((wave.end_date - wave.date).days - timeout_duration) * 1440]
            
            if survey is None:
                wave_list = []
                for wave in waves:
                    wave_list.append(SurveyWave(
                        date=parse(wave["date"]).date(),
                        time=parse(wave["time"]).time(),
                        end_date=parse(wave["end_date"]).date(),
                        form_id=wave["form_id"],
                        reminder_definitions={},
                        delegation_tasks={},
                    ))
                
                if send_automatically:
                    for wave in wave_list:
                        for sample in samples:
                            if sample["method"] == "SMS":
                                handler = CaseReminderHandler(
                                    domain = domain,
                                    nickname = "Survey '%s'" % name,
                                    default_lang = "en",
                                    method = "survey",
                                    recipient = RECIPIENT_SURVEY_SAMPLE,
                                    start_condition_type = ON_DATETIME,
                                    start_datetime = datetime.combine(wave.date, time(0,0)),
                                    start_offset = 0,
                                    events = [CaseReminderEvent(
                                        day_num = 0,
                                        fire_time = wave.time,
                                        form_unique_id = wave.form_id,
                                        callback_timeout_intervals = timeout_intervals + final_timeout(wave),
                                    )],
                                    schedule_length = 1,
                                    event_interpretation = EVENT_AS_SCHEDULE,
                                    max_iteration_count = 1,
                                    sample_id = sample["sample_id"],
                                    survey_incentive = sample["incentive"],
                                    submit_partial_forms = True,
                                )
                                handler.save()
                                wave.reminder_definitions[sample["sample_id"]] = handler._id
                
                survey = Survey (
                    domain = domain,
                    name = name,
                    waves = wave_list,
                    followups = followups,
                    samples = samples,
                    send_automatically = send_automatically,
                    send_followup = send_followup
                )
            else:
                current_waves = survey.waves
                survey.waves = []
                unchanged_wave_json = []
                
                # Keep any waves that didn't change in case the surveys are in progress
                for wave in current_waves:
                    for wave_json in waves:
                        parsed_date = parse(wave_json["date"]).date()
                        parsed_time = parse(wave_json["time"]).time()
                        if parsed_date == wave.date and parsed_time == wave.time and wave_json["form_id"] == wave.form_id:
                            wave.end_date = parse(wave_json["end_date"]).date()
                            survey.waves.append(wave)
                            unchanged_wave_json.append(wave_json)
                            continue
                
                for wave in survey.waves:
                    current_waves.remove(wave)
                
                for wave_json in unchanged_wave_json:
                    waves.remove(wave_json)
                
                # Retire reminder definitions / close delegation tasks for old waves
                for wave in current_waves:
                    for sample_id, handler_id in wave.reminder_definitions.items():
                        handler = CaseReminderHandler.get(handler_id)
                        handler.retire()
                    for sample_id, delegation_data in wave.delegation_tasks.items():
                        for case_id, delegation_case_id in delegation_data.items():
                            close_task(domain, delegation_case_id, request.couch_user.get_id)
                
                # Add in new waves
                for wave_json in waves:
                    survey.waves.append(SurveyWave(
                        date=parse(wave_json["date"]).date(),
                        time=parse(wave_json["time"]).time(),
                        end_date=parse(wave_json["end_date"]).date(),
                        form_id=wave_json["form_id"],
                        reminder_definitions={},
                        delegation_tasks={},
                    ))
                
                # Retire reminder definitions that are no longer needed
                if send_automatically:
                    new_sample_ids = [sample_json["sample_id"] for sample_json in samples if sample_json["method"] == "SMS"]
                else:
                    new_sample_ids = []
                
                for wave in survey.waves:
                    for sample_id, handler_id in wave.reminder_definitions.items():
                        if sample_id not in new_sample_ids:
                            handler = CaseReminderHandler.get(handler_id)
                            handler.retire()
                            del wave.reminder_definitions[sample_id]
                
                # Update existing reminder definitions
                for wave in survey.waves:
                    for sample_id, handler_id in wave.reminder_definitions.items():
                        handler = CaseReminderHandler.get(handler_id)
                        handler.events[0].callback_timeout_intervals = timeout_intervals + final_timeout(wave)
                        handler.nickname = "Survey '%s'" % name
                        handler.survey_incentive = sample_data[sample_id]["incentive"]
                        handler.save()
                
                # Create additional reminder definitions as necessary
                for wave in survey.waves:
                    for sample_id in new_sample_ids:
                        if sample_id not in wave.reminder_definitions:
                            handler = CaseReminderHandler(
                                domain = domain,
                                nickname = "Survey '%s'" % name,
                                default_lang = "en",
                                method = "survey",
                                recipient = RECIPIENT_SURVEY_SAMPLE,
                                start_condition_type = ON_DATETIME,
                                start_datetime = datetime.combine(wave.date, time(0,0)),
                                start_offset = 0,
                                events = [CaseReminderEvent(
                                    day_num = 0,
                                    fire_time = wave.time,
                                    form_unique_id = wave.form_id,
                                    callback_timeout_intervals = timeout_intervals + final_timeout(wave),
                                )],
                                schedule_length = 1,
                                event_interpretation = EVENT_AS_SCHEDULE,
                                max_iteration_count = 1,
                                sample_id = sample_id,
                                survey_incentive = sample_data[sample_id]["incentive"],
                                submit_partial_forms = True,
                            )
                            handler.save()
                            wave.reminder_definitions[sample_id] = handler._id
                
                # Set the rest of the survey info
                survey.name = name
                survey.followups = followups
                survey.samples = samples
                survey.send_automatically = send_automatically
                survey.send_followup = send_followup
            
            # Sort the questionnaire waves by date and time
            survey.waves = sorted(survey.waves, key = lambda wave : datetime.combine(wave.date, wave.time))
            
            # Create / Close delegation tasks as necessary for samples with method "CATI"
            survey.update_delegation_tasks(request.couch_user.get_id)
            
            survey.save()
            return HttpResponseRedirect(reverse("survey_list", args=[domain]))
    else:
        initial = {}
        if survey is not None:
            waves = []
            samples = [SurveySample.get(sample["sample_id"]) for sample in survey.samples]
            utcnow = datetime.utcnow()
            for wave in survey.waves:
                wave_json = {
                    "date" : str(wave.date),
                    "form_id" : wave.form_id,
                    "time" : str(wave.time),
                    "ignore" : wave.has_started(survey),
                    "end_date" : str(wave.end_date),
                }
                
                waves.append(wave_json)
            
            initial["name"] = survey.name
            initial["waves"] = waves
            initial["followups"] = survey.followups
            initial["samples"] = survey.samples
            initial["send_automatically"] = survey.send_automatically
            initial["send_followup"] = survey.send_followup
            
        form = SurveyForm(initial=initial)
    
    form_list = get_form_list(domain)
    form_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    sample_list = get_sample_list(domain)
    sample_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    
    context = {
        "domain" : domain,
        "survey_id" : survey_id,
        "form" : form,
        "form_list" : form_list,
        "sample_list" : sample_list,
        "method_list" : SURVEY_METHOD_LIST,
        "user_list" : CommCareUser.by_domain(domain),
        "started" : survey.has_started() if survey is not None else False,
    }
    return render(request, "reminders/partial/add_survey.html", context)
Example #3
0
def add_survey(request, domain, survey_id=None):
    survey = None

    if survey_id is not None:
        survey = Survey.get(survey_id)

    if request.method == "POST":
        form = SurveyForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            waves = form.cleaned_data.get("waves")
            followups = form.cleaned_data.get("followups")
            samples = form.cleaned_data.get("samples")
            send_automatically = form.cleaned_data.get("send_automatically")
            send_followup = form.cleaned_data.get("send_followup")

            sample_data = {}
            for sample in samples:
                sample_data[sample["sample_id"]] = sample

            if send_followup:
                timeout_intervals = [
                    int(followup["interval"]) * 1440 for followup in followups
                ]
            else:
                timeout_intervals = []

            timeout_duration = sum(timeout_intervals) / 1440
            final_timeout = lambda wave: [(
                (wave.end_date - wave.date).days - timeout_duration) * 1440]

            if survey is None:
                wave_list = []
                for wave in waves:
                    wave_list.append(
                        SurveyWave(
                            date=parse(wave["date"]).date(),
                            time=parse(wave["time"]).time(),
                            end_date=parse(wave["end_date"]).date(),
                            form_id=wave["form_id"],
                            reminder_definitions={},
                            delegation_tasks={},
                        ))

                if send_automatically:
                    for wave in wave_list:
                        for sample in samples:
                            if sample["method"] == "SMS":
                                handler = CaseReminderHandler(
                                    domain=domain,
                                    nickname="Survey '%s'" % name,
                                    default_lang="en",
                                    method="survey",
                                    recipient=RECIPIENT_SURVEY_SAMPLE,
                                    start_condition_type=ON_DATETIME,
                                    start_datetime=datetime.combine(
                                        wave.date, time(0, 0)),
                                    start_offset=0,
                                    events=[
                                        CaseReminderEvent(
                                            day_num=0,
                                            fire_time=wave.time,
                                            form_unique_id=wave.form_id,
                                            callback_timeout_intervals=
                                            timeout_intervals +
                                            final_timeout(wave),
                                        )
                                    ],
                                    schedule_length=1,
                                    event_interpretation=EVENT_AS_SCHEDULE,
                                    max_iteration_count=1,
                                    sample_id=sample["sample_id"],
                                    survey_incentive=sample["incentive"],
                                    submit_partial_forms=True,
                                )
                                handler.save()
                                wave.reminder_definitions[
                                    sample["sample_id"]] = handler._id

                survey = Survey(domain=domain,
                                name=name,
                                waves=wave_list,
                                followups=followups,
                                samples=samples,
                                send_automatically=send_automatically,
                                send_followup=send_followup)
            else:
                current_waves = survey.waves
                survey.waves = []
                unchanged_wave_json = []

                # Keep any waves that didn't change in case the surveys are in progress
                for wave in current_waves:
                    for wave_json in waves:
                        parsed_date = parse(wave_json["date"]).date()
                        parsed_time = parse(wave_json["time"]).time()
                        if parsed_date == wave.date and parsed_time == wave.time and wave_json[
                                "form_id"] == wave.form_id:
                            wave.end_date = parse(wave_json["end_date"]).date()
                            survey.waves.append(wave)
                            unchanged_wave_json.append(wave_json)
                            continue

                for wave in survey.waves:
                    current_waves.remove(wave)

                for wave_json in unchanged_wave_json:
                    waves.remove(wave_json)

                # Retire reminder definitions / close delegation tasks for old waves
                for wave in current_waves:
                    for sample_id, handler_id in wave.reminder_definitions.items(
                    ):
                        handler = CaseReminderHandler.get(handler_id)
                        handler.retire()
                    for sample_id, delegation_data in wave.delegation_tasks.items(
                    ):
                        for case_id, delegation_case_id in delegation_data.items(
                        ):
                            close_task(domain, delegation_case_id,
                                       request.couch_user.get_id)

                # Add in new waves
                for wave_json in waves:
                    survey.waves.append(
                        SurveyWave(
                            date=parse(wave_json["date"]).date(),
                            time=parse(wave_json["time"]).time(),
                            end_date=parse(wave_json["end_date"]).date(),
                            form_id=wave_json["form_id"],
                            reminder_definitions={},
                            delegation_tasks={},
                        ))

                # Retire reminder definitions that are no longer needed
                if send_automatically:
                    new_sample_ids = [
                        sample_json["sample_id"] for sample_json in samples
                        if sample_json["method"] == "SMS"
                    ]
                else:
                    new_sample_ids = []

                for wave in survey.waves:
                    for sample_id, handler_id in wave.reminder_definitions.items(
                    ):
                        if sample_id not in new_sample_ids:
                            handler = CaseReminderHandler.get(handler_id)
                            handler.retire()
                            del wave.reminder_definitions[sample_id]

                # Update existing reminder definitions
                for wave in survey.waves:
                    for sample_id, handler_id in wave.reminder_definitions.items(
                    ):
                        handler = CaseReminderHandler.get(handler_id)
                        handler.events[
                            0].callback_timeout_intervals = timeout_intervals + final_timeout(
                                wave)
                        handler.nickname = "Survey '%s'" % name
                        handler.survey_incentive = sample_data[sample_id][
                            "incentive"]
                        handler.save()

                # Create additional reminder definitions as necessary
                for wave in survey.waves:
                    for sample_id in new_sample_ids:
                        if sample_id not in wave.reminder_definitions:
                            handler = CaseReminderHandler(
                                domain=domain,
                                nickname="Survey '%s'" % name,
                                default_lang="en",
                                method="survey",
                                recipient=RECIPIENT_SURVEY_SAMPLE,
                                start_condition_type=ON_DATETIME,
                                start_datetime=datetime.combine(
                                    wave.date, time(0, 0)),
                                start_offset=0,
                                events=[
                                    CaseReminderEvent(
                                        day_num=0,
                                        fire_time=wave.time,
                                        form_unique_id=wave.form_id,
                                        callback_timeout_intervals=
                                        timeout_intervals +
                                        final_timeout(wave),
                                    )
                                ],
                                schedule_length=1,
                                event_interpretation=EVENT_AS_SCHEDULE,
                                max_iteration_count=1,
                                sample_id=sample_id,
                                survey_incentive=sample_data[sample_id]
                                ["incentive"],
                                submit_partial_forms=True,
                            )
                            handler.save()
                            wave.reminder_definitions[sample_id] = handler._id

                # Set the rest of the survey info
                survey.name = name
                survey.followups = followups
                survey.samples = samples
                survey.send_automatically = send_automatically
                survey.send_followup = send_followup

            # Sort the questionnaire waves by date and time
            survey.waves = sorted(
                survey.waves,
                key=lambda wave: datetime.combine(wave.date, wave.time))

            # Create / Close delegation tasks as necessary for samples with method "CATI"
            survey.update_delegation_tasks(request.couch_user.get_id)

            survey.save()
            return HttpResponseRedirect(reverse("survey_list", args=[domain]))
    else:
        initial = {}
        if survey is not None:
            waves = []
            samples = [
                SurveySample.get(sample["sample_id"])
                for sample in survey.samples
            ]
            utcnow = datetime.utcnow()
            for wave in survey.waves:
                wave_json = {
                    "date": str(wave.date),
                    "form_id": wave.form_id,
                    "time": str(wave.time),
                    "ignore": wave.has_started(survey),
                    "end_date": str(wave.end_date),
                }

                waves.append(wave_json)

            initial["name"] = survey.name
            initial["waves"] = waves
            initial["followups"] = survey.followups
            initial["samples"] = survey.samples
            initial["send_automatically"] = survey.send_automatically
            initial["send_followup"] = survey.send_followup

        form = SurveyForm(initial=initial)

    form_list = get_form_list(domain)
    form_list.insert(0, {"code": "--choose--", "name": "-- Choose --"})
    sample_list = get_sample_list(domain)
    sample_list.insert(0, {"code": "--choose--", "name": "-- Choose --"})

    context = {
        "domain": domain,
        "survey_id": survey_id,
        "form": form,
        "form_list": form_list,
        "sample_list": sample_list,
        "method_list": SURVEY_METHOD_LIST,
        "user_list": CommCareUser.by_domain(domain),
        "started": survey.has_started() if survey is not None else False,
    }
    return render(request, "reminders/partial/add_survey.html", context)
Example #4
0
def add_complex_reminder_schedule(request, domain, handler_id=None):
    if handler_id:
        h = CaseReminderHandler.get(handler_id)
        if h.doc_type != 'CaseReminderHandler' or h.domain != domain:
            raise Http404
    else:
        h = None
    
    form_list = get_form_list(domain)
    sample_list = get_sample_list(domain)
    
    if request.method == "POST":
        form = ComplexCaseReminderForm(request.POST)
        if form.is_valid():
            if h is None:
                h = CaseReminderHandler(domain=domain)
                h.ui_type = UI_COMPLEX
            else:
                if h.start_condition_type != form.cleaned_data["start_condition_type"]:
                    for reminder in h.get_reminders():
                        reminder.retire()
            h.active = form.cleaned_data["active"]
            h.case_type = form.cleaned_data["case_type"]
            h.nickname = form.cleaned_data["nickname"]
            h.default_lang = form.cleaned_data["default_lang"]
            h.method = form.cleaned_data["method"]
            h.recipient = form.cleaned_data["recipient"]
            h.start_property = form.cleaned_data["start_property"]
            h.start_value = form.cleaned_data["start_value"]
            h.start_date = form.cleaned_data["start_date"]
            h.start_offset = form.cleaned_data["start_offset"]
            h.start_match_type = form.cleaned_data["start_match_type"]
            h.schedule_length = form.cleaned_data["schedule_length"]
            h.event_interpretation = form.cleaned_data["event_interpretation"]
            h.max_iteration_count = form.cleaned_data["max_iteration_count"]
            h.until = form.cleaned_data["until"]
            h.events = form.cleaned_data["events"]
            h.submit_partial_forms = form.cleaned_data["submit_partial_forms"]
            h.include_case_side_effects = form.cleaned_data["include_case_side_effects"]
            h.ui_frequency = form.cleaned_data["frequency"]
            h.start_condition_type = form.cleaned_data["start_condition_type"]
            h.max_question_retries = form.cleaned_data["max_question_retries"]
            if form.cleaned_data["start_condition_type"] == "ON_DATETIME":
                dt = parse(form.cleaned_data["start_datetime_date"]).date()
                tm = parse(form.cleaned_data["start_datetime_time"]).time()
                h.start_datetime = datetime.combine(dt, tm)
            else:
                h.start_datetime = None
            h.sample_id = form.cleaned_data["sample_id"]
            h.save()
            return HttpResponseRedirect(reverse('list_reminders', args=[domain]))
    else:
        if h is not None:
            initial = {
                "active"                : h.active,
                "case_type"             : h.case_type,
                "nickname"              : h.nickname,
                "default_lang"          : h.default_lang,
                "method"                : h.method,
                "recipient"             : h.recipient,
                "start_property"        : h.start_property,
                "start_value"           : h.start_value,
                "start_date"            : h.start_date,
                "start_match_type"      : h.start_match_type,
                "start_offset"          : h.start_offset,
                "schedule_length"       : h.schedule_length,
                "event_interpretation"  : h.event_interpretation,
                "max_iteration_count"   : h.max_iteration_count,
                "until"                 : h.until,
                "events"                : h.events,
                "submit_partial_forms"  : h.submit_partial_forms,
                "include_case_side_effects" : h.include_case_side_effects,
                "start_condition_type"  : h.start_condition_type,
                "start_datetime_date"   : str(h.start_datetime.date()) if isinstance(h.start_datetime, datetime) else None,
                "start_datetime_time"   : str(h.start_datetime.time()) if isinstance(h.start_datetime, datetime) else None,
                "frequency"             : h.ui_frequency,
                "sample_id"             : h.sample_id,
                "use_until"             : "Y" if h.until is not None else "N",
                "max_question_retries"  : h.max_question_retries,
            }
        else:
            initial = {
                "events"    : [CaseReminderEvent(day_num=0, fire_time=time(0,0), message={"":""}, callback_timeout_intervals=[], form_unique_id=None)],
                "use_until" : "N",
                "max_question_retries" : QUESTION_RETRY_CHOICES[-1],
                "active" : True,
            }
        
        form = ComplexCaseReminderForm(initial=initial)
    
    return render(request, "reminders/partial/add_complex_reminder.html", {
        "domain":       domain,
        "form":         form,
        "form_list":    form_list,
        "handler_id":   handler_id,
        "sample_list":  sample_list,
    })
Example #5
0
def add_complex_reminder_schedule(request, domain, handler_id=None):
    if handler_id:
        h = CaseReminderHandler.get(handler_id)
        if h.doc_type != 'CaseReminderHandler' or h.domain != domain:
            raise Http404
    else:
        h = None

    form_list = get_form_list(domain)
    sample_list = get_sample_list(domain)

    if request.method == "POST":
        form = ComplexCaseReminderForm(request.POST)
        if form.is_valid():
            if h is None:
                h = CaseReminderHandler(domain=domain)
                h.ui_type = UI_COMPLEX
            else:
                if h.start_condition_type != form.cleaned_data[
                        "start_condition_type"]:
                    for reminder in h.get_reminders():
                        reminder.retire()
            h.active = form.cleaned_data["active"]
            h.case_type = form.cleaned_data["case_type"]
            h.nickname = form.cleaned_data["nickname"]
            h.default_lang = form.cleaned_data["default_lang"]
            h.method = form.cleaned_data["method"]
            h.recipient = form.cleaned_data["recipient"]
            h.start_property = form.cleaned_data["start_property"]
            h.start_value = form.cleaned_data["start_value"]
            h.start_date = form.cleaned_data["start_date"]
            h.start_offset = form.cleaned_data["start_offset"]
            h.start_match_type = form.cleaned_data["start_match_type"]
            h.schedule_length = form.cleaned_data["schedule_length"]
            h.event_interpretation = form.cleaned_data["event_interpretation"]
            h.max_iteration_count = form.cleaned_data["max_iteration_count"]
            h.until = form.cleaned_data["until"]
            h.events = form.cleaned_data["events"]
            h.submit_partial_forms = form.cleaned_data["submit_partial_forms"]
            h.include_case_side_effects = form.cleaned_data[
                "include_case_side_effects"]
            h.ui_frequency = form.cleaned_data["frequency"]
            h.start_condition_type = form.cleaned_data["start_condition_type"]
            h.max_question_retries = form.cleaned_data["max_question_retries"]
            h.recipient_case_match_property = form.cleaned_data[
                "recipient_case_match_property"]
            h.recipient_case_match_type = form.cleaned_data[
                "recipient_case_match_type"]
            h.recipient_case_match_value = form.cleaned_data[
                "recipient_case_match_value"]
            if form.cleaned_data["start_condition_type"] == "ON_DATETIME":
                dt = parse(form.cleaned_data["start_datetime_date"]).date()
                tm = parse(form.cleaned_data["start_datetime_time"]).time()
                h.start_datetime = datetime.combine(dt, tm)
            else:
                h.start_datetime = None
            h.sample_id = form.cleaned_data["sample_id"]
            h.save()
            return HttpResponseRedirect(
                reverse('list_reminders', args=[domain]))
    else:
        if h is not None:
            initial = {
                "active":
                h.active,
                "case_type":
                h.case_type,
                "nickname":
                h.nickname,
                "default_lang":
                h.default_lang,
                "method":
                h.method,
                "recipient":
                h.recipient,
                "start_property":
                h.start_property,
                "start_value":
                h.start_value,
                "start_date":
                h.start_date,
                "start_match_type":
                h.start_match_type,
                "start_offset":
                h.start_offset,
                "schedule_length":
                h.schedule_length,
                "event_interpretation":
                h.event_interpretation,
                "max_iteration_count":
                h.max_iteration_count,
                "until":
                h.until,
                "events":
                h.events,
                "submit_partial_forms":
                h.submit_partial_forms,
                "include_case_side_effects":
                h.include_case_side_effects,
                "start_condition_type":
                h.start_condition_type,
                "start_datetime_date":
                str(h.start_datetime.date()) if isinstance(
                    h.start_datetime, datetime) else None,
                "start_datetime_time":
                str(h.start_datetime.time()) if isinstance(
                    h.start_datetime, datetime) else None,
                "frequency":
                h.ui_frequency,
                "sample_id":
                h.sample_id,
                "use_until":
                "Y" if h.until is not None else "N",
                "max_question_retries":
                h.max_question_retries,
                "recipient_case_match_property":
                h.recipient_case_match_property,
                "recipient_case_match_type":
                h.recipient_case_match_type,
                "recipient_case_match_value":
                h.recipient_case_match_value,
            }
        else:
            initial = {
                "events": [
                    CaseReminderEvent(day_num=0,
                                      fire_time=time(0, 0),
                                      message={"": ""},
                                      callback_timeout_intervals=[],
                                      form_unique_id=None)
                ],
                "use_until":
                "N",
                "max_question_retries":
                QUESTION_RETRY_CHOICES[-1],
                "active":
                True,
            }

        form = ComplexCaseReminderForm(initial=initial)

    return render(
        request, "reminders/partial/add_complex_reminder.html", {
            "domain": domain,
            "form": form,
            "form_list": form_list,
            "handler_id": handler_id,
            "sample_list": sample_list,
        })