@Test
  public void shouldRecordSymptomReported() {
    SymptomReport expectedReport = new SymptomReport("patientDocumentId", "callId", DateUtil.now());
    expectedReport.addSymptomId(FEVER_ID);
    when(allSymptomReports.findByCallId("callId")).thenReturn(null);

    symptomRecordingService.save(FEVER_ID, "patientDocumentId", "callId", DateUtil.now());

    ArgumentCaptor<SymptomReport> reportCapture = ArgumentCaptor.forClass(SymptomReport.class);
    verify(allSymptomReports).addOrReplace(reportCapture.capture());
    assertEquals(expectedReport, reportCapture.getValue());
  }
  @Test
  public void shouldCloseMotherAndECDuringDeliveryOutcomeIfWomanDied() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.exists("mother id 1")).thenReturn(true);
    when(allMothers.findByCaseId("mother id 1"))
        .thenReturn(new Mother("mother id 1", "ec id 1", "1234567"));
    when(allEligibleCouples.findByCaseId("ec id 1"))
        .thenReturn(new EligibleCouple("ec id 1", "123"));

    FormSubmission submission =
        create()
            .withFormName("delivery_outcome")
            .withANMId("anm id 1")
            .withEntityId("mother id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "")
            .addFormField("didMotherSurvive", "no")
            .withSubForm(
                new SubFormData("child_registration", Collections.<Map<String, String>>emptyList()))
            .build();
    service.deliveryOutcome(submission);

    Mother expectedMother = new Mother("mother id 1", "ec id 1", "1234567").setIsClosed(true);
    EligibleCouple expectedEC = new EligibleCouple("ec id 1", "123").setIsClosed(true);

    verify(allMothers).update(expectedMother);
    verify(allEligibleCouples).update(expectedEC);
    verify(actionService).markAllAlertsAsInactive("mother id 1");
    verify(pncSchedulesService).unEnrollFromSchedules("mother id 1");
    verifyZeroInteractions(pncSchedulesService);
  }
  @Test
  public void shouldUpdateANMInformationOfEligibleCoupleWhenOAPNCIsRegistered() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByEcCaseId("ec id 1"))
        .thenReturn(asList(new Mother("mother id 1", "ec id 1", "tc 1")));
    when(allEligibleCouples.findByCaseId("ec id 1"))
        .thenReturn(new EligibleCouple("ec id 1", "123"));
    FormSubmission submission =
        create()
            .withFormName("pnc_registration_oa")
            .withANMId("anm id 1")
            .withEntityId("ec id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "yes")
            .withSubForm(
                new SubFormData(
                    "child_registration_oa", Collections.<Map<String, String>>emptyList()))
            .build();

    service.pncRegistrationOA(submission);

    verify(allEligibleCouples)
        .update(new EligibleCouple("ec id 1", "123").withANMIdentifier("anm id 1"));
  }
  @Test
  public void shouldMakeACallForActivePatient_AndRecordDosageAsNotReported_WhenCalledFirstTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService).initiateCall(callRequestArgumentCaptor.capture());
    verify(dailyPillReminderAdherenceService)
        .recordDosageAdherenceAsNotCaptured(
            PATIENT_DOC_ID, "pillRegimenId", dose, DosageStatus.NOT_RECORDED, now);
    Map<String, String> payload = callRequestArgumentCaptor.getValue().getPayload();
    assertEquals(
        String.valueOf(TOTAL_TIMES_TO_SEND), payload.get(PillReminderCall.TOTAL_TIMES_TO_SEND));
    assertEquals(String.valueOf(TIMES_SENT), payload.get(PillReminderCall.TIMES_SENT));
    assertEquals(String.valueOf(RETRY_INTERVAL), payload.get(PillReminderCall.RETRY_INTERVAL));
  }
  @Test
  public void shouldNotMakeACallWhenCurrentTimeIsConfiguredMinutesLessThanScheduledTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID,
        NOW.minusMinutes(16).toDate(),
        TIMES_SENT,
        TOTAL_TIMES_TO_SEND,
        RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService, never()).initiateCall(callRequestArgumentCaptor.capture());
  }
  @Test
  public void
      shouldMakeACallForActivePatient_DoesNotRecordDosageAsNotReported_WhenCalledAfterFirstTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();
    TIMES_SENT = 1;

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    pillReminderCall.execute(
        PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService).initiateCall(callRequestArgumentCaptor.capture());
    verifyZeroInteractions(dailyPillReminderAdherenceService);
    verifyZeroInteractions(dailyPillReminderService);
    Map<String, String> payload = callRequestArgumentCaptor.getValue().getPayload();
    assertEquals(
        String.valueOf(TOTAL_TIMES_TO_SEND), payload.get(PillReminderCall.TOTAL_TIMES_TO_SEND));
    assertEquals(String.valueOf(TIMES_SENT), payload.get(PillReminderCall.TIMES_SENT));
    assertEquals(String.valueOf(RETRY_INTERVAL), payload.get(PillReminderCall.RETRY_INTERVAL));
  }
 private CallEvent endOfCallEvent() {
   CallEvent event = new CallEvent(CallState.MAIN_MENU.name());
   CallEventCustomData data = new CallEventCustomData();
   event.setTimeStamp(DateUtil.now().plusMinutes(1));
   event.setData(data);
   return event;
 }
  @Test
  public void shouldMarkDoseAsNotRecordedWhenCurrentTimeIsConfiguredMinutesMoreThanScheduledTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID,
        NOW.plusMinutes(16).toDate(),
        TIMES_SENT,
        TOTAL_TIMES_TO_SEND,
        RETRY_INTERVAL);

    verify(dailyPillReminderAdherenceService)
        .recordDosageAdherenceAsNotCaptured(
            PATIENT_DOC_ID, "pillRegimenId", dose, DosageStatus.NOT_RECORDED, now);
  }
  @Test
  public void shouldValidateNhisExpiryDate() {
    Date nhisExpires = DateUtil.now().minusDays(30).toDate();

    List<FormError> formErrors = formValidator.validateNHISExpiry(nhisExpires);
    assertThat(formErrors, hasItem(new FormError(NHIS_EXPIRY, IN_PAST)));
  }
 @Test
 public void shouldSetAdviceGivenOnSymptomsReport() {
   SymptomReport expectedReport = new SymptomReport("patientDocumentId", "callId", DateUtil.now());
   when(allSymptomReports.findByCallId("callId")).thenReturn(expectedReport);
   symptomRecordingService.saveAdviceGiven("patientDocumentId", "callId", "some advice");
   verify(allSymptomReports).addOrReplace(expectedReport);
   assertEquals("some advice", expectedReport.getAdviceGiven());
 }
  @Test
  public void
      shouldScheduleDailyAdherenceQualityJobsForAPatientOnDailyReminderStartingFromTodayIfTreatmentAdviceStartDateIsInPast() {
    final String patientId = "123456";
    Patient patient =
        PatientBuilder.startRecording()
            .withDefaults()
            .withId(patientId)
            .withCallPreference(CallPreference.DailyPillReminder)
            .build();

    final LocalDate startDate = DateUtil.today().minusDays(2);
    final LocalDate endDate = DateUtil.today().plusDays(2);
    final DateTime timeFewMillisBack = DateUtil.now().minusMillis(1000);

    TreatmentAdvice advice = getTreatmentAdvice(startDate, endDate);

    schedulerService.scheduleJobForDeterminingAdherenceQualityInDailyPillReminder(patient, advice);

    final ArgumentCaptor<CronSchedulableJob> cronArgCaptor =
        ArgumentCaptor.forClass(CronSchedulableJob.class);
    verify(motechSchedulerService).safeScheduleJob(cronArgCaptor.capture());

    CronSchedulableJob jobScheduledWithParams = cronArgCaptor.getValue();
    final MotechEvent motechEventInScheduledJob = jobScheduledWithParams.getMotechEvent();
    Map<String, Object> paramsInScheduledJob = motechEventInScheduledJob.getParameters();

    assertEquals(
        "Should setup the cron expression to run at every midnight.",
        jobScheduledWithParams.getCronExpression(),
        "0 0 0 * * ?");

    DateTime actualTimeWhenTriggerWasActivated =
        DateUtil.newDateTime(jobScheduledWithParams.getStartTime());
    assertTrue(
        "Since the advice has already started in past, we should schedule it starting now, which is after a time few milli seconds back.",
        timeFewMillisBack.isBefore(actualTimeWhenTriggerWasActivated));
    DateTime rightNow = DateUtil.now();
    assertTrue(rightNow.isEqual(actualTimeWhenTriggerWasActivated));

    assertEquals(jobScheduledWithParams.getEndTime(), endDate.plusDays(1).toDate());

    assertEquals(paramsInScheduledJob.get(EventKeys.EXTERNAL_ID_KEY), patientId);
    assertEquals(
        motechEventInScheduledJob.getSubject(), TAMAConstants.DAILY_ADHERENCE_IN_RED_ALERT_SUBJECT);
  }
 private CallEvent messagesEvent() {
   CallEvent event = new CallEvent(CallState.PULL_MESSAGES.name());
   CallEventCustomData data = new CallEventCustomData();
   data.add(
       CallEventConstants.CUSTOM_DATA_LIST,
       "<response><playaudio>http://localhost/response1.wav</playaudio><playaudio>http://localhost/response2.wav</playaudio></response>");
   data.add(CallEventConstants.CALL_STATE, CallState.PULL_MESSAGES.name());
   event.setTimeStamp(DateUtil.now());
   event.setData(data);
   return event;
 }
  @Test
  public void shouldNotAutoClosePNCCaseWhenMotherDoesNotExist() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByCaseId("MOTHER-CASE-1")).thenReturn(null);

    service.autoClosePNCCase("MOTHER-CASE-1");

    verify(allMothers, times(0)).close("MOTHER-CASE-1");
    verifyZeroInteractions(actionService);
  }
  @Test
  public void shouldBuildCallSummaryWithEmptyCallFlowDetailsWhenCallLogDoesNotHaveAnyFlows() {
    DateTime callStartTime = DateUtil.now();
    CallLog callLog = new CallLog();
    callLog.setStartTime(callStartTime);
    callLog.setEndTime(callStartTime.plusMinutes(1));

    CallLogSummary logSummary =
        new CallLogSummaryBuilder(allPatients, new Patients(allPatients.getAll()), allIVRLanguages)
            .build(callLog);
    assertNotNull(logSummary.getFlowDetailsMap());
  }
  @Test
  public void shouldReturnCallFlowDuration() {
    callEventView = new CallEventView(new CallEvent(IVREvent.GotDTMF.toString()));
    callFlowGroupView = new CallFlowGroupView("flow", callEventView);
    DateTime flowStartTime = DateUtil.now();

    callFlowGroupView.setFlowStartTime(flowStartTime);
    callFlowGroupView.setFlowEndTime(flowStartTime.plusMinutes(2).plusSeconds(3));

    assertEquals(123, callFlowGroupView.getFlowDuration());
    assertEquals("flow", callFlowGroupView.toString());
  }
  @Test
  public void shouldFetchFormSubmissionsBasedOnANMIDTimeStampAndBatchSize() throws Exception {
    long baseTimeStamp = DateUtil.now().getMillis();
    FormSubmission firstFormSubmission =
        new FormSubmission(
            "ANM 1", "instance id 1", "form name 1", "entity id 1", 0L, "1", null, baseTimeStamp);
    formSubmissions.add(firstFormSubmission);

    FormSubmission secondFormSubmission =
        new FormSubmission(
            "ANM 1",
            "instance id 2",
            "form name 1",
            "entity id 2",
            1L,
            "1",
            null,
            baseTimeStamp + 1);
    formSubmissions.add(secondFormSubmission);

    FormSubmission thirdFormSubmission =
        new FormSubmission(
            "ANM 1",
            "instance id 3",
            "form name 1",
            "entity id 3",
            2L,
            "1",
            null,
            baseTimeStamp + 2);
    formSubmissions.add(thirdFormSubmission);

    assertEquals(
        asList(firstFormSubmission, secondFormSubmission, thirdFormSubmission),
        formSubmissions.findByANMIDAndServerVersion("ANM 1", 0L, null));
    assertEquals(
        asList(secondFormSubmission, thirdFormSubmission),
        formSubmissions.findByANMIDAndServerVersion(
            "ANM 1", firstFormSubmission.serverVersion(), null));
    assertEquals(
        asList(thirdFormSubmission),
        formSubmissions.findByANMIDAndServerVersion(
            "ANM 1", secondFormSubmission.serverVersion(), null));
    assertEquals(
        asList(firstFormSubmission, secondFormSubmission),
        formSubmissions.findByANMIDAndServerVersion("ANM 1", 0L, 2));

    assertEquals(
        0,
        formSubmissions
            .findByANMIDAndServerVersion("ANM 1", thirdFormSubmission.serverVersion(), null)
            .size());
  }
  @Test
  public void shouldFetchAllFormSubmissionsAfterServerVersion() throws Exception {
    long baseTimeStamp = DateUtil.now().getMillis();

    FormSubmission firstFormSubmission =
        new FormSubmission(
            "anm id 1",
            "instance id 1",
            "form name 1",
            "entity id 1",
            0L,
            "1",
            null,
            baseTimeStamp);
    formSubmissions.add(firstFormSubmission);

    FormSubmission secondFormSubmission =
        new FormSubmission(
            "anm id 2",
            "instance id 2",
            "form name 1",
            "entity id 2",
            1L,
            "1",
            null,
            baseTimeStamp + 1);
    formSubmissions.add(secondFormSubmission);

    FormSubmission thirdFormSubmission =
        new FormSubmission(
            "anm id 3",
            "instance id 3",
            "form name 1",
            "entity id 3",
            2L,
            "1",
            null,
            baseTimeStamp + 2);
    formSubmissions.add(thirdFormSubmission);

    assertEquals(
        asList(firstFormSubmission, secondFormSubmission, thirdFormSubmission),
        formSubmissions.findByServerVersion(0L));
    assertEquals(
        asList(secondFormSubmission, thirdFormSubmission),
        formSubmissions.findByServerVersion(firstFormSubmission.serverVersion()));
    assertEquals(
        asList(thirdFormSubmission),
        formSubmissions.findByServerVersion(secondFormSubmission.serverVersion()));
    assertEquals(
        0, formSubmissions.findByServerVersion(thirdFormSubmission.serverVersion()).size());
  }
 Subscription rollOverSubscriptionFrom(Subscription subscription) {
   return subscription != null
       ? new Subscription(
               subscription.getSubscriber(),
               subscription.rollOverProgramType(),
               SubscriptionStatus.ACTIVE,
               new WeekAndDay(
                   new Week(subscription.rollOverProgramType().getMinWeek()),
                   new DateUtils().today()),
               DateUtil.now())
           .updateCycleInfo(programMessageCycle)
       : null;
 }
