ProgramOrgUnitCheck implements Checker { @Override public ImportSummary check( ImmutableEvent event, WorkContext ctx ) { ProgramInstance programInstance = ctx.getProgramInstanceMap().get( event.getUid() ); if ( programInstance != null ) { final IdScheme orgUnitIdScheme = ctx.getImportOptions().getIdSchemes().getOrgUnitIdScheme(); OrganisationUnit orgUnit = null; final Set<OrganisationUnit> organisationUnits = programInstance.getProgram().getOrganisationUnits(); for ( OrganisationUnit ou : organisationUnits ) { if ( orgUnitIdScheme.isAttribute() ) { final Optional<OrganisationUnit> ouByAttributeScheme = getByAttributeScheme( ou, event, orgUnitIdScheme ); if ( ouByAttributeScheme.isPresent() ) { orgUnit = ouByAttributeScheme.get(); break; } } else { if ( functionMap.getOrDefault( orgUnitIdScheme, DEFAULT_FUNCTION ).apply( ou, event ) ) { orgUnit = ou; break; } } } if ( orgUnit == null ) { return error( "Program is not assigned to this Organisation Unit: " + event.getOrgUnit(), event.getEvent() ); } } return success(); }  @Override ImportSummary check( ImmutableEvent event, WorkContext ctx );  }
@Test public void verifyCheckUsingAttributeScheme() { event.setOrgUnit( "blue" ); Program program = createProgram( 'P' ); program.setOrganisationUnits( create( 3, CodeGenerator.generateUid(), IdScheme.UID ) ); OrganisationUnit ou = createOrganisationUnit( RandomStringUtils.randomAlphabetic( 1 ) ); Attribute attribute = new Attribute( "color", ValueType.TEXT ); attribute.setUid( CodeGenerator.generateUid() ); AttributeValue attributeValue = new AttributeValue( attribute, "blue" ); ou.setAttributeValues( Collections.singleton( attributeValue ) ); program.getOrganisationUnits().add( ou ); ProgramInstance pi = new ProgramInstance(); pi.setProgram( program ); Map<String, ProgramInstance> programInstanceMap = new HashMap<>(); programInstanceMap.put( event.getUid(), pi ); when( workContext.getProgramInstanceMap() ).thenReturn( programInstanceMap ); ImportOptions importOptions = ImportOptions.getDefaultImportOptions(); importOptions.setOrgUnitIdScheme( IdScheme.ATTR_ID_SCHEME_PREFIX + attribute.getUid() ); when( workContext.getImportOptions() ).thenReturn( importOptions ); ImportSummary summary = rule.check( new ImmutableEvent( event ), workContext ); assertNoError( summary ); }
@Test public void failWhenProgramHasNoOrgUnitMatchingEventOrgUnit() { event.setOrgUnit( CodeGenerator.generateUid() ); Program program = createProgram( 'P' ); program.setOrganisationUnits( create( 5, CodeGenerator.generateUid(), IdScheme.UID ) ); ProgramInstance pi = new ProgramInstance(); pi.setProgram( program ); Map<String, ProgramInstance> programInstanceMap = new HashMap<>(); programInstanceMap.put( event.getUid(), pi ); when( workContext.getProgramInstanceMap() ).thenReturn( programInstanceMap ); ImportSummary summary = rule.check( new ImmutableEvent( event ), workContext ); assertHasError( summary, event, "Program is not assigned to this Organisation Unit: " + event.getOrgUnit() ); }