/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import org.apache.commons.lang.time.DateUtils;

import gov.va.med.esr.common.util.RuleAbstractTestCase;


import gov.va.med.esr.common.infra.ImpreciseDate;
import gov.va.med.esr.common.infra.ImpreciseDateUtils;
import gov.va.med.esr.common.infra.TriState;
//////////////////////

////////////////////////
import gov.va.med.esr.common.model.person.Association;
import gov.va.med.esr.common.model.person.Dependent;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.DeathRecord;
import gov.va.med.esr.common.model.person.Ethnicity;
import gov.va.med.esr.common.model.person.Race;
import gov.va.med.esr.common.model.person.Spouse;
import gov.va.med.esr.common.model.person.Employment;
import gov.va.med.esr.common.model.person.PreferredFacility;
import gov.va.med.esr.common.model.person.SSN;
import gov.va.med.esr.common.model.person.id.PersonIdEntityKeyImpl;
import gov.va.med.esr.common.model.ee.CampLejeuneVerification;
import gov.va.med.esr.common.model.ee.CombatEpisode;
import gov.va.med.esr.common.model.ee.IncomingMessageInfo;
import gov.va.med.esr.common.model.ee.Eligibility;
import gov.va.med.esr.common.model.ee.MilitaryService;
import gov.va.med.esr.common.model.ee.MedalOfHonor;
import gov.va.med.esr.common.model.ee.EligibilityVerification;
import gov.va.med.esr.common.model.ee.EnrollmentDetermination;
import gov.va.med.esr.common.model.ee.MilitaryServiceSiteRecord;
import gov.va.med.esr.common.model.ee.MilitarySexualTrauma;
import gov.va.med.esr.common.model.ee.NoseThroatRadium;
import gov.va.med.esr.common.model.ee.ReceivedEligibility;
import gov.va.med.esr.common.model.ee.RatedDisability;
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.ee.VerificationInfo;
import gov.va.med.esr.common.model.ee.MilitaryServiceEpisode;
import gov.va.med.esr.common.model.ee.VoaFileAttachment;
import gov.va.med.esr.common.model.ee.VoaFileAttachmentDetail;
import gov.va.med.esr.common.model.registry.Registry;
import gov.va.med.esr.common.model.financials.PatientVisitSummary;
import gov.va.med.esr.common.model.insurance.InsurancePolicy;
import gov.va.med.esr.common.model.financials.Asset;
import gov.va.med.esr.common.model.financials.Debt;
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.Expense;
import gov.va.med.esr.common.model.financials.FinancialInformation;
import gov.va.med.esr.common.model.financials.Income;
import gov.va.med.esr.common.model.financials.IncomeTest;
import gov.va.med.esr.common.model.financials.SpouseFinancials;
import gov.va.med.esr.common.model.financials.FinancialStatement;
import gov.va.med.esr.common.model.financials.IncomeTestStatus;
import gov.va.med.esr.common.model.financials.Hardship;
import gov.va.med.esr.common.model.lookup.AACIndicator;
import gov.va.med.esr.common.model.lookup.DeathDataSource;
import gov.va.med.esr.common.model.lookup.EthnicityType;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.lookup.MilitarySexualTraumaStatus;
import gov.va.med.esr.common.model.lookup.NTRVerificationMethod;
import gov.va.med.esr.common.model.lookup.RaceType;
import gov.va.med.esr.common.model.lookup.AddressType;
import gov.va.med.esr.common.model.lookup.AlliedCountry;
import gov.va.med.esr.common.model.lookup.AssetType;
import gov.va.med.esr.common.model.lookup.AssociationType;
import gov.va.med.esr.common.model.lookup.ConflictLocation;
import gov.va.med.esr.common.model.lookup.Disability;
import gov.va.med.esr.common.model.lookup.DischargeType;
import gov.va.med.esr.common.model.lookup.EligibilityStatus;
import gov.va.med.esr.common.model.lookup.EligibilityVerificationSource;
import gov.va.med.esr.common.model.lookup.EligibilityType;
import gov.va.med.esr.common.model.lookup.EnrollmentPriorityGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentPrioritySubGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentStatus;
import gov.va.med.esr.common.model.lookup.EnrollmentSource;
import gov.va.med.esr.common.model.lookup.EmploymentStatus;
import gov.va.med.esr.common.model.lookup.ExpenseType;
import gov.va.med.esr.common.model.lookup.Gender;
import gov.va.med.esr.common.model.lookup.IncomeTestType;
import gov.va.med.esr.common.model.lookup.IncomeTestSource;
import gov.va.med.esr.common.model.lookup.IncomeType;
import gov.va.med.esr.common.model.lookup.MessageType;
import gov.va.med.esr.common.model.lookup.MeansTestStatus;
import gov.va.med.esr.common.model.lookup.RegistryType;
import gov.va.med.esr.common.model.lookup.Relationship;
import gov.va.med.esr.common.model.lookup.ServiceBranch;
import gov.va.med.esr.common.model.lookup.SSNType;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.lookup.EligibilityDocType;
import gov.va.med.esr.common.rule.data.FinancialInputData;
import gov.va.med.esr.common.rule.parameter.EmploymentInputParameter;
import gov.va.med.esr.common.rule.parameter.FinancialInputParameter;
import gov.va.med.esr.service.EligibilityEnrollmentService;
import gov.va.med.esr.service.MilitaryInfoService;
import gov.va.med.fw.validation.ValidationMessages;
import gov.va.med.fw.rule.SimpleRuleMethod;
import gov.va.med.fw.scheduling.ScheduledProcess;
import gov.va.med.fw.scheduling.ScheduledProcessInvocationContext;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.validation.ValidationServiceException;
import gov.va.med.esr.service.RegistryService;
import gov.va.med.esr.service.RegistrySearchCriteria;
import gov.va.med.esr.service.impl.FinancialsHelperServiceImpl;

public class EligibilityEnrollmentServiceTest extends RuleAbstractTestCase {
	private static final ExpenseType.Code[]     EXPENSE_TYPES_VETERAN      = {
		ExpenseType.EXPENSE_TYPE_FUNERAL_AND_BURIAL,
		ExpenseType.EXPENSE_TYPE_COLLEGE_AND_VOCATION};

	private static final ExpenseType.Code[]     EXPENSE_TYPES_DEPENDENT    = { ExpenseType.EXPENSE_TYPE_EDUCATIONAL_EXPENSES_BY_DEPENDENT};
	private static final Relationship.Code[]     DEPENDENT_RELATIONSHIPS    = { Relationship.CODE_DAUGHTER,
		Relationship.CODE_SON, Relationship.CODE_STEPSON,
		Relationship.CODE_STEPDAUGHTER};
	private interface Factors {
		public static final String AO_VIETNAM = "AO_VIETNAM";
		public static final String V_ENROLL = "V_ENROLL";
		public static final String V_ELIG = "V_ELIG";
		public static final String P_ELIG = "P_ELIG";
	}

	private EligibilityEnrollmentService eligibilityEnrollmentService = null;

	private MilitaryInfoService militaryInfoService = null;

	private RegistryService registryService = null;

	protected static final String INVALID_APPLICATION_DATE_PRIOR_10011996 = "INVALID_APPLICATION_DATE_PRIOR_10011996";
	protected static final String OCCUPATION = "Programmer";
	protected static final String EMPLOYERNAME = "Code Right";
	protected static final String PHONE = "9998881234";

	public static final String PERSON_ID = "241099";

	public EligibilityEnrollmentServiceTest(String testName) {
		super(testName);
	}

	protected void customSetUp() throws Exception {
		super.customSetUp();

	}
	public void testDeathRecord() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachMeansTestWithMtCopayExempt(onFile);
	    SSN ssn = this.createSSN();
	    ssn.setType(this.getLookupService().getSSNTypeByCode(SSNType.CODE_ACTIVE.getName()));
        onFile.addSsn(ssn);
		Person incoming = this.savePerson(onFile);
		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName());

		DeathRecord dr = this.createDeathRecord();
		dr.setDeathDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		dr.setDeathReportDate(new Date());
		dr.setFacilityReceived(sendingFacility);
		dr.setDataSource(this.getLookupService().getDeathDataSourceByCode(
				DeathDataSource.CODE_DEATH_CERT_ON_FILE.getCode()));

		incoming.setDeathRecord(dr);
		Person updated = this.getDemographicService().processDeathRecordFromIdm(incoming);
		assertNotNull(updated.getDeathRecord());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
		//this.setComplete(); // only enable this when you want to test persistence capability
	}
	public void updatePersonForHandbookTesting() throws Exception {
		//PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("490924"));
		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("373975270"));
		Person onFile = this.getPersonService().getPerson(personKey);
//		this.attachCatastrophicDisability(onFile);
//		this.attachPrisonerOfWar(onFile, ImpreciseDateUtils.createImpreciseDate(2008, 1, 1), ImpreciseDateUtils.createImpreciseDate(2008, 4, 1));
//		onFile.addClinicalDetermination(createNTR());
//		onFile.addClinicalDetermination(createMST());
		this.attachRadiationExposure(onFile);
		Person incoming = savePerson(onFile);
		System.out.println("done");
		setComplete();
	}
	 private MilitarySexualTrauma createMST()
	   throws Exception
	   {
	       MilitarySexualTrauma mst = new MilitarySexualTrauma();

	       MilitarySexualTraumaStatus status = (MilitarySexualTraumaStatus)this.getLookupService().getByCode(MilitarySexualTraumaStatus.class,MilitarySexualTraumaStatus.CODE_SCREENED_REPORTS_MST);
	       mst.setStatus(status);
	       mst.setStatusChangeDate(this.getDate(1980,5,16));
	       VAFacility facility = (VAFacility)this.getLookupService().getByCode(VAFacility.class,VAFacility.CODE_CONNECTICUT_HCS);
	       mst.setDeterminationFacility(facility);

	       return mst;
	   }
	 private NoseThroatRadium createNTR()
	   throws Exception
	   {
	       NoseThroatRadium ntr = new NoseThroatRadium();

	       ntr.setVerificationDate(this.getDate(1970,5,16));

	       NTRVerificationMethod method = (NTRVerificationMethod)this.getLookupService().getByCode(NTRVerificationMethod.class,NTRVerificationMethod.CODE_MILITARY_RECORD);
	       ntr.setVerificationMethod(method);

	       VAFacility facility = (VAFacility)this.getLookupService().getByCode(VAFacility.class,VAFacility.CODE_CONNECTICUT_HCS);
	       ntr.setVerificationFacility(facility);

	       ntr.setReceivingTreatment(TriState.TRUE);
	       ntr.setFromAviatorServiceBefore1955(Boolean.TRUE);
	       ntr.setFromSubmarinerServiceBefore1965(Boolean.FALSE);
	       ntr.setDiagnosedWithCancer(Boolean.TRUE);
	       ntr.setDiagnosisVerifiedDate(getDate(2000,1,20));

	       return ntr;
	   }
	public void testBulletinForHandbook() throws Exception {
	     ScheduledProcessInvocationContext context = new ScheduledProcessInvocationContext();
	     context.setExecutionContext("JUnit");
		 ScheduledProcess process = this.getProcess("common.batchprocess.handbookBatchProcess");
		 process.invoke(context);
	}

	public void testTriggerForHandBook() throws Exception {
	     ScheduledProcessInvocationContext context = new ScheduledProcessInvocationContext();
	     context.setExecutionContext("JUnit");
		 ScheduledProcess process = this.getProcess("common.batchprocess.expireMeansTestProcess");
		 process.invoke(context);
	}

	private ScheduledProcess getProcess(String processName) throws Exception {
		return (ScheduledProcess)applicationContext.getBean(processName);
	}
	public void createMHPerson() throws Exception {
		Person onFile = buildSimplePerson(); // bare-bones person
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToVerified(onFile);
		MedalOfHonor mh = new MedalOfHonor();
		mh.setMhIndicator(Boolean.TRUE);
		onFile.setMedalOfHonor(mh);
		Person incoming = savePerson(onFile);
		this.setComplete();
		System.out.println("Person id="
				+ incoming.getPersonEntityKey().getKeyValueAsString());
	}

	public void testMHForCe() throws Exception {

		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("373965033"));
		Person onFile = this.getPersonService().getPerson(personKey);
		Integer incomeYear = new Integer(2010);
		IncomeTest incomeTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED, incomeYear);
		incomeTest.setGmtThresholdAmount(new BigDecimal(1010));
		incomeTest.setDiscloseFinancialInformation(Boolean.TRUE);
		incomeTest.setThresholdA(new BigDecimal(1000));

		incomeTest.setEffectiveDate(getDate(2011,1,1));
		incomeTest.setTotalIncome(new BigDecimal(1011));
		incomeTest.setAgreesToPayDeductible(Boolean.TRUE);
		onFile.setIncomeTest(incomeYear, incomeTest);
		Person incoming = savePerson(onFile);
		incoming.setMedalOfHonor(null);
		Person result = this.getMilitaryInfoService().updateMilitaryServiceInformation(incoming);
		assertNotNull(result.getEnrollmentDetermination().getPriorityGroup());
		assertTrue(result.getEnrollmentDetermination().getPriorityGroup().getCode().equals(EnrollmentPriorityGroup.GROUP_8.getCode()));
		assertTrue(result.getEnrollmentDetermination().getPrioritySubGroup().getCode().equals(EnrollmentPrioritySubGroup.SUBGROUP_D.getCode()));
		System.out.println("done");
		//setComplete();
	}
	public void testAddSkelatalPersonFromZ07() throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");


		Person onFile = this.buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),null);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());

	}

	 public void createPerson() throws Exception {
	        Person onFile = buildSimplePerson(); // bare-bones person
	        this.attachApplication(onFile);
	        onFile.getApplication().setApplicationDate(getDate(2006,1,1));
	        this.attachVerifiedEnrollment(onFile);
	        Person incoming = savePerson(onFile);
	        this.setComplete();
	        System.out.println("Person id=" + incoming.getPersonEntityKey().getKeyValueAsString());
	    }

	public void testAddAddressFromUI() throws Exception {

		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("373973231"));
		Person onFile = this.getPersonService().getPerson(personKey);
		Person incoming = (Person)onFile.clone();
		System.out.println("Person =" +incoming.getIdentityTraits().getLegalName().getGivenName());

