@Test
 public void weeksElapsedSince() {
   assertEquals(0, WHPDateUtil.weeksElapsedSince(DateUtil.today()));
   assertEquals(0, WHPDateUtil.weeksElapsedSince(DateUtil.today().minusDays(6)));
   assertEquals(1, WHPDateUtil.weeksElapsedSince(DateUtil.today().minusDays(7)));
   assertEquals(1, WHPDateUtil.weeksElapsedSince(DateUtil.today().minusDays(8)));
 }
  @Test
  public void shouldAddANewSmearTestResultPreservingOrder() {
    SmearTestResults smearTestResults = new SmearTestResults();

    SmearTestRecord SmearTestRecord1 =
        new SmearTestRecord(
            SampleInstance.EndIP,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");
    SmearTestRecord SmearTestRecord2 =
        new SmearTestRecord(
            SampleInstance.ExtendedIP,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");

    smearTestResults.add(SmearTestRecord1);
    smearTestResults.add(SmearTestRecord2);

    assertEquals(2, smearTestResults.size());
    assertThat(smearTestResults.get(0).getSmear_sample_instance(), is(SampleInstance.EndIP));
    assertThat(smearTestResults.get(1).getSmear_sample_instance(), is(SampleInstance.ExtendedIP));
  }
  @Test
  public void shouldReturnSmearTestResultForGivenSampleInstance() {
    SmearTestResults smearTestResults = new SmearTestResults();
    SmearTestRecord pretreatmentSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.PreTreatment,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");
    SmearTestRecord endIpSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.EndIP,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");

    smearTestResults.add(endIpSmearTestRecord);
    smearTestResults.add(pretreatmentSmearTestRecord);

    assertThat(
        smearTestResults.resultForInstance(SampleInstance.PreTreatment),
        is(pretreatmentSmearTestRecord));
    assertThat(smearTestResults.resultForInstance(SampleInstance.EndIP), is(endIpSmearTestRecord));
    assertThat(smearTestResults.resultForInstance(SampleInstance.ExtendedIP), nullValue());
  }
  @Test
  public void shouldGetPreTreatmentSmearTestResult() {
    SmearTestResults smearTestResults = new SmearTestResults();
    SmearTestRecord pretreatmentSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.PreTreatment,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");
    SmearTestRecord endIpSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.EndIP,
            DateUtil.today(),
            SmearTestResult.Negative,
            DateUtil.today(),
            SmearTestResult.Negative,
            "labName",
            "labNumber");
    smearTestResults.add(endIpSmearTestRecord);
    smearTestResults.add(pretreatmentSmearTestRecord);

    assertEquals(SmearTestResult.Positive, smearTestResults.getPreTreatmentResult());
  }
  @Test
  public void shouldReturnIfPreTreatmentSmearTestResultExists() {
    SmearTestResults smearTestResults = new SmearTestResults();
    SmearTestRecord pretreatmentSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.PreTreatment,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");
    SmearTestRecord endIpSmearTestRecord =
        new SmearTestRecord(
            SampleInstance.EndIP,
            DateUtil.today(),
            SmearTestResult.Positive,
            DateUtil.today(),
            SmearTestResult.Positive,
            "labName",
            "labNumber");
    smearTestResults.add(endIpSmearTestRecord);
    smearTestResults.add(pretreatmentSmearTestRecord);

    assertTrue(smearTestResults.hasPreTreatmentResult());
  }
  @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());
  }
Exemple #7
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 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 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);
  }
 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 shouldSetUpCorrectCronExpressionForDailyJob() {
    final LocalDate today = DateUtil.today();
    pillRegimen = new PillRegimen(externalId, dosages, new DailyScheduleDetails(15, 2));
    pillRegimen.setId(pillRegimenId);
    final HashSet<Medicine> medicines =
        new HashSet<Medicine>() {
          {
            add(new Medicine("med1", today.minusDays(1), null));
          }
        };
    final Dosage dosage1 = new Dosage(new Time(10, 5), medicines);

    jobScheduler =
        new PillRegimenJobScheduler(schedulerService) {
          @Override
          public CronSchedulableJob getSchedulableDailyJob(
              String pillRegimenId, String externalId, Dosage dosage) {
            return super.getSchedulableDailyJob(pillRegimenId, externalId, dosage);
          }
        };

    final CronSchedulableJob schedulableJob =
        jobScheduler.getSchedulableDailyJob(pillRegimenId, externalId, dosage1);
    assertEquals(String.format("0 %d %d * * ?", 5, 10), schedulableJob.getCronExpression());
    assertEquals(
        EventKeys.PILLREMINDER_REMINDER_EVENT_SUBJECT_SCHEDULER,
        schedulableJob.getMotechEvent().getSubject());
    assertTrue(schedulableJob.getStartTime().getTime() > today.minusDays(1).toDate().getTime());
  }
  @Test
  public void
      shouldScheduleDailyAdherenceQualityJobsForAPatientOnDailyReminderStartingFromTreatmentAdviceStartDate() {
    final String patientId = "123456";
    Patient patient =
        PatientBuilder.startRecording()
            .withDefaults()
            .withId(patientId)
            .withCallPreference(CallPreference.DailyPillReminder)
            .build();

    final LocalDate startDate = DateUtil.today().plusDays(1);
    final LocalDate endDate = startDate.plusDays(1);

    TreatmentAdvice advice = getTreatmentAdvice(startDate, endDate);

    schedulerService.scheduleJobForDeterminingAdherenceQualityInDailyPillReminder(patient, advice);

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

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

    assertCronSchedulableJob(
        jobScheduledWithParams, "0 0 0 * * ?", startDate.toDate(), endDate.plusDays(1).toDate());

    assertEquals(paramsInScheduledJob.get(EventKeys.EXTERNAL_ID_KEY), patientId);
    assertEquals(
        motechEventInScheduledJob.getSubject(), TAMAConstants.DAILY_ADHERENCE_IN_RED_ALERT_SUBJECT);
  }
  @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 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_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));
  }
  @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 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);
  }
  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 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);
  }
  @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 testFilterIsNotGreaterThanOneYear() {
    LocalDate startDate = DateUtil.today();
    LocalDate endDate = startDate.plusYears(1).minusDays(1);

    FilterWithPatientIDAndDateRange filter = new FilterWithPatientIDAndDateRange();
    filter.setStartDate(startDate);
    filter.setEndDate(endDate);

    assertFalse(filter.isMoreThanOneYear());
  }
 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 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 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 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 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;
 }
  @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)));
  }