Beispiel #19
0
 @JsonIgnore
 public boolean isTodaysDosageResponseCaptured() {
   LocalDate today = DateUtil.today();
   LocalDate yesterday = today.minusDays(1);
   LocalTime localNow = DateUtil.now().toLocalTime();
   if (responseLastCapturedDate == null) {
     return false;
   }
   if (responseLastCapturedDate.equals(today)) {
     return true;
   }
   return responseLastCapturedDate.equals(yesterday)
       && new Time(localNow.getHourOfDay(), localNow.getMinuteOfHour()).isBefore(dosageTime);
 }
  @Test
  public void shouldAutoClosePNCCaseWhenMotherExists() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByCaseId("MOTHER-CASE-1"))
        .thenReturn(new Mother("MOTHER-CASE-1", "EC-CASE-1", "TC1").withAnm("ANM 1"));

    service.autoClosePNCCase("MOTHER-CASE-1");

    verify(allMothers).close("MOTHER-CASE-1");
    verify(actionService).markAllAlertsAsInactive("MOTHER-CASE-1");
    verify(actionService).closeMother("MOTHER-CASE-1", "ANM 1", "Auto Close PNC");
    verifyZeroInteractions(motherReportingService);
  }
  @Test
  public void shouldAddHangupTransitionWhenThereAreNoPatientsRemaining() {
    setAdherenceProvided(patient1);
    setAdherenceProvided(patient2);

    AdherenceSummaryByProvider adherenceSummary = adherenceSummary(asList(patient1, patient2));
    when(adherenceDataService.getAdherenceSummary(PROVIDER_ID)).thenReturn(adherenceSummary);
    mockCurrentDate(DateUtil.now());

    Node actualNode = adherenceSummaryTransition.getDestinationNode("", flowSession);
    assertEquals(flowSession.get(IvrSession.CALL_STATUS), CallStatus.ADHERENCE_ALREADY_PROVIDED);
    assertEquals(new HangupTransition(), actualNode.getTransitions().get("hangup"));
    assertThat(actualNode.getOperations(), hasItem(isA(RecordCallStartTimeOperation.class)));
  }
  private void setUpCallLog(CallDirection callDirection) {
    String patientDocId = "patientDocId";
    String clinicId = "clinicId";
    callLog = new CallLog(patientDocId);
    callLog.patientId("patientId");
    initiatedTime = DateUtil.newDateTime(2011, 10, 10, 10, 9, 10);
    startTime = DateUtil.newDateTime(2011, 10, 10, 10, 10, 10);
    callLog.setStartTime(initiatedTime);
    callLog.setEndTime(DateUtil.now());
    callLog.setCallDirection(callDirection);
    callLog.clinicId(clinicId);
    callLog.setPhoneNumber("1234567890");
    callLog.callLanguage("en");

    final CallEvent callEvent = mock(CallEvent.class);
    when(callEvent.getTimeStamp()).thenReturn(startTime);
    CallEventCustomData customData = new CallEventCustomData();
    customData.add(TAMAIVRContext.MESSAGE_CATEGORY_NAME, "All Messages");
    when(callEvent.getData()).thenReturn(customData);
    callLog.setCallEvents(
        new ArrayList<CallEvent>() {
          {
            add(callEvent);
          }
        });
    Clinic clinic = new Clinic(clinicId);
    Patient patient =
        PatientBuilder.startRecording()
            .withId(patientDocId)
            .withPatientId("patientId")
            .withGender(Gender.newGender("Male"))
            .withClinic(clinic)
            .withTravelTimeToClinicInDays(1)
            .withTravelTimeToClinicInHours(1)
            .withTravelTimeToClinicInMinutes(1)
            .withDateOfBirth(DateUtil.today().minusYears(40))
            .build();
    CallLogView callLogView = mock(CallLogView.class);
    clinic.setName("clinicName");

    when(allIVRLanguages.getByCode("en")).thenReturn(IVRLanguage.newIVRLanguage("English", "en"));
    when(allPatients.getAll()).thenReturn(asList(patient));
    when(callLogViewMapper.toCallLogView(asList(callLog))).thenReturn(asList(callLogView));

    callLogSummaryBuilder =
        new CallLogSummaryBuilder(allPatients, new Patients(allPatients.getAll()), allIVRLanguages);
  }
  @Test
  public void shouldFetchAllProvidersWithActivePatients() {
    Patient patientWithCurrentTreatment =
        new PatientBuilder().withDefaults().withPatientId("patientId1").build();

    Patient patientWithoutCurrentTreatment =
        new PatientBuilder().withDefaults().withPatientId("patientId2").build();
    patientWithoutCurrentTreatment.closeCurrentTreatment(
        TreatmentOutcome.Cured, null, DateUtil.now());

    allPatients.add(patientWithCurrentTreatment);
    allPatients.add(patientWithoutCurrentTreatment);

    assertEquals(
        new ProviderIds(asList(patientWithCurrentTreatment.getCurrentTreatment().getProviderId())),
        allPatients.providersWithActivePatients());
  }
  @Test
  public void shouldFetchAllActivePatients() {
    Patient activePatient =
        new PatientBuilder()
            .withDefaults()
            .withPatientId("patientId1")
            .withAdherenceProvidedForLastWeek()
            .build();
    Patient inactivePatient =
        new PatientBuilder().withDefaults().withPatientId("patientId2").build();
    inactivePatient.closeCurrentTreatment(TreatmentOutcome.Died, null, DateUtil.now());

    allPatients.add(activePatient);
    allPatients.add(inactivePatient);

    List<String> patientIds = allPatients.findAllActivePatientIds();
    assertThat(patientIds.size(), is(1));
    assertThat(patientIds, hasItem(activePatient.getPatientId()));
  }
  @Test
  public void shouldNotEnrollPNCIntoSchedulesDuringDeliveryOutcomeIfMotherDoesNotExists() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.exists("mother id 1")).thenReturn(false);
    FormSubmission submission =
        create()
            .withFormName("delivery_outcome")
            .withANMId("anm id 1")
            .withEntityId("mother id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "no")
            .withSubForm(
                new SubFormData("child_registration", Collections.<Map<String, String>>emptyList()))
            .build();
    service.deliveryOutcome(submission);

    verifyZeroInteractions(pncSchedulesService);
  }
  @Test
  public void shouldNotEnrollPNCIntoSchedulesDuringPNCRegistrationIfMotherDoesNotExists() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByEcCaseId("ec id 1")).thenReturn(Collections.EMPTY_LIST);
    FormSubmission submission =
        create()
            .withFormName("pnc_registration_oa")
            .withANMId("anm id 1")
            .withEntityId("ec id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "")
            .withSubForm(
                new SubFormData("child_registration", Collections.<Map<String, String>>emptyList()))
            .build();

    service.pncRegistrationOA(submission);

    verifyZeroInteractions(pncSchedulesService);
  }
  @Test
  public void shouldScheduleWeeklyAdherenceTrendJob_StartDateIsBeforeToday() {
    DateTime now = DateUtil.now();
    LocalDate today = now.toLocalDate();

    Patient patient =
        PatientBuilder.startRecording()
            .withDefaults()
            .withId("patientId")
            .withCallPreference(CallPreference.DailyPillReminder)
            .build();
    treatmentAdvice.getDrugDosages().get(0).setStartDate(today.minusMonths(2));

    schedulerService.scheduleJobForAdherenceTrendFeedbackForDailyPillReminder(
        patient, treatmentAdvice);
    ArgumentCaptor<CronSchedulableJob> jobCaptor =
        ArgumentCaptor.forClass(CronSchedulableJob.class);
    verify(motechSchedulerService).safeScheduleJob(jobCaptor.capture());
    assertEquals(today, DateUtil.newDate(jobCaptor.getValue().getStartTime()));
  }
  @Test
  public void shouldEnrollPNCIntoSchedulesDuringDeliveryOutcomeIfWomanOrMotherSurvives() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByCaseId("mother id 1"))
        .thenReturn(new Mother("mother id 1", "ec id 1", "1234567"));
    FormSubmission submission =
        create()
            .withFormName("delivery_outcome")
            .withANMId("anm id 1")
            .withEntityId("mother id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "yes")
            .addFormField("didMotherSurvive", "")
            .withSubForm(
                new SubFormData("child_registration", Collections.<Map<String, String>>emptyList()))
            .build();
    service.deliveryOutcome(submission);

    verify(pncSchedulesService).deliveryOutcome("mother id 1", "2012-01-01");
  }
  @Test
  public void
      shouldAddPromptsForWelcomeMessage_AdherenceSummary_AndCompletion_WhenThereAreNoPatientsRemaining() {
    setAdherenceProvided(patient1);
    setAdherenceProvided(patient2);

    AdherenceSummaryByProvider adherenceSummary = adherenceSummary(asList(patient1, patient2));
    when(adherenceDataService.getAdherenceSummary(PROVIDER_ID)).thenReturn(adherenceSummary);
    mockCurrentDate(DateUtil.now());
    List<Prompt> expectedPrompts =
        new PromptBuilder(whpIvrMessage)
            .addAll(welcomeMessagePrompts(whpIvrMessage))
            .addAll(
                adherenceSummaryWithCallCompletionPrompts(
                    whpIvrMessage,
                    adherenceSummary.countOfAllPatients(),
                    adherenceSummary.countOfPatientsWithAdherence()))
            .buildList();

    Node actualNode = adherenceSummaryTransition.getDestinationNode("", flowSession);
    assertThat(actualNode.getPrompts(), is(expectedPrompts));
  }
  @Test
  public void shouldNotEnrollPNCIntoSchedulesPNCRegistrationIfWomanDied() {
    DateTime currentTime = DateUtil.now();
    mockCurrentDate(currentTime);
    when(allMothers.findByEcCaseId("ec id 1"))
        .thenReturn(asList(new Mother("mother id 1", "ec id 1", "tc 1")));
    when(allEligibleCouples.findByCaseId("ec id 1"))
        .thenReturn(new EligibleCouple("ec id 1", "123"));
    FormSubmission submission =
        create()
            .withFormName("pnc_registration_oa")
            .withANMId("anm id 1")
            .withEntityId("ec id 1")
            .addFormField("referenceDate", "2012-01-01")
            .addFormField("didWomanSurvive", "no")
            .withSubForm(
                new SubFormData(
                    "child_registration_oa", Collections.<Map<String, String>>emptyList()))
            .build();

    service.pncRegistrationOA(submission);

    verifyZeroInteractions(pncSchedulesService);
  }