//		incoming.addAddress(this.createAddress( this.getAddressType( AddressType.CODE_PERMANENT_ADDRESS)));
//		incoming.addAddress(createAddress("Atlanta", "Road Street", "GA", "30305",Calendar.getInstance().getTime(),
//				AddressType.CODE_PERMANENT_ADDRESS.getName()));
//
//		Person updated = this.getDemographicService().updateContactInformation(incoming);
//
//		System.out.println("Person id="
//				+ updated.getPersonEntityKey().getKeyValueAsString());

	}

	public void testAddAPerson() throws Exception {
		Person onFile = buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		String stationNumber = "200ESR";
		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(stationNumber);
		Association association = this.createPersonAssociation( "EDS", "Manager " , AssociationType.CODE_PRIMARY_NEXT_OF_KIN.getName() );
		association.setAddress( this.createAddress( this.getAddressType( AddressType.CODE_PERMANENT_ADDRESS)));
		association.setLastUpdateDate( new Date());
		incoming.addAssociation( association );
		Ethnicity eth = new Ethnicity();
		eth.setEthnicityType(this.getLookupService().getEthnicityTypeByCode(EthnicityType.CODE_UNKNOWN.getCode()));
		incoming.setEthnicity(eth);
		Race race = new Race();
		race.setRaceType(this.getLookupService().getRaceTypeByCode(RaceType.CODE_UNKNOWN.getCode()));
		incoming.removeAllRaces();
		incoming.addRace(race);

		Employment emp = new Employment();
		emp.setEmployerName("TESTER EMPLOYER");
		emp.setEmployerAddress(this.createAddress( this.getAddressType( AddressType.CODE_BUSINESS_ADDRESS)));
		emp.setEmployerPhone("1234567890");
		emp.setEmploymentStatus(this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));

		incoming.setEmployment(emp);

		VAFacility fac = this.getLookupService().getVaFacilityByCode("722");
		PreferredFacility pfac = new PreferredFacility();
		pfac.setFacility(fac);
		incoming.addPreferredFacility(pfac);
		incoming.setMostRecentPreferredFacility(fac);

		incoming.setMilitaryService(new MilitaryService());
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(this.getLookupService().getServiceBranchByCode(ServiceBranch.CODE_ARMY.getCode()));
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(2009, 1, 1));
		mse.setServiceNumber("12345");
		MilitaryServiceSiteRecord m = this.createMilitaryServiceSireRecord();
		m.setSite(this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName()));
		m.addMilitaryServiceEpisode(mse);
		incoming.getMilitaryService().addMilitaryServiceSiteRecord(m);

		CombatEpisode ce = new CombatEpisode();
		ce.setConflictLocation(this.getLookupService().getConflictByCode(ConflictLocation.CODE_UNKNOWN_OEF_OIF.getCode()));
		ce.setStartDate(ImpreciseDateUtils.createImpreciseDate(2002,2,1));
		ce.setEndDate(ImpreciseDateUtils.createImpreciseDate(2007,11,1));
		incoming.getMilitaryService().addCombatEpisode(ce);

		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(this.getRandomVAFacility());
		incoming.getEligibilityVerification().setVerificationSource(
				this.getLookupService().getEligibilityVerificationSourceByCode(EligibilityVerificationSource.CODE_CEV.getCode()));

		this.setServiceConnectedPercentage(new Integer(100), incoming);
		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),null);
		incoming.getPermanentAddress().setChangeDate(null);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		Iterator iter = incoming.getServiceConnectionAward().getRatedDisabilities().iterator();
		while (iter.hasNext()) {
			RatedDisability rd = (RatedDisability) iter.next();
			rd.setPercentage(new Integer(100));
		}
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processAddPerson(incoming,sendingFacility, vi);
		assertNotNull(updated.getPermanentAddress().getChangeDate());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
		this.setComplete();
	}

	public void testAddAPerson11457() throws Exception {
		Person onFile = buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		String stationNumber = "200ESR";

		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(stationNumber);

		Association association = this.createPersonAssociation( "EDS", "Manager " , AssociationType.CODE_PRIMARY_NEXT_OF_KIN.getName() );
		association.setAddress( this.createAddress( this.getAddressType( AddressType.CODE_PERMANENT_ADDRESS)));
		association.setLastUpdateDate( new Date());
		incoming.addAssociation( association );

		Ethnicity eth = new Ethnicity();
		eth.setEthnicityType(this.getLookupService().getEthnicityTypeByCode(EthnicityType.CODE_UNKNOWN.getCode()));
		incoming.setEthnicity(eth);

		Race race = new Race();
		race.setRaceType(this.getLookupService().getRaceTypeByCode(RaceType.CODE_UNKNOWN.getCode()));
		incoming.removeAllRaces();
		incoming.addRace(race);

		Employment emp = new Employment();
		emp.setEmployerName("TESTER EMPLOYER");
		emp.setEmployerAddress(this.createAddress( this.getAddressType( AddressType.CODE_BUSINESS_ADDRESS)));
		emp.setEmployerPhone("1234567890");
		emp.setEmploymentStatus(this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));

		incoming.setEmployment(emp);

		VAFacility fac = this.getLookupService().getVaFacilityByCode("553");
		PreferredFacility pfac = new PreferredFacility();
		pfac.setFacility(fac);
		incoming.addPreferredFacility(pfac);
		incoming.setMostRecentPreferredFacility(fac);


		incoming.setMilitaryService(new MilitaryService());
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(this.getLookupService().getServiceBranchByCode(ServiceBranch.CODE_ARMY.getCode()));
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(2009, 1, 1));
		mse.setServiceNumber("12345");

		MilitaryServiceSiteRecord m = this.createMilitaryServiceSireRecord();
		m.setSite(this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName()));
		m.addMilitaryServiceEpisode(mse);
		incoming.getMilitaryService().addMilitaryServiceSiteRecord(m);


		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(this.getRandomVAFacility());
		incoming.getEligibilityVerification().setVerificationSource(
				this.getLookupService().getEligibilityVerificationSourceByCode(EligibilityVerificationSource.CODE_CEV.getCode()));

		this.setServiceConnectedPercentage(new Integer(0), incoming);

		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),null);
		incoming.getPermanentAddress().setChangeDate(null);

		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		Iterator iter = incoming.getServiceConnectionAward().getRatedDisabilities().iterator();
		while (iter.hasNext()) {
			RatedDisability rd = (RatedDisability) iter.next();
			rd.setPercentage(new Integer(0));
		}

		vi.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processAddPerson(incoming,sendingFacility, vi);
		assertNotNull(updated.getPermanentAddress().getChangeDate());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
		//this.setComplete();
	}

	public void testAAP_NSC_11457() throws Exception {
		Person onFile = buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		String stationNumber = "200ESR";

		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(stationNumber);

		Association association = this.createPersonAssociation( "EDS", "Manager " , AssociationType.CODE_PRIMARY_NEXT_OF_KIN.getName() );
		association.setAddress( this.createAddress( this.getAddressType( AddressType.CODE_PERMANENT_ADDRESS)));
		association.setLastUpdateDate( new Date());
		incoming.addAssociation( association );

		Ethnicity eth = new Ethnicity();
		eth.setEthnicityType(this.getLookupService().getEthnicityTypeByCode(EthnicityType.CODE_UNKNOWN.getCode()));
		incoming.setEthnicity(eth);

		Race race = new Race();
		race.setRaceType(this.getLookupService().getRaceTypeByCode(RaceType.CODE_UNKNOWN.getCode()));
		incoming.removeAllRaces();
		incoming.addRace(race);

		Employment emp = new Employment();
		emp.setEmployerName("TESTER EMPLOYER");
		emp.setEmployerAddress(this.createAddress( this.getAddressType( AddressType.CODE_BUSINESS_ADDRESS)));
		emp.setEmployerPhone("1234567890");
		emp.setEmploymentStatus(this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));

		incoming.setEmployment(emp);

		VAFacility fac = this.getLookupService().getVaFacilityByCode("553");
		PreferredFacility pfac = new PreferredFacility();
		pfac.setFacility(fac);
		incoming.addPreferredFacility(pfac);
		incoming.setMostRecentPreferredFacility(fac);

		incoming.setMilitaryService(new MilitaryService());
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(this.getLookupService().getServiceBranchByCode(ServiceBranch.CODE_ARMY.getCode()));
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(2009, 1, 1));
		mse.setServiceNumber("12345");

		MilitaryServiceSiteRecord m = this.createMilitaryServiceSireRecord();
		m.setSite(this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName()));
		m.addMilitaryServiceEpisode(mse);
		incoming.getMilitaryService().addMilitaryServiceSiteRecord(m);


		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(this.getRandomVAFacility());
		incoming.getEligibilityVerification().setVerificationSource(
				this.getLookupService().getEligibilityVerificationSourceByCode(EligibilityVerificationSource.CODE_CEV.getCode()));

		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),null);
		incoming.getPermanentAddress().setChangeDate(null);

		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processAddPerson(incoming,sendingFacility, vi);
		assertNotNull(updated.getPermanentAddress().getChangeDate());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
		//this.setComplete();
	}
	public void testAddASkeletalPerson() throws Exception {
		Person onFile = buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		String stationNumber = "200ESR";
		VAFacility sendingFacility = this.getLookupService().getVaFacilityByStationNumber(stationNumber);
		Association association = this.createPersonAssociation( "EDS", "Manager " , AssociationType.CODE_GUARDIAN_VA.getName() );
		association.setAddress( this.createAddress( this.getAddressType( AddressType.CODE_PERMANENT_ADDRESS)));
		association.setLastUpdateDate( new Date());
		incoming.addAssociation( association );

		this.setEligibilityStatusToVerified(incoming);

		VAFacility fac = this.getLookupService().getVaFacilityByCode("722");
		PreferredFacility pfac = new PreferredFacility();
		pfac.setFacility(fac);
		incoming.addPreferredFacility(pfac);
		incoming.setMostRecentPreferredFacility(fac);
		this.attachIncomeTest(incoming, new Integer(2010), fac, MeansTestStatus.MT_STATUS_EXEMPT);
		IncomeTest test = incoming.getIncomeTest(new Integer(2010));
		test.setEffectiveDate(new Date());
		test.removeAllStatuses();
		FinancialStatement fs = incoming.getFinancialStatement(new Integer(2010));
		fs.setDebt(null);

		InsurancePolicy policy = this.createPrivateInsurance();
		policy.setReportSite(this.getLookupService().getVaFacilityByCode("742"));
		policy.setAddress(createAddress());
		incoming.addInsurance(policy);

		incoming.setMilitaryService(new MilitaryService());
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(this.getLookupService().getServiceBranchByCode(ServiceBranch.CODE_ARMY.getCode()));
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(2009, 1, 1));
		mse.setServiceNumber("12345");
		MilitaryServiceSiteRecord m = this.createMilitaryServiceSireRecord();
		m.setSite(this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName()));
		m.addMilitaryServiceEpisode(mse);
		incoming.getMilitaryService().addMilitaryServiceSiteRecord(m);

		CombatEpisode ce = new CombatEpisode();
		ce.setConflictLocation(this.getLookupService().getConflictByCode(ConflictLocation.CODE_UNKNOWN_OEF_OIF.getCode()));
		ce.setStartDate(ImpreciseDateUtils.createImpreciseDate(2002,2,1));
		ce.setEndDate(ImpreciseDateUtils.createImpreciseDate(2007,11,1));
		incoming.getMilitaryService().addCombatEpisode(ce);

		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(this.getRandomVAFacility());
		this.setServiceConnectedPercentage(new Integer(0), incoming);
		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),null);
		VerificationInfo vi = new VerificationInfo(null,	MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		Iterator iter = incoming.getServiceConnectionAward().getRatedDisabilities().iterator();
		while (iter.hasNext()) {
			RatedDisability rd = (RatedDisability) iter.next();
			rd.setPercentage(new Integer(0));
		}
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processAddPerson(incoming,sendingFacility, vi);
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
		//this.setComplete();
	}

	public void testMHcausesP3() throws Exception {
		Person onFile = buildSimplePerson();

		this.setEligibilityStatusToVerified(onFile);
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_4.getCode()));

		this.attachMeansTestWithMtCopayExempt(onFile);
		this.attachMilitaryService(onFile);
		MedalOfHonor mh = new MedalOfHonor();
		mh.setMhIndicator(Boolean.TRUE);
		onFile.setMedalOfHonor(mh);
		Person incoming = this.savePerson(onFile);


		this.getEnrollmentRuleService().calculateEE(incoming, true, false);
		assertNotNull(incoming.getEnrollmentDetermination().getPriorityGroup());
		assertTrue(incoming.getEnrollmentDetermination().getPriorityGroup().getCode().equals(EnrollmentPriorityGroup.GROUP_3.getCode()));
		System.out.println("Person id="
				+ incoming.getPersonEntityKey().getKeyValueAsString());
	}

	public void testMHFromYesToNo() throws Exception {
		Person onFile = buildSimplePerson();

		this.setEligibilityStatusToVerified(onFile);
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_3.getCode()));

		this.attachMeansTestWithMtCopayRequired(onFile,new BigDecimal(1000), new BigDecimal(2000));
		this.attachMilitaryService(onFile);
		MedalOfHonor mh = new MedalOfHonor();
		mh.setMhIndicator(Boolean.TRUE);
		onFile.setMedalOfHonor(mh);
		Person incoming = this.savePerson(onFile);


		incoming.setMedalOfHonor(null);
		this.getEnrollmentRuleService().calculateEE(incoming, true, false);
		assertNotNull(incoming.getEnrollmentDetermination().getPriorityGroup());
		assertTrue(incoming.getEnrollmentDetermination().getPriorityGroup().getCode().equals(EnrollmentPriorityGroup.GROUP_8.getCode()));
		assertTrue(incoming.getEnrollmentDetermination().getPrioritySubGroup().getCode().equals(EnrollmentPrioritySubGroup.SUBGROUP_G.getCode()));
		System.out.println("Person id=" + incoming.getPersonEntityKey().getKeyValueAsString());
	}
	public void testUpdatingMH() throws Exception {
		Person onFile = buildSimplePerson();

		this.setEligibilityStatusToVerified(onFile);
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_4.getCode()));

		this.attachMeansTestWithMtCopayExempt(onFile);
		this.attachMilitaryService(onFile);
		Person incoming = this.savePerson(onFile);
		MedalOfHonor mh = new MedalOfHonor();
		mh.setMhIndicator(Boolean.TRUE);
		incoming.setMedalOfHonor(mh);

		Person result = this.getMilitaryRuleService().manageMilitaryService(incoming.getMilitaryService(), onFile);

		assertNotNull(result.getMedalOfHonor());
		assertTrue(result.getMedalOfHonor().getMhIndicator().booleanValue());
	}


	/*
	 * FROM DENA Vet was in Chey 3 – current IY2009 MT Copay Exempt – PG 5
	 *
	 * I registered this vet in VsID  – site queried ESR and ESR returns
	 * Z05/Z10/Z11 as expected – all data uploaded to VsID 
	 *
	 * I added Cat Dis to Chey3 (has the Public Law Vista patch for Cat Dis
	 * logic) – Chey3 appropriately made the veteran PG 4 and his MT = NLR
	 *
	 * Transmitted Z07 from Chey3 ESR correctly set veteran to PG 4, MT to NLR
	 * and Rx to NLA
	 *
	 * And here’s the odd part…..only Z10s were sent to the sites (with the NLR
	 * status on the ZMT). No Z11s went out at all. I went back into Chey3 to
	 * check the MT status, and it’s back to MT Copay Exempt! (same scenario we
	 * sent Dennis Bricker earlier today)
	 *
	 */
	public void testCdZ11Issue() throws Exception {
		Person onFile = buildSimplePerson();

		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getName()));
		this.attachVerifiedEnrollment(onFile);
		this.attachMeansTestWithNoLongerRequired(onFile);

		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_4.getCode()));

		this.attachCatastrophicDisability(onFile);
		this.attachMilitaryService(onFile);
		VAFacility fac = onFile.getCatastrophicDisability()
		.getDeterminationFacility();
		Person incoming = this.savePerson(onFile);

//		incoming.getCatastrophicDisability().setCatastrophicallyDisabled(
//		Boolean.FALSE);
		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(fac);

		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),
				null);
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				vi);
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testPerson838() throws Exception {
		//	Person onFile = this.getPerson("838");
		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("838"));
		Person onFile = this.getPersonService().getPerson(personKey);

		this.savePerson(onFile);
		this.setComplete();

	}
	protected void setFinancialInfo(FinancialInformation finInfo, double incomeAmount, double expenseAmount,
			double assetAmount, double debtAmount) throws Exception {
		Asset asset = (Asset) finInfo.getAssets().values().iterator().next();
		asset.setAmount(new BigDecimal(assetAmount));
		Income income = (Income) finInfo.getIncome().values().iterator().next();
		income.setAmount(new BigDecimal(incomeAmount));
		Expense expense = (Expense) finInfo.getExpenses().values().iterator().next();
		expense.setAmount(new BigDecimal(expenseAmount));
		Debt debt = finInfo.getDebt();
		debt.setAmount(new BigDecimal(debtAmount));
	}
	protected FinancialStatement buildFinancialStatementData(Integer incomeYear, Person person)
	throws Exception {
		FinancialStatement stmt = person.getFinancialStatement(incomeYear);
		if (stmt == null) {
			stmt = createFinancialStatement();
			setFinancialInfo(stmt, 50000, 0, 0, 2000);
			createAsset(stmt, 50000, AssetType.CODE_CASH);
			createAsset(stmt, 100000, AssetType.CODE_REAL_ESTATE);
			createAsset(stmt, 10000, AssetType.CODE_OTHER);
			setExpense(stmt, 2000, ExpenseType.EXPENSE_TYPE_FUNERAL_AND_BURIAL);
			setExpense(stmt, 4000, ExpenseType.EXPENSE_TYPE_NON_REIMBURSED_MEDICAL);
			person.setFinancialStatement(incomeYear, stmt);
		}
		Calendar startDate = Calendar.getInstance();
		startDate.set(Calendar.YEAR, incomeYear.intValue() - 1);
		Spouse spouse = createSpouse();
		spouse.setStartDate(new ImpreciseDate(startDate));

		SpouseFinancials sf = createSpouseFinancials(spouse);
		setFinancialInfo(sf, 30000, 500, 5000, 1000);
		createAsset(sf, 5000, AssetType.CODE_OTHER);
		stmt.setMarriedLastCalendarYear(Boolean.TRUE);
		stmt.removeActiveSpouseFinancials();
		stmt.addSpouseFinancials(sf);

		DependentFinancials df1 = createDependentFinancials(incomeYear, Relationship.CODE_DAUGHTER);
		stmt.addDependentFinancials(df1);

		Dependent dependent2 = createDependent();
		DependentFinancials df2 = createDependentFinancials(dependent2);
		dependent2.setRelationship(getLookupService().getRelationshipByCode(Relationship.CODE_SON.getName()));
		dependent2.setStartDate(new ImpreciseDate(startDate));
		df2.setLivedWithPatient(Boolean.FALSE);
		df2.setHasIncome(Boolean.TRUE);
		df2.setIncomeAvailableToPatient(Boolean.TRUE);
		df2.setContributedToSupport(Boolean.TRUE);
		setFinancialInfo(df2, 20000, 1200, 2050, 1000);
		createIncome(df2, 2000, IncomeType.INCOME_TYPE_TOTAL_INCOME_FROM_EMPLOYMENT);
		stmt.addDependentFinancials(df2);

		return stmt;
	}

	private DependentFinancials createDependentFinancials(Integer incomeYear, Relationship.Code relationship)
	throws Exception, UnknownLookupTypeException, UnknownLookupCodeException {
		Calendar startDate = Calendar.getInstance();
		startDate.set(Calendar.YEAR, incomeYear.intValue() - 1);

		Dependent dependent1 = createDependent();
		DependentFinancials df1 = createDependentFinancials(dependent1);
		dependent1.setRelationship(getLookupService().getRelationshipByCode(relationship.getName()));
		dependent1.setStartDate(new ImpreciseDate(startDate));
		df1.setLivedWithPatient(Boolean.TRUE);
		df1.setHasIncome(Boolean.TRUE);
		df1.setIncomeAvailableToPatient(Boolean.TRUE);
		setFinancialInfo(df1, 10000, 1500, 1750, 750);
		createIncome(df1, 5000, IncomeType.INCOME_TYPE_TOTAL_INCOME_FROM_EMPLOYMENT);
		setExpense(df1, 500, ExpenseType.EXPENSE_TYPE_EDUCATIONAL_EXPENSES_BY_DEPENDENT);
		return df1;
	}
	protected DependentFinancials createDependentFinancials(Dependent dependent)
	throws Exception {
		return createDependentFinancials(dependent, getRandomAssetType(),
				getRandomIncomeType(), getRandomExpenseType());
	}

	protected SpouseFinancials createSpouseFinancials(Spouse spouse)
	throws Exception {
		return createSpouseFinancials(spouse, getRandomAssetType(),
				getRandomIncomeType(), getRandomExpenseType());
	}

	private FinancialInputParameter buildFinancialInputParameter(FinancialInputData data) throws ServiceException {
		FinancialInputParameter fip = new FinancialInputParameter();//(FinancialInputParameter) applicationContext.getBean("financialRuleParameter"); //new FinancialInputParameter();
		fip.setRuleDataAware(data);
		fip.setLookupService(getLookupService());
		fip.setHelperService(getPersonHelperService());
		fip.setFinancialsHelperService(new FinancialsHelperServiceImpl());
		fip.setVeteranExpenseTypes(EXPENSE_TYPES_VETERAN);
		fip.setChildExpenseTypes(EXPENSE_TYPES_DEPENDENT);
		fip.setChildRelationships(DEPENDENT_RELATIONSHIPS);
		return fip;
	}

	public void testSpouseEmploymentZ07AddsWithMockPerson() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachMeansTestWithMtCopayExempt(onFile);

		Integer incomeYear =  (Integer)onFile.getIncomeTests().keySet().iterator().next();
		IncomeTest test = onFile.getIncomeTest(incomeYear);
		test.setSiteConductingTest(getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER));
		test.setSource(this.getLookupService().getIncomeTestSourceByCode(
				IncomeTestSource.CODE_VAMC.getCode()));

		VAFacility fac = test.getSiteConductingTest();
		FinancialStatement stmt = buildFinancialStatementData(incomeYear, onFile);

		SpouseFinancials sf = stmt.getActiveSpouseFinancials();

		sf.getReportedOn().setEmployment(new Employment());
		sf.getReportedOn().getEmployment().setEmploymentStatus(
				this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_RETIRED.getCode()));
		sf.getReportedOn().getEmployment().setRetirementDate(new ImpreciseDate(new Date()));
		//FinancialInputData data = new FinancialInputData(incomingTmp, onFile, pristineTmp, incomeYear, getVaFacility(VAFacility.CODE_HEC), true);
		FinancialStatement fsO = onFile.getFinancialStatement(incomeYear);
		SpouseFinancials sfO = fsO.getActiveSpouseFinancials();
		Spouse sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());

		this.attachVerifiedEnrollment(onFile);
		this.attachEligibilityVerification(onFile, EligibilityVerificationSource.CODE_VAMC.getCode());
		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(fac);
		//============================
		Person incoming = this.savePerson(onFile);
		//============================

		FinancialStatement fs = incoming.getFinancialStatement(incomeYear);
		SpouseFinancials incomingSf = fs.getActiveSpouseFinancials();
		Spouse incomingSpouse = incomingSf.getReportedOn();
		incomingSpouse.getEmployment().setEmployerAddress(this.createAddress());

		incomingSpouse.getEmployment().setRetirementDate(null);
		incomingSpouse.getEmployment().setEmployerPhone(PHONE);
		incomingSpouse.getEmployment().setOccupation(OCCUPATION);
		incomingSpouse.getEmployment().setEmployerName(EMPLOYERNAME);;
		incomingSpouse.getEmployment().setEmploymentStatus(
				this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));
		incomingSpouse.getEmployment().getEmployerAddress().setLine2("x");
		incomingSpouse.getEmployment().getEmployerAddress().setLine3("x");
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(fac.getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,vi);

		fsO = updated.getFinancialStatement(new Integer(2005));
		sfO = fsO.getActiveSpouseFinancials();
		sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());
		assertEquals(OCCUPATION, sO.getEmployment().getOccupation());
		assertEquals(PHONE, sO.getEmployment().getEmployerPhone());
		assertEquals(EMPLOYERNAME, sO.getEmployment().getEmployerName());
		assertEquals(EmploymentStatus.CODE_FULL_TIME.getCode(), sO.getEmployment().getEmploymentStatus().getCode());
		assertNotNull(sO.getEmployment().getEmployerAddress());
		assertNotNull(sO.getEmployment().getEmployerAddress().getCity());
		assertNotNull(sO.getEmployment().getEmployerAddress().getLine1());
		assertNotNull(sO.getEmployment().getEmployerAddress().getLine2());
		assertNotNull(sO.getEmployment().getEmployerAddress().getLine3());
		assertNotNull(sO.getEmployment().getEmployerAddress().getState());
		assertNotNull(sO.getEmployment().getEmployerAddress().getZipCode());
		//this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testSpouseEmploymentZ07DeletesWithMockPerson() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachMeansTestWithMtCopayExempt(onFile);

		Integer incomeYear =  (Integer)onFile.getIncomeTests().keySet().iterator().next();
		IncomeTest test = onFile.getIncomeTest(incomeYear);
		test.setSiteConductingTest(getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER));
		test.setSource(this.getLookupService().getIncomeTestSourceByCode(
				IncomeTestSource.CODE_VAMC.getCode()));

		VAFacility fac = test.getSiteConductingTest();
		FinancialStatement stmt = buildFinancialStatementData(incomeYear, onFile);

		SpouseFinancials sf = stmt.getActiveSpouseFinancials();

		sf.getReportedOn().setEmployment(new Employment());
		sf.getReportedOn().getEmployment().setEmploymentStatus(
				this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_RETIRED.getCode()));
		sf.getReportedOn().getEmployment().setRetirementDate(new ImpreciseDate(new Date()));
		//FinancialInputData data = new FinancialInputData(incomingTmp, onFile, pristineTmp, incomeYear, getVaFacility(VAFacility.CODE_HEC), true);
		FinancialStatement fsO = onFile.getFinancialStatement(incomeYear);
		SpouseFinancials sfO = fsO.getActiveSpouseFinancials();
		Spouse sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());

		sO.getEmployment().setEmployerAddress(this.createAddress());
		sO.getEmployment().setRetirementDate(null);
		sO.getEmployment().setEmployerPhone(PHONE);
		sO.getEmployment().setOccupation(OCCUPATION);
		sO.getEmployment().setEmployerName(EMPLOYERNAME);;
		sO.getEmployment().setEmploymentStatus(
				this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));
		sO.getEmployment().getEmployerAddress().setLine2("x");
		sO.getEmployment().getEmployerAddress().setLine3("x");

		this.attachVerifiedEnrollment(onFile);
		this.attachEligibilityVerification(onFile, EligibilityVerificationSource.CODE_VAMC.getCode());
		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(fac);
		//============================
		Person incoming = this.savePerson(onFile);
		//============================

		FinancialStatement fs = incoming.getFinancialStatement(incomeYear);
		SpouseFinancials incomingSf = fs.getActiveSpouseFinancials();
		Spouse incomingSpouse = incomingSf.getReportedOn();
		incomingSpouse.getEmployment().getEmployerAddress().setLine1(null);
		incomingSpouse.getEmployment().getEmployerAddress().setLine2(null);
		incomingSpouse.getEmployment().getEmployerAddress().setLine3(null);
		incomingSpouse.getEmployment().getEmployerAddress().setCity(null);
		incomingSpouse.getEmployment().getEmployerAddress().setState(null);
		incomingSpouse.getEmployment().getEmployerAddress().setZipCode(null);


		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(fac.getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,vi);

		fsO = updated.getFinancialStatement(new Integer(2005));
		sfO = fsO.getActiveSpouseFinancials();
		sO = sfO.getReportedOn();
		assertEquals(OCCUPATION, sO.getEmployment().getOccupation());
		assertEquals(PHONE, sO.getEmployment().getEmployerPhone());
		assertEquals(EMPLOYERNAME, sO.getEmployment().getEmployerName());
		assertEquals(EmploymentStatus.CODE_FULL_TIME.getCode(), sO.getEmployment().getEmploymentStatus().getCode());

		assertNull(sO.getEmployment().getEmployerAddress().getCity());
		assertNull("expected line 1 to be null",sO.getEmployment().getEmployerAddress().getLine1());
		assertNull(sO.getEmployment().getEmployerAddress().getLine2());
		assertNull(sO.getEmployment().getEmployerAddress().getLine3());
		assertNull(sO.getEmployment().getEmployerAddress().getState());
		assertNull(sO.getEmployment().getEmployerAddress().getZipCode());
		//this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testSpouseEmploymentZ07DeletesEmploymentWithMockPerson() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachMeansTestWithMtCopayExempt(onFile);

		Integer incomeYear =  (Integer)onFile.getIncomeTests().keySet().iterator().next();
		IncomeTest test = onFile.getIncomeTest(incomeYear);
		test.setSiteConductingTest(getVaFacility(VAFacility.CODE_IRON_MOUNTAIN_VA_MEDICAL_CENTER));
		test.setSource(this.getLookupService().getIncomeTestSourceByCode(
				IncomeTestSource.CODE_VAMC.getCode()));

		VAFacility fac = test.getSiteConductingTest();
		FinancialStatement stmt = buildFinancialStatementData(incomeYear, onFile);

		SpouseFinancials sf = stmt.getActiveSpouseFinancials();

		sf.getReportedOn().setEmployment(new Employment());
		sf.getReportedOn().getEmployment().setEmploymentStatus(
				this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_RETIRED.getCode()));
		sf.getReportedOn().getEmployment().setRetirementDate(new ImpreciseDate(new Date()));
		//FinancialInputData data = new FinancialInputData(incomingTmp, onFile, pristineTmp, incomeYear, getVaFacility(VAFacility.CODE_HEC), true);
		FinancialStatement fsO = onFile.getFinancialStatement(incomeYear);
		SpouseFinancials sfO = fsO.getActiveSpouseFinancials();
		Spouse sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());

		this.attachVerifiedEnrollment(onFile);
		this.attachEligibilityVerification(onFile, EligibilityVerificationSource.CODE_VAMC.getCode());
		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(fac);
		//============================
		Person incoming = this.savePerson(onFile);
		//============================

		FinancialStatement fs = incoming.getFinancialStatement(incomeYear);
		SpouseFinancials incomingSf = fs.getActiveSpouseFinancials();
		Spouse incomingSpouse = incomingSf.getReportedOn();
		incomingSpouse.getEmployment().setEmploymentStatus(this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_UNKNOWN.getCode()));

		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(fac.getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,vi);

		fsO = updated.getFinancialStatement(new Integer(2005));
		sfO = fsO.getActiveSpouseFinancials();
		sO = sfO.getReportedOn();
		assertNull("expected address to be null",sO.getEmployment().getEmployerAddress());
		assertEquals("expected status to be updated",sO.getEmployment().getEmploymentStatus().getCode(),EmploymentStatus.CODE_UNKNOWN.getCode());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}
	public void testSpouseEmploymentZ07WithNullRetirementDate() throws Exception {
		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("838"));
		Person onFile = this.getPersonService().getPerson(personKey);
		FinancialStatement fsO = onFile.getFinancialStatement(new Integer(2005));
		SpouseFinancials sfO = fsO.getActiveSpouseFinancials();
		Spouse sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());

		Person incoming = (Person)onFile.clone();

		FinancialStatement fs = incoming.getFinancialStatement(new Integer(2005));
		SpouseFinancials sf = fs.getActiveSpouseFinancials();
		Spouse s = sf.getReportedOn();
		s.getEmployment().setRetirementDate(null);

		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(incoming.getEligibilityVerification().getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processZ07(incoming, incoming.getEligibilityVerification().getVerificationFacility(),
				vi);
		//this.setComplete();
		fsO = updated.getFinancialStatement(new Integer(2005));
		sfO = fsO.getActiveSpouseFinancials();
		sO = sfO.getReportedOn();
		assertNotNull(sO.getEmployment().getRetirementDate());

		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testSpouseEmploymentZ07WithWrongStatus() throws Exception {
		this.fail("this is for VOA only so don't run yet" );

		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal("838"));
		Person onFile = this.getPersonService().getPerson(personKey);
		FinancialStatement onfilefsO = onFile.getFinancialStatement(new Integer(2005));
		SpouseFinancials onfilesfO = onfilefsO.getActiveSpouseFinancials();
		Spouse onfilesO = onfilesfO.getReportedOn();
		assertNotNull(onfilesO.getEmployment().getRetirementDate());

		Person incoming = (Person)onFile.clone();

		FinancialStatement fs = incoming.getFinancialStatement(new Integer(2005));
		SpouseFinancials sf = fs.getActiveSpouseFinancials();
		Spouse s = sf.getReportedOn();
		s.getEmployment().setRetirementDate(null);
		s.getEmployment().setEmploymentStatus(this.getLookupService().getEmploymentStatusByCode(EmploymentStatus.CODE_FULL_TIME.getCode()));
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(incoming.getEligibilityVerification().getVerificationFacility().getCode());

		EmploymentInputParameter parm = new EmploymentInputParameter();
		parm.setRuleMethod(new SimpleRuleMethod());
		boolean flag1 = parm.isEqual(s.getEmployment().getEmploymentStatus().getCode(), onfilesO.getEmployment().getEmploymentStatus().getCode() );

		Person updated = this.getMessagingService().processZ07(incoming, incoming.getEligibilityVerification().getVerificationFacility(),
				vi);
		//this.setComplete();
		FinancialStatement fsO = updated.getFinancialStatement(new Integer(2005));
		SpouseFinancials sfO = fsO.getActiveSpouseFinancials();
		Spouse sO = sfO.getReportedOn();
		assertNull(sO.getEmployment().getRetirementDate());

		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	/**
	 * Use for creating data to test appointment batch job
	 *
	 * @throws Exception
	 */
	public void testCreateApptCancelPerson() throws Exception {
		this.doCreateAppPerson(EnrollmentStatus.CODE_CANCELLED_DECLINED
				.getCode());
	}

	/**
	 * Use for creating data to test appointment batch job
	 *
	 * @throws Exception
	 */
	public void testCreateApptEGTRejectPerson() throws Exception {
		this.doCreateAppPerson(EnrollmentStatus.CODE_REJECTED_BELOW_ENROLLMENT_GROUP_THRESHOLD
				.getCode());
	}

	/**
	 * Use for creating data to test appointment batch job
	 *
	 * @throws Exception
	 */
	public void testCreateApptRecRejectPerson() throws Exception {
		this.doCreateAppPerson(EnrollmentStatus.CODE_REJECTED_INITIAL_APPLICATION_BY_VAMC
				.getCode());
	}

	private void doCreateAppPerson(String status) throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.setAppointmentRequestDate(this.getDate(2007, 0, 1));
		onFile.setAppointmentRequestResponse(Boolean.TRUE);
		onFile.getEnrollmentDetermination().setEnrollmentStatus(
				this.getLookupService().getEnrollmentStatusByCode(status));
		onFile.getEnrollmentDetermination().setEffectiveDate(
				this.getDate(2005, 7, 1)); // month starts at 0
		Person updated = getPersonService().save(onFile);
		this.setComplete();
		assertNotNull(updated.getEntityKey());
		System.out.println("Created Person: " + updated.getEntityKey());
	}

	public void testZ07Add2006ToNewPerson() throws Exception {

		assertNotNull(this.addMTtoNewPerson("657", "657"));
	}

	public void testAgentOrange() throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		List factors = new ArrayList();
		factors.add(Factors.AO_VIETNAM);
		factors.add(Factors.V_ENROLL);
		factors.add(Factors.P_ELIG);
		Integer incomeYear = new Integer(2009);
		Person onFile = this.buildPersonFromZ07(incomeYear.intValue(), factors, fac);
		IncomeTest clonedTest = new IncomeTest();
		this.getMergeRuleService().mergeIncomeTest(onFile.getIncomeTest(incomeYear), clonedTest);
		Person incoming = savePerson(onFile);
		this.attachIneligibleFactorFromSite(incoming);
		incoming.setVeteran(Boolean.FALSE);
		incoming.removeAllIncomeTests();
		incoming.setIncomeTest(incomeYear, this.convertIncomeTestToIVM(clonedTest));

		Person updated = this.processZ07(incoming, fac);
		assertNotNull(updated.getAgentOrangeExposure().getAgentOrangeExposureIndicator());
		assertTrue(updated.getAgentOrangeExposure().getAgentOrangeExposureIndicator().toBoolean().booleanValue());
	}

	private Person processZ07(Person incoming, VAFacility fac) throws Exception {
		VerificationInfo info = new VerificationInfo("x", MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());

		return this.getMessagingService().processZ07(incoming, fac,	info);
	}

	public void testAgentOrangeNonVeteran() throws Exception {
		/*
		 * Test scenario:
		 *
		 * Onfile is Pending, has AO Vietnam, and is Veteran=Yes
		 * Incoming is Verified, has AO Vietnam, and is Veteran=No and has Ineligible data
		 *
		 */
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		List factors = new ArrayList();
		factors.add(Factors.AO_VIETNAM);
		factors.add(Factors.V_ENROLL);
		factors.add(Factors.P_ELIG);
		Person onFile = this.buildPersonFromZ07(2009, factors, fac);

		Integer incomeYear = new Integer(2009);
		IncomeTest clonedTest = new IncomeTest();
		this.getMergeRuleService().mergeIncomeTest(onFile.getIncomeTest(incomeYear), clonedTest);
		Person incoming = savePerson(onFile);
		incoming.removeAllIncomeTests();
		incoming.setIncomeTest(incomeYear, this.convertIncomeTestToIVM(clonedTest));
		this.setEligibilityStatusToVerified(incoming);
		this.attachIneligibleFactorFromSite(incoming);
		incoming.setVeteran(Boolean.FALSE);

		Person updated = this.processZ07(incoming, fac);
		assertFalse(updated.getAgentOrangeExposure().getAgentOrangeExposureIndicator().toBoolean().booleanValue());
		assertFalse(updated.getVeteran().booleanValue());
	}

	private Person buildPersonFromZ07(int incomeYear, List factors, VAFacility fac) throws Exception {
		Person person = this.buildSimplePerson();

		if (factors.contains("AO_VIETNAM")) {
			this.attachAgentOrangeExposure(person);
		}
		if (factors.contains("V_ENROLL")) {
			this.attachVerifiedEnrollment(person);
		}

		if (factors.contains("V_ELIG")) {
			this.setEligibilityStatusToVerified(person);
		}
		if (factors.contains("P_ELIG")) {
			this.setEligibilityStatusToPendingVerification(person);
		}
		attachIncomeTest(person, new Integer(incomeYear), fac, MeansTestStatus.MT_STATUS_GMT_COPAY_REQUIRED);
		IncomeTest test = person.getIncomeTest(new Integer(incomeYear));
		test.setEffectiveDate(getDate(incomeYear+1, 11, 23));
		test.setLastEditedDate(getDate(incomeYear+1, 1, 25));
		test.setFutureTest(Boolean.FALSE);
		person.setFinancialStatement(new Integer(incomeYear),	this.createFinancialStatement());
		return person;
	}
	private IncomeTest convertIncomeTestToIVM(IncomeTest test) throws Exception {
		// MODIFY to make IVM CONVERTED TEST
		test.setMeansTestStatus(this.getLookupService().getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED.getCode()));
		test.setCompletedDate(new Date());
		test.setEffectiveDate(new Date());
		test.setLastEditedDate(new Date());
		test.setSource(this.getLookupService().getIncomeTestSourceByCode(IncomeTestSource.CODE_IVM.getCode()));
		return test;
	}

	public void testAddMTandRx() throws Exception {
		Person onFile = this.buildSimplePerson();
		Integer year2008 = new Integer(2008);
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToVerified(onFile);
		IncomeTest incomeMTTest = this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_NO_LONGER_REQUIRED, year2008);
		onFile.setIncomeTest(year2008, incomeMTTest);
		IncomeTestStatus incomeTestStatus = new IncomeTestStatus();
		incomeTestStatus.setStatus(this.getLookupService()
				.getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_EXEMPT.getName()));
		incomeTestStatus.setType(this.getLookupService()
				.getIncomeTestTypeByCode(
						IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST.getCode()));
		incomeTestStatus.setDeterminedStatus(this.getLookupService()
				.getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED.getName()));
		incomeTestStatus.setCompletedDate(new Date());
		incomeMTTest.addStatus(incomeTestStatus);

		Person updated = this.savePerson(onFile);
		assertTrue(updated.getIncomeTest(year2008).getType().getCode()
				.equals(IncomeTestType.CODE_MEANS_TEST.getCode()));
		// this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());

	}

	private IncomeTest addMTtoNewPerson(String sender, String conductedBy)
			throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode(sender);
		VAFacility facAO = this.getLookupService().getVaFacilityByCode(
				conductedBy);

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);
		incoming.setIncomeTest(new Integer(2006), this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, new Integer(2006)));
		incoming.setFinancialStatement(new Integer(2006),
				this.createFinancialStatement());
		incoming.getIncomeTest(new Integer(2006)).setCompletedDate(
				this.getDate(2007, 6, 1));
		incoming.getIncomeTest(new Integer(2006)).setEffectiveDate(
				this.getDate(2007, 2, 1));
		incoming.getIncomeTest(new Integer(2006)).setLastEditedDate(
				this.getDate(2007, 6, 1));
		incoming.getIncomeTest(new Integer(2006)).setSiteConductingTest(facAO);
		incoming.getIncomeTest(new Integer(2006)).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_VAMC.getCode()));
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2008, 1, 1));
		visit.setIncomeYear(new Integer(2006));
		visit.setFacilityVisited(incoming.getIncomeTest(new Integer(2006))
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		/*
		 * Hardship hardship = this.createHardship("test1");
		 * hardship.setEffectiveDate(this.getDate(2008, 0, 1));
		 * hardship.setSiteGrantingHardship(fac); incoming.getIncomeTest(new
		 * Integer(2007)).setHardship(hardship);
		 */
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		return updated.getIncomeTest(new Integer(2006));

	}

	/**
	 * Cancel/decline = Y App Date = 1/17/2003 MT = null Status =
	 * Canceled/Declined
	 *
	 * @throws Exception
	 */
	public void testCreateRule5Data_Scenario1() throws Exception {

		Person onFile = buildSimplePerson(); // bare-bones person
		this.setEligibilityStatusToVerified(onFile);
		attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEffectiveDate(new Date());
		this.attachApplication(onFile);
		onFile.getApplication().setApplicationDate(this.getDate(2003, 0, 17));
		this.attachCancelDecline(onFile);
		// this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
		// new BigDecimal(1));
		// EnrollmentPriorityGroup;
		// import gov.va.med.esr.common.model.lookup.EnrollmentPrioritySubGroup;

		onFile.getEnrollmentDetermination().setEnrollmentStatus(
				this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_CANCELLED_DECLINED.getCode()));
		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_8.getCode()));
		onFile.getEnrollmentDetermination().setPrioritySubGroup(
				this.getLookupService().getEnrollmentPrioritySubGroupByCode(
						EnrollmentPrioritySubGroup.SUBGROUP_C.getCode()));

		// this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
		// new BigDecimal(1));
		// EnrollmentPriorityGroup;
		// import gov.va.med.esr.common.model.lookup.EnrollmentPrioritySubGroup;

		Person incoming = savePerson(onFile);
		this.setComplete();
		System.out.println("Person id="
				+ incoming.getPersonEntityKey().getKeyValueAsString());
	}

	public void testCreateRule5Data_migrated_verified() throws Exception {

		Person onFile = buildSimplePerson(); // bare-bones person
		this.setEligibilityStatusToVerified(onFile);
		attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEffectiveDate(new Date());
		this.attachApplication(onFile);
		onFile.getApplication().setApplicationDate(this.getDate(2002, 0, 17));
		this.attachCancelDecline(onFile);
		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_8.getCode()));
		onFile.getEnrollmentDetermination().setPrioritySubGroup(
				this.getLookupService().getEnrollmentPrioritySubGroupByCode(
						EnrollmentPrioritySubGroup.SUBGROUP_C.getCode()));

		Person incoming = savePerson(onFile);
		this.setComplete();
		System.out.println("Person id="
				+ incoming.getPersonEntityKey().getKeyValueAsString());
	}

	public void testRule5Defect() throws Exception {
		Person onFile = this.getPerson("100613");
		onFile.setCancelDecline(null);
		onFile.getEligibilityVerification().setVerificationMethod("test");

		Person result = this.getEligibilityEnrollmentService()
				.updateEnrollmentData(onFile);
		assertTrue(
				"expected:"
						+ EnrollmentStatus.CODE_REJECTED_BELOW_ENROLLMENT_GROUP_THRESHOLD.getCode()
						+ " was:"
						+ result.getEnrollmentDetermination()
								.getEnrollmentStatus().getCode(),
				result.getEnrollmentDetermination()
						.getEnrollmentStatus()
						.getCode()
						.equals(EnrollmentStatus.CODE_REJECTED_BELOW_ENROLLMENT_GROUP_THRESHOLD
								.getCode()));
		System.out.println("Person id="
				+ result.getPersonEntityKey().getKeyValueAsString());
	}
/*
	public void testFindVoaFileAttachment() throws Exception {

		BigDecimal personId = new BigDecimal("1");

		List result = this.getVoaApplicationService()
				.findVoaAttachmentByPersonId(personId);
		super.assertEquals(result.size(), 1);

		personId = new BigDecimal("2");
		result = this.getVoaApplicationService()
				.findVoaAttachmentByPersonId(personId);
		super.assertEquals(result.size(), 2);

		personId = new BigDecimal("3");
		result = this.getVoaApplicationService().findVoaAttachmentByPersonId(personId);
		super.assertEquals(result.size(), 3);

		personId = new BigDecimal("10");
		result = this.getVoaApplicationService().findVoaAttachmentByPersonId(personId);

		super.assertEquals(result, null);

		BigDecimal applicationId = new BigDecimal("289170");

		result = this.getVoaApplicationService().findVoaAttachmentByApplicationId(applicationId);
		super.assertEquals(result.size(), 1);

		applicationId = new BigDecimal("289171");
		result = this.getVoaApplicationService().findVoaAttachmentByApplicationId(applicationId);
		super.assertEquals(result, null);

	}

	public void testUpdateFileAttachment() throws Exception {

		BigDecimal personId = new BigDecimal("1");

		List result = this.getVoaApplicationService()
				.findVoaAttachmentByPersonId(personId);
		VoaFileAttachment attachment = (VoaFileAttachment) result.get(0);

		Date now = new Date();
		attachment.setAttachmentReviewDate(now);
		attachment.setAttachmentReviewUserName("Tick2");
		attachment.setAttchmentAcceptableInd(new Boolean(false));

		// delete existing attachment details so a full update can be done
		attachment.removeAllVoaAttachmentDetails();

		VoaFileAttachmentDetail detail1 = new VoaFileAttachmentDetail();
		detail1.setElligibilityDocType((EligibilityDocType) getLookupService()
				.getByCode(EligibilityDocType.class, EligibilityDocType.DD_214));
		attachment.addVoaAttachmentDetail(detail1);

		VoaFileAttachmentDetail detail2 = new VoaFileAttachmentDetail();
		detail2.setElligibilityDocType((EligibilityDocType) getLookupService()
				.getByCode(EligibilityDocType.class, EligibilityDocType.DD_214));
		attachment.addVoaAttachmentDetail(detail2);

		this.getVoaApplicationService().updateAttachmentAttributes(
				attachment);

		// override default jUnit test rolls-back behavior, commits here.
		setComplete();

		super.assertEquals(result.size(), 1);
	}

	public void testUpdateVoaAttachmentWithPersonId() throws Exception {
		String msgControlId = new String("12345");
		BigDecimal personId = new BigDecimal("4");
		this.getVoaApplicationService().updateVoaAttachmentWithPersonId(
				msgControlId, personId);

		// override default jUnit test rolls-back behavior, commits here.
		setComplete();
	}
*/
	public void testORUZ07_NewNonVet() throws Exception {
		Person onFile = this.buildSimpleNonVeteran();

		Person incoming = this.savePerson(onFile);
		incoming.setReceivedPrimaryEligiblity(this
				.createReceivedEligibility(EligibilityType.HUMANTARIAN_EMERGENCY));
		this.setEligibilityStatusToVerified(incoming);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		incoming.setGender(this.getLookupService().getGenderByCode(
				Gender.AMBIGUOUS.getCode()));

		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());

		this.assessIfHasPrimaryRanking(
				EligibilityType.HUMANTARIAN_EMERGENCY.getCode(), updated);
		assertNotNull(updated.getEligibilityVerification());
		assertTrue(updated.getEligibilityVerification().getEligibilityStatus()
				.getCode()
				.equals(EligibilityStatus.CODE_PENDING_VERIFICATION.getCode()));
	}

	public void testProcessORUZ07NonVetWithAllied() throws Exception {
		Person onFile = this.buildSimpleNonVeteran();
		this.attachMilitaryService(onFile);
		this.setEligibilityStatusToVerified(onFile);
		Person incoming = this.savePerson(onFile);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		this.attachAlliedVeteran(incoming);
		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertNotNull(updated.isVeteran());
	}

	public void testProcessORUZ07_NonVet() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		Eligibility e = new Eligibility();
		e.setType(this.getLookupService().getEligibilityTypeByCode(
				EligibilityType.SERVICE_CONNECTED_50_TO_100_PERCENT.getCode()));
		onFile.getEnrollmentDetermination().setPrimaryEligiblity(e);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getCode()));
		Person incoming = this.savePerson(onFile);
		incoming.setReceivedPrimaryEligiblity(this.createAlliedVeteran());
		incoming.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getCode()));
		incoming.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		this.setEligibilityStatusToVerified(incoming);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(this.getRandomVAFacility().getCode());

		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertNotNull(updated.isVeteran());
	}

	public void testVBA1() throws Exception {
		Person onFile = buildSimplePerson();
		// this.attachDeathRecord(onFile);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getName()));
		// this.attachVerifiedEnrollment(onFile);
		// this.setEnrollmentStatus(EnrollmentStatus.CODE_PENDING_ELIGIBILITY_STATUS_IS_UNVERIFIED.getCode(),
		// onFile);
		this.attachServiceConnectionAward(onFile, new Integer(80));
		this.attachMilitaryService(onFile);
		MilitaryServiceEpisode mse = new MilitaryServiceEpisode();
		mse.setServiceBranch(this.getRandomServiceBranch());
		mse.setDischargeType(this.getLookupService().getDischargeTypeByCode(DischargeType.CODE_HONORABLE.getCode()));
		mse.setStartDate(ImpreciseDateUtils.createImpreciseDate(2008, 1, 1));
		mse.setEndDate(ImpreciseDateUtils.createImpreciseDate(2009, 1, 1));
		mse.setServiceNumber("12345");
		MilitaryServiceSiteRecord m = this.createMilitaryServiceSireRecord();
		m.setSite(this.getLookupService().getVaFacilityByStationNumber(VAFacility.CODE_HEC.getName()));
		m.addMilitaryServiceEpisode(mse);
		onFile.getMilitaryService().addMilitaryServiceSiteRecord(m);
		CombatEpisode ce = new CombatEpisode();
		ce.setConflictLocation(this.getLookupService().getConflictByCode(ConflictLocation.CODE_UNKNOWN_OEF_OIF.getCode()));
		ce.setStartDate(ImpreciseDateUtils.createImpreciseDate(2002,2,1));
		ce.setEndDate(ImpreciseDateUtils.createImpreciseDate(2007,11,1));
		onFile.getMilitaryService().addCombatEpisode(ce);
		Person incoming = this.savePerson(onFile);


		this.setEligibilityStatusToVerified(incoming);
		incoming.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		this.setServiceConnectedPercentage(new Integer(0), incoming);
		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),
				null);
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		Iterator iter = incoming.getServiceConnectionAward()
				.getRatedDisabilities().iterator();
		while (iter.hasNext()) {
			RatedDisability rd = (RatedDisability) iter.next();
			rd.setPercentage(new Integer(0));
		}
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), vi);
		// this.setComplete();
		// assertTrue(updated.getEligibilityVerification().getEligibilityStatus()
		// .getCode().equals(EligibilityStatus.CODE_VERIFIED.getName()));
		// assertEquals(0,
		// updated.getServiceConnectionAward().getServiceConnectedPercentage().intValue());
	}

	/**
	 * Please verify if this is possible as a root cause for a new enrollment
	 * for an existing person as non-veteran, primary eligibility = Humanitarian
	 * Emergency, and Combat Veteran Eligible. Here is the scenario:
	 *
	 * Existing person in ESR is a non-veteran (Veteran = No) with Verified
	 * Eligibility Status. Site sends veteran = yes, Primary Eligibility Code =
	 * NSC, Military Service Episode and OEF/OIF data.
	 *
	 * During upload of the site data I know calculations occur – could it be
	 * that the military service data is uploaded and the CV End Date is
	 * calculated based on the incoming data? And then there’s a determination
	 * that the eligibility data cannot be persisted because of the verified
	 * eligibility status?
	 *
	 * That’s what it looks like to me. Before the message the Veteran Indicator
	 * on file is No. After processing the message the Veteran Indicator is No.
	 * CV End Date requires that there is a veteran indicator = yes but we do
	 * not have a history of that existing. It makes me think that we calculated
	 * using incoming data and not data on file.
	 *
	 *
	 * @throws Exception
	 */
	public void testNonVeteran() throws Exception {
		Person onFile = this.buildSimpleNonVeteran();

		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getName()));
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEnrollmentStatus(
				this.getLookupService().getEnrollmentStatusByCode(
						EnrollmentStatus.CODE_NOT_APPLICABLE.getCode()));
		Person incoming = this.savePerson(onFile);
		incoming.setVeteran(Boolean.TRUE);
		this.attachMilitaryServiceEpisode(incoming);

		incoming.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),
				null);
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());
		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), vi);
		assertTrue(updated.getEligibilityVerification().getEligibilityStatus()
				.getCode().equals(EligibilityStatus.CODE_VERIFIED.getName()));

	}

	public void testDoNotAutoEnrollNewPerson() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachMeansTestWithMtCopayExempt(onFile);
		onFile.getIncomeTest(new Integer(2005)).setCompletedDate(
				this.getDate(1995, 1, 1));
		onFile.getIncomeTest(new Integer(2005));
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(1995, 1, 1));
		visit.setIncomeYear(new Integer(2005));
		visit.setFacilityVisited(onFile.getIncomeTest(new Integer(2005))
				.getSiteConductingTest());
		onFile.addPatientVisitSummary(visit);
		Person incoming = this.savePerson(onFile);
		ReceivedEligibility e = new ReceivedEligibility();

		e.setType(this.getLookupService().getEligibilityTypeByCode(
				EligibilityType.NSC.getCode()));
		incoming.setReceivedPrimaryEligiblity(e);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");

		info.setSiteNumber(this.getRandomVAFacility().getCode());

		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertNotNull(updated.isVeteran());
	}

	public void testRegistrySearch() throws Exception {
		Person onFile = this.buildSimplePerson();
		Person incoming = this.savePerson(onFile);
		RegistrySearchCriteria crit = this.getRegistryService()
				.getRegistrySearchCriteria(incoming,
						RegistryType.CODE_PH_REGISTRY.getCode());
		crit.setSsn("999999998");
		crit.setFirstName("John");
		crit.setLastName("Doe");
		Registry r = this.getRegistryService().getMatchingRegistry(crit);
		assertNotNull(r);
		assertNull(r.getPerson());
	}

	public void testDoNotAutoEnrollExistingPerson() throws Exception {
		Person onFile = this.buildSimplePerson();
		onFile.setEnrollmentDetermination(new EnrollmentDetermination());
		Eligibility e = new Eligibility();

		e.setType(this.getLookupService().getEligibilityTypeByCode(
				EligibilityType.NSC.getCode()));
		onFile.getEnrollmentDetermination().setPrimaryEligiblity(e);
		onFile.getEnrollmentDetermination().setEgtSetting(
				this.getEgtService().getCurrentEGTSetting());
		Person incoming = this.savePerson(onFile);
		SSN ssn = new SSN();
		ssn.setSsnText("999999998");
		incoming.getLegalName().setFamilyName("Doe");
		incoming.getLegalName().setGivenName("John");
		ssn.setType(this.getLookupService().getSSNTypeByCode(
				SSNType.CODE_ACTIVE.getCode()));
		incoming.addSsn(ssn);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(this.getRandomVAFacility().getCode());

		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertNotNull(updated.isVeteran());
	}

	public void testProcessNonQueryZ11_601B() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination()
				.setEnrollmentStatus(
						this.getLookupService()
								.getEnrollmentStatusByCode(
										EnrollmentStatus.CODE_PENDING_ELIGIBILITY_STATUS_IS_UNVERIFIED
												.getCode()));
		onFile.getEnrollmentDetermination().setPriorityGroup(null);
		onFile.getEnrollmentDetermination().setPrioritySubGroup(null);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_PENDING.getCode()));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		onFile.getIncomeTest(new Integer(2005)).setAgreesToPayDeductible(
				Boolean.FALSE);
		onFile.getIncomeTest(new Integer(2005))
				.setDiscloseFinancialInformation(Boolean.TRUE);

		Person incoming = this.savePerson(onFile);
		incoming.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_NO_DATA.getCode()));
		incoming.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		this.setEligibilityStatusToVerified(incoming);

		VerificationInfo info = new VerificationInfo("01",
				MessageType.CODE_ORFZ11_TO_ESR.getCode(), "x");
		info.setSiteNumber(this.getRandomVAFacility().getCode());

		Person updated = this.getMessagingService().processNonQueryZ11(
				incoming, info);

		assertNotNull(updated.isVeteran());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testProcessResponseToQueryZ11() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination()
				.setEnrollmentStatus(
						this.getLookupService()
								.getEnrollmentStatusByCode(
										EnrollmentStatus.CODE_PENDING_ELIGIBILITY_STATUS_IS_UNVERIFIED
												.getCode()));
		onFile.getEnrollmentDetermination().setPriorityGroup(null);
		onFile.getEnrollmentDetermination().setPrioritySubGroup(null);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_PENDING.getCode()));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		onFile.getIncomeTest(new Integer(2005)).setAgreesToPayDeductible(
				Boolean.FALSE);
		onFile.getIncomeTest(new Integer(2005))
				.setDiscloseFinancialInformation(Boolean.TRUE);
		VAFacility site = this.getRandomVAFacility();

		Person incoming = this.savePerson(onFile);
		this.setServiceConnectedPercentage(new Integer(1), incoming);
		incoming.getServiceConnectionAward().removeAllRatedDisability();
		incoming.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_RECEIVED.getCode()));
		incoming.getEligibilityVerification().setVerificationFacility(site);
		this.setEligibilityStatusToVerified(incoming);

		VerificationInfo info = new VerificationInfo("01",
				MessageType.CODE_ORFZ11_TO_ESR.getCode(), "x");
		info.setSiteNumber(site.getCode());

		Person updated = this.getMessagingService().processNonQueryZ11(
				incoming, info);

		assertNotNull(updated.isVeteran());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testProcessQRYZ10() throws Exception {
		Person onFile = buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachMeansTestWithMtCopayExempt(onFile);

		Person incoming = this.getPersonService().save(onFile);

		IncomingMessageInfo imi = new IncomingMessageInfo();
		imi.setQueryDateTime(new Date());
		imi.setReferenceMessageId("1234");
		imi.setSendingFacility(this.getRandomVAFacility());
		this.getMessagingService().processQRYZ10(incoming, new Integer(2006),
				imi);
	}

	public void testProcessQRYZ10NoTest() throws Exception {
		Person onFile = buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		Person incoming = this.getPersonService().save(onFile);

		IncomingMessageInfo imi = new IncomingMessageInfo();
		imi.setQueryDateTime(new Date());
		imi.setReferenceMessageId("1234");
		imi.setSendingFacility(this.getRandomVAFacility());
		this.getMessagingService().processQRYZ10(incoming, new Integer(2005),
				imi);
	}

	public void testUpdateEEDataByAddingRD() throws Exception {
		Person onFile = this.buildSimplePerson();
		EligibilityVerification ev = new EligibilityVerification();
		onFile.setEligibilityVerification(ev);
		onFile.getEligibilityVerification().setEligibilityStatus(
				this.getLookupService().getEligibilityStatusByCode(
						EligibilityStatus.CODE_PENDING_VERIFICATION.getCode()));
		// Step 1: save person
		this.attachServiceConnectionAward(onFile, new Integer(0));
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setPriorityGroup(null);
		Person incoming = savePerson(onFile);
		incoming.getServiceConnectionAward().removeAllRatedDisability();
		incoming.getServiceConnectionAward()
				.setServiceConnectedPercentage(null);

		Person updated = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);
		assertNull(updated.getServiceConnectionAward()
				.getServiceConnectedPercentage());

	}

	public void testUpdateEEData() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachServiceConnectionAward(onFile, new Integer(0));
		this.attachMeansTestWithMtCopayExempt(onFile);
		this.setEligibilityStatusToVerified(onFile);
		Person incoming = savePerson(onFile);

		Person updated = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);
		assertNotNull(updated.getServiceConnectionAward()
				.getServiceConnectedPercentage());
	}

	public void testUpdateEnrollmentData() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachServiceConnectionAward(onFile, new Integer(0));
		this.attachMeansTestWithMtCopayExempt(onFile);
		this.setEligibilityStatusToVerified(onFile);
		this.attachApplication(onFile);
		Date dt = this.getDate(2008, 1, 1);
		onFile.getApplication().setApplicationDate(dt);
		Person incoming = savePerson(onFile);
		Date dt2 = this.getDate(2008, 2, 2);
		incoming.getApplication().setApplicationDate(dt2);
		Person updated = this.getEligibilityEnrollmentService()
				.updateEnrollmentData(incoming);
		assertNotNull(updated.getServiceConnectionAward()
				.getServiceConnectedPercentage());
		assertTrue(isSameDay(updated.getApplication().getApplicationDate(), dt2));
	}

	/**
	 * @return Returns the eligibilityEnrollmentService.
	 */
	public EligibilityEnrollmentService getEligibilityEnrollmentService() {
		return eligibilityEnrollmentService;
	}

	/**
	 * @param eligibilityEnrollmentService
	 *            The eligibilityEnrollmentService to set.
	 */
	public void setEligibilityEnrollmentService(
			EligibilityEnrollmentService eligibilityEnrollmentService) {
		this.eligibilityEnrollmentService = eligibilityEnrollmentService;
	}

	/**
	 * @return Returns the militaryInfoService.
	 */
	public MilitaryInfoService getMilitaryInfoService() {
		return militaryInfoService;
	}

	/**
	 * @param militaryInfoService
	 *            The militaryInfoService to set.
	 */
	public void setMilitaryInfoService(MilitaryInfoService militaryInfoService) {
		this.militaryInfoService = militaryInfoService;
	}

	public void testNonVetToVetViaZ07() throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		Person onFile = this.buildSimpleNonVeteran();
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getCode()));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		this.attachAlliedVeteranAsPrimary(onFile);
		Person incoming = this.savePerson(onFile);
		incoming.setVeteran(Boolean.TRUE);
		incoming.setReceivedPrimaryEligiblity(null);
		this.setEligibilityStatusToVerified(incoming);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);
		assertTrue(updated.isVeteran().booleanValue());

		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testMergeReceivedEligibility() throws Exception {

		Person onFile = this.buildSimpleNonVeteran();
		this.attachAlliedVeteran(onFile);
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getCode()));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		Person incoming = this.savePerson(onFile);
		((ReceivedEligibility) incoming.getReceivedSecondaryEligibilities()
				.iterator().next())
				.setAlliedCountry(this.getLookupService()
						.getAlliedCountryByCode(
								AlliedCountry.CODE_AUSTRALIA.getCode()));
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertTrue(updated.getReceivedSecondaryEligibilities().size() > 0);

		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testBulkEE() throws Exception {
		Person onFile = this.buildSimplePerson();

		this.attachApplication(onFile);
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination().setEnrollmentDate(
				this.getDate(2002, 1, 1));
		this.setEligibilityStatusToVerified(onFile);
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(1));
		Person incoming = this.getPersonService().save(onFile);
		this.getPersonService().processEEForMigratedPerson(
				incoming.getPersonEntityKey());
		this.setComplete();
		System.out.println("Person id="
				+ incoming.getPersonEntityKey().getKeyValueAsString());
	}

	public void testProcessQRYZ11() throws Exception {
		testQRYZ11(AACIndicator.CODE_DATA_ACCEPTED.getCode(), true);
	}

	public void testProcessQRYZ11_Neg() throws Exception {
		testQRYZ11(AACIndicator.CODE_AAC_QUERIED_PENDING.getCode(), false);
	}

	private void testQRYZ11(String aacInd, boolean verified) throws Exception {
		Person onFile = buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);

		if (!verified) {
			this.setEligibilityStatusToPendingVerification(onFile);
			onFile.getEnrollmentDetermination().setEnrollmentStatus(
					this.getLookupService().getEnrollmentStatusByCode(
							EnrollmentStatus.CODE_PENDING_OTHER.getCode()));
		} else {
			this.setEligibilityStatusToVerified(onFile);
		}
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(aacInd));
		Person incoming = this.getPersonService().save(onFile);
		IncomingMessageInfo imi = new IncomingMessageInfo();
		imi.setQueryDateTime(new Date());
		imi.setReferenceMessageId("1234");
		imi.setSendingFacility(this.getRandomVAFacility());
		this.getMessagingService().processQRYZ11(incoming, imi);
	}

	public void testRemoveAllData() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachAgentOrangeExposure(onFile);
		this.attachAidAndAttendance(onFile);
		this.attachDischargeDueToDisability(onFile);
		this.attachEnvironmentalContaminationExposure(onFile);
		this.attachHousebound(onFile);
		this.attachMedicaidFactor(onFile);
		this.attachMedicare(onFile);
		this.attachPrisonerOfWar(onFile,
				ImpreciseDateUtils.createImpreciseDate(2002, 1, 1),
				ImpreciseDateUtils.createImpreciseDate(2002, 3, 3));
		this.attachPurpleHeartWithPHStatusPending(onFile);
		onFile.getPurpleHeart().addDocument(this.createPHDocument());

		this.attachPurpleHeartWithPHStatusPending(onFile);
		this.attachRadiationExposure(onFile);
		this.attachVaDisabilityCompensation(onFile);
		this.attachUnemployable(onFile);
		this.attachTotalAnnualCheckAmount(onFile);
		onFile.getServiceConnectionAward().setServiceConnectedIndicator(
				Boolean.FALSE);
		onFile.getServiceConnectionAward().removeAllRatedDisability();
		Person incoming = this.savePerson(onFile);
		this.attachIneligibleFactor(incoming);
		Person result = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);

		System.out.println("Person id="
				+ result.getPersonEntityKey().getKeyValueAsString());
	}

	public void testProcessZ07forNewNonVetWithInelig() throws Exception {
		Person onFile = this.buildSimpleNonVeteran();
		this.setEligibilityStatusToVerified(onFile);
		onFile.setReceivedPrimaryEligiblity(this
				.createReceivedEligibility(EligibilityType.HUMANTARIAN_EMERGENCY));
		testProcessZ07forNonVet(onFile, false);
	}

	public void testProcessZ07forNonVetWithInelig() throws Exception {
		Person onFile = this.buildSimpleNonVeteran();
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToVerified(onFile);
		onFile.setReceivedPrimaryEligiblity(this
				.createReceivedEligibility(EligibilityType.TRICARE_CHAMPUS));
		testProcessZ07forNonVet(onFile, true);
	}

	private void testProcessZ07forNonVet(Person onFile, boolean ignore)
			throws Exception {
		onFile.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_PENDING.getCode()));
		Person incoming = this.savePerson(onFile);
		this.attachIneligibleFactorFromSite(incoming);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(this.getRandomVAFacility().getCode());

		Person updated = this.getMessagingService().processZ07(incoming,
				this.getRandomVAFacility(), info);

		assertNotNull(updated.isVeteran());
		if (!ignore)
			assertNotNull(updated.getIneligibilityFactor());
	}

	public void testUpdateEE_600D() throws Exception {
		Person onFile = this.buildSimplePerson();
		onFile.getBirthRecord().setBirthDate(
				ImpreciseDateUtils.createImpreciseDate(1920, 1, 1));
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToPendingVerification(onFile);
		this.attachApplication(onFile);
		this.attachAgentOrangeExposure(onFile);
		onFile.getApplication().setApplicationDate(this.getDate(1998, 1, 1));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		IncomeTestStatus rx = new IncomeTestStatus();
		rx.setStatus(this.getLookupService().getMeansTestStatusByCode(
				MeansTestStatus.MT_STATUS_EXEMPT.getCode()));
		rx.setType(this.getLookupService().getIncomeTestTypeByCode(
				IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST.getCode()));
		onFile.getIncomeTest(new Integer(2005)).addIncomeTestStatus(rx);
		Person incoming = savePerson(onFile);
		this.setEligibilityStatusToVerified(incoming);
		this.attachMilitaryServiceEpisode(incoming);
		incoming.getMilitaryService().getHECMilitaryServiceSiteRecord()
				.setServicePeriod(null);
		((MilitaryServiceEpisode) incoming.getMilitaryService()
				.getHECMilitaryServiceSiteRecord().getMilitaryServiceEpisodes()
				.iterator().next()).setServiceBranch(this.getLookupService()
				.getServiceBranchByCode(ServiceBranch.CODE_ARMY.getCode()));
		((MilitaryServiceEpisode) incoming.getMilitaryService()
				.getHECMilitaryServiceSiteRecord().getMilitaryServiceEpisodes()
				.iterator().next()).setStartDate(ImpreciseDateUtils
				.createImpreciseDate(1942, 1, 1));
		((MilitaryServiceEpisode) incoming.getMilitaryService()
				.getHECMilitaryServiceSiteRecord().getMilitaryServiceEpisodes()
				.iterator().next()).setEndDate(ImpreciseDateUtils
				.createImpreciseDate(1945, 1, 1));

		Person updated = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());

	}

	/*
	 * IF The veteran is subject to a means test is TRUE AND The veteran has a
	 * current income test on file is FALSE THEN Set the local means test status
	 * to Required (Do not update mt, just needed for eligibility)
	 */
	public void testIsMTupdateToRequired() throws Exception {
		Person onFile = this.buildSimplePerson();

		this.setEligibilityStatusToVerified(onFile);
		this.attachServiceConnectionAward(onFile, new Integer(100));
		Person incoming = savePerson(onFile);
		incoming.setServiceConnectionAward(null);
		this.getEligibilityEnrollmentService().updateEligibilityData(incoming);
	}

	public void testHasNoEnrollRecordPriorNDAA() throws Exception {

		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(2008, Calendar.JANUARY, 28); // 01/28/2008
		Date NDAA_DATE = cal.getTime();

		boolean hasAnyEnrollRec = this.getEligibilityEnrollmentService()
				.hasAnyEnrollmentRecordBeforeDate(
						this.getPerson("104").getEntityKey(), NDAA_DATE);

		this.assertEquals(false, hasAnyEnrollRec);

	}

	/**
	 * IF The RX copay test is applicable for the veteran is TRUE AND The
	 * veteran has a current income test on file is TRUE AND the RX copay status
	 * for the income test is equal to No Longer Applicable THEN Set the RX
	 * copay test status to the RX copay test determined status
	 */
	public void testIsRXUpdateFromNoLongerApplicable() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachPharmacyCopayTestWithNoLongerApplicable(onFile);
		Person incoming = savePerson(onFile);
		Person updated = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);
		assertNotNull(updated.getIncomeTest(new Integer(2005)));
	}

	/*
	 * The veteran is subject to a means test is TRUE AND the veteran has an
	 * "never expires" income test on file AND The means test status of the
	 * current income test is equal to No Longer Required THEN Update the Means
	 * test status of the income test to the test determined status of the
	 * income test
	 */
	public void testIsMTUpdateFromNoLongerRequired() throws Exception {
		testMTUpdateFromNoLongerRequired(new Date(), true);
	}

	public void testIsMTUpdateFromNoLongerRequired_GT365() throws Exception {
		testMTUpdateFromNoLongerRequired(this.getDate(2005, 1, 1), false);
	}

	public void testPurpleHeart() throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachPurpleHeartWithPHStatusPending(onFile);
		onFile.getPurpleHeart().addDocument(this.createPHDocument());
		Person incoming = this.savePerson(onFile);

		Person result = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);

		// this.setComplete();

		System.out.println("Person id="
				+ result.getPersonEntityKey().getKeyValueAsString());
	}

	private void testMTUpdateFromNoLongerRequired(Date date, boolean skipTest)
			throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.setEligibilityStatusToVerified(onFile);
		// this.attachMeansTestWithNoLongerRequired(onFile);
		this.attachPharmacyCopayTestWithRXCopayExempt(onFile);
		IncomeTestStatus status = new IncomeTestStatus();
		status.setCompletedDate(new Date());
		status.setStatus(this.getLookupService().getMeansTestStatusByCode(
				MeansTestStatus.MT_STATUS_NO_LONGER_REQUIRED.getCode()));
		status.setDeterminedStatus(this.getLookupService()
				.getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED.getCode()));
		status.setType(this.getLookupService().getIncomeTestTypeByCode(
				IncomeTestType.CODE_MEANS_TEST.getCode()));
		onFile.getIncomeTest(new Integer(2005)).addIncomeTestStatus(status);
		onFile.getIncomeTest(new Integer(2005)).setEffectiveDate(date);
		onFile.getIncomeTest(new Integer(2005)).setAgreesToPayDeductible(
				Boolean.TRUE);
		onFile.getIncomeTest(new Integer(2005)).setCompletedDate(
				this.getDate(2007, 1, 1));
		assertTrue(onFile.getIncomeTest(new Integer(2005)).getType().getCode()
				.equals(IncomeTestType.CODE_CO_PAY_EXEMPTION_TEST.getCode()));
		if (!skipTest) {
			assertNull(this.getPersonHelperService().getCurrentIncomeTest(
					onFile));
		}
		Person incoming = savePerson(onFile);
		incoming.setServiceConnectionAward(null);
		Person updated = this.getEligibilityEnrollmentService()
				.updateEligibilityData(incoming);
		assertNotNull(updated.getIncomeTest(new Integer(2005)));
		// Should have switched tests to make MT primary
		assertTrue(this.getPersonHelperService().getCurrentIncomeTest(updated)
				.getType().getCode()
				.equals(IncomeTestType.CODE_MEANS_TEST.getCode()));
		assertTrue(this.getPersonHelperService().getCurrentIncomeTest(updated)
				.getStatus().getCode()
				.equals(MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED.getCode()));
	}

	public void testZ07RemovingHardship() throws Exception {
		VAFacility fac = this.getRandomVAFacility();
		Person onFile = this.buildSimplePerson();
		this.attachMeansTestWithMtCopayExempt(onFile);
		Hardship hardship = this.createHardship("test1");
		hardship.setEffectiveDate(this.getDate(2008, 0, 1));
		hardship.setSiteGrantingHardship(fac);
		onFile.getIncomeTest(new Integer(2005)).setCompletedDate(
				this.getDate(1995, 1, 1));
		onFile.getIncomeTest(new Integer(2005)).setHardship(hardship);
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(1995, 1, 1));
		visit.setIncomeYear(new Integer(2005));
		visit.setFacilityVisited(onFile.getIncomeTest(new Integer(2005))
				.getSiteConductingTest());
		onFile.addPatientVisitSummary(visit);
		IncomeTestStatus orig = onFile.getIncomeTest(new Integer(2005))
				.getIncomeTestStatus();
		assertEquals(MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT.getCode(),
				onFile.getIncomeTest(new Integer(2005)).getIncomeTestStatus()
						.getStatus().getCode());
		Person incoming = this.savePerson(onFile);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());

		incoming.getIncomeTest(new Integer(2005)).setHardship(null);
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);

		assertNotNull(updated.isVeteran());
		assertEquals(orig.getDeterminedStatus().getCode(), updated
				.getIncomeTest(new Integer(2005)).getIncomeTestStatus()
				.getStatus().getCode());
	}

	/**
	 * CCR 10021 - CPB (DNS   barryc) - Tests that multiple identical incoming
	 * RatedDisabilities are all included in the Set after calling mergeService.
	 *
	 * @throws Exception
	 */
	public void testProcessNonQueryZ11_DuplicateRatedDisabilities()
			throws Exception {
		Person onFile = buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		onFile.getEnrollmentDetermination()
				.setEnrollmentStatus(
						this.getLookupService()
								.getEnrollmentStatusByCode(
										EnrollmentStatus.CODE_PENDING_ELIGIBILITY_STATUS_IS_UNVERIFIED
												.getCode()));
		onFile.getEnrollmentDetermination().setPriorityGroup(null);
		onFile.getEnrollmentDetermination().setPrioritySubGroup(null);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_PENDING.getCode()));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(1),
				new BigDecimal(2));
		onFile.getIncomeTest(new Integer(2005)).setAgreesToPayDeductible(
				Boolean.FALSE);
		onFile.getIncomeTest(new Integer(2005))
				.setDiscloseFinancialInformation(Boolean.TRUE);

		ServiceConnectionAward serviceConnectionAward = new ServiceConnectionAward();
		onFile.setServiceConnectionAward(serviceConnectionAward);

		RatedDisability rdOnFile = this.createRatedDisability(
				this.getLookupService()
						.getDisabilityByCode(
								Disability.CODE_RESPIRATORY_CONDITION_GENERAL
										.getCode()), new Integer(1));
		serviceConnectionAward.addRatedDisability(rdOnFile);

		Person incoming = this.savePerson(onFile);
		this.setServiceConnectedPercentage(new Integer(80), incoming);

		RatedDisability rd1 = this.createRatedDisability(
				this.getLookupService()
						.getDisabilityByCode(
								Disability.CODE_RESPIRATORY_CONDITION_GENERAL
										.getCode()), new Integer(1));
		incoming.getServiceConnectionAward().addRatedDisability(rd1);

		RatedDisability rd2 = this.createRatedDisability(
				this.getLookupService()
						.getDisabilityByCode(
								Disability.CODE_RESPIRATORY_CONDITION_GENERAL
										.getCode()), new Integer(1));
		incoming.getServiceConnectionAward().addRatedDisability(rd2);

		RatedDisability rd3 = this.createRatedDisability(
				this.getLookupService().getDisabilityByCode(
						Disability.CODE_NEUROGENIC_BLADDER.getCode()),
				new Integer(1));
		incoming.getServiceConnectionAward().addRatedDisability(rd3);

		incoming.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_AAC_QUERIED_NO_DATA.getCode()));
		incoming.getEligibilityVerification().setVerificationFacility(
				this.getRandomVAFacility());
		this.setEligibilityStatusToVerified(incoming);

		VerificationInfo info = new VerificationInfo("01",
				MessageType.CODE_ORUZ11_TO_ESR.getCode(), "x");
		info.setSiteNumber(this.getRandomVAFacility().getCode());
		info.setUnsolicitedType("HNQ");

		Person updated = this.getMessagingService().processNonQueryZ11(
				incoming, info);

		assertTrue("disabilities not merged correctly", updated
				.getServiceConnectionAward().getRatedDisabilities().size() == 4);
		assertNotNull(updated.isVeteran());
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void testZ07AddingMTFromSatellite() throws Exception {
		assertNotNull(this.addMTFromSatellite("657", "657A0"));
	}

	public void testZ07AddingMTFromGrandChild() throws Exception {
		assertNotNull(this.addMTFromSatellite(/*"657", "6579AB")*/"740", "740MA"));
	}

	public void testZ07AddingMTFromGreatGrandChild() throws Exception {
		assertNotNull(this.addMTFromSatellite("671", "740MA"));
	}

	public void testZ07AddingFinancialStatementFromSatellite() throws Exception {
		assertNotNull(this.addFinancialStatementFromSatellite("657", "657A0"));
	}

	public void testZ07AddingFinancialStatementFromSatellite_pos()
			throws Exception {
		assertNotNull(this.addFinancialStatementFromSatellite("657", "657"));
	}

	public void testZ07AddingFinancialStatementFromSatellite_neg()
			throws Exception {
		assertNull(this.addFinancialStatementFromSatellite("657", "614"));
	}

	public void testZ07AddingMTFromSatellite_Neg() throws Exception {
		assertNull(this.addMTFromSatellite("657", "614PA"));
	}

	public void testZ07AddingMTFromSatellite_Pos() throws Exception {

		assertNotNull(this.addMTFromSatellite("657", "657"));
	}

	private IncomeTest addMTFromSatellite(String sender, String conductedBy)
			throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode(sender);
		VAFacility facAO = this.getLookupService().getVaFacilityByCode(
				conductedBy);

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);
		incoming.setIncomeTest(new Integer(2007), this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, new Integer(2007)));
		incoming.setFinancialStatement(new Integer(2007),
				this.createFinancialStatement());
		incoming.getIncomeTest(new Integer(2007)).setCompletedDate(
				this.getDate(2007, 11, 1));
		incoming.getIncomeTest(new Integer(2007)).setSiteConductingTest(facAO);
		incoming.getIncomeTest(new Integer(2007)).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_VAMC.getCode()));
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2008, 1, 1));
		visit.setIncomeYear(new Integer(2007));
		visit.setFacilityVisited(incoming.getIncomeTest(new Integer(2007))
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);
		this.attachApplication(incoming);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		/*
		 * Hardship hardship = this.createHardship("test1");
		 * hardship.setEffectiveDate(this.getDate(2008, 0, 1));
		 * hardship.setSiteGrantingHardship(fac); incoming.getIncomeTest(new
		 * Integer(2007)).setHardship(hardship);
		 */
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		return updated.getIncomeTest(new Integer(2007));

	}

	private FinancialStatement addFinancialStatementFromSatellite(
			String sender, String conductedBy) throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode(sender);
		VAFacility facAO = this.getLookupService().getVaFacilityByCode(
				conductedBy);

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);
		incoming.setIncomeTest(new Integer(2007), this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, new Integer(2007)));
		incoming.setFinancialStatement(new Integer(2007),
				this.createFinancialStatement());
		// setup it data
		incoming.getIncomeTest(new Integer(2007)).setCompletedDate(
				this.getDate(2007, 11, 1));
		incoming.getIncomeTest(new Integer(2007)).setSiteConductingTest(facAO);
		incoming.getIncomeTest(new Integer(2007)).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_VAMC.getCode()));
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2008, 1, 1));
		visit.setIncomeYear(new Integer(2007));
		visit.setFacilityVisited(incoming.getIncomeTest(new Integer(2007))
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		return updated.getFinancialStatement(new Integer(2007));

	}

	public void testZ07SameAppDate() throws Exception {
		Date dt = this.getDate(2008, 1, 1);
		Person person = testZ07AppDate(dt);

		assertNotNull(person.getApplication());
		assertTrue(isSameDay(person.getApplication().getApplicationDate(), dt));
		assertNull(person.getReceivedEnrollment());
	}

	public boolean isSameDay(Date value1, Date value2) {
		if (value1 != null && value2 != null) {
			return DateUtils.isSameDay(value1, value2);
		}
		if (logger.isDebugEnabled()) {
			logger.debug(" Value 1: " + value1);
			logger.debug(" Value 2: " + value2);
		}
		return false;
	}

	public void testZ07NewAppDate() throws Exception {
		Date dt = this.getDate(2008, 2, 2);
		Person person = testZ07AppDate(dt);

		assertNotNull(person.getApplication());
		assertTrue(isSameDay(person.getApplication().getApplicationDate(), dt));
		assertNotNull(person.getReceivedEnrollment());
	}

	public void testPersonDeleteMTWithZ07_Neg() throws Exception {
		Person onFile = this.getPerson("100044215");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("548GF");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("548GF");
		onFile.setIncomeTest(new Integer(2007), null);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2007)));
		System.out.println("time ="
				+ updated.getIncomeTest(new Integer(2007)).getEffectiveDate()
						.toString());

	}

	// 657A0
	public void testPersonDeleteMTWithZ07_Pos() throws Exception {
		Person onFile = this.getPerson("100044215");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");
		onFile.setIncomeTest(new Integer(2007), null);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNull(updated.getIncomeTest(new Integer(2007)));

	}

	private Person testZ07AppDate(Date date) throws Exception {
		VAFacility fac = this.getRandomVAFacility();
		Person onFile = this.buildSimplePerson();
		this.attachApplication(onFile);
		onFile.getApplication().setApplicationDate(this.getDate(2008, 1, 1));
		this.attachMeansTestWithMtCopayRequired(onFile, new BigDecimal(20000),
				new BigDecimal(25000));
		onFile.getIncomeTest(new Integer(2005)).setCompletedDate(new Date());
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(1995, 1, 1));
		visit.setIncomeYear(new Integer(2005));
		visit.setFacilityVisited(onFile.getIncomeTest(new Integer(2005))
				.getSiteConductingTest());
		onFile.addPatientVisitSummary(visit);
		this.setEligibilityStatusToVerified(onFile);
		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getName()));
		this.attachVerifiedEnrollment(onFile);
		this.attachCancelDecline(onFile);
		this.setEnrollmentStatus(
				EnrollmentStatus.CODE_CANCELLED_DECLINED.getCode(), onFile);
		Person incoming = this.savePerson(onFile);
		this.attachReceivedEnrollment(incoming);
		incoming.getReceivedEnrollment().setCalculationSource(
				this.getLookupService().getEnrollmentSourceByCode(
						EnrollmentSource.CODE_VAMC.getCode()));
		incoming.getApplication().setApplicationDate(date);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());

		return this.getMessagingService().processZ07(incoming, fac, info);
	}

	public void testAddingMTFromZ07() throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);
		/*
		 * incoming.setIncomeTest(new Integer(2007),
		 * this.createIncomeTest(IncomeTestType.CODE_MEANS_TEST,
		 * MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, new Integer(2007)));
		 * incoming.setFinancialStatement(new
		 * Integer(2007),this.createFinancialStatement());
		 * incoming.getIncomeTest(new
		 * Integer(2007)).setCompletedDate(this.getDate(2007, 11, 1));
		 * incoming.getIncomeTest(new
		 * Integer(2007)).setSiteConductingTest(facAO);
		 * incoming.getIncomeTest(new
		 * Integer(2007)).setSource(this.getLookupService
		 * ().getIncomeTestSourceByCode(IncomeTestSource.CODE_VAMC.getCode()));
		 */
		attachIncomeTest(incoming, new Integer(2005), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED);
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2006, 1, 1));
		visit.setIncomeYear(new Integer(2005));
		visit.setFacilityVisited(incoming.getIncomeTest(new Integer(2005))
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		Person p2 = (Person) updated.clone();
		attachIncomeTest(p2, new Integer(2007), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);

		Person p3 = this.getMessagingService().processZ07(p2, fac, info);
		assertNotNull(p3.getIncomeTest(new Integer(2007)));
	}

	public void createDataForAddingMTFromZ07() throws Exception {
		createDataForMTFromZ07(new Integer(2005),
				MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED);
	}

	public void createDataForAddingOldMTFromZ07() throws Exception {
		this.createDataForOldMTFromZ07(getDate(2007, 1, 23), new Integer(2006),
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
	}

	// 100044074
	public void addDataForAddingMTFromZ07() throws Exception {
		Person onFile = this.getPerson("100044074");
		addDataForMTFromZ07(onFile, new Integer(2007),
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
	}

	public void createDataFor2007CopayExemptMTFromZ07() throws Exception {
		createDataForMTFromZ07(getDate(2008, 3, 23), new Integer(2007),
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
	}

	private void addDataForMTFromZ07(Person onFile, Integer year,
			MeansTestStatus.Code status) throws Exception {

		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");
		attachIncomeTest(onFile, year, facAO, status);
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2006, 1, 1));
		visit.setIncomeYear(year);
		visit.setFacilityVisited(onFile.getIncomeTest(year)
				.getSiteConductingTest());
		onFile.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);
		this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	private void createDataForMTFromZ07(Integer year,
			MeansTestStatus.Code status) throws Exception {
		createDataForMTFromZ07(getDate(2008, 3, 24), new Integer(2007),
				MeansTestStatus.MT_STATUS_REQUIRED);
	}

	private void createDataForMTFromZ07(Date effective, Integer year,
			MeansTestStatus.Code status) throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657A0");

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);

		attachIncomeTest(effective, incoming, year, facAO, status);
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2006, 1, 1));
		visit.setIncomeYear(year);
		visit.setFacilityVisited(incoming.getIncomeTest(year)
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	private void createDataForOldMTFromZ07(Date effective, Integer year,
			MeansTestStatus.Code status) throws Exception {
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657A0");

		Person onFile = this.buildSimplePerson();

		Person incoming = this.savePerson(onFile);

		attachIncomeTest(effective, incoming, year, facAO, status);
		PatientVisitSummary visit = new PatientVisitSummary();
		visit.setLastVisitDate(this.getDate(2006, 1, 1));
		visit.setIncomeYear(year);
		visit.setFacilityVisited(incoming.getIncomeTest(year)
				.getSiteConductingTest());
		incoming.addPatientVisitSummary(visit);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		this.setComplete();
		System.out.println("Person id="
				+ updated.getPersonEntityKey().getKeyValueAsString());
	}

	public void createDataFor2007RequiredStatusMTFromZ07() throws Exception {
		createDataForMTFromZ07(getDate(2008, 3, 23), new Integer(2007),
				MeansTestStatus.MT_STATUS_REQUIRED);
	}

	public void testPersonAddMTFromDBZ07() throws Exception {
		Person onFile = this.getPerson("100043827");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");

		attachIncomeTest(onFile, new Integer(2007), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2007)));
	}

	// 100094526

	public void testAddSame2006MTFromZ07Pos() throws Exception {
		Person onFile = this.getPerson("5618");
		Date date = this.getDate(2008, 9, 19);
		VAFacility fac = this.getLookupService().getVaFacilityByCode("552");

		// VAFacility facSatellite =
		// this.getLookupService().getVaFacilityByCode("552GB");

		// IncomeTest incoming = new IncomeTest();
		IncomeTest it = onFile.getIncomeTest(new Integer(2006));
		onFile.getIncomeTest(new Integer(2006)).setLastEditedDate(date);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2006)));
		System.out.println("time ="
				+ updated.getIncomeTest(new Integer(2006)).getEffectiveDate()
						.toString());
	}

	public void testAddSameYearMTFromZ07Pos() throws Exception {

		// private IncomeTest testSameYearMTFromZ07(Date c, Date lastEdit,
		// IncomeTestSource source ) throws Exception {
		// Person onFile = this.getPerson("100088341");
		// 100092328
		// Person onFile = this.getPerson("5613");
		Person onFile = this.getPerson("100092328");
		Date date = this.getDate(2008, 9, 19);
		// IncomeTestSource source =
		// this.getLookupService().getIncomeTestSourceByCode(IncomeTestSource.CODE_VAMC.getCode());
		// IncomeTest test = testSameYearMTFromZ07(date, date, source );
		// System.out.println("last edit time =" +
		// test.getLastEditedDate().toString()+ " effective=" +
		// test.getEffectiveDate().toString()+ "  expected="+ date.toString());
		// assertNotNull( test.getNetIncome());

		// VAFacility fac =
		// this.getLookupService().getVaFacilityByCode("548GF");
		// VAFacility facAO =
		// this.getLookupService().getVaFacilityByCode("548GF");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("552");
		// VAFacility facSatellite =
		// this.getLookupService().getVaFacilityByCode("552GB");
		VAFacility facSatellite = this.getLookupService().getVaFacilityByCode(
				"552");
		// attachIncomeTest(getDate(2008,8,23),onFile, new Integer(2007), facAO,
		// MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
		// IncomeTestStatus incomeTestStatus = null;

		// IncomeTest incoming = new IncomeTest();
		IncomeTest it = onFile.getIncomeTest(new Integer(2007));
		onFile.getIncomeTest(new Integer(2007)).setLastEditedDate(date);
		// onFile.getIncomeTest(new Integer(2007)).setEffectiveDate(date);
		// //TODO fix
		onFile.getIncomeTest(new Integer(2007)).setSiteConductingTest(
				facSatellite);
		onFile.getIncomeTest(new Integer(2007)).setGmtThresholdAmount(
				new BigDecimal(55552));
		onFile.getIncomeTest(new Integer(2007))
				.setDiscloseFinancialInformation(Boolean.TRUE);
		onFile.getIncomeTest(new Integer(2007)).setNetIncome(
				new BigDecimal(77772));
		onFile.getIncomeTest(new Integer(2007)).setNetWorth(new BigDecimal(50));

		onFile.getIncomeTest(new Integer(2007)).setTotalIncome(
				new BigDecimal(22841));

		onFile.getIncomeTest(new Integer(2007)).setThresholdA(
				new BigDecimal(34117));
		onFile.getIncomeTest(new Integer(2007)).setDeductibleExpenses(
				new BigDecimal(3384.35));
		onFile.getIncomeTest(new Integer(2007)).setPensionThreshold(
				new BigDecimal(3384.35));

		// TEMPORARY to set source=other
		// source =
		// this.getLookupService().getIncomeTestSourceByCode(IncomeTestSource.CODE_VAMC.getCode());

		// onFile.getIncomeTest(new Integer(2007)).setSource(source);
		// onFile.getIncomeTest(new Integer(2007))
		// IncomeTestStatus incomeTestStatus =
		// it.getIncomeTestStatusOfType(IncomeTestType.CODE_MEANS_TEST);
		// incomeTestStatus.setStatus(this.getLookupService().getMeansTestStatusByCode(MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT.getCode()));

		// onFile.setIncomeTest(new Integer(2007), it);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);
		IncomeTest test = updated.getIncomeTest(new Integer(2007));
		assertNotNull(updated.getIncomeTest(new Integer(2007)));
		System.out.println("time ="
				+ updated.getIncomeTest(new Integer(2007)).getEffectiveDate()
						.toString());

	}

	public void testCR7582Add2003MTFromDBZ07() throws Exception {
		// Notice that the person MUST already have 2003 and 2007 tests for this
		// to correctly simulate the defect as reported. Dena said the
		// person will already have the old test from data migration
		IncomeTest test = this.testPersonAddTestFromDBZ07(new Integer(2003),
				"100074373");
		assertNotNull(test);
	}

	public void testCR7582_7598Fix() throws Exception {
		// Notice that the person MUST already have 2003 and 2007 tests for this
		// to correctly simulate the defect as reported. Dena said the
		// person will already have the old test from data migration
		// IncomeTest test = this.testPersonAddTestFromDBZ07(new Integer(2003),
		// "100074373");
		// assertNotNull( test);

		// private IncomeTest testPersonAddTestFromDBZ07(BigDecimal net, Integer
		// effYear, Integer year, String id) throws Exception {
		Person onFile = this.getPerson("100079335");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657A0");

		attachIncomeTest(onFile, new Integer(2006), new Integer(2006), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
		onFile.getIncomeTest(new Integer(2006)).setEffectiveDate(
				this.getDate(2007, 10, 1));
		onFile.getIncomeTest(new Integer(2006)).setLastEditedDate(
				this.getDate(2007, 1, 1));
		// onFile.getIncomeTest(new
		// Integer(2006)).setDiscloseFinancialInformation(null);
		onFile.getIncomeTest(new Integer(2006)).setCompletedDate(
				this.getDate(2007, 1, 1));
		// TEMPORARY to set source=other
		onFile.getIncomeTest(new Integer(2006)).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_HEC.getCode()));
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2006)));
		IncomeTest x = this.getPersonHelperService().getCurrentIncomeTest(
				updated);
		assertNotNull(x);
		// return x;
		// }
	}

	public void testOnceOnlyAdd2003MTFromDBZ07() throws Exception {
		// Person onFile = getPerson("100074373");

		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(
				new BigDecimal("100074373"));
		Person onFile = this.getPersonService().getPerson(personKey);

		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");

		onFile.setIncomeTest(new Integer(2003), this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT, new Integer(2003)));

		onFile.getIncomeTest(new Integer(2003)).setEffectiveDate(
				this.getDate(2008, 1, 1));
		onFile.getIncomeTest(new Integer(2003)).setSiteConductingTest(fac);
		onFile.getIncomeTest(new Integer(2003)).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_VAMC.getCode()));
		this.savePerson(onFile);
		this.setComplete();
	}

	public void testPersonAdd2008MTFromDBZ07() throws Exception {
		Person onFile = this.getPerson("100071802");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657A0");

		attachIncomeTest(onFile, new Integer(2008), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2008)));
		IncomeTest x = this.getPersonHelperService().getCurrentIncomeTest(
				updated);
		assertNotNull(x);
	}

	public void testPersonAdd2007MTFromDBZ07() throws Exception {
		IncomeTest test = this.testPersonAddTestFromDBZ07(new BigDecimal(3),
				new Integer(2008), new Integer(2007), "100071802");
		assertNotNull(test);
	}

	// private void attachIVMIncomeTest(Date effective, Person person, Integer
	// incomeYear, VAFacility facAO, MeansTestStatus.Code status,
	// IncomeTestType.Code type) throws Exception {
	public void testAddIVMFromDBZ07() throws Exception {
		Integer incomeYear = new Integer(2008);
		Person onFile = this.buildSimplePerson();
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("552");
		attachIncomeTest(onFile, new Integer(2008), fac,
				MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED);
		onFile.getIncomeTest(incomeYear).setEffectiveDate(getDate(2008, 6, 23));
		onFile.getIncomeTest(incomeYear).setLastEditedDate(
				getDate(2008, 11, 23));

		Person incoming = savePerson(onFile);

		// this.attachIVMIncomeTest(getDate(2008, 4,23), incoming, new
		// Integer(2008), fac, MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
		incoming.setFinancialStatement(incomeYear,
				this.createFinancialStatement());
		incoming.getIncomeTest(incomeYear).setCompletedDate(
				this.getDate(incomeYear.intValue(), 11, 1));
		incoming.getIncomeTest(incomeYear).setEffectiveDate(new Date());
		incoming.getIncomeTest(incomeYear).setSiteConductingTest(facAO);
		incoming.getIncomeTest(incomeYear).setLastEditedDate(new Date());
		incoming.getIncomeTest(incomeYear).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_IVM.getCode()));

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2008)));
	}

	public void testAddIVMconversion2007withExisting2008FDT() throws Exception {
		Integer incomeYear2008 = new Integer(2008);
		Integer incomeYear2007 = new Integer(2007);

		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("552");
		attachIncomeTest(onFile, incomeYear2007, fac,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
		attachIncomeTest(onFile, incomeYear2008, fac,
				MeansTestStatus.MT_STATUS_GMT_COPAY_REQUIRED);
		onFile.getIncomeTest(incomeYear2007).setEffectiveDate(
				getDate(2008, 11, 23));
		onFile.getIncomeTest(incomeYear2007).setLastEditedDate(
				getDate(2008, 6, 23));
		onFile.getIncomeTest(incomeYear2008).setEffectiveDate(
				getDate(2009, 11, 23));
		onFile.getIncomeTest(incomeYear2008).setLastEditedDate(
				getDate(2009, 1, 25));
		onFile.getIncomeTest(incomeYear2008).setFutureTest(Boolean.TRUE);
		onFile.setFinancialStatement(incomeYear2007,
				this.createFinancialStatement());
		onFile.setFinancialStatement(incomeYear2008,
				this.createFinancialStatement());
		IncomeTest clonedTest = new IncomeTest();
		this.getMergeRuleService().mergeIncomeTest(
				onFile.getIncomeTest(incomeYear2007), clonedTest);

		Person incoming = savePerson(onFile);

		incoming.removeAllIncomeTests();
		incoming.setIncomeTest(incomeYear2007, clonedTest);

		// MODIFY 2007 to make INCOMING IVM CONVERTED TEST
		incoming.getIncomeTest(incomeYear2007).setMeansTestStatus(
				this.getLookupService().getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_MT_COPAY_REQUIRED.getCode()));
		incoming.getIncomeTest(incomeYear2007).setCompletedDate(
				this.getDate(2008, 11, 1));
		incoming.getIncomeTest(incomeYear2007).setEffectiveDate(
				getDate(2009, 8, 1));
		incoming.getIncomeTest(incomeYear2007).setSiteConductingTest(facAO);
		incoming.getIncomeTest(incomeYear2007).setLastEditedDate(new Date());
		incoming.getIncomeTest(incomeYear2007).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_IVM.getCode()));

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,
				info);
		assertNotNull(updated.getIncomeTest(incomeYear2007));
		assertTrue(IncomeTestSource.CODE_IVM.getCode().equals(
				updated.getIncomeTest(incomeYear2007).getSource().getCode()));
		IncomeTest result = this.getPersonHelperService().getCurrentIncomeTest(
				updated);
		assertTrue(incomeYear2008.equals(result.getIncomeYear()));
		assertFalse(result.getFutureTest().booleanValue());
		// this.setComplete();
		// System.out.println("pid =" +
		// updated.getPersonEntityKey().toString());
	}

	// 100072028

	public void testPersonAddNew2007MTFromDBZ07() throws Exception {
		IncomeTest test = this.testPersonAddTestFromDBZ07(new Integer(2008),
				new Integer(2007), "100072028");
		assertNotNull(test);
	}

	private IncomeTest testPersonAddTestFromDBZ07(Integer year, String id)
			throws Exception {
		return this.testPersonAddTestFromDBZ07(year, year, id);
	}

	private IncomeTest testPersonAddTestFromDBZ07(Integer effYear,
			Integer year, String id) throws Exception {
		return this.testPersonAddTestFromDBZ07(null, year, year, id);
	}

	private IncomeTest testPersonAddTestFromDBZ07(BigDecimal net,
			Integer effYear, Integer year, String id) throws Exception {
		Person onFile = this.getPerson(id);
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");

		attachIncomeTest(onFile, effYear, year, facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);
		onFile.getIncomeTest(year).setNetIncome(net);
		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(fac.getCode());
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(year));
		IncomeTest x = this.getPersonHelperService().getCurrentIncomeTest(
				updated);
		assertNotNull(x);
		return x;
	}

	public void testPersonAddIncomplete2007MTFromDBZ07() throws Exception {
		Person onFile = this.getPerson("100043827");
		VAFacility fac = this.getLookupService().getVaFacilityByCode("657");
		VAFacility facAO = this.getLookupService().getVaFacilityByCode("657");

		attachIncomeTest(onFile, new Integer(2007), facAO,
				MeansTestStatus.MT_STATUS_MT_COPAY_EXEMPT);

		VerificationInfo info = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		info.setSiteNumber(facAO.getCode());
		onFile.getIncomeTest(new Integer(2007)).setMeansTestStatus(
				this.getLookupService().getMeansTestStatusByCode(
						MeansTestStatus.MT_STATUS_REQUIRED.getCode()));
		onFile.getIncomeTest(new Integer(2007))
				.getIncomeTestStatus()
				.setDeterminedStatus(
						this.getLookupService()
								.getMeansTestStatusByCode(
										MeansTestStatus.MT_STATUS_NP_LONGER_APPLICABLE_RX_COPAY_ONLY
												.getCode()));
		Person updated = this.getMessagingService().processZ07(onFile, fac,
				info);

		assertNotNull(updated.getIncomeTest(new Integer(2007)));
	}

	private void attachIncomeTest(Person person, Integer incomeYear,
			VAFacility facAO, MeansTestStatus.Code status) throws Exception {
		attachIncomeTest(this.getDate(incomeYear.intValue(), 3, 1), person,
				incomeYear, facAO, status);
	}

	private void attachIncomeTest(Person person, Integer effYear,
			Integer incomeYear, VAFacility facAO, MeansTestStatus.Code status)
			throws Exception {
		attachIncomeTest(this.getDate(effYear.intValue(), 3, 1), person,
				incomeYear, facAO, status);
	}

	private void attachIncomeTest(Date effective, Person person,
			Integer incomeYear, VAFacility facAO, MeansTestStatus.Code status)
			throws Exception {
		person.setIncomeTest(incomeYear, this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST, status, incomeYear));
		person.setFinancialStatement(incomeYear,
				this.createFinancialStatement());
		person.getIncomeTest(incomeYear).setCompletedDate(
				this.getDate(incomeYear.intValue(), 11, 1));
		person.getIncomeTest(incomeYear).setEffectiveDate(effective);
		person.getIncomeTest(incomeYear).setLastEditedDate(effective);
		person.getIncomeTest(incomeYear).setSiteConductingTest(facAO);
		person.getIncomeTest(incomeYear).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_VAMC.getCode()));
	}

	private void attachIVMIncomeTest(Date effective, Person person,
			Integer incomeYear, VAFacility facAO, MeansTestStatus.Code status)
			throws Exception {
		person.setIncomeTest(incomeYear, this.createIncomeTest(
				IncomeTestType.CODE_MEANS_TEST, status, incomeYear));
		person.setFinancialStatement(incomeYear,
				this.createFinancialStatement());
		person.getIncomeTest(incomeYear).setCompletedDate(
				this.getDate(incomeYear.intValue(), 11, 1));
		person.getIncomeTest(incomeYear).setEffectiveDate(effective);
		person.getIncomeTest(incomeYear).setSiteConductingTest(facAO);
		person.getIncomeTest(incomeYear).setSource(
				this.getLookupService().getIncomeTestSourceByCode(
						IncomeTestSource.CODE_IVM.getCode()));
	}

	public RegistryService getRegistryService() {
		return registryService;
	}

	public void setRegistryService(RegistryService registryService) {
		this.registryService = registryService;
	}

	public void testUpdateEnrollmentValidAppDate() throws Exception {
		doTestApplicationDate(this.getDate(1996, 9, 30));
	}

	public void testUpdateEnrollmentInvalidAppDate() throws Exception {
		try {
			doTestApplicationDate(this.getDate(1996, 8, 30));
			fail("validation exception not thrown");
		} catch (Exception ex) {
			if (ex instanceof ValidationServiceException) {
				ValidationServiceException vse = (ValidationServiceException) ex;
				ValidationMessages vm = vse.getValidationMessages();
				assertTrue(vm.contains(INVALID_APPLICATION_DATE_PRIOR_10011996));
			} else
				fail("not a validation exception");
		}
	}

	private void doTestApplicationDate(Date date) throws Exception {
		Person onFile = this.buildSimplePerson();
		this.attachVerifiedEnrollment(onFile);
		this.attachPharmacyCopayTestWithNoLongerApplicable(onFile);

		Person incoming = savePerson(onFile);
		this.attachApplication(incoming);
		incoming.getApplication().setApplicationDate(date);
		this.getEligibilityEnrollmentService().updateEnrollmentData(incoming);
	}

	protected String createTestMessageFromFile(String fileName) {
		StringBuffer content = new StringBuffer();
		try {
			InputStreamReader input = new InputStreamReader(
					new BufferedInputStream(ClassLoader
							.getSystemResourceAsStream(fileName)));
			BufferedReader in = new BufferedReader(input);
			String data = null;
			while ((data = in.readLine()) != null) {
				content.append(data).append("\n");
			}
		} catch (Exception e) {

		}
		return content.toString();
	}

	private Object getComponent(String comp) {
		return this.applicationContext.getBean(comp);
	}

	//This is a template for testing CampLejune Z07 process
	public void testCampLejuneZ07() throws Exception {
		Person onFile = buildSimplePerson();

		this.attachVerifiedEnrollment(onFile); //existing person  * new person - don't attach VerifiedEnrollment
		Eligibility elig = new Eligibility();
		elig.setType(this.getLookupService().getEligibilityTypeByCode(EligibilityType.NSC.getCode()));
		//elig.setType(this.getLookupService().getEligibilityTypeByCode(EligibilityType.EMPLOYEE.getCode()));

		onFile.getEnrollmentDetermination().setPrimaryEligiblity(elig);
		this.attachMilitaryServiceEpisode(onFile);  // setup MSE here
	    //this.setEligibilityStatusToVerified(onFile);
	    this.setEligibilityStatusToPendingVerification(onFile);

		onFile.getEligibilityVerification().setAacIndicator(
				this.getLookupService().getAACIndicatorByCode(
						AACIndicator.CODE_DATA_ACCEPTED.getName()));

		onFile.getEnrollmentDetermination().setPriorityGroup(
				this.getLookupService().getEnrollmentPriorityGroupByCode(
						EnrollmentPriorityGroup.GROUP_8.getCode()));

		Person incoming = this.savePerson(onFile);

        //setup CampLejeune data for onFile
		CampLejeuneVerification onFilecampLejeuneVerification = new CampLejeuneVerification();
		onFilecampLejeuneVerification.setSpecialFactorIndicator(getLookupService().getIndicatorByCode(Indicator.NO));
		onFilecampLejeuneVerification.setChangeSite(getRandomVAFacility());
		onFile.addSpecialFactor(onFilecampLejeuneVerification);
		elig = new Eligibility();
		elig.setType(this.getLookupService().getEligibilityTypeByCode(EligibilityType.EMPLOYEE.getCode()));
		onFile.getEnrollmentDetermination().setPrimaryEligiblity(elig);
		//this.setEligibilityStatusToVerified(onFile);
		this.setEligibilityStatusToPendingVerification(onFile);
		onFile.setVeteran(false);
		//VAFacility fac = onFile.getCampLejeuneVerification().getChangeSite();

		//setupCampLejune data for incoming
		CampLejeuneVerification incomingCampLejeuneVerification = new CampLejeuneVerification();
		incomingCampLejeuneVerification.setSpecialFactorIndicator(getLookupService().getIndicatorByCode(Indicator.YES));
		incoming.addSpecialFactor(incomingCampLejeuneVerification);
		//this.setEligibilityStatusToPendingVerification(onFile);  - test for unverified eligibility status
		VAFacility fac = onFile.getCampLejeuneVerification().getChangeSite();
		incoming.getEligibilityVerification().setVerificationFacility(fac);
	    incoming.setVeteran(true);

		this.addPermanentAddress(incoming, Calendar.getInstance().getTime(),
				null);
		VerificationInfo vi = new VerificationInfo("x",
				MessageType.CODE_ORUZ07_TO_ESR.getCode(), "x");
		vi.setSiteNumber(incoming.getEligibilityVerification()
				.getVerificationFacility().getCode());

		Person updated = this.getMessagingService().processZ07(incoming, fac,
				vi);
		System.out.println("Result Camp Lejeune Indicator ="
			+ updated.getCampLejeuneVerification().getSpecialFactorIndicator().getCode());

		System.out.println("Result Person Veteran Indicator ="
				+ updated.isVeteran() );

	}

}
