src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
PropertyUtils { public static void setProperty(Object bean, String name, Object value) { requireNonNull(bean, "bean cannot be null"); requireNonNull(name, "name cannot be null"); Class<?> beanClass = bean.getClass(); try { PropertyDescriptor descriptor = findPropertyDescriptor(beanClass, name); Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null) { throw new IllegalArgumentException("Unable to set property '" + name + " on " + bean.getClass() + " because setter of type " + descriptor.getPropertyType() + " is not available"); } writeMethod.invoke(bean, value); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Unable to set property " + name + " on " + bean.getClass(), e); } } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }
@Test public void shouldSetProperties() { Bean bean = new Bean(); setProperty(bean, "intValue", 1); assertThat(bean.getIntValue()).isEqualTo(1); setProperty(bean, "stringValue", "string"); assertThat(bean.getStringValue()).isEqualTo("string"); Bean beanValue = new Bean(); setProperty(bean, "beanValue", beanValue); assertThat(bean.getBeanValue()).isSameAs(beanValue); setProperty(bean, "stringValue", null); assertThat(bean.getStringValue()).isNull(); } @Test public void setPropertyShouldThrowExceptionWhenPropertyTypeMismatch() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "beanValue", "invalid-type")); } @Test public void setPropertyShouldThrowNoSuchMethodExceptionWhenPropertyNotFound() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "unknownProperty", null)); } @Test public void setPropertyShouldThrowNoSuchMethodExceptionWhenPropertyIsCapitalized() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "BeanValue", null)); } @Test public void setPropertyShouldThrowNullPointerExceptionWhenNullBean() { assertThrows(NullPointerException.class, () -> setProperty(null, "intValue", 1)); } @Test public void setPropertyShouldThrowNullPointerExceptionWhenNullPropertyName() { assertThrows(NullPointerException.class, () -> setProperty(new Bean(), null, null)); }
JaxbConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class && ((AnnotatedElement) type).getAnnotation(XmlRootElement.class) != null; } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test public void shouldBeApplicableForMultipleXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration01.class, null)).isTrue(); assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration02.class, null)).isTrue(); } @Test public void shouldNotBeApplicableForNonXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(NonXmlConfiguration.class, null)).isFalse(); }
PropertyUtils { public static String getPropertyName(Method method) { requireNonNull(method, "method cannot be null"); String name = method.getName(); if (name.startsWith("set")) { if (method.getParameterCount() != 1) { throw new IllegalArgumentException("Method " + method + " is not a valid setter."); } name = name.substring(3); } else if (name.startsWith("get") || name.startsWith("is")) { if (method.getParameterCount() != 0 || void.class.equals(method.getReturnType())) { throw new IllegalArgumentException("Method " + method + " is not a valid getter."); } name = name.substring(name.startsWith("get") ? 3 : 2); } else { throw new IllegalArgumentException("Method " + name + " is not a valid getter nor setter."); } return decapitalize(name); } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }
@Test public void getPropertyNameShouldProvidePropertyNameFromValidAccessor() { assertThat(getPropertyName(getMethod(Bean.class, "getIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "setIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "getStringValue"))).isEqualTo("stringValue"); assertThat(getPropertyName(getMethod(Bean.class, "isBooleanValue"))).isEqualTo("booleanValue"); assertThat(getPropertyName(getMethod(Bean.class, "setBooleanValue"))).isEqualTo("booleanValue"); } @Test public void getPropertyNameShouldThrowNPEWhenMethodIsNull() { assertThrows(NullPointerException.class, () -> getPropertyName(null)); } @Test public void getPropertyNameShouldThrowIAEWhenMethodIsNotGetterNorSetter() { assertThrows(IllegalArgumentException.class, () -> getPropertyName(getMethod(Bean.class, "equals"))); }
MultiConfigurationSource implements ConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (ConfigurationSource source : sources) { OptionalValue<String> value = source.getValue(key, attributes); if (value.isPresent()) { return value; } } return absent(); } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }
@Test public void shouldReturnValuesFromProperSource() { assertThat(source.getValue(A_KEY, null).get()).isEqualTo(A_KEY); assertThat(source.getValue(B_KEY, null).get()).isEqualTo(B_KEY); }
MultiConfigurationSource implements ConfigurationSource { @Override public ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes) { requireNonNull(keys, "keys cannot be null"); for (ConfigurationSource source : sources) { ConfigurationEntry entry = source.findEntry(keys, attributes); if (entry != null) { return entry; } } return null; } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }
@Test public void shouldFindValuesInProperSource() { assertThat(source.findEntry(asList("NotExistingKey", B_KEY), null)).isEqualTo(new ConfigurationEntry(B_KEY, B_KEY)); }
MapConfigurationSource implements IterableConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); String value = source.get(key); return value != null || source.containsKey(key) ? present(value) : absent(); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }
@Test public void shouldGetSingleValueFromUnderlyingMap() { ConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); String value = source.getValue("key2", null).get(); assertThat(value).isEqualTo("value2"); }
MapConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { return new MapConfigurationEntryIterable(source); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }
@Test public void shouldIterateOver() { MapConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); Iterable<ConfigurationEntry> iterable = source.getAllConfigurationEntries(); assertThat(iterable).containsExactly(new ConfigurationEntry("key1", "value1"), new ConfigurationEntry("key2", "value2")); }
WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public void setValue(String key, String value, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); source.put(key, value); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }
@Test public void shouldSetAndGetValue() { WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(new HashMap<>()); mapConfigurationSource.setValue("key", "value", null); OptionalValue<String> value = mapConfigurationSource.getValue("key", null); assertThat(value.isPresent()).isTrue(); assertThat(value.get()).isEqualTo("value"); }
MatchingChangeoverNormsDetailsListeners { public void matchingChangeoverNorm(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) { Entity fromTechnology = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_FROM_TECHNOLOGY)) .getEntity(); Entity toTechnology = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_TO_TECHNOLOGY)).getEntity(); Entity productionLine = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_PRODUCTION_LINE)) .getEntity(); FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference("form"); Entity changeoverNorm = changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine); if (changeoverNorm == null) { clearField(viewDefinitionState); changeStateEditButton(viewDefinitionState, false); form.setFieldValue(null); } else { form.setFieldValue(changeoverNorm.getId()); fillField(viewDefinitionState, changeoverNorm); changeStateEditButton(viewDefinitionState, true); } } void matchingChangeoverNorm(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args); void redirectToChangedNormsDetails(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args); void enabledButtonAfterSelectionTechnologies(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args); void changeStateEditButton(final ViewDefinitionState view, final boolean enabled); void clearField(final ViewDefinitionState view); void fillField(final ViewDefinitionState view, final Entity entity); }
@Test public void shouldClearFieldAndDisabledButtonWhenMatchingChangeoverNormWasnotFound() throws Exception { when(changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine)).thenReturn(null); when(view.getComponentByReference(NUMBER)).thenReturn(number); when(view.getComponentByReference(FROM_TECHNOLOGY)).thenReturn(fromTechLookup); when(view.getComponentByReference(TO_TECHNOLOGY)).thenReturn(toTechLookup); when(view.getComponentByReference(FROM_TECHNOLOGY_GROUP)).thenReturn(fromTechGpLookup); when(view.getComponentByReference(TO_TECHNOLOGY_GROUP)).thenReturn(toTechGpLookup); when(view.getComponentByReference(CHANGEOVER_TYPE)).thenReturn(changeoverTypField); when(view.getComponentByReference(DURATION)).thenReturn(durationField); when(view.getComponentByReference(PRODUCTION_LINE)).thenReturn(productionLineLookup); when(view.getComponentByReference("form")).thenReturn(form); when(view.getComponentByReference("window")).thenReturn((ComponentState) window); when(window.getRibbon()).thenReturn(ribbon); when(ribbon.getGroupByName("matching")).thenReturn(matching); when(ribbon.getGroupByName("editing")).thenReturn(matching); when(matching.getItemByName("edit")).thenReturn(edit); listeners.matchingChangeoverNorm(view, state, null); Mockito.verify(fromTechLookup).setFieldValue(null); Mockito.verify(edit).setEnabled(false); }
AbstractStateChangeAspect implements StateChangeService { @Override public void changeState(final StateChangeContext stateChangeContext) { try { performStateChange(stateChangeContext); } catch (Exception exception) { LOGGER.warn("Can't perform state change", exception); stateChangeContext.setStatus(StateChangeStatus.FAILURE); stateChangeContext.addMessage("states.messages.change.failure.internalServerError", StateMessageType.FAILURE); stateChangeContext.save(); throw new StateChangeException(exception); } } @Override void changeState(final StateChangeContext stateChangeContext); }
@Test public final void shouldNotPerformEntityStateChangeIfOwnerHasValidationErrors() { AlmostRealStateChangeService stateChangeService = new AlmostRealStateChangeService(); given(stateChangeContext.isOwnerValid()).willReturn(true, false); stateChangeService.changeState(stateChangeContext); verify(stateChangeContext).setStatus(StateChangeStatus.FAILURE); } @Test public final void shouldMarkStateChangeAsFailureAndRethrowExceptionWhenStateChangePhaseThrowsException() { ExceptionThrowingStateChangeService stateChangeService = new ExceptionThrowingStateChangeService(); try { stateChangeService.changeState(stateChangeContext); } catch (StateChangeException e) { verify(stateChangeContext).setStatus(StateChangeStatus.FAILURE); verify(stateChangeContext, Mockito.atLeastOnce()).save(); } } @Test public final void shouldMarkStateChangeAsFailureAndRethrowExceptionWhenOwnerEntityValidatorThrowException() { AlmostRealStateChangeService stateChangeService = new AlmostRealStateChangeService(); given(ownerDD.callValidators(Mockito.any(Entity.class))).willThrow(new RuntimeException()); try { stateChangeService.changeState(stateChangeContext); } catch (StateChangeException e) { verify(stateChangeContext).setStatus(StateChangeStatus.FAILURE); verify(stateChangeContext, Mockito.atLeastOnce()).save(); } } @Test public final void shouldMarkStateChangeAsFailureWhenOwnerIsInvalid() { AlmostRealStateChangeService stateChangeService = new AlmostRealStateChangeService(); given(owner.isValid()).willReturn(false); given(ownerDD.callValidators(owner)).willReturn(false); stateChangeService.changeState(stateChangeContext); verify(stateChangeContext).setStatus(StateChangeStatus.FAILURE); verify(stateChangeContext, Mockito.atLeastOnce()).save(); } @Test public final void shouldFireListenersAndChangeState() { TestStateChangeService testStateChangeService = new TestStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); stubStringField(stateChangeEntity, DESCRIBER.getTargetStateFieldName(), STATE_FIELD_VALUE); stubEntityMock("", ""); testStateChangeService.changeState(stateChangeContext); verify(stateChangeEntity).setField("marked", true); verify(ownerEntity).setField(STATE_FIELD_NAME, STATE_FIELD_VALUE); } @Test public final void shouldNotFireListenersForOtherStateChangeService() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); stubStringField(stateChangeEntity, DESCRIBER.getTargetStateFieldName(), STATE_FIELD_VALUE); stubEntityMock("", ""); anotherStateChangeService.changeState(stateChangeContext); verify(stateChangeEntity, never()).setField("marked", true); verify(ownerEntity).setField(STATE_FIELD_NAME, STATE_FIELD_VALUE); } @Test public final void shouldNotFireChangeStateIfStateChangeWasSuccessfulFinished() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); given(stateChangeEntity.getStringField(DESCRIBER.getStatusFieldName())).willReturn( StateChangeStatus.SUCCESSFUL.getStringValue()); mockStateChangeStatus(stateChangeEntity, StateChangeStatus.SUCCESSFUL); anotherStateChangeService.changeState(stateChangeContext); verify(ownerEntity, never()).setField(Mockito.eq(STATE_FIELD_NAME), Mockito.any()); } @Test public final void shouldNotFireChangeStateIfStateChangeWasFailureFinished() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); given(stateChangeEntity.getStringField(DESCRIBER.getStatusFieldName())).willReturn( StateChangeStatus.SUCCESSFUL.getStringValue()); mockStateChangeStatus(stateChangeEntity, StateChangeStatus.FAILURE); anotherStateChangeService.changeState(stateChangeContext); verify(ownerEntity, never()).setField(Mockito.eq(STATE_FIELD_NAME), Mockito.any()); } @Test public final void shouldNotFireChangeStateIfStateChangeWasPaused() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); given(stateChangeEntity.getStringField(DESCRIBER.getStatusFieldName())).willReturn( StateChangeStatus.SUCCESSFUL.getStringValue()); mockStateChangeStatus(stateChangeEntity, StateChangeStatus.PAUSED); anotherStateChangeService.changeState(stateChangeContext); verify(ownerEntity, never()).setField(Mockito.eq(STATE_FIELD_NAME), Mockito.any()); } @Test public final void shouldNotFireListenersIfStateChangeWasAlreadyFinished() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); given(stateChangeEntity.getBelongsToField(DESCRIBER.getOwnerFieldName())).willReturn(ownerEntity); given(stateChangeEntity.getBooleanField(DESCRIBER.getStatusFieldName())).willReturn(true); given(stateChangeEntity.getField(DESCRIBER.getStatusFieldName())).willReturn(true); anotherStateChangeService.changeState(stateChangeContext); verify(stateChangeEntity, never()).setField("marked", true); } @Test public final void shouldNotFireChangeStateIfStateChangeHaveErrorMessages() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); EntityList messagesEntityList = mockEntityList(Lists.newArrayList(mockMessage(StateMessageType.FAILURE, "fail"))); given(stateChangeEntity.getHasManyField(DESCRIBER.getMessagesFieldName())).willReturn(messagesEntityList); given(stateChangeEntity.getField(DESCRIBER.getMessagesFieldName())).willReturn(messagesEntityList); anotherStateChangeService.changeState(stateChangeContext); verify(ownerEntity, never()).setField(Mockito.eq(STATE_FIELD_NAME), Mockito.any()); } @Test public final void shouldNotFireListenersIfStateChangeHaveErrorMessages() { AnotherStateChangeService anotherStateChangeService = new AnotherStateChangeService(); EntityList messagesEntityList = mockEntityList(Lists.newArrayList(mockMessage(StateMessageType.FAILURE, "fail"))); given(stateChangeEntity.getHasManyField(DESCRIBER.getMessagesFieldName())).willReturn(messagesEntityList); given(stateChangeEntity.getField(DESCRIBER.getMessagesFieldName())).willReturn(messagesEntityList); anotherStateChangeService.changeState(stateChangeContext); verify(stateChangeEntity, never()).setField("marked", true); }
ProductionTrackingDetailsHooks { public void initializeProductionTrackingDetailsView(final ViewDefinitionState view) { FormComponent productionTrackingForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent stateField = (FieldComponent) view.getComponentByReference(ProductionTrackingFields.STATE); LookupComponent orderLookup = (LookupComponent) view.getComponentByReference(ProductionTrackingFields.ORDER); FieldComponent isDisabledField = (FieldComponent) view.getComponentByReference(L_IS_DISABLED); Entity productionTracking = productionTrackingForm.getEntity(); stateField.setFieldValue(productionTracking.getField(ProductionTrackingFields.STATE)); stateField.requestComponentUpdateState(); Entity order = orderLookup.getEntity(); isDisabledField.setFieldValue(false); if (order != null) { productionTrackingService.setTimeAndPieceworkComponentsVisible(view, order); } } void onBeforeRender(final ViewDefinitionState view); void setCriteriaModifierParameters(final ViewDefinitionState view); void initializeProductionTrackingDetailsView(final ViewDefinitionState view); void changeFieldComponentsEnabledAndGridsEditable(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); }
@Test public void shouldSetStateToDraftWhenInitializeTrackingDetailsViewIfProductionTrackingIsntSaved() { given(productionTrackingForm.getEntityId()).willReturn(null); given(productionTrackingForm.getEntity()).willReturn(productionTracking); given(productionTracking.getField(ProductionTrackingFields.STATE)).willReturn(ProductionTrackingStateStringValues.DRAFT); productionTrackingDetailsHooks.initializeProductionTrackingDetailsView(view); verify(stateField, times(1)).setFieldValue(ProductionTrackingStateStringValues.DRAFT); verify(isDisabledField, times(1)).setFieldValue(false); verify(productionTrackingService, never()).setTimeAndPieceworkComponentsVisible(view, order); } @Test public void shouldSetStateToAcceptedWhenInitializeTrackingDetailsViewIfProductionTrackingIsSaved() { given(productionTrackingForm.getEntityId()).willReturn(1L); given(productionTrackingForm.getEntity()).willReturn(productionTracking); given(productionTracking.getField(ProductionTrackingFields.STATE)).willReturn( ProductionTrackingStateStringValues.ACCEPTED); given(orderLookup.getEntity()).willReturn(order); productionTrackingDetailsHooks.initializeProductionTrackingDetailsView(view); verify(stateField, times(1)).setFieldValue(ProductionTrackingStateStringValues.ACCEPTED); verify(isDisabledField, times(1)).setFieldValue(false); verify(productionTrackingService, times(1)).setTimeAndPieceworkComponentsVisible(view, order); }
ProductionTrackingServiceImpl implements ProductionTrackingService { @Override public void setTimeAndPieceworkComponentsVisible(final ViewDefinitionState view, final Entity order) { String recordingType = order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING); boolean recordingTypeEqualsForEach = TypeOfProductionRecording.FOR_EACH.getStringValue().equals(recordingType); boolean recordingTypeEqualsBasic = TypeOfProductionRecording.BASIC.getStringValue().equals(recordingType); LookupComponent tocComponent = (LookupComponent) view .getComponentByReference(ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT); tocComponent.setVisible(recordingTypeEqualsForEach); tocComponent.setRequired(recordingTypeEqualsForEach); boolean registerProductionTime = order.getBooleanField(OrderFieldsPC.REGISTER_PRODUCTION_TIME); view.getComponentByReference(L_TIME_TAB).setVisible(registerProductionTime && !recordingTypeEqualsBasic); ProductionTrackingState recordState = getTrackingState(view); final FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); if (form.getEntityId() != null) { WindowComponent window = (WindowComponent) view.getComponentByReference(L_WINDOW); RibbonActionItem calcTotalLaborTimeBtn = window.getRibbon().getGroupByName(L_WORK_TIME_RIBBON_GROUP) .getItemByName(L_CALC_LABOR_TOTAL_TIME_RIBBON_BUTTON); calcTotalLaborTimeBtn.setEnabled(registerProductionTime && !recordingTypeEqualsBasic && ProductionTrackingState.DRAFT.equals(recordState)); calcTotalLaborTimeBtn.requestUpdate(true); } boolean registerPiecework = order.getBooleanField(OrderFieldsPC.REGISTER_PIECEWORK); view.getComponentByReference(L_PIECEWORK_TAB).setVisible(registerPiecework && recordingTypeEqualsForEach); } @Override void setTimeAndPieceworkComponentsVisible(final ViewDefinitionState view, final Entity order); @Override ProductionTrackingState getTrackingState(final ViewDefinitionState view); @Override void changeProducedQuantityFieldState(final ViewDefinitionState viewDefinitionState); @Override void fillProductionLineLookup(final ViewDefinitionState view); @Override void changeState(Entity productionTracking, ProductionTrackingState state); @Override Entity correct(Entity productionTracking); @Override void unCorrect(Entity correctingProductionTracking); }
@Test public void shouldNotSetTimeAndPieceworkTabVisibleIfTypeIsBasic() { String typeOfProductionRecording = TypeOfProductionRecording.BASIC.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(order.getBooleanField(OrderFieldsPC.REGISTER_PRODUCTION_TIME)).willReturn(true); given(order.getBooleanField(OrderFieldsPC.REGISTER_PIECEWORK)).willReturn(true); given(productionCountingService.isTypeOfProductionRecordingBasic(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(false); productionTrackingService.setTimeAndPieceworkComponentsVisible(view, order); verify(technologyOperationComponentLookup).setVisible(false); verify(timeTab).setVisible(false); verify(pieceworkTab).setVisible(false); verify(calcTotalLaborTimeRibbonBtn).setEnabled(false); verify(calcTotalLaborTimeRibbonBtn).requestUpdate(true); } @Test public void shoulsSetTimeAndPieceworkTabVisibleIfTypeIsCumulated() { String typeOfProductionRecording = TypeOfProductionRecording.CUMULATED.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(order.getBooleanField(OrderFieldsPC.REGISTER_PRODUCTION_TIME)).willReturn(true); given(order.getBooleanField(OrderFieldsPC.REGISTER_PIECEWORK)).willReturn(true); given(productionCountingService.isTypeOfProductionRecordingBasic(typeOfProductionRecording)).willReturn(false); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(false); productionTrackingService.setTimeAndPieceworkComponentsVisible(view, order); verify(technologyOperationComponentLookup).setVisible(false); verify(timeTab).setVisible(true); verify(pieceworkTab).setVisible(false); verify(calcTotalLaborTimeRibbonBtn).setEnabled(true); verify(calcTotalLaborTimeRibbonBtn).requestUpdate(true); } @Test public void shoulsSetTimeAndPieceworkTabVisibleIfTypeIsForEach() { String typeOfProductionRecording = TypeOfProductionRecording.FOR_EACH.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(order.getBooleanField(OrderFieldsPC.REGISTER_PRODUCTION_TIME)).willReturn(true); given(order.getBooleanField(OrderFieldsPC.REGISTER_PIECEWORK)).willReturn(true); given(productionCountingService.isTypeOfProductionRecordingBasic(typeOfProductionRecording)).willReturn(false); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(true); productionTrackingService.setTimeAndPieceworkComponentsVisible(view, order); verify(technologyOperationComponentLookup).setVisible(true); verify(timeTab).setVisible(true); verify(pieceworkTab).setVisible(true); verify(calcTotalLaborTimeRibbonBtn).setEnabled(true); verify(calcTotalLaborTimeRibbonBtn).requestUpdate(true); }
OrderClosingHelper { public boolean orderShouldBeClosed(final Entity productionTracking) { Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER); if (order == null) { return false; } Boolean autoCloseOrder = order.getBooleanField(OrderFieldsPC.AUTO_CLOSE_ORDER); Boolean isLastRecord = productionTracking.getBooleanField(ProductionTrackingFields.LAST_TRACKING); TypeOfProductionRecording recType = TypeOfProductionRecording.parseString(order .getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)); return isLastRecord && autoCloseOrder && (!(TypeOfProductionRecording.FOR_EACH.equals(recType)) || eachOperationHasLastRecords(order, productionTracking)); } boolean orderShouldBeClosed(final Entity productionTracking); }
@Test public final void shouldOrderCanBeClosedWhenTypeIsCummulativeAndAcceptingLastRecord() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.CUMULATED); productionTrackingIsLast(); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertTrue(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsCummulativeAndAcceptingLastRecordButAutoCloseIsNotEnabled() { stubTypeOfProductionRecording(TypeOfProductionRecording.CUMULATED); productionTrackingIsLast(); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsCummulativeAndAcceptingNotLastRecord() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.CUMULATED); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndAcceptingNotLastRecord() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); stubSearchCriteriaResults(1L, 2L, 3L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndThereIsNotEnoughtLastRecords() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndRecordIsNotLastAndThereIsNotEnoughtLastRecords() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); stubSearchCriteriaResults(1L, 2L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanBeClosedWhenTypeIsForEachOpAndRecordIsLastAndThereIsEnoughtLastRecords() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L, 3L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertTrue(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndRecordIsLastAndThereIsEnoughtLastRecordsButAutoCloseIsNotEnabled() { stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L, 3L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanBeClosedWhenTypeIsForEachOpAndRecordIsLastAndThereIsMoreThanEnoughtLastRecords() { orderHasEnabledAutoClose(); productionTrackingIsLast(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); stubSearchCriteriaResults(1L, 2L, 3L, 4L, 5L, 6L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertTrue(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndRecordIsLastAndThereIsMoreThanEnoughtLastRecordsButAutoCloseIsNotEnabled() { stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L, 3L, 4L, 5L, 6L); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); } @Test public final void shouldOrderCanBeClosedWhenTypeIsForEachOpAndRecordIsLastAndIsAlreadyAcceptedButThereIsEnoughtRecords() { orderHasEnabledAutoClose(); stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L, 3L, PRODUCTION_RECORD_ID); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertTrue(shouldClose); } @Test public final void shouldOrderCanNotBeClosedWhenTypeIsForEachOpAndRecordIsLastButIsAlreadyAccepted() { stubTypeOfProductionRecording(TypeOfProductionRecording.FOR_EACH); productionTrackingIsLast(); stubSearchCriteriaResults(1L, 2L, PRODUCTION_RECORD_ID); boolean shouldClose = orderClosingHelper.orderShouldBeClosed(productionTracking); assertFalse(shouldClose); }
AvgLaborCostCalcForOrderDetailsHooks { public void enabledButtonForCopyNorms(final ViewDefinitionState view) { WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonActionItem copyToOperationsNorms = window.getRibbon().getGroupByName("hourlyCostNorms") .getItemByName("copyToOperationsNorms"); FieldComponent averageLaborHourlyCost = (FieldComponent) view.getComponentByReference(AVERAGE_LABOR_HOURLY_COST); if (StringUtils.isEmpty((String) averageLaborHourlyCost.getFieldValue())) { copyToOperationsNorms.setEnabled(false); } else { copyToOperationsNorms.setEnabled(true); } copyToOperationsNorms.requestUpdate(true); } void enabledButtonForCopyNorms(final ViewDefinitionState view); }
@Test public void shouldEnabledButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = "50"; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(true); } @Test public void shouldDisbaleButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = ""; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(false); }
GenerateProductionBalanceWithCosts implements Observer { public void doTheCostsPart(final Entity productionBalance) { Entity order = productionBalance.getBelongsToField(ProductionBalanceFields.ORDER); Entity technology = order.getBelongsToField(OrderFields.TECHNOLOGY); Entity productionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE); productionBalance.setField(ProductionBalanceFields.ORDER, order); BigDecimal quantity = order.getDecimalField(OrderFields.PLANNED_QUANTITY); productionBalance.setField(ProductionBalanceFieldsPCWC.QUANTITY, quantity); productionBalance.setField(ProductionBalanceFieldsPCWC.TECHNOLOGY, technology); productionBalance.setField(ProductionBalanceFieldsPCWC.PRODUCTION_LINE, productionLine); costCalculationService.calculateOperationsAndProductsCosts(productionBalance); final BigDecimal productionCosts = costCalculationService.calculateProductionCost(productionBalance); final BigDecimal doneQuantity = order.getDecimalField(OrderFields.DONE_QUANTITY); costCalculationService.calculateTotalCosts(productionBalance, productionCosts, doneQuantity); BigDecimal perUnit = BigDecimal.ZERO; if (!BigDecimalUtils.valueEquals(BigDecimal.ZERO, doneQuantity)) { BigDecimal totalTechnicalProductionCosts = productionBalance .getDecimalField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COSTS); perUnit = totalTechnicalProductionCosts.divide(doneQuantity, numberService.getMathContext()); } productionBalance.setField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COST_PER_UNIT, numberService.setScale(perUnit)); } @Override void update(final Observable observable, final Object object); void doTheCostsPart(final Entity productionBalance); void fillFieldsAndGrids(final Entity productionBalance); }
@Test public void shouldSetQuantityTechnologyProductionLineAndTechnicalProductionCostPerUnitFieldsAndSaveEntity() { BigDecimal quantity = BigDecimal.TEN; BigDecimal doneQuantity = BigDecimal.TEN; given(productionBalance.getDecimalField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COSTS)).willReturn( BigDecimal.valueOf(100)); given(order.getDecimalField(OrderFields.PLANNED_QUANTITY)).willReturn(quantity); given(order.getDecimalField(OrderFields.DONE_QUANTITY)).willReturn(doneQuantity); given(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); generateProductionBalanceWithCosts.doTheCostsPart(productionBalance); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.QUANTITY, quantity); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.TECHNOLOGY, technology); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.PRODUCTION_LINE, productionLine); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COST_PER_UNIT, BigDecimal.TEN.setScale(5, RoundingMode.HALF_EVEN)); }
GenerateProductionBalanceWithCosts implements Observer { void generateBalanceWithCostsReport(final Entity productionBalance) { Locale locale = LocaleContextHolder.getLocale(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix); String localePrefixToMatch = localePrefix; try { productionBalanceWithCostsPdfService.generateDocument(productionBalanceWithFileName, locale, localePrefixToMatch); productionBalanceWithFileName.setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); productionBalanceWithFileName.getDataDefinition().save(productionBalanceWithFileName); } catch (IOException e) { throw new IllegalStateException("Problem with saving productionBalanceWithCosts report", e); } catch (DocumentException e) { throw new IllegalStateException("Problem with generating productionBalanceWithCosts report", e); } } @Override void update(final Observable observable, final Object object); void doTheCostsPart(final Entity productionBalance); void fillFieldsAndGrids(final Entity productionBalance); }
@Test public void shouldGenerateReportCorrectly() throws Exception { Locale locale = Locale.getDefault(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = mock(Entity.class); given(productionBalanceWithFileName.getDataDefinition()).willReturn(productionBalanceDD); given(fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix)).willReturn( productionBalanceWithFileName); generateProductionBalanceWithCosts.generateBalanceWithCostsReport(productionBalance); verify(productionBalanceWithCostsPdfService).generateDocument(productionBalanceWithFileName, locale, localePrefix); verify(productionBalanceWithFileName).setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); verify(productionBalanceDD).save(productionBalanceWithFileName); }
ProductionBalanceWithCostsPdfService extends PdfDocumentService { @Override protected void buildPdfContent(final Document document, final Entity productionBalance, final Locale locale) throws DocumentException { String documentTitle = translationService.translate("productionCounting.productionBalance.report.title", locale); String documentAuthor = translationService.translate("smartReport.commons.generatedBy.label", locale); pdfHelper.addDocumentHeader(document, "", documentTitle, documentAuthor, productionBalance.getDateField(ProductionBalanceFields.DATE)); PdfPTable topTable = pdfHelper.createPanelTable(2); topTable.addCell(productionBalancePdfService.createLeftPanel(productionBalance, locale)); topTable.addCell(productionBalancePdfService.createRightPanel(productionBalance, locale)); topTable.setSpacingBefore(20); document.add(topTable); PdfPTable parametersForCostsPanel = createParametersForCostsPanel(productionBalance, locale); parametersForCostsPanel.setSpacingBefore(20); document.add(parametersForCostsPanel); Entity order = productionBalance.getBelongsToField(ProductionBalanceFields.ORDER); String typeOfProductionRecording = order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING); String calculateOperationCostMode = productionBalance .getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE); final boolean isTypeOfProductionRecordingCumulated = productionCountingService .isTypeOfProductionRecordingCumulated(typeOfProductionRecording); final boolean isTypeOfProductionRecordingForEach = productionCountingService .isTypeOfProductionRecordingForEach(typeOfProductionRecording); final boolean isCalculateOperationCostModeHourly = productionCountingService .isCalculateOperationCostModeHourly(calculateOperationCostMode); final boolean isCalculateOperationCostModePiecework = productionCountingService .isCalculateOperationCostModePiecework(calculateOperationCostMode); if (isCalculateOperationCostModeHourly && isTypeOfProductionRecordingCumulated) { PdfPTable assumptionForCumulatedRecordsPanel = createAssumptionsForCumulatedRecordsPanel(productionBalance, locale); assumptionForCumulatedRecordsPanel.setSpacingBefore(20); document.add(assumptionForCumulatedRecordsPanel); } PdfPTable bottomTable = pdfHelper.createPanelTable(2); bottomTable.addCell(createCostsPanel(productionBalance, locale)); bottomTable.addCell(createOverheadsAndSummaryPanel(productionBalance, locale)); bottomTable.setSpacingBefore(20); bottomTable.setSpacingAfter(20); document.add(bottomTable); productionBalancePdfService.addInputProductsBalance(document, productionBalance, locale); addMaterialCost(document, productionBalance, locale); productionBalancePdfService.addOutputProductsBalance(document, productionBalance, locale); if (isCalculateOperationCostModeHourly) { if (isTypeOfProductionRecordingCumulated) { productionBalancePdfService.addTimeBalanceAsPanel(document, productionBalance, locale); addProductionCosts(document, productionBalance, locale); } else if (isTypeOfProductionRecordingForEach) { productionBalancePdfService.addMachineTimeBalance(document, productionBalance, locale); addCostsBalance("machine", document, productionBalance, locale); productionBalancePdfService.addLaborTimeBalance(document, productionBalance, locale); addCostsBalance("labor", document, productionBalance, locale); } } else if (isCalculateOperationCostModePiecework) { productionBalancePdfService.addPieceworkBalance(document, productionBalance, locale); addCostsBalance("cycles", document, productionBalance, locale); } costCalculationPdfService.printMaterialAndOperationNorms(document, productionBalance, locale); } PdfPTable createParametersForCostsPanel(final Entity productionBalance, final Locale locale); @Override String getReportTitle(final Locale locale); }
@Test public void shouldAddTimeBalanceAndProductionCostsIfTypeCumulatedAndHourly() throws Exception { String typeOfProductionRecording = TypeOfProductionRecording.CUMULATED.getStringValue(); String calculateOperationCostMode = CalculateOperationCostMode.HOURLY.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( calculateOperationCostMode); given(productionCountingService.isTypeOfProductionRecordingCumulated(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isCalculateOperationCostModeHourly(calculateOperationCostMode)).willReturn(true); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(productionBalancePdfService).addTimeBalanceAsPanel(document, productionBalance, locale); verify(document).add(threeColumnTable); } @Test public void shouldNotAddTimeBalanceAndProductionCostsIfTypeIsNotHourly() throws Exception { String typeOfProductionRecording = TypeOfProductionRecording.CUMULATED.getStringValue(); String calculateOperationCostMode = CalculateOperationCostMode.PIECEWORK.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( calculateOperationCostMode); given(productionCountingService.isTypeOfProductionRecordingCumulated(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isCalculateOperationCostModePiecework(calculateOperationCostMode)).willReturn(true); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(productionBalancePdfService, never()).addTimeBalanceAsPanel(document, productionBalance, locale); verify(document, never()).add(threeColumnTable); } @Test public void shouldNotAddTimeBalanceAndProductionCostsIfTypeIsNotCumulated() throws Exception { String typeOfProductionRecording = TypeOfProductionRecording.FOR_EACH.getStringValue(); String calculateOperationCostMode = CalculateOperationCostMode.HOURLY.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( calculateOperationCostMode); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isCalculateOperationCostModeHourly(calculateOperationCostMode)).willReturn(true); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(productionBalancePdfService, never()).addTimeBalanceAsPanel(document, productionBalance, locale); verify(document, never()).add(threeColumnTable); } @Test public void shouldAddMachineTimeBalanceAndLaborTimeBalanceIfTypeIsHourlyAndForEach() throws Exception { String typeOfProductionRecording = TypeOfProductionRecording.FOR_EACH.getStringValue(); String calculateOperationCostMode = CalculateOperationCostMode.HOURLY.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( calculateOperationCostMode); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isCalculateOperationCostModeHourly(calculateOperationCostMode)).willReturn(true); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(productionBalancePdfService).addMachineTimeBalance(document, productionBalance, locale); verify(productionBalancePdfService).addLaborTimeBalance(document, productionBalance, locale); } @Test public void shouldCallProductAndOperationNormsPrintingMethodNoMatterWhatIncludingrHourlyAndForEachType() throws Exception { String typeOfProductionRecording = TypeOfProductionRecording.FOR_EACH.getStringValue(); String calculateOperationCostMode = CalculateOperationCostMode.HOURLY.getStringValue(); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn(typeOfProductionRecording); given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( calculateOperationCostMode); given(productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)).willReturn(true); given(productionCountingService.isCalculateOperationCostModeHourly(calculateOperationCostMode)).willReturn(true); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(costCalculationPdfService).printMaterialAndOperationNorms(document, productionBalance, locale); } @Test public void shouldCallProductAndOperationNormsPrintingMethodNoMatterWhatIncludingPieceworkAndCumulatedType() throws Exception { given(productionBalance.getStringField(ProductionBalanceFields.CALCULATE_OPERATION_COST_MODE)).willReturn( CalculateOperationCostMode.PIECEWORK.getStringValue()); given(order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING)).willReturn( TypeOfProductionRecording.CUMULATED.getStringValue()); productionBalanceWithCostsPdfService.buildPdfContent(document, productionBalance, locale); verify(costCalculationPdfService).printMaterialAndOperationNorms(document, productionBalance, locale); }
ProductDetailsListenersT { public final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); }
@Test public void shouldntAddTechnologyGroupIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldAddTechnologyGroupIfProductIsSaved() { given(product.getId()).willReturn(L_ID); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
CostNormsForOperationService { public void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState, final String[] args) { ComponentState operationLookup = view.getComponentByReference(OPERATION_FIELD); if (operationLookup.getFieldValue() == null) { if (!OPERATION_FIELD.equals(operationLookupState.getName())) { view.getComponentByReference("form").addMessage("costNormsForOperation.messages.info.missingOperationReference", INFO); } return; } Entity operation = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_OPERATION).get((Long) operationLookup.getFieldValue()); applyCostNormsFromGivenSource(view, operation); } void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState, final String[] args); void inheritOperationNormValues(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void fillCurrencyFields(final ViewDefinitionState view); void copyCostNormsToTechnologyOperationComponent(final DataDefinition dd, final Entity technologyOperationComponent); }
@Test public void shouldReturnWhenOperationIsNull() throws Exception { costNormsForOperationService.copyCostValuesFromOperation(view, state, null); } @Test public void shouldApplyCostNormsForGivenSource() throws Exception { when(state.getFieldValue()).thenReturn(1L); Long operationId = 1L; when(operationDD.get(operationId)).thenReturn(operationEntity); when(operationEntity.getField("pieceworkCost")).thenReturn(obj1); when(operationEntity.getField("numberOfOperations")).thenReturn(obj2); when(operationEntity.getField("laborHourlyCost")).thenReturn(obj3); when(operationEntity.getField("machineHourlyCost")).thenReturn(obj4); costNormsForOperationService.copyCostValuesFromOperation(view, state, null); Mockito.verify(field1).setFieldValue(obj1); Mockito.verify(field2).setFieldValue(obj2); Mockito.verify(field3).setFieldValue(obj3); Mockito.verify(field4).setFieldValue(obj4); }
ProductDetailsListenersT { public final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } Entity technologyGroup = product.getBelongsToField("technologyGroup"); if (technologyGroup == null) { return; } String technologyGroupNumber = technologyGroup.getStringField(NUMBER); Map<String, String> filters = Maps.newHashMap(); filters.put("technologyGroupNumber", technologyGroupNumber); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); }
@Test public void shouldntShowTechnologiesWithTechnologyGroupIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldntShowTechnologiesWithTechnologyGroupIfProductIsSavedAndTechnologyGroupIsNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldShowTechnologiesWithTechnologyGroupIfProductIsSavedAndTechnologyGroupIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(technologyGroup.getStringField(NUMBER)).willReturn(L_TECHNOLOGY_GROUP_NUMBER); filters.put("technologyGroupNumber", L_TECHNOLOGY_GROUP_NUMBER); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
ProductDetailsListenersT { public final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); }
@Test public void shouldntShowTechnologiesWithProductIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldntShowTechnologiesWithProductIfProductIsntSavedAndProductNameIsNull() { given(product.getId()).willReturn(1L); given(product.getStringField(NAME)).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldShowTechnologiesWithProductIfProductIsSavedAndProductNameIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "["+ L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
ProductDetailsViewHooksT { public void updateRibbonState(final ViewDefinitionState view) { Entity loggedUser = dataDefinitionService .get(QcadooSecurityConstants.PLUGIN_IDENTIFIER, QcadooSecurityConstants.MODEL_USER) .get(securityService.getCurrentUserId()); if (!securityService.hasRole(loggedUser, "ROLE_TECHNOLOGIES")) { view.getComponentByReference("technologyTab").setVisible(false); } FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup technologies = (RibbonGroup) window.getRibbon().getGroupByName("technologies"); RibbonActionItem showTechnologiesWithTechnologyGroup = (RibbonActionItem) technologies .getItemByName("showTechnologiesWithTechnologyGroup"); RibbonActionItem showTechnologiesWithProduct = (RibbonActionItem) technologies .getItemByName("showTechnologiesWithProduct"); if (product.getId() != null) { Entity technologyGroup = product.getBelongsToField("technologyGroup"); if (technologyGroup == null) { updateButtonState(showTechnologiesWithTechnologyGroup, false); } else { updateButtonState(showTechnologiesWithTechnologyGroup, true); } updateButtonState(showTechnologiesWithProduct, true); return; } updateButtonState(showTechnologiesWithTechnologyGroup, false); updateButtonState(showTechnologiesWithProduct, false); } void updateRibbonState(final ViewDefinitionState view); }
@Test @Ignore public void shouldntUpdateRibbonStateIfProductIsntSaved() { given(product.getId()).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(false); verify(showTechnologiesWithProduct).setEnabled(false); } @Test @Ignore public void shouldUpdateRibbonStateIfProductIsSavedAndTechnologyGroupIsNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(false); verify(showTechnologiesWithProduct).setEnabled(true); } @Ignore @Test public void shouldUpdateRibbonStateIfProductIsSavedAndTechnologyGroupIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(true); verify(showTechnologiesWithProduct).setEnabled(true); }
TechnologyGroupDetailsViewHooks { public void addTechnologyGroupToProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent technologyGroupForm = (FormComponent) view.getComponentByReference("form"); Entity technologyGroup = technologyGroupForm.getEntity(); if (technologyGroup.getId() == null) { return; } FormComponent productForm = (FormComponent) view.getComponentByReference("product"); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } product = getProductFromDB(product.getId()); product.setField("technologyGroup", technologyGroup); product.getDataDefinition().save(product); } void addTechnologyGroupToProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldntAddTechnologyGroupToProductIfTechnologyGroupIsntSaved() { given(technologyGroup.getId()).willReturn(null); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product, never()).setField("technologyGroup", technologyGroup); verify(productDD, never()).save(product); } @Test public void shouldntAddTechnologyGroupToProductIfTechnologyGroupIsSavedAndProductIsNull() { given(technologyGroup.getId()).willReturn(L_ID); given(product.getId()).willReturn(null); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product, never()).setField("technologyGroup", technologyGroup); verify(productDD, never()).save(product); } @Test public void shouldAddTechnologyGroupToProductIfTechnologyGroupIsSavedAndProductIsntNull() { given(technologyGroup.getId()).willReturn(L_ID); given(product.getId()).willReturn(L_ID); given(product.getDataDefinition()).willReturn(productDD); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(productDD.get(L_ID)).willReturn(product); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product).setField("technologyGroup", technologyGroup); verify(productDD).save(product); }
TechnologyTreeValidators { public boolean checkConsumingTheSameProductFromManySubOperations(final DataDefinition technologyDD, final Entity technology, final boolean autoCloseMessage) { Entity techFromDB = technologyDD.get(technology.getId()); EntityTree tree = techFromDB.getTreeField(TechnologyFields.OPERATION_COMPONENTS); Map<String, Set<Entity>> nodesMap = technologyTreeValidationService .checkConsumingTheSameProductFromManySubOperations(tree); for (Entry<String, Set<Entity>> entry : nodesMap.entrySet()) { String parentNodeNumber = entry.getKey(); for (Entity product : entry.getValue()) { String productName = product.getStringField(ProductFields.NAME); String productNumber = product.getStringField(ProductFields.NUMBER); technology.addGlobalError( "technologies.technology.validate.global.error.subOperationsProduceTheSameProductThatIsConsumed", autoCloseMessage, parentNodeNumber, productName, productNumber); } } return nodesMap.isEmpty(); } boolean invalidateIfWrongFormula(final DataDefinition dataDefinition, final Entity entity); boolean checkConsumingTheSameProductFromManySubOperations(final DataDefinition technologyDD, final Entity technology, final boolean autoCloseMessage); boolean invalidateIfBelongsToAcceptedTechnology(final DataDefinition dataDefinition, final Entity entity); }
@Test public void shouldAddMessagesCorrectly() { String messageKey = "technologies.technology.validate.global.error.subOperationsProduceTheSameProductThatIsConsumed"; String parentNode = "1."; String productName = "name"; String productNumber = "abc123"; Long techId = 1L; given(technology.getStringField("state")).willReturn("02accepted"); given(technology.getId()).willReturn(techId); given(techDataDefinition.get(techId)).willReturn(technology); given(technology.getTreeField("operationComponents")).willReturn(tree); given(product.getStringField("name")).willReturn(productName); given(product.getStringField("number")).willReturn(productNumber); Map<String, Set<Entity>> nodesMap = Maps.newHashMap(); Set<Entity> productSet = Sets.newHashSet(); productSet.add(product); nodesMap.put("1.", productSet); given(technologyTreeValidationService.checkConsumingTheSameProductFromManySubOperations(tree)).willReturn(nodesMap); technologyTreeValidators.checkConsumingTheSameProductFromManySubOperations(techDataDefinition, technology, true); Mockito.verify(technology).addGlobalError(messageKey, true, parentNode, productName, productNumber); }
TechnologyTreeValidators { public boolean invalidateIfBelongsToAcceptedTechnology(final DataDefinition dataDefinition, final Entity entity) { Entity technology = null; String errorMessageKey = "technologies.technology.state.error.modifyBelongsToAcceptedTechnology"; if (TechnologiesConstants.MODEL_TECHNOLOGY.equals(dataDefinition.getName())) { technology = entity; errorMessageKey = "technologies.technology.state.error.modifyAcceptedTechnology"; } else if (TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT.equals(dataDefinition.getName())) { technology = entity.getBelongsToField(TechnologyOperationComponentFields.TECHNOLOGY); } else if (TechnologiesConstants.MODEL_OPERATION_PRODUCT_IN_COMPONENT.equals(dataDefinition.getName()) || TechnologiesConstants.MODEL_OPERATION_PRODUCT_OUT_COMPONENT.equals(dataDefinition.getName())) { final Entity operationComponent = entity.getBelongsToField(L_OPERATION_COMPONENT); if (operationComponent == null) { return true; } technology = operationComponent.getBelongsToField(TechnologyOperationComponentFields.TECHNOLOGY); } if (technologyIsAcceptedAndNotDeactivated(dataDefinition, entity, technology)) { entity.addGlobalError(errorMessageKey, technology.getStringField(TechnologyFields.NAME)); return false; } return true; } boolean invalidateIfWrongFormula(final DataDefinition dataDefinition, final Entity entity); boolean checkConsumingTheSameProductFromManySubOperations(final DataDefinition technologyDD, final Entity technology, final boolean autoCloseMessage); boolean invalidateIfBelongsToAcceptedTechnology(final DataDefinition dataDefinition, final Entity entity); }
@Test public final void shouldInvalidateAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertFalse(isValid); } @Test public final void shouldInvalidateAlreadyAcceptedInactiveTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(technology.isActive()).willReturn(false); given(existingTechnology.isActive()).willReturn(false); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertFalse(isValid); } @Test public final void shouldInvalidateAlreadyAcceptedActiveTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(technology.isActive()).willReturn(true); given(existingTechnology.isActive()).willReturn(true); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertFalse(isValid); } @Test public final void shouldValidateAcceptedTechnologyDuringEntityActivation() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(technology.isActive()).willReturn(true); given(existingTechnology.isActive()).willReturn(false); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateAcceptedTechnologyDuringEntityDeactivation() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(technology.isActive()).willReturn(false); given(existingTechnology.isActive()).willReturn(true); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateJustCreatedTechnology() { given(technology.getId()).willReturn(null); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateTechnologyDuringAccepting() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateTechnologyDuringWithdrawing() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.OUTDATED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateTechnologyDraft() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateTechnologyIfNotChanged() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(technology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(techDataDefinition, technology); assertTrue(isValid); } @Test public final void shouldValidateTocBelongingToDraftTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(tocDataDefinition, toc); assertTrue(isValid); } @Test public final void shouldValidateUnchangedTocBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(toc.getId()).willReturn(202L); given(tocDataDefinition.get(202L)).willReturn(toc); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(tocDataDefinition, toc); assertTrue(isValid); } @Test public final void shouldInvalidateChangedTocBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(toc.getId()).willReturn(202L); final Entity existingToc = mock(Entity.class); given(tocDataDefinition.get(202L)).willReturn(existingToc); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(tocDataDefinition, toc); assertFalse(isValid); } @Test public final void shouldValidateOpicBelongingToDraftTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opicDataDefinition, opic); assertTrue(isValid); } @Test public final void shouldValidateOpocBelongingToDraftTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.DRAFT.getStringValue()); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opocDataDefinition, opoc); assertTrue(isValid); } @Test public final void shouldValidateUnchangedOpicBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(opic.getId()).willReturn(303L); given(opicDataDefinition.get(303L)).willReturn(opic); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opicDataDefinition, opic); assertTrue(isValid); } @Test public final void shouldValidateUnchangedOpocBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(opoc.getId()).willReturn(404L); given(opocDataDefinition.get(404L)).willReturn(opoc); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opocDataDefinition, opoc); assertTrue(isValid); } @Test public final void shouldInvalidateChangedOpicBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(opic.getId()).willReturn(505L); final Entity existingOpic = mock(Entity.class); given(opicDataDefinition.get(505L)).willReturn(existingOpic); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opicDataDefinition, opic); assertFalse(isValid); } @Test public final void shouldInvalidateChangedOpocBelongingToAlreadyAcceptedTechnology() { given(technology.getId()).willReturn(101L); given(techDataDefinition.get(101L)).willReturn(existingTechnology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(existingTechnology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyState.ACCEPTED.getStringValue()); given(opoc.getId()).willReturn(606L); final Entity existingOpoc = mock(Entity.class); given(opocDataDefinition.get(606L)).willReturn(existingOpoc); final boolean isValid = technologyTreeValidators.invalidateIfBelongsToAcceptedTechnology(opocDataDefinition, opoc); assertFalse(isValid); }
CostNormsForOperationService { public void fillCurrencyFields(final ViewDefinitionState view) { String currencyStringCode = currencyService.getCurrencyAlphabeticCode(); FieldComponent component = null; for (String componentReference : Sets.newHashSet("pieceworkCostCURRENCY", "laborHourlyCostCURRENCY", "machineHourlyCostCURRENCY")) { component = (FieldComponent) view.getComponentByReference(componentReference); if (component == null) { continue; } component.setFieldValue(currencyStringCode); component.requestComponentUpdateState(); } } void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState, final String[] args); void inheritOperationNormValues(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void fillCurrencyFields(final ViewDefinitionState view); void copyCostNormsToTechnologyOperationComponent(final DataDefinition dd, final Entity technologyOperationComponent); }
@Test public void shouldFillCurrencyFields() throws Exception { String currency = "PLN"; when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); when(view.getComponentByReference("pieceworkCostCURRENCY")).thenReturn(field1); when(view.getComponentByReference("laborHourlyCostCURRENCY")).thenReturn(field2); when(view.getComponentByReference("machineHourlyCostCURRENCY")).thenReturn(field3); costNormsForOperationService.fillCurrencyFields(view); Mockito.verify(field1).setFieldValue(currency); Mockito.verify(field2).setFieldValue(currency); Mockito.verify(field3).setFieldValue(currency); }
StockCorrectionModelValidators { public boolean validateStockCorrection(final DataDefinition stockCorrectionDD, final Entity stockCorrection) { Entity location = stockCorrection.getBelongsToField(LOCATION); if (location != null) { String locationType = location.getStringField(TYPE); if (!CONTROL_POINT.getStringValue().equals(locationType)) { stockCorrection.addError(stockCorrectionDD.getField(LOCATION), "materialFlow.validate.global.error.locationIsNotSimpleControlPoint"); return false; } } return true; } boolean validateStockCorrection(final DataDefinition stockCorrectionDD, final Entity stockCorrection); boolean checkIfLocationHasExternalNumber(final DataDefinition stockCorrectionDD, final Entity stockCorrection); }
@Test public void shouldReturnFalseAndAddErrorWhenValidateStockCorrectionIfLocationIsntNullAndLocationTypeIsntControlPoint() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(location); given(location.getStringField(TYPE)).willReturn("otherLocation"); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertFalse(result); verify(stockCorrection).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } @Test public void shouldReturnTrueWhenValidateStockCorrectionIfLocationIsntNullAndLocationTypeIsControlPoint() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(location); given(location.getStringField(TYPE)).willReturn(CONTROL_POINT.getStringValue()); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertTrue(result); verify(stockCorrection, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } @Test public void shouldReturnTrueWhenValidateStockCorrectionIfLocationIsNull() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(null); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertTrue(result); verify(stockCorrection, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
ProductQuantitiesServiceImpl implements ProductQuantitiesService { @Override public ProductQuantitiesHolder getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity) { Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); OperationProductComponentWithQuantityContainer productQuantities = getProductComponentQuantities(technology, givenQuantity, operationRuns); return new ProductQuantitiesHolder(productQuantities, operationRuns); } @Override ProductQuantitiesHolder getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity technology, final BigDecimal givenQuantity, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity order, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final Map<Long, BigDecimal> operationRuns); @Override Map<Long, BigDecimal> getNeededProductQuantitiesForComponents(final List<Entity> components, final MrpAlgorithm mrpAlgorithm); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantitiesForTechnology(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override OperationProductComponentWithQuantityContainer groupOperationProductComponentWithQuantities( final Map<Long, OperationProductComponentWithQuantityContainer> operationProductComponentWithQuantityContainerForOrders); @Override void preloadProductQuantitiesAndOperationRuns(final EntityTree operationComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Map<Long, BigDecimal> operationRuns); @Override void preloadOperationProductComponentQuantity(final List<Entity> operationProductComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, Map<Long, Entity> entitiesById, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantities(final List<Entity> orders, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override Map<Long, BigDecimal> getProductWithQuantities( final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName); @Override void addProductQuantitiesToList(final Entry<OperationProductComponentHolder, BigDecimal> productComponentWithQuantity, final Map<Long, BigDecimal> productWithQuantities); @Override Entity getOutputProductsFromOperationComponent(final Entity operationComponent); @Override Entity getTechnologyOperationComponent(final Long technologyOperationComponentId); @Override Entity getProduct(final Long productId); @Override Map<Entity, BigDecimal> convertOperationsRunsFromProductQuantities( final Map<Long, BigDecimal> operationRunsFromProductionQuantities); }
@Test(expected = IllegalStateException.class) public void shouldReturnIllegalStateExceptionIfTheresNoTechnology() { when(order.getBelongsToField("technology")).thenReturn(null); productQuantitiesService.getProductComponentQuantities(order); } @Test public void shouldReturnCorrectQuantities() { OperationProductComponentWithQuantityContainer productQuantities = productQuantitiesService .getProductComponentQuantities(order); assertEquals(new BigDecimal(50), productQuantities.get(productInComponent1)); assertEquals(new BigDecimal(10), productQuantities.get(productInComponent2)); assertEquals(new BigDecimal(5), productQuantities.get(productInComponent3)); assertEquals(new BigDecimal(10), productQuantities.get(productOutComponent2)); assertEquals(new BigDecimal(5), productQuantities.get(productOutComponent4)); } @Test public void shouldReturnOperationRunsAlsoForComponents() { Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getProductComponentQuantities(order, operationRuns); assertEquals(2, operationRuns.size()); assertEquals(new BigDecimal(5), operationRuns.get(operationComponent2.getId())); assertEquals(new BigDecimal(10), operationRuns.get(operationComponent1.getId())); } @Test public void shouldReturnOperationRunsAlsoForPlainTechnology() { Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getProductComponentQuantities(technology, plannedQty, operationRuns); assertEquals(2, operationRuns.size()); assertEquals(new BigDecimal(5), operationRuns.get(operationComponent2.getId())); assertEquals(new BigDecimal(10), operationRuns.get(operationComponent1.getId())); } @Test public void shouldTraverseAlsoThroughReferencedTechnologies() { Entity refTech = mock(Entity.class); Entity someOpComp = mock(Entity.class); EntityList child = mockEntityListIterator(asList(someOpComp)); when(operationComponent2.getHasManyField("children")).thenReturn(child); when(someOpComp.getStringField("entityType")).thenReturn("referenceTechnology"); when(someOpComp.getBelongsToField("referenceTechnology")).thenReturn(refTech); EntityTree refTree = mockEntityTreeIterator(asList((Entity) operationComponent1)); when(refTree.getRoot()).thenReturn(operationComponent1); when(refTech.getTreeField("operationComponents")).thenReturn(refTree); OperationProductComponentWithQuantityContainer productQuantities = productQuantitiesService .getProductComponentQuantities(order); assertEquals(new BigDecimal(50), productQuantities.get(productInComponent1)); assertEquals(new BigDecimal(10), productQuantities.get(productInComponent2)); assertEquals(new BigDecimal(5), productQuantities.get(productInComponent3)); assertEquals(new BigDecimal(10), productQuantities.get(productOutComponent2)); assertEquals(new BigDecimal(5), productQuantities.get(productOutComponent4)); } @Test public void shouldNotRoundToTheIntegerOperationRunsIfOperationComponentHasDivisableProductQuantities() { when(operationComponent1.getBooleanField("areProductQuantitiesDivisible")).thenReturn(true); when(operationComponent2.getBooleanField("areProductQuantitiesDivisible")).thenReturn(true); OperationProductComponentWithQuantityContainer productQuantities = productQuantitiesService .getProductComponentQuantities(order); assertEquals(0, new BigDecimal(45).compareTo(productQuantities.get(productInComponent1))); assertEquals(0, new BigDecimal(9).compareTo(productQuantities.get(productInComponent2))); assertEquals(0, new BigDecimal(4.5).compareTo(productQuantities.get(productInComponent3))); assertEquals(0, new BigDecimal(9).compareTo(productQuantities.get(productOutComponent2))); assertEquals(0, new BigDecimal(4.5).compareTo(productQuantities.get(productOutComponent4))); }
ProductQuantitiesServiceImpl implements ProductQuantitiesService { @Override public Map<Long, BigDecimal> getNeededProductQuantities(final Entity technology, final BigDecimal givenQuantity, final MrpAlgorithm mrpAlgorithm) { Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); Set<OperationProductComponentHolder> nonComponents = Sets.newHashSet(); OperationProductComponentWithQuantityContainer productComponentWithQuantities = getProductComponentWithQuantitiesForTechnology( technology, givenQuantity, operationRuns, nonComponents); return getProductWithQuantities(productComponentWithQuantities, nonComponents, mrpAlgorithm, TechnologiesConstants.MODEL_OPERATION_PRODUCT_IN_COMPONENT); } @Override ProductQuantitiesHolder getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity technology, final BigDecimal givenQuantity, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity order, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final Map<Long, BigDecimal> operationRuns); @Override Map<Long, BigDecimal> getNeededProductQuantitiesForComponents(final List<Entity> components, final MrpAlgorithm mrpAlgorithm); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantitiesForTechnology(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override OperationProductComponentWithQuantityContainer groupOperationProductComponentWithQuantities( final Map<Long, OperationProductComponentWithQuantityContainer> operationProductComponentWithQuantityContainerForOrders); @Override void preloadProductQuantitiesAndOperationRuns(final EntityTree operationComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Map<Long, BigDecimal> operationRuns); @Override void preloadOperationProductComponentQuantity(final List<Entity> operationProductComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, Map<Long, Entity> entitiesById, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantities(final List<Entity> orders, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override Map<Long, BigDecimal> getProductWithQuantities( final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName); @Override void addProductQuantitiesToList(final Entry<OperationProductComponentHolder, BigDecimal> productComponentWithQuantity, final Map<Long, BigDecimal> productWithQuantities); @Override Entity getOutputProductsFromOperationComponent(final Entity operationComponent); @Override Entity getTechnologyOperationComponent(final Long technologyOperationComponentId); @Override Entity getProduct(final Long productId); @Override Map<Entity, BigDecimal> convertOperationsRunsFromProductQuantities( final Map<Long, BigDecimal> operationRunsFromProductionQuantities); }
@Test @Ignore public void shouldReturnCorrectQuantitiesOfInputProductsForTechnology() { Map<Long, BigDecimal> productQuantities = productQuantitiesService.getNeededProductQuantities(technology, plannedQty, MrpAlgorithm.ALL_PRODUCTS_IN); assertEquals(3, productQuantities.size()); assertEquals(new BigDecimal(50), productQuantities.get(product1.getId())); assertEquals(new BigDecimal(10), productQuantities.get(product2.getId())); assertEquals(new BigDecimal(5), productQuantities.get(product3.getId())); } @Test public void shouldReturnQuantitiesOfInputProductsForOrdersAndIfToldCountOnlyComponents() { Map<Long, BigDecimal> productQuantities = productQuantitiesService.getNeededProductQuantities(order, MrpAlgorithm.ONLY_COMPONENTS); assertEquals(2, productQuantities.size()); assertEquals(new BigDecimal(50), productQuantities.get(product1.getId())); assertEquals(new BigDecimal(5), productQuantities.get(product3.getId())); } @Test public void shouldReturnOperationRuns() { Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getNeededProductQuantities(orders, MrpAlgorithm.ALL_PRODUCTS_IN, operationRuns); assertEquals(2, operationRuns.size()); assertEquals(new BigDecimal(5), operationRuns.get(operationComponent2.getId())); assertEquals(new BigDecimal(10), operationRuns.get(operationComponent1.getId())); } @Test public void shouldNotRoundOperationRunsIfTjIsDivisable() { when(operationComponent1.getBooleanField("areProductQuantitiesDivisible")).thenReturn(true); when(operationComponent2.getBooleanField("areProductQuantitiesDivisible")).thenReturn(true); when(operationComponent1.getBooleanField("isTjDivisible")).thenReturn(true); when(operationComponent2.getBooleanField("isTjDivisible")).thenReturn(true); Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getNeededProductQuantities(orders, MrpAlgorithm.ALL_PRODUCTS_IN, operationRuns); assertEquals(2, operationRuns.size()); assertEquals(0, new BigDecimal(4.5).compareTo(operationRuns.get(operationComponent2))); assertEquals(0, new BigDecimal(9.0).compareTo(operationRuns.get(operationComponent1))); }
ProductQuantitiesServiceImpl implements ProductQuantitiesService { @Override public Map<Long, BigDecimal> getNeededProductQuantitiesForComponents(final List<Entity> components, final MrpAlgorithm mrpAlgorithm) { return getNeededProductQuantitiesForComponents(components, mrpAlgorithm, false); } @Override ProductQuantitiesHolder getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantities(final Entity order, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders); @Override OperationProductComponentWithQuantityContainer getProductComponentQuantitiesWithoutNonComponents( final List<Entity> orders, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity technology, final BigDecimal givenQuantity, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final Entity order, final MrpAlgorithm mrpAlgorithm); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final boolean onTheFly); @Override Map<Long, BigDecimal> getNeededProductQuantities(final List<Entity> orders, final MrpAlgorithm mrpAlgorithm, final Map<Long, BigDecimal> operationRuns); @Override Map<Long, BigDecimal> getNeededProductQuantitiesForComponents(final List<Entity> components, final MrpAlgorithm mrpAlgorithm); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantitiesForTechnology(final Entity technology, final BigDecimal givenQuantity, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override OperationProductComponentWithQuantityContainer groupOperationProductComponentWithQuantities( final Map<Long, OperationProductComponentWithQuantityContainer> operationProductComponentWithQuantityContainerForOrders); @Override void preloadProductQuantitiesAndOperationRuns(final EntityTree operationComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Map<Long, BigDecimal> operationRuns); @Override void preloadOperationProductComponentQuantity(final List<Entity> operationProductComponents, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override void traverseProductQuantitiesAndOperationRuns(final Entity technology, Map<Long, Entity> entitiesById, final BigDecimal givenQuantity, final Entity operationComponent, final Entity previousOperationComponent, final OperationProductComponentWithQuantityContainer operationProductComponentWithQuantityContainer, final Set<OperationProductComponentHolder> nonComponents, final Map<Long, BigDecimal> operationRuns); @Override OperationProductComponentWithQuantityContainer getProductComponentWithQuantities(final List<Entity> orders, final Map<Long, BigDecimal> operationRuns, final Set<OperationProductComponentHolder> nonComponents); @Override Map<Long, BigDecimal> getProductWithQuantities( final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName); @Override void addProductQuantitiesToList(final Entry<OperationProductComponentHolder, BigDecimal> productComponentWithQuantity, final Map<Long, BigDecimal> productWithQuantities); @Override Entity getOutputProductsFromOperationComponent(final Entity operationComponent); @Override Entity getTechnologyOperationComponent(final Long technologyOperationComponentId); @Override Entity getProduct(final Long productId); @Override Map<Entity, BigDecimal> convertOperationsRunsFromProductQuantities( final Map<Long, BigDecimal> operationRunsFromProductionQuantities); }
@Test public void shouldReturnQuantitiesAlsoForListOfComponents() { Entity component = mock(Entity.class); when(component.getBelongsToField("order")).thenReturn(order); Map<Long, BigDecimal> productQuantities = productQuantitiesService.getNeededProductQuantitiesForComponents( Arrays.asList(component), MrpAlgorithm.ALL_PRODUCTS_IN); assertEquals(3, productQuantities.size()); assertEquals(new BigDecimal(50), productQuantities.get(product1.getId())); assertEquals(new BigDecimal(10), productQuantities.get(product2.getId())); assertEquals(new BigDecimal(5), productQuantities.get(product3.getId())); }
ProductionLinesServiceImpl implements ProductionLinesService { @Override public Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine) { List<Entity> workstationTypeComponents = productionLine.getHasManyField(ProductionLineFields.WORKSTATION_TYPE_COMPONENTS); Entity desiredWorkstation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION) .getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation != null) { for (Entity workstationTypeComponent : workstationTypeComponents) { Entity workstation = workstationTypeComponent.getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation.getId().equals(workstation.getId())) { return (Integer) workstationTypeComponent.getField(WorkstationTypeComponentFields.QUANTITY); } } } return productionLine.getIntegerField(ProductionLineFields.QUANTITY_FOR_OTHER_WORKSTATION_TYPES); } @Override Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine); @Override Integer getWorkstationTypesCount(final Long productionLineId, final String workstationTypeNumber); }
@Test public void shouldReturnCorrectWorkstationCount() { given(operation.getBelongsToField("workstationType")).willReturn(work2); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(234), workstationCount); } @Test public void shouldReturnSpecifiedQuantityIfNoWorkstationIsFound() { given(productionLine.getIntegerField("quantityForOtherWorkstationTypes")).willReturn(456); given(operation.getBelongsToField("workstationType")).willReturn(work3); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(456), workstationCount); }
TechnologyDataProviderImpl implements TechnologyDataProvider { public Optional<Entity> tryFind(final Long id) { return Optional.ofNullable(id).map(i -> getDataDefinition().get(i)); } Optional<Entity> tryFind(final Long id); }
@Test public final void shouldReturnTechnology() { Entity technologyFromDb = mockEntity(); stubDataDefGetResult(technologyFromDb); Optional<Entity> res = technologyDataProvider.tryFind(1L); Assert.assertEquals(Optional.of(technologyFromDb), res); } @Test public final void shouldReturnEmptyIfIdIsMissing() { Optional<Entity> res = technologyDataProvider.tryFind(null); Assert.assertEquals(Optional.<Entity> empty(), res); } @Test public final void shouldReturnEmptyIfEntityCannotBeFound() { stubDataDefGetResult(null); Optional<Entity> res = technologyDataProvider.tryFind(1L); Assert.assertEquals(Optional.<Entity> empty(), res); }
TechnologyNameAndNumberGenerator { public String generateNumber(final Entity product) { String numberPrefix = product.getField(ProductFields.NUMBER) + "-"; return numberGeneratorService.generateNumberWithPrefix(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY, 3, numberPrefix); } String generateNumber(final Entity product); String generateName(final Entity product); }
@Test public final void shouldGenerateNumber() { Entity product = mockEntity(); stubStringField(product, ProductFields.NUMBER, "SomeProductNumber"); technologyNameAndNumberGenerator.generateNumber(product); verify(numberGeneratorService).generateNumberWithPrefix(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY, 3, "SomeProductNumber-"); }
TechnologyNameAndNumberGenerator { public String generateName(final Entity product) { LocalDate date = LocalDate.now(); String currentDateString = String.format("%s.%s", date.getYear(), date.getMonthValue()); String productName = product.getStringField(ProductFields.NAME); String productNumber = product.getStringField(ProductFields.NUMBER); return translationService.translate("technologies.operation.name.default", LocaleContextHolder.getLocale(), productName, productNumber, currentDateString); } String generateNumber(final Entity product); String generateName(final Entity product); }
@Test public final void shouldGenerateName() { String productNumber = "SomeProductNumber"; String productName = "Some product name"; Entity product = mockEntity(); stubStringField(product, ProductFields.NUMBER, productNumber); stubStringField(product, ProductFields.NAME, productName); technologyNameAndNumberGenerator.generateName(product); LocalDate date = LocalDate.now(); String expectedThirdArgument = String.format("%s.%s", date.getYear(), date.getMonthValue()); verify(translationService).translate("technologies.operation.name.default", LocaleContextHolder.getLocale(), productName, productNumber, expectedThirdArgument); }
OperationProductComponentImpl implements InternalOperationProductComponent { @Override public void setField(final String name, final Object value) { entity.setField(name, value); } OperationProductComponentImpl(final OperationCompType operationType, final DataDefinition opcDataDef); @Override void setField(final String name, final Object value); @Override Entity getWrappedEntity(); @Override void setProduct(final Entity product); @Override void setQuantity(final BigDecimal quantity); @Override void setPriority(final int priority); }
@Test public final void shouldThrowExceptionWhenTryToAddProductWithIncorrectTypeToOutputProductComponent() { performWrongTypeProductTest(buildOpoc()); verify(wrappedEntity, Mockito.never()).setField(OperationProductInComponentFields.PRODUCT, product); } @Test public final void shouldThrowExceptionWhenTryToAddProductWithIncorrectTypeToInputProductComponent() { performWrongTypeProductTest(buildOpic()); verify(wrappedEntity, Mockito.never()).setField(OperationProductOutComponentFields.PRODUCT, product); } @Test public final void shouldNotThrowExceptionWhenAddingProductWithCorrectTypeToOutputProductComponent() { performCorrectTypeProductTest(buildOpoc()); verify(wrappedEntity).setField(OperationProductOutComponentFields.PRODUCT, product); } @Test public final void shouldNotThrowExceptionWhenAddingProductWithCorrectTypeToInputProductComponent() { performCorrectTypeProductTest(buildOpic()); verify(wrappedEntity).setField(OperationProductInComponentFields.PRODUCT, product); }
TechnologyTreeBuildServiceImpl implements TechnologyTreeBuildService { @Override public <T, P> EntityTree build(final T from, final TechnologyTreeAdapter<T, P> transformer) { TechnologyTreeBuilder<T, P> builder = new TechnologyTreeBuilder<T, P>(componentsFactory, transformer); Entity root = builder.build(from, numberService); return EntityTreeUtilsService.getDetachedEntityTree(Lists.newArrayList(root)); } @Override EntityTree build(final T from, final TechnologyTreeAdapter<T, P> transformer); }
@Test public final void shouldBuildTree() { TocHolder customTreeRoot = mockCustomTreeRepresentation(); EntityTree tree = treeBuildService.build(customTreeRoot, new TestTreeAdapter()); EntityTreeNode root = tree.getRoot(); assertNotNull(root); Entity toc1 = extractEntity(root); verify(toc1).setField(TechnologyOperationComponentFields.ENTITY_TYPE, TechnologyOperationComponentType.OPERATION.getStringValue()); verify(toc1).setField(TechnologyOperationComponentFields.OPERATION, toc1op); verify(toc1).setField(Mockito.eq(TechnologyOperationComponentFields.OPERATION_PRODUCT_IN_COMPONENTS), toc1opicCaptor.capture()); Collection<Entity> toc1opics = toc1opicCaptor.getValue(); assertEquals(1, toc1opics.size()); Entity toc1opic = toc1opics.iterator().next(); verify(toc1opic).setField(OperationProductInComponentFields.QUANTITY, BigDecimal.ONE); verify(toc1opic).setField(OperationProductInComponentFields.PRODUCT, toc1opic1prod); verify(toc1).setField(Mockito.eq(TechnologyOperationComponentFields.OPERATION_PRODUCT_OUT_COMPONENTS), toc1opocCaptor.capture()); Collection<Entity> toc1opocs = toc1opocCaptor.getValue(); assertEquals(1, toc1opocs.size()); Entity toc1opoc = toc1opocs.iterator().next(); verify(toc1opoc).setField(OperationProductInComponentFields.QUANTITY, BigDecimal.ONE); verify(toc1opoc).setField(OperationProductInComponentFields.PRODUCT, toc1opoc1prod); verify(toc1).setField(Mockito.eq(TechnologyOperationComponentFields.CHILDREN), toc1childrenCaptor.capture()); Collection<Entity> toc1children = toc1childrenCaptor.getValue(); assertEquals(1, toc1children.size()); Entity toc2 = toc1children.iterator().next(); verify(toc2).setField(TechnologyOperationComponentFields.ENTITY_TYPE, TechnologyOperationComponentType.OPERATION.getStringValue()); verify(toc2).setField(TechnologyOperationComponentFields.OPERATION, toc2op); verify(toc2).setField(Mockito.eq(TechnologyOperationComponentFields.OPERATION_PRODUCT_IN_COMPONENTS), toc2opicCaptor.capture()); Collection<Entity> toc2opics = toc2opicCaptor.getValue(); assertEquals(1, toc2opics.size()); Entity toc2opic = toc2opics.iterator().next(); verify(toc2opic).setField(OperationProductInComponentFields.QUANTITY, BigDecimal.ONE); verify(toc2opic).setField(OperationProductInComponentFields.PRODUCT, toc2opic1prod); verify(toc2).setField(Mockito.eq(TechnologyOperationComponentFields.OPERATION_PRODUCT_OUT_COMPONENTS), toc2opocCaptor.capture()); Collection<Entity> toc2opocs = toc2opocCaptor.getValue(); assertEquals(1, toc2opocs.size()); Entity toc2opoc = toc2opocs.iterator().next(); verify(toc2opoc).setField(OperationProductInComponentFields.QUANTITY, BigDecimal.ONE); verify(toc2opoc).setField(OperationProductInComponentFields.PRODUCT, toc2opoc1prod); verify(toc2).setField(Mockito.eq(TechnologyOperationComponentFields.CHILDREN), toc2childrenCaptor.capture()); Collection<Entity> toc2children = toc2childrenCaptor.getValue(); assertTrue(toc2children.isEmpty()); }
TechnologyTreeValidationServiceImpl implements TechnologyTreeValidationService { @Override public final Map<String, Set<String>> checkConsumingManyProductsFromOneSubOp(final EntityTree technologyTree) { final Map<String, Set<String>> parentToChildsMap = Maps.newHashMap(); if (technologyTree != null && !technologyTree.isEmpty()) { final EntityTreeNode rootNode = technologyTree.getRoot(); collectChildrenProducingManyParentInputs(parentToChildsMap, rootNode); } return parentToChildsMap; } @Override final Map<String, Set<String>> checkConsumingManyProductsFromOneSubOp(final EntityTree technologyTree); @Override Map<String, Set<Entity>> checkConsumingTheSameProductFromManySubOperations(final EntityTree technologyTree); }
@Test public final void shouldReturnEmptyMapForNullTree() { resultMap = technologyTreeValidationService.checkConsumingManyProductsFromOneSubOp(null); assertNotNull(resultMap); assertTrue(resultMap.isEmpty()); } @Test public final void shouldReturnEmptyMapForEmptyTree() { given(tree.isEmpty()).willReturn(true); resultMap = technologyTreeValidationService.checkConsumingManyProductsFromOneSubOp(tree); assertNotNull(resultMap); assertTrue(resultMap.isEmpty()); } @Test public final void shouldReturnNotEmptyMapIfParentOpConsumeManyOutputsFromOneSubOp() { Entity product1 = mockProductComponent(1L); Entity product2 = mockProductComponent(2L); Entity product3 = mockProductComponent(3L); Entity product4 = mockProductComponent(4L); Entity product5 = mockProductComponent(5L); Entity product6 = mockProductComponent(6L); EntityTreeNode node3 = mockOperationComponent("3.", newArrayList(product6), newArrayList(product3, product4, product5)); EntityTreeNode node2 = mockOperationComponent("2.", newArrayList(product3, product4), newArrayList(product2), newArrayList(node3)); EntityTreeNode node1 = mockOperationComponent("1.", newArrayList(product2), newArrayList(product1), newArrayList(node2)); given(tree.getRoot()).willReturn(node1); resultMap = technologyTreeValidationService.checkConsumingManyProductsFromOneSubOp(tree); assertNotNull(resultMap); assertFalse(resultMap.isEmpty()); assertEquals(1, resultMap.size()); hasNodeNumbersFor(node2, node3); } @Test public final void shouldReturnNotEmptyMapIfManyParentOpConsumesManyOutputsFromOneSubOp() { Entity product1 = mockProductComponent(1L); Entity product2 = mockProductComponent(2L); Entity product3 = mockProductComponent(3L); Entity product4 = mockProductComponent(4L); Entity product5 = mockProductComponent(5L); Entity product6 = mockProductComponent(6L); Entity product7 = mockProductComponent(7L); Entity product8 = mockProductComponent(8L); Entity product9 = mockProductComponent(9L); Entity product10 = mockProductComponent(10L); Entity product11 = mockProductComponent(11L); Entity product12 = mockProductComponent(12L); EntityTreeNode node1A3 = mockOperationComponent("1.A.3.", newArrayList(product11, product12), newArrayList(product10)); EntityTreeNode node1A2 = mockOperationComponent("1.A.2.", newArrayList(product10), newArrayList(product7, product8, product9), newArrayList(node1A3)); EntityTreeNode node1A1 = mockOperationComponent("1.A.1.", newArrayList(product7, product8, product9), newArrayList(product2, product3), newArrayList(node1A2)); EntityTreeNode node1B1 = mockOperationComponent("1.B.1.", newArrayList(product6), newArrayList(product4, product5)); EntityTreeNode node1 = mockOperationComponent("1.", newArrayList(product2, product3, product4, product5), newArrayList(product1), newArrayList(node1A1, node1B1)); given(tree.getRoot()).willReturn(node1); resultMap = technologyTreeValidationService.checkConsumingManyProductsFromOneSubOp(tree); assertNotNull(resultMap); assertFalse(resultMap.isEmpty()); assertEquals(2, resultMap.size()); assertEquals(2, resultMap.get(node1.getStringField(NODE_NUMBER)).size()); hasNodeNumbersFor(node1, node1A1); hasNodeNumbersFor(node1, node1B1); hasNodeNumbersFor(node1A1, node1A2); } @Test public final void shouldReturnEmptyMapIfParentOpNotConsumeManyOutputsFromOneSubOp() { Entity product1 = mockProductComponent(1L); Entity product2 = mockProductComponent(2L); Entity product3 = mockProductComponent(3L); Entity product4 = mockProductComponent(4L); Entity product5 = mockProductComponent(5L); Entity product6 = mockProductComponent(6L); EntityTreeNode node2B = mockOperationComponent("2.B.", newArrayList(product6), newArrayList(product4)); EntityTreeNode node2A = mockOperationComponent("2.A.", newArrayList(product5), newArrayList(product3)); EntityTreeNode node2 = mockOperationComponent("2.", newArrayList(product3, product4), newArrayList(product2), newArrayList(node2A, node2B)); EntityTreeNode node1 = mockOperationComponent("1.", newArrayList(product2), newArrayList(product1), newArrayList(node2)); given(tree.getRoot()).willReturn(node1); resultMap = technologyTreeValidationService.checkConsumingManyProductsFromOneSubOp(tree); assertNotNull(resultMap); assertTrue(resultMap.isEmpty()); }
TechnologyTreeValidationServiceImpl implements TechnologyTreeValidationService { @Override public Map<String, Set<Entity>> checkConsumingTheSameProductFromManySubOperations(final EntityTree technologyTree) { Map<String, Set<Entity>> parentToProductsMap = Maps.newHashMap(); if (technologyTree != null && !technologyTree.isEmpty()) { final EntityTreeNode rootNode = technologyTree.getRoot(); collectChildrenProducingTheSameParentInputs(parentToProductsMap, rootNode); } return parentToProductsMap; } @Override final Map<String, Set<String>> checkConsumingManyProductsFromOneSubOp(final EntityTree technologyTree); @Override Map<String, Set<Entity>> checkConsumingTheSameProductFromManySubOperations(final EntityTree technologyTree); }
@Test public final void shouldReturnNotEmptyMapIfSubOpsProduceTheSameOutputsWhichAreConsumed() { Entity product1 = mockProductComponent(1L); Entity product2 = mockProductComponent(2L); Entity product3 = mockProductComponent(3L); Entity product4 = mockProductComponent(4L); Entity product5 = mockProductComponent(5L); Entity product6 = mockProductComponent(6L); EntityTreeNode node3 = mockOperationComponent(3L, "3.", newArrayList(product5), newArrayList(product2, product3)); EntityTreeNode node2 = mockOperationComponent(2L, "2.", newArrayList(product6), newArrayList(product2, product4)); EntityTreeNode node1 = mockOperationComponent(1L, "1.", newArrayList(product2), newArrayList(product1), newArrayList(node2, node3)); given(tree.getRoot()).willReturn(node1); Map<String, Set<Entity>> returnedMap = technologyTreeValidationService .checkConsumingTheSameProductFromManySubOperations(tree); assertNotNull(returnedMap); assertFalse(returnedMap.isEmpty()); assertEquals(1, returnedMap.size()); assertTrue(returnedMap.containsKey("1.")); assertTrue(returnedMap.get("1.").contains(product2)); }
TransformationsModelValidators { public boolean checkIfTransfersAreValid(final DataDefinition transformationsDD, final Entity transformations) { List<Entity> transfersConsumption = transformations.getHasManyField(TRANSFERS_CONSUMPTION); List<Entity> transfersProduction = transformations.getHasManyField(TRANSFERS_PRODUCTION); Iterable<Boolean> validationResults = Lists.newArrayList(areTransfersValid(transfersConsumption), areTransfersValid(transfersProduction), checkIfTransfersNumbersAreDistinct(transfersConsumption, transfersProduction), checkIfTransfersNumbersAreDistinct(transfersProduction, transfersConsumption)); return Iterables.all(validationResults, Predicates.equalTo(true)); } boolean checkIfTransfersAreValid(final DataDefinition transformationsDD, final Entity transformations); boolean checkIfLocationFromOrLocationToHasExternalNumber(final DataDefinition transformationDD, final Entity transformation); }
@Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransfersArentNull() { Entity transferConsumption = mockTransfer(null, null, null); Entity transferProduction = mockTransfer(null, null, null); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption)); stubHasManyField(transformations, TRANSFERS_PRODUCTION, Lists.newArrayList(transferProduction)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); } @Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransferProductAlreadyAdded() { Entity transferConsumption1 = mockTransfer(L_NUMBER_CONSUMPTION_1, productConsumption, BigDecimal.ONE); Entity transferConsumption2 = mockTransfer(L_NUMBER_CONSUMPTION_2, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption1, transferConsumption2)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); } @Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransfersNumersArentDistinct() { Entity transferConsumption1 = mockTransfer(L_NUMBER_CONSUMPTION_1, productConsumption, BigDecimal.ONE); Entity transferConsumption2 = mockTransfer(L_NUMBER_CONSUMPTION_1, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption1, transferConsumption2)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); } @Test public void shouldReturnTrueWhenCheckIfTransfersAreValidAndTransfersArentNull() { Entity transferConsumption = mockTransfer(L_NUMBER_CONSUMPTION_1, productProduction, BigDecimal.ONE); Entity transferProduction = mockTransfer(L_NUMBER_PRODUCTION_1, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption)); stubHasManyField(transformations, TRANSFERS_PRODUCTION, Lists.newArrayList(transferProduction)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertTrue(result); } @Test public void shouldReturnTrueWhenCheckIfTransfersAreValidAndAllTransfersAreNull() { boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertTrue(result); }
TechnologyService { public BigDecimal getProductCountForOperationComponent(final Entity operationComponent) { return getMainOutputProductComponent(operationComponent).getDecimalField(L_QUANTITY); } void copyCommentAndAttachmentFromLowerInstance(final Entity technologyOperationComponent, final String belongsToName); boolean checkIfTechnologyStateIsOtherThanCheckedAndAccepted(final Entity technology); boolean isTechnologyUsedInActiveOrder(final Entity technology); void loadProductsForReferencedTechnology(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args); void generateTechnologyGroupNumber(final ViewDefinitionState viewDefinitionState); void generateTechnologyNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void generateTechnologyName(final ViewDefinitionState view, final ComponentState state, final String[] args); void setLookupDisableInTechnologyOperationComponent(final ViewDefinitionState viewDefinitionState); void toggleDetailsViewEnabled(final ViewDefinitionState view); String getProductType(final Entity product, final Entity technology); void addOperationsFromSubtechnologiesToList(final EntityTree entityTree, final List<Entity> technologyOperationComponents); boolean invalidateIfAllreadyInTheSameOperation(final DataDefinition operationProductComponentDD, final Entity operationProductComponent); Optional<Entity> tryGetMainOutputProductComponent(Entity technologyOperationComponent); Entity getMainOutputProductComponent(Entity technologyOperationComponent); BigDecimal getProductCountForOperationComponent(final Entity operationComponent); boolean isExternalSynchronized(final Long technologyId); boolean isIntermediateProduct(final Entity opic); boolean isFinalProduct(final Entity opoc); static final String L_01_COMPONENT; static final String L_02_INTERMEDIATE; static final String L_03_FINAL_PRODUCT; static final String L_04_WASTE; static final String L_00_UNRELATED; }
@Test public void shouldReturnOutputProductCountForOperationComponent() { BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); } @Test public void shouldThrowAnExceptionIfThereAreNoProductsOrIntermediates() { EntityList opComp2prodOuts = mockEntityIterator(asList(prodOutComp2)); when(opComp2.getHasManyField("operationProductOutComponents")).thenReturn(opComp2prodOuts); try { technologyService.getProductCountForOperationComponent(opComp2); fail(); } catch (IllegalStateException e) { } } @Test public void shouldReturnOutputProductCountForOperationComponentAlsoForTechnologyInstanceOperationComponent() { when(dataDefinition.getName()).thenReturn("technologyInstanceOperationComponent"); when(opComp2.getBelongsToField("technologyOperationComponent")).thenReturn(opComp2); when(opComp1.getBelongsToField("technologyOperationComponent")).thenReturn(opComp1); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); } @Test public void shouldReturnOutputProductCountForOperationComponentAlsoForReferenceTechnology() { when(opComp2.getStringField("entityType")).thenReturn("referenceTechnology"); Entity refTech = mock(Entity.class); when(opComp2.getBelongsToField("referenceTechnology")).thenReturn(refTech); EntityTree tree = mock(EntityTree.class); when(refTech.getTreeField("operationComponents")).thenReturn(tree); when(tree.getRoot()).thenReturn(opComp2); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); } @Test public void shouldReturnOutputProductCountForOperationComponentAlsoIfParentOperationIsNull() { when(opComp2.getBelongsToField("parent")).thenReturn(null); when(prodOutComp2.getBelongsToField("product")).thenReturn(product2); when(prodOutComp1.getBelongsToField("product")).thenReturn(product1); when(technology.getBelongsToField("product")).thenReturn(product2); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); }
OrderDetailsListenersPPS { public void redirectToProductionPerShift(final ViewDefinitionState view, final ComponentState state, final String[] args) { Long orderId = (Long) state.getFieldValue(); if (orderId == null) { return; } Long ppsId = ppsHelper.getPpsIdForOrder(orderId); if (ppsId == null) { ppsId = ppsHelper.createPpsForOrderAndReturnId(orderId); Preconditions.checkNotNull(ppsId); } redirect(view, ppsId); } void redirectToProductionPerShift(final ViewDefinitionState view, final ComponentState state, final String[] args); }
@Test public void shouldRedirectToProductionPerShiftView() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(expectedPpsId); orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); verifyRedirectToPpsDetails(expectedPpsId); } @Test public void shouldRedirectToJustCreatedProductionPerShiftView() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(null); given(ppsHelper.createPpsForOrderAndReturnId(givenOrderId)).willReturn(expectedPpsId); orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); verifyRedirectToPpsDetails(expectedPpsId); } @Test public void shouldThrowExceptionIfProductionPerShiftCanNotBeSaved() { Long givenOrderId = 1L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(null); given(ppsHelper.createPpsForOrderAndReturnId(givenOrderId)).willReturn(null); try { orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); Assert.fail(); } catch (NullPointerException ex) { } }
LineChangeoverNormsHooks { public boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm) { SearchCriteriaBuilder searchCriteriaBuilder = dataDefinitionService .get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS) .find() .add(SearchRestrictions.belongsTo(FROM_TECHNOLOGY, changeoverNorm.getBelongsToField(FROM_TECHNOLOGY))) .add(SearchRestrictions.belongsTo(TO_TECHNOLOGY, changeoverNorm.getBelongsToField(TO_TECHNOLOGY))) .add(SearchRestrictions.belongsTo(FROM_TECHNOLOGY_GROUP, changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP))) .add(SearchRestrictions.belongsTo(TO_TECHNOLOGY_GROUP, changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP))) .add(SearchRestrictions.belongsTo(PRODUCTION_LINE, changeoverNorm.getBelongsToField(PRODUCTION_LINE))); if (changeoverNorm.getId() != null) { searchCriteriaBuilder.add(SearchRestrictions.ne("id", changeoverNorm.getId())); } Entity existingChangeoverNorm = searchCriteriaBuilder.uniqueResult(); if (existingChangeoverNorm != null) { changeoverNorm.addGlobalError(L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_NOT_UNIQUE, existingChangeoverNorm.getStringField(NUMBER)); return false; } return true; } boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm); boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm); }
@Test public void shouldAddErrorForEntityWhenNotUnique() { Long id = 1L; String changeoverNumber = "0002"; given(changeoverNorm.getId()).willReturn(id); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY)).willReturn(fromTechnology); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY)).willReturn(toTechnology); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP)).willReturn(fromTechnologyGroup); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP)).willReturn(toTechnologyGroup); given(changeoverNorm.getBelongsToField(PRODUCTION_LINE)).willReturn(productionLine); given( dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS)).willReturn(changeoverNormDD); given(changeoverNormDD.find()).willReturn(searchCriteria); searchMatchingChangeroverNorms(fromTechnology, toTechnology, fromTechnologyGroup, toTechnologyGroup, productionLine); given(searchCriteria.uniqueResult()).willReturn(changeover); given(changeover.getStringField(NUMBER)).willReturn(changeoverNumber); hooks.checkUniqueNorms(changeoverNormDD, changeoverNorm); verify(changeoverNorm).addGlobalError("lineChangeoverNorms.lineChangeoverNorm.notUnique", changeoverNumber); }
ProductionPerShiftListeners { public void updateProgressForDays(final ViewDefinitionState view, final ComponentState state, final String[] args) { ProgressType progressType = detailsHooks.resolveProgressType(view); Entity order = getEntityFromLookup(view, ORDER_LOOKUP_REF).get(); Optional<OrderDates> maybeOrderDates = resolveOrderDates(order); if (!maybeOrderDates.isPresent()) { return; } int lastDay = -1; List<Shift> shifts = shiftsDataProvider.findAll(); LazyStream<OrderRealizationDay> realizationDaysStream = orderRealizationDaysResolver.asStreamFrom( progressType.extractStartDateTimeFrom(maybeOrderDates.get()), shifts); AwesomeDynamicListComponent progressForDaysADL = (AwesomeDynamicListComponent) view .getComponentByReference(PROGRESS_ADL_REF); for (FormComponent progressForDayForm : progressForDaysADL.getFormComponents()) { FieldComponent dayField = progressForDayForm.findFieldComponentByName(DAY_NUMBER_INPUT_REF); Integer dayNum = IntegerUtils.parse((String) dayField.getFieldValue()); if (dayNum == null) { final int maxDayNum = lastDay; if (realizationDaysStream != null) { realizationDaysStream = realizationDaysStream.dropWhile(new Predicate<OrderRealizationDay>() { @Override public boolean apply(final OrderRealizationDay input) { return input.getRealizationDayNumber() > maxDayNum; } }); OrderRealizationDay realizationDay = realizationDaysStream.head(); setUpProgressForDayRow(progressForDayForm, realizationDay); lastDay = realizationDay.getRealizationDayNumber(); } } else { lastDay = dayNum; } } } void generateProgressForDays(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void onTechnologyOperationChange(final ViewDefinitionState view, final ComponentState state, final String[] args); void savePlan(final ViewDefinitionState view, final ComponentState state, final String[] args); void refreshView(final ViewDefinitionState view, final ComponentState state, final String[] args); void changeView(final ViewDefinitionState view, final ComponentState state, final String[] args); void copyFromPlanned(final ViewDefinitionState view, final ComponentState state, final String[] args); void deleteProgressForDays(final ViewDefinitionState view, final ComponentState state, final String[] args); void updateProgressForDays(final ViewDefinitionState view, final ComponentState state, final String[] args); static final String L_FORM; }
@Test public final void shouldFillNewlyAddedRowsAccordingToPlannedDaysAndDates() { stubRealizationDaysStream(PLANNED_ORDER_START, Sets.newHashSet(0, 1, 2, 3, 4, 5, 8, 9, 10), shifts); stubRealizationDaysStream(CORRECTED_ORDER_START, Sets.newHashSet(1, 2, 3, 6, 7, 8, 9, 10), shifts); stubProgressType(ProgressType.PLANNED); FieldComponent day1 = mockFieldComponent("0"); FieldComponent date1 = mockFieldComponent(null); FormComponent row1 = mockFormComponent(day1, date1); AwesomeDynamicListComponent row1DailyProgresses = mockDailyProgressForShiftAdl(row1); FieldComponent day2 = mockFieldComponent("3"); FieldComponent date2 = mockFieldComponent(null); FormComponent row2 = mockFormComponent(day2, date2); AwesomeDynamicListComponent row2DailyProgresses = mockDailyProgressForShiftAdl(row2); FieldComponent day3 = mockFieldComponent(null); FieldComponent date3 = mockFieldComponent(null); FormComponent row3 = mockFormComponent(day3, date3); AwesomeDynamicListComponent row3DailyProgresses = mockDailyProgressForShiftAdl(row3); FieldComponent day4 = mockFieldComponent(null); FieldComponent date4 = mockFieldComponent(null); FormComponent row4 = mockFormComponent(day4, date4); AwesomeDynamicListComponent row4DailyProgresses = mockDailyProgressForShiftAdl(row4); stubProgressForDaysAdlRows(row1, row2, row3, row4); productionPerShiftListeners.updateProgressForDays(view, progressForDaysAdl, new String[] {}); verify(day1, never()).setFieldValue(any()); verify(date1, never()).setFieldValue(any()); verify(row1DailyProgresses, never()).setFieldValue(any()); verify(day2, never()).setFieldValue(any()); verify(date2, never()).setFieldValue(any()); verify(row2DailyProgresses, never()).setFieldValue(any()); verify(day3).setFieldValue(4); verify(date3).setFieldValue(DateUtils.toDateString(PLANNED_ORDER_START.plusDays(3).toLocalDate().toDate())); verify(row3DailyProgresses).setFieldValue(eq(Lists.newArrayList(firstShiftDailyProgress, secondShiftDailyProgress))); verify(day4).setFieldValue(5); verify(date4).setFieldValue(DateUtils.toDateString(PLANNED_ORDER_START.plusDays(4).toLocalDate().toDate())); verify(row4DailyProgresses).setFieldValue(eq(Lists.newArrayList(firstShiftDailyProgress, secondShiftDailyProgress))); } @Test public final void shouldFillNewlyAddedRowsAccordingToCorrectedDaysAndDates() { stubRealizationDaysStream(PLANNED_ORDER_START, Sets.newHashSet(1, 2, 3, 4, 5, 8, 9, 10), shifts); stubRealizationDaysStream(CORRECTED_ORDER_START, Sets.newHashSet(1, 2, 3, 6, 7, 8, 9, 10), shifts); stubProgressType(ProgressType.CORRECTED); FieldComponent day1 = mockFieldComponent("1"); FieldComponent date1 = mockFieldComponent(null); FormComponent row1 = mockFormComponent(day1, date1); AwesomeDynamicListComponent row1DailyProgresses = mockDailyProgressForShiftAdl(row1); FieldComponent day2 = mockFieldComponent("3"); FieldComponent date2 = mockFieldComponent(null); FormComponent row2 = mockFormComponent(day2, date2); AwesomeDynamicListComponent row2DailyProgresses = mockDailyProgressForShiftAdl(row2); FieldComponent day3 = mockFieldComponent(null); FieldComponent date3 = mockFieldComponent(null); FormComponent row3 = mockFormComponent(day3, date3); AwesomeDynamicListComponent row3DailyProgresses = mockDailyProgressForShiftAdl(row3); FieldComponent day4 = mockFieldComponent(null); FieldComponent date4 = mockFieldComponent(null); FormComponent row4 = mockFormComponent(day4, date4); AwesomeDynamicListComponent row4DailyProgresses = mockDailyProgressForShiftAdl(row4); stubProgressForDaysAdlRows(row1, row2, row3, row4); productionPerShiftListeners.updateProgressForDays(view, progressForDaysAdl, new String[] {}); verify(day1, never()).setFieldValue(any()); verify(date1, never()).setFieldValue(any()); verify(row1DailyProgresses, never()).setFieldValue(any()); verify(day2, never()).setFieldValue(any()); verify(date2, never()).setFieldValue(any()); verify(row2DailyProgresses, never()).setFieldValue(any()); } @Test public final void shouldDoNothingIfPlannedDateIsNotPresent() { stubOrderStartDates(null, null, null); stubProgressType(ProgressType.PLANNED); FieldComponent day1 = mockFieldComponent(null); FieldComponent date1 = mockFieldComponent(null); FormComponent row1 = mockFormComponent(day1, date1); AwesomeDynamicListComponent row1DailyProgresses = mockDailyProgressForShiftAdl(row1); stubProgressForDaysAdlRows(row1); productionPerShiftListeners.updateProgressForDays(view, progressForDaysAdl, new String[] {}); verifyNoMoreInteractions(day1); verifyNoMoreInteractions(date1); verifyNoMoreInteractions(row1DailyProgresses); } @Test public final void shouldFillFirstDayForShiftThatStartsWorkDayBefore() { stubRealizationDaysStream(PLANNED_ORDER_START, Sets.newHashSet(0, 1, 2, 3, 4, 5, 8, 9, 10), shifts); stubRealizationDaysStream(CORRECTED_ORDER_START, Sets.newHashSet(1, 2, 3, 6, 7, 8, 9, 10), shifts); stubProgressType(ProgressType.PLANNED); FieldComponent day1 = mockFieldComponent(null); FieldComponent date1 = mockFieldComponent(null); FormComponent row1 = mockFormComponent(day1, date1); AwesomeDynamicListComponent row1DailyProgresses = mockDailyProgressForShiftAdl(row1); stubProgressForDaysAdlRows(row1); stubOrderDate(OrderFields.DATE_TO, null); productionPerShiftListeners.updateProgressForDays(view, progressForDaysAdl, new String[] {}); verify(day1).setFieldValue(0); verify(date1).setFieldValue(DateUtils.toDateString(PLANNED_ORDER_START.minusDays(1).toDate())); verify(row1DailyProgresses).setFieldValue(Lists.newArrayList(firstShiftDailyProgress)); }
PpsCorrectionReasonAppender { public Either<String, Entity> append(final ProductionPerShiftId ppsId, final PpsCorrectionReason reason) { if (ppsId == null) { return Either.left("Missing pps id!"); } if (reason == null || StringUtils.isBlank(reason.get())) { return Either.left("Missing or blank reason type value!"); } return trySave(createCorrectionReason(ppsId, reason)); } @Autowired PpsCorrectionReasonAppender(final DataDefinitionService dataDefinitionService); Either<String, Entity> append(final ProductionPerShiftId ppsId, final PpsCorrectionReason reason); }
@Test public final void shouldFailDueToMissingPpsId() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(null, CORRECTION_REASON); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing pps id!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); } @Test public final void shouldFailDueToMissingReason() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, null); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); } @Test public final void shouldFailDueToMissingReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason(null)); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); } @Test public final void shouldFailDueToEmptyReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason("")); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); } @Test public final void shouldFailDueToBlankReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason(" ")); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); } @Test public final void shouldFailDueToValidationErrors() { Entity invalidEntity = mockEntity(null, correctionReasonDataDef); given(invalidEntity.isValid()).willReturn(false); given(correctionReasonDataDef.save(anyEntity())).willReturn(invalidEntity); Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, CORRECTION_REASON); Assert.assertTrue(res.isLeft()); String expectedMsg = String.format("Cannot save %s.%s because of validation errors", ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_REASON_TYPE_OF_CORRECTION_PLAN); Assert.assertEquals(expectedMsg, res.getLeft()); verify(correctionReasonDataDef, times(1)).save(newlyCreatedReasonEntity); } @Test public final void shouldAppendReason() { Entity validSavedEntity = mockEntity(null, correctionReasonDataDef); given(validSavedEntity.isValid()).willReturn(true); given(correctionReasonDataDef.save(anyEntity())).willReturn(validSavedEntity); Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, CORRECTION_REASON); Assert.assertTrue(res.isRight()); Assert.assertEquals(validSavedEntity, res.getRight()); verify(correctionReasonDataDef, times(1)).save(newlyCreatedReasonEntity); verify(newlyCreatedReasonEntity).setField(ReasonTypeOfCorrectionPlanFields.PRODUCTION_PER_SHIFT, PPS_ID.get()); verify(newlyCreatedReasonEntity).setField(ReasonTypeOfCorrectionPlanFields.REASON_TYPE_OF_CORRECTION_PLAN, CORRECTION_REASON.get()); }
NonWorkingShiftsNotifier { public void checkAndNotify(final ViewDefinitionState view, final DateTime orderStartDateTime, final Entity technologyOperation, final ProgressType progressType) { for (FormComponent form : view.<FormComponent> tryFindComponentByReference("form").asSet()) { List<ShiftAndDate> shiftsAndDates = getShiftAndDates(technologyOperation, progressType); for (ShiftAndDate shiftAndDate : filterShiftsNotStartingOrderAtZeroDay(orderStartDateTime, shiftsAndDates)) { notifyAboutShiftNotStartingOrderAtZeroDay(form, shiftAndDate, orderStartDateTime); } for (ShiftAndDate shiftAndDate : filterShiftsNotWorkingAtWeekday(shiftsAndDates)) { notifyAboutShiftNotWorkingAtWeekday(form, shiftAndDate); } } } void checkAndNotify(final ViewDefinitionState view, final DateTime orderStartDateTime, final Entity technologyOperation, final ProgressType progressType); }
@Test public final void shouldNotify() { LocalDate mondayDate = new LocalDate(2014, 9, 1); LocalDate tuesdayDate = new LocalDate(2014, 9, 2); DateTime orderStartDateTime = mondayDate.toDateTime(new LocalTime(23, 0, 0)); Entity shift1 = mockShiftEntity("firstShift", ImmutableSet.of(DateTimeConstants.MONDAY, DateTimeConstants.TUESDAY)); Entity shift2 = mockShiftEntity("secondShift", ImmutableSet.of(DateTimeConstants.TUESDAY, DateTimeConstants.WEDNESDAY)); stubStringField(shift1, ShiftFields.MONDAY_HOURS, "22:00-10:00"); stubStringField(shift1, ShiftFields.TUESDAY_HOURS, "22:00-10:00"); stubStringField(shift2, ShiftFields.TUESDAY_HOURS, "10:00-20:00"); Entity pfd1 = mockProgressForDay(mondayDate, 1, ImmutableList.of(shift1, shift2)); Entity pfd2 = mockProgressForDay(tuesdayDate, 2, ImmutableList.of(shift1, shift2)); stubProgressForDayFindResults(ImmutableList.of(pfd1, pfd2)); nonWorkingShiftsNotifier.checkAndNotify(view, orderStartDateTime, mockEntity(), ProgressType.CORRECTED); verify(form).addMessage("productionPerShift.progressForDay.shiftDoesNotWork", ComponentState.MessageType.INFO, "secondShift", DateUtils.toDateString(mondayDate.toDate())); verifyNoMoreInteractions(form); } @Test public final void shouldNotifyAboutZeroDay() { LocalDate mondayDate = new LocalDate(2014, 9, 1); LocalDate tuesdayDate = new LocalDate(2014, 9, 2); DateTime orderStartDateTime = tuesdayDate.toDateTime(new LocalTime(2, 0, 0)); Entity shift1 = mockShiftEntity("firstShift", ImmutableSet.of(DateTimeConstants.MONDAY, DateTimeConstants.TUESDAY)); Entity shift2 = mockShiftEntity("secondShift", ImmutableSet.of(DateTimeConstants.MONDAY, DateTimeConstants.TUESDAY, DateTimeConstants.WEDNESDAY)); stubStringField(shift1, ShiftFields.MONDAY_HOURS, "22:00-10:00"); stubStringField(shift1, ShiftFields.TUESDAY_HOURS, "22:00-10:00"); stubStringField(shift2, ShiftFields.TUESDAY_HOURS, "10:00-20:00"); Entity pfd1 = mockProgressForDay(mondayDate, 0, ImmutableList.of(shift1, shift2)); Entity pfd2 = mockProgressForDay(tuesdayDate, 1, ImmutableList.of(shift1, shift2)); stubProgressForDayFindResults(ImmutableList.of(pfd1, pfd2)); nonWorkingShiftsNotifier.checkAndNotify(view, orderStartDateTime, mockEntity(), ProgressType.CORRECTED); verify(form).addMessage("productionPerShift.progressForDay.shiftDoesNotStartOrderAtZeroDay", ComponentState.MessageType.INFO, "secondShift", DateUtils.toDateString(mondayDate.toDate())); verifyNoMoreInteractions(form); } @Test public final void shouldNotNotify() { LocalDate mondayDate = new LocalDate(2014, 9, 1); LocalDate tuesdayDate = new LocalDate(2014, 9, 2); DateTime orderStartDateTime = mondayDate.toDateTime(new LocalTime(9, 0, 0)); Entity shift1 = mockShiftEntity("firstShift", ImmutableSet.of(DateTimeConstants.MONDAY, DateTimeConstants.TUESDAY)); Entity shift2 = mockShiftEntity("secondShift", ImmutableSet.of(DateTimeConstants.TUESDAY, DateTimeConstants.WEDNESDAY)); stubStringField(shift1, ShiftFields.MONDAY_HOURS, "22:00-10:00"); stubStringField(shift1, ShiftFields.TUESDAY_HOURS, "22:00-10:00"); stubStringField(shift2, ShiftFields.TUESDAY_HOURS, "10:00-20:00"); Entity pfd1 = mockProgressForDay(mondayDate, 1, ImmutableList.of(shift1)); Entity pfd2 = mockProgressForDay(tuesdayDate, 2, ImmutableList.of(shift1, shift2)); stubProgressForDayFindResults(ImmutableList.of(pfd1, pfd2)); nonWorkingShiftsNotifier.checkAndNotify(view, orderStartDateTime, mockEntity(), ProgressType.CORRECTED); verify(form, never()).addMessage(eq("productionPerShift.progressForDay.shiftDoesNotWork"), any(ComponentState.MessageType.class), Matchers.<String> anyVararg()); verifyNoMoreInteractions(form); }
PPSReportHooks { public boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report) { int days = ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report); if (days > 7) { report.addError(reportDD.getField(PPSReportFields.DATE_FROM), "productionPerShift.report.onlyFiveDays"); report.addError(reportDD.getField(PPSReportFields.DATE_TO), "productionPerShift.report.onlyFiveDays"); return false; } return true; } boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report); final boolean validateDates(final DataDefinition reportDD, final Entity report); void clearGenerated(final DataDefinition reportDD, final Entity report); }
@Test public void shouldReturnFalseWhenCheckIfIsMoreThatFiveDays() { given(ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report)).willReturn(10); boolean result = hooks.checkIfIsMoreThatFiveDays(reportDD, report); Assert.assertFalse(result); verify(report, times(2)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } @Test public void shouldReturnTrueWhenCheckIfIsMoreThatFiveDays() { given(ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report)).willReturn(3); boolean result = hooks.checkIfIsMoreThatFiveDays(reportDD, report); Assert.assertTrue(result); verify(report, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
PPSReportHooks { public void clearGenerated(final DataDefinition reportDD, final Entity report) { report.setField(PPSReportFields.GENERATED, false); report.setField(PPSReportFields.FILE_NAME, null); } boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report); final boolean validateDates(final DataDefinition reportDD, final Entity report); void clearGenerated(final DataDefinition reportDD, final Entity report); }
@Test public void shouldClearGenerated() { hooks.clearGenerated(reportDD, report); verify(report, times(2)).setField(Mockito.anyString(), Mockito.any()); }
PPSReportDetailsHooks { public void disableFields(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); Long reportId = form.getEntityId(); if (reportId == null) { setFieldsState(view, REPORT_FIELDS, true); } else { Entity report = getReportFromDb(reportId); if (report != null) { boolean generated = report.getBooleanField(PPSReportFields.GENERATED); if (generated) { setFieldsState(view, REPORT_FIELDS, false); } else { setFieldsState(view, REPORT_FIELDS, true); } } } } void generateReportNumber(final ViewDefinitionState view); void disableFields(final ViewDefinitionState view); }
@Test public void shouldntDisableFieldsWhenEntityIsntSaved() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(null); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(true); } @Test public void shouldntDisableFieldsWhenEntityIsSavedAndReportIsntGenerated() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PPS_REPORT)).willReturn(reportDD); given(reportDD.get(1L)).willReturn(report); given(report.getBooleanField(PPSReportFields.GENERATED)).willReturn(false); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(true); } @Test public void shouldDisableFieldsWhenEntityIsSavedAndReportIsGenerated() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PPS_REPORT)).willReturn(reportDD); given(reportDD.get(1L)).willReturn(report); given(report.getBooleanField(PPSReportFields.GENERATED)).willReturn(true); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(false); }
ProductionPerShiftDetailsHooks { void fillTechnologyOperationLookup(final ViewDefinitionState view, final Entity technology) { LookupComponent technologyOperationLookup = (LookupComponent) view.getComponentByReference(OPERATION_LOOKUP_REF); for (Entity rootOperation : technologyOperationDataProvider.findRoot(technology.getId()).asSet()) { technologyOperationLookup.setFieldValue(rootOperation.getId()); technologyOperationLookup.requestComponentUpdateState(); } technologyOperationLookup.setEnabled(true); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view, final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }
@Test public void shouldAddRootForOperation() throws Exception { final Long rootOperationId = 2L; LookupComponent technologyOperationLookup = mockLookup(mockEntity()); stubViewComponent(OPERATION_LOOKUP_REF, technologyOperationLookup); Entity rootOperation = mockEntity(rootOperationId); given(technologyOperationDataProvider.findRoot(anyLong())).willReturn(Optional.of(rootOperation)); productionPerShiftDetailsHooks.fillTechnologyOperationLookup(view, technology); verify(technologyOperationLookup).setFieldValue(rootOperationId); }
ProductionPerShiftDetailsHooks { void setupProgressTypeComboBox(final ViewDefinitionState view, final OrderState orderState, final ProgressType progressType) { FieldComponent plannedProgressType = (FieldComponent) view.getComponentByReference(PROGRESS_TYPE_COMBO_REF); plannedProgressType.setFieldValue(progressType.getStringValue()); plannedProgressType.requestComponentUpdateState(); plannedProgressType.setEnabled(orderState != OrderState.PENDING); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view, final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }
@Test public void shouldEnabledPlannedProgressTypeForInProgressOrder() throws Exception { ProgressType progressType = ProgressType.PLANNED; productionPerShiftDetailsHooks.setupProgressTypeComboBox(view, OrderState.IN_PROGRESS, progressType); verify(progressTypeComboBox).setFieldValue(progressType.getStringValue()); verify(progressTypeComboBox).setEnabled(true); }
ProductionPerShiftDetailsHooks { void fillOrderDateComponents(final ViewDefinitionState view, final Entity order) { for (ImmutableMap.Entry<String, String> modelFieldToViewReference : ORDER_DATE_FIELDS_TO_VIEW_COMPONENTS.entrySet()) { FieldComponent dateComponent = (FieldComponent) view.getComponentByReference(modelFieldToViewReference.getValue()); Date date = order.getDateField(modelFieldToViewReference.getKey()); dateComponent.setFieldValue(DateUtils.toDateTimeString(date)); dateComponent.requestComponentUpdateState(); } } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view, final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }
@Test public void shouldSetOrderStartDatesWhenPlannedDateExists() throws Exception { ComponentState plannedDateField = mockFieldComponent(null); ComponentState correctedDateField = mockFieldComponent(null); ComponentState effectiveDateField = mockFieldComponent(null); stubViewComponent(PLANNED_START_DATE_TIME_REF, plannedDateField); stubViewComponent(CORRECTED_START_DATE_TIME_REF, correctedDateField); stubViewComponent(EFFECTIVE_START_DATE_TIME_REF, effectiveDateField); Date planned = new Date(); stubDateField(order, OrderFields.DATE_FROM, planned); stubDateField(order, OrderFields.CORRECTED_DATE_FROM, null); stubDateField(order, OrderFields.EFFECTIVE_DATE_FROM, null); productionPerShiftDetailsHooks.fillOrderDateComponents(view, order); verify(plannedDateField).setFieldValue(DateUtils.toDateTimeString(planned)); verify(correctedDateField).setFieldValue(""); verify(effectiveDateField).setFieldValue(""); } @Test public void shouldSetOrderStartDatesWhenPlannedAndCorrectedDateExists() throws Exception { ComponentState plannedDateField = mockFieldComponent(null); ComponentState correctedDateField = mockFieldComponent(null); ComponentState effectiveDateField = mockFieldComponent(null); stubViewComponent(PLANNED_START_DATE_TIME_REF, plannedDateField); stubViewComponent(CORRECTED_START_DATE_TIME_REF, correctedDateField); stubViewComponent(EFFECTIVE_START_DATE_TIME_REF, effectiveDateField); Date planned = new Date(); Date corrected = new Date(); Date effective = new Date(); stubDateField(order, OrderFields.DATE_FROM, planned); stubDateField(order, OrderFields.CORRECTED_DATE_FROM, corrected); stubDateField(order, OrderFields.EFFECTIVE_DATE_FROM, effective); productionPerShiftDetailsHooks.fillOrderDateComponents(view, order); verify(plannedDateField).setFieldValue(DateUtils.toDateTimeString(planned)); verify(correctedDateField).setFieldValue(DateUtils.toDateTimeString(corrected)); verify(effectiveDateField).setFieldValue(DateUtils.toDateTimeString(effective)); }
ProductionPerShiftDetailsHooks { public void setProductAndFillProgressForDays(final ViewDefinitionState view) { Entity order = getEntityFromLookup(view, "order").get(); OrderState orderState = OrderState.of(order); ProgressType progressType = resolveProgressType(view); AwesomeDynamicListComponent progressForDaysADL = (AwesomeDynamicListComponent) view .getComponentByReference(PROGRESS_ADL_REF); setProductAndFillProgressForDays(view, progressForDaysADL, orderState, progressType); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view, final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }
@Test public void shouldFillProgressesADL() throws Exception { Entity technologyOperation = mockEntity(3L); stubViewComponent(OPERATION_LOOKUP_REF, mockLookup(technologyOperation)); LookupComponent producedProductLookup = mockLookup(null); stubViewComponent(PRODUCED_PRODUCT_LOOKUP_REF, producedProductLookup); long productId = 100L; Entity product = mockEntity(productId); stubMainTocProduct(product); stubProgressType(ProgressType.CORRECTED); stubOrderState(OrderState.PENDING); Entity firstPfd = mockEntity(); Entity secondPfd = mockEntity(); stubProgressForDayDataProviderFindForOp(technologyOperation, true, Lists.newArrayList(firstPfd, secondPfd)); String productUnit = "someArbitraryUnit"; stubStringField(product, ProductFields.UNIT, productUnit); FieldComponent firstDayField = mockFieldComponent(null); LookupComponent firstShiftLookup = mockLookup(mockEntity()); FieldComponent firstQuantityFieldComponent = mockFieldComponent(null); FieldComponent firstUnitFieldComponent = mockFieldComponent(null); FormComponent firstPfdForm = mockProgressForDayRowForm(firstDayField, firstShiftLookup, firstQuantityFieldComponent, firstUnitFieldComponent); FieldComponent secondDayField = mockFieldComponent(null); LookupComponent secondShiftLookup = mockLookup(mockEntity()); FieldComponent secondQuantityFieldComponent = mockFieldComponent(null); FieldComponent secondUnitFieldComponent = mockFieldComponent(null); FormComponent secondPfdForm = mockProgressForDayRowForm(secondDayField, secondShiftLookup, secondQuantityFieldComponent, secondUnitFieldComponent); AwesomeDynamicListComponent progressesAdl = mock(AwesomeDynamicListComponent.class); stubViewComponent("progressForDays", progressesAdl); given(progressesAdl.getFormComponents()).willReturn(Lists.newArrayList(firstPfdForm, secondPfdForm)); productionPerShiftDetailsHooks.setProductAndFillProgressForDays(view); verify(progressesAdl).setFieldValue(Lists.newArrayList(firstPfd, secondPfd)); verify(producedProductLookup).setFieldValue(productId); verify(firstUnitFieldComponent).setFieldValue(productUnit); verify(secondUnitFieldComponent).setFieldValue(productUnit); }
ProductionPerShiftDetailsHooks { void disableComponents(final AwesomeDynamicListComponent progressForDaysADL, final ProgressType progressType, final OrderState orderState) { boolean isEnabled = (progressType == ProgressType.CORRECTED || orderState == OrderState.PENDING) && !UNSUPPORTED_ORDER_STATES.contains(orderState); for (FormComponent progressForDaysForm : progressForDaysADL.getFormComponents()) { progressForDaysForm.setFormEnabled(isEnabled); AwesomeDynamicListComponent dailyProgressADL = (AwesomeDynamicListComponent) progressForDaysForm .findFieldComponentByName(DAILY_PROGRESS_ADL_REF); for (FormComponent dailyProgressForm : dailyProgressADL.getFormComponents()) { Entity dpEntity = dailyProgressForm.getPersistedEntityWithIncludedFormValues(); boolean isLocked = dpEntity.getBooleanField(DailyProgressFields.LOCKED); dailyProgressForm.setFormEnabled(isEnabled && !isLocked); } dailyProgressADL.setEnabled(isEnabled); } progressForDaysADL.setEnabled(isEnabled); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view, final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }
@Test public void shouldDisableDailyProgressRowsForLockedEntities() { FormComponent firstPfdFirstDailyForm = mockForm(mockEntity()); FormComponent firstPfdSecondDailyForm = mockForm(mockLockedEntity()); AwesomeDynamicListComponent firstPfdDailyAdl = mock(AwesomeDynamicListComponent.class); given(firstPfdDailyAdl.getFormComponents()).willReturn( Lists.newArrayList(firstPfdFirstDailyForm, firstPfdSecondDailyForm)); FormComponent firstPfdForm = mockForm(mockEntity()); stubFormComponent(firstPfdForm, DAILY_PROGRESS_ADL_REF, firstPfdDailyAdl); FormComponent secondPfdFirstDailyForm = mockForm(mockEntity()); AwesomeDynamicListComponent secondPfdDailyAdl = mock(AwesomeDynamicListComponent.class); given(secondPfdDailyAdl.getFormComponents()).willReturn(Lists.newArrayList(secondPfdFirstDailyForm)); FormComponent secondPfdForm = mockForm(mockEntity()); stubFormComponent(secondPfdForm, DAILY_PROGRESS_ADL_REF, secondPfdDailyAdl); AwesomeDynamicListComponent progressForDaysAdl = mock(AwesomeDynamicListComponent.class); stubViewComponent("progressForDays", progressForDaysAdl); given(progressForDaysAdl.getFormComponents()).willReturn(Lists.newArrayList(firstPfdForm, secondPfdForm)); productionPerShiftDetailsHooks.disableComponents(progressForDaysAdl, ProgressType.PLANNED, OrderState.PENDING); verify(progressForDaysAdl).setEnabled(true); verify(firstPfdFirstDailyForm).setFormEnabled(true); verify(firstPfdSecondDailyForm).setFormEnabled(false); verify(firstPfdDailyAdl).setEnabled(true); verify(firstPfdForm).setFormEnabled(true); verify(secondPfdFirstDailyForm).setFormEnabled(true); verify(secondPfdDailyAdl).setEnabled(true); verify(secondPfdForm).setFormEnabled(true); }
TechnologyOperationComponentValidatorsPPS { public boolean checkGrowingNumberOfDays(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent) { List<Entity> progressForDays = technologyOperationComponent .getHasManyField(TechnologyOperationComponentFieldsPPS.PROGRESS_FOR_DAYS); if (progressForDays.isEmpty()) { return true; } Integer dayNumber = Integer.valueOf(0); for (Entity progressForDay : progressForDays) { if (progressForDay.getBooleanField(ProgressForDayFields.CORRECTED) != technologyOperationComponent .getBooleanField(TechnologyOperationComponentFieldsPPS.HAS_CORRECTIONS) || progressForDay.getField(ProgressForDayFields.DAY) == null) { continue; } Object dayObject = progressForDay.getField(ProgressForDayFields.DAY); if (!(dayObject instanceof Long) && !(dayObject instanceof Integer)) { progressForDay.addError(progressForDay.getDataDefinition().getField(ProgressForDayFields.DAY), "productionPerShift.progressForDay.haveToBeInteger"); return false; } Integer day = Integer.valueOf(0); if (dayObject instanceof Integer) { day = progressForDay.getIntegerField(ProgressForDayFields.DAY); } else { day = ((Long) progressForDay.getField(ProgressForDayFields.DAY)).intValue(); } if (day != null && dayNumber.compareTo(day) <= 0) { dayNumber = day; } else { technologyOperationComponent.addGlobalError("productionPerShift.progressForDay.daysAreNotInAscendingOrder", progressForDay.getField(ProgressForDayFields.DAY).toString()); return false; } } return true; } boolean checkGrowingNumberOfDays(final DataDefinition technologyOperationComponentDD, final Entity technologyOperationComponent); }
@Test public void shouldReturnTrueWhenProgressForDayHMIsEmpty() { given(technologyOperationComponent.getHasManyField(TechnologyOperationComponentFieldsPPS.PROGRESS_FOR_DAYS)).willReturn( progressForDays); given(progressForDays.isEmpty()).willReturn(true); boolean result = technologyOperationComponentValidatorsPPS.checkGrowingNumberOfDays(technologyOperationComponentDD, technologyOperationComponent); Assert.assertTrue(result); } @Test public void shouldReturnFalseAndEntityHasErrorWhenDaysAreNotOrderDesc() { Long day1 = 11L; Long day2 = 10L; Entity progressForDay1 = mock(Entity.class); Entity progressForDay2 = mock(Entity.class); EntityList progressForDays = mockEntityList(Lists.newArrayList(progressForDay1, progressForDay2)); given(technologyOperationComponent.getHasManyField(TechnologyOperationComponentFieldsPPS.PROGRESS_FOR_DAYS)).willReturn( progressForDays); given(progressForDays.get(0)).willReturn(progressForDay1); given(progressForDays.get(1)).willReturn(progressForDay2); given(progressForDay1.getField(ProgressForDayFields.DAY)).willReturn(day1); given(progressForDay2.getField(ProgressForDayFields.DAY)).willReturn(day2); boolean result = technologyOperationComponentValidatorsPPS.checkGrowingNumberOfDays(technologyOperationComponentDD, technologyOperationComponent); Assert.assertFalse(result); Mockito.verify(technologyOperationComponent).addGlobalError( "productionPerShift.progressForDay.daysAreNotInAscendingOrder", day2.toString()); } @Test public void shouldReturnTrueWhenDaysAreOrderDesc() { Long day1 = 10L; Long day2 = 11L; Entity progressForDay1 = mock(Entity.class); Entity progressForDay2 = mock(Entity.class); EntityList progressForDays = mockEntityList(Lists.newArrayList(progressForDay1, progressForDay2)); given(technologyOperationComponent.getHasManyField(TechnologyOperationComponentFieldsPPS.PROGRESS_FOR_DAYS)).willReturn( progressForDays); given(progressForDays.get(0)).willReturn(progressForDay1); given(progressForDays.get(1)).willReturn(progressForDay2); given(progressForDay1.getField(ProgressForDayFields.DAY)).willReturn(day1); given(progressForDay2.getField(ProgressForDayFields.DAY)).willReturn(day2); boolean result = technologyOperationComponentValidatorsPPS.checkGrowingNumberOfDays(technologyOperationComponentDD, technologyOperationComponent); Assert.assertTrue(result); }
PPSHelper { public Long getPpsIdForOrder(final Long orderId) { DataDefinition ppsDateDef = getProductionPerShiftDD(); String query = "select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId"; Entity projectionResults = ppsDateDef.find(query).setLong("orderId", orderId).setMaxResults(1).uniqueResult(); if (projectionResults == null) { return null; } return (Long) projectionResults.getField("ppsId"); } Long getPpsIdForOrder(final Long orderId); Long createPpsForOrderAndReturnId(final Long orderId); Entity createDailyProgressWithShift(final Entity shiftEntity); }
@Test public final void shouldGetPpsForOrderReturnExistingPpsId() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given( dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT)).willReturn(dataDefinition); SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class); given(dataDefinition.find("select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId")) .willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(entity); given(entity.getField("ppsId")).willReturn(expectedPpsId); final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId); Assert.assertEquals(expectedPpsId, resultPpsId); } @Test public final void shouldGetPpsForOrderReturnNullIfPpsDoesNotExists() { Long givenOrderId = 1L; given( dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT)).willReturn(dataDefinition); SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class); given(dataDefinition.find("select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId")) .willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(null); final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId); Assert.assertNull(resultPpsId); }
OrderRealizationDaysResolver { public OrderRealizationDay find(final DateTime orderStartDateTime, final int startingFrom, final boolean isFirstDay, final List<Shift> shifts) { OrderRealizationDay firstWorkingDay = findFirstWorkingDayFrom(orderStartDateTime.toLocalDate(), startingFrom, shifts); if (isFirstDay) { return tryResolveFirstDay(firstWorkingDay, orderStartDateTime).or(firstWorkingDay); } return firstWorkingDay; } LazyStream<OrderRealizationDay> asStreamFrom(final DateTime orderStartDateTime, final List<Shift> shifts); OrderRealizationDay find(final DateTime orderStartDateTime, final int startingFrom, final boolean isFirstDay, final List<Shift> shifts); }
@Test public final void shouldResolveRealizationDay1() { DateTime startDate = new DateTime(2014, 8, 14, 10, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 1, true, shifts); assertRealizationDayState(realizationDay, 1, startDate.toLocalDate(), shifts); } @Test public final void shouldResolveRealizationDay2() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 1, true, shifts); assertRealizationDayState(realizationDay, 0, startDate.toLocalDate().minusDays(1), ImmutableList.of(shift1)); } @Test public final void shouldResolveRealizationDay3() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 1, false, shifts); assertRealizationDayState(realizationDay, 1, startDate.toLocalDate(), shifts); } @Test public final void shouldResolveRealizationDay4() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 3, false, shifts); assertRealizationDayState(realizationDay, 5, startDate.toLocalDate().plusDays(4), shifts); } @Test public final void shouldResolveRealizationDay5() { DateTime startDate = new DateTime(2014, 8, 14, 12, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 3, false, shifts); assertRealizationDayState(realizationDay, 5, startDate.toLocalDate().plusDays(4), shifts); } @Test public final void shouldResolveRealizationDay6() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 3, true, shifts); assertRealizationDayState(realizationDay, 5, startDate.toLocalDate().plusDays(4), shifts); } @Test public final void shouldNotResultInAnInfiniteCycleIfThereIsNoShiftsDefined() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 1, true, shifts); assertRealizationDayState(realizationDay, 1, startDate.toLocalDate(), ImmutableList.<Shift> of()); } @Test public final void shouldNotResultInAnInfiniteCycleIfShiftsNeverWorks() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); Shift lazyShift = mockShift(new TimeRange(SH_1_START, SH_1_END), ImmutableSet.<Integer> of()); List<Shift> shifts = ImmutableList.of(lazyShift); OrderRealizationDay realizationDay = orderRealizationDaysResolver.find(startDate, 1, true, shifts); assertRealizationDayState(realizationDay, 1, startDate.toLocalDate(), ImmutableList.<Shift> of()); }
OrderRealizationDaysResolver { public LazyStream<OrderRealizationDay> asStreamFrom(final DateTime orderStartDateTime, final List<Shift> shifts) { OrderRealizationDay firstDay = find(orderStartDateTime, 1, true, shifts); return LazyStream.create(firstDay, prevElement -> find(orderStartDateTime, prevElement.getRealizationDayNumber() + 1, false, shifts)); } LazyStream<OrderRealizationDay> asStreamFrom(final DateTime orderStartDateTime, final List<Shift> shifts); OrderRealizationDay find(final DateTime orderStartDateTime, final int startingFrom, final boolean isFirstDay, final List<Shift> shifts); }
@Test public final void shouldProduceStreamWithCorrectFirstDayDate() { DateTime startDate = new DateTime(2014, 12, 4, 23, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); Optional<OrderRealizationDay> firstRealizationDay = FluentIterable.from(stream).limit(1).first(); assertTrue(firstRealizationDay.isPresent()); assertRealizationDayState(firstRealizationDay.get(), 1, startDate.toLocalDate(), ImmutableList.of(shift1)); } @Test public final void shouldProduceStreamOfRealizationDays1() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); OrderRealizationDay[] streamVals = FluentIterable.from(stream).limit(5).toArray(OrderRealizationDay.class); assertRealizationDayState(streamVals[0], 0, startDate.toLocalDate().minusDays(1), ImmutableList.of(shift1)); assertRealizationDayState(streamVals[1], 1, startDate.toLocalDate(), shifts); assertRealizationDayState(streamVals[2], 2, startDate.toLocalDate().plusDays(1), shifts); assertRealizationDayState(streamVals[3], 5, startDate.toLocalDate().plusDays(4), shifts); assertRealizationDayState(streamVals[4], 6, startDate.toLocalDate().plusDays(5), shifts); } @Test public final void shouldProduceStreamOfRealizationDays2() { DateTime startDate = new DateTime(2014, 8, 14, 14, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); OrderRealizationDay[] streamVals = FluentIterable.from(stream).limit(5).toArray(OrderRealizationDay.class); assertRealizationDayState(streamVals[0], 1, startDate.toLocalDate(), shifts); assertRealizationDayState(streamVals[1], 2, startDate.toLocalDate().plusDays(1), shifts); assertRealizationDayState(streamVals[2], 5, startDate.toLocalDate().plusDays(4), shifts); assertRealizationDayState(streamVals[3], 6, startDate.toLocalDate().plusDays(5), shifts); assertRealizationDayState(streamVals[4], 7, startDate.toLocalDate().plusDays(6), shifts); }
TransferDetailsViewHooks { public void checkIfTransferHasTransformations(final ViewDefinitionState view) { FormComponent transferForm = (FormComponent) view.getComponentByReference(L_FORM); Long transferId = transferForm.getEntityId(); if (transferId == null) { return; } Entity transfer = dataDefinitionService .get(MaterialFlowConstants.PLUGIN_IDENTIFIER, MaterialFlowConstants.MODEL_TRANSFER).get(transferId); if (transfer == null) { return; } if (transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION) != null || transfer.getBelongsToField(TransferFields.TRANSFORMATIONS_PRODUCTION) != null) { FieldComponent type = (FieldComponent) view.getComponentByReference(TYPE); FieldComponent date = (FieldComponent) view.getComponentByReference(TIME); FieldComponent locationTo = (FieldComponent) view.getComponentByReference(LOCATION_TO); FieldComponent locationFrom = (FieldComponent) view.getComponentByReference(LOCATION_FROM); FieldComponent staff = (FieldComponent) view.getComponentByReference(STAFF); type.setEnabled(false); date.setEnabled(false); locationTo.setEnabled(false); locationFrom.setEnabled(false); staff.setEnabled(false); } } void onBeforeRender(final ViewDefinitionState view); void checkIfTransferHasTransformations(final ViewDefinitionState view); void disableFormWhenTransferIsSaved(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); void showMessageAfterSaving(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldReturnWhenCheckIfTransferHasTransformationsAndNumberIsNull() { given(view.getComponentByReference(L_FORM)).willReturn(transferForm); given(view.getComponentByReference(TYPE)).willReturn(typeField); given(view.getComponentByReference(TIME)).willReturn(typeField); given(view.getComponentByReference(LOCATION_FROM)).willReturn(locationFromField); given(view.getComponentByReference(LOCATION_TO)).willReturn(locationToField); given(view.getComponentByReference(STAFF)).willReturn(staffField); given(transferForm.getEntityId()).willReturn(null); transferDetailsViewHooks.checkIfTransferHasTransformations(view); verify(typeField, never()).setEnabled(false); verify(timeField, never()).setEnabled(false); verify(locationFromField, never()).setEnabled(false); verify(locationToField, never()).setEnabled(false); verify(staffField, never()).setEnabled(false); } @Test public void shouldReturnWhenCheckIfTransferHasTransformationsAndTransferIsNull() { given(view.getComponentByReference(L_FORM)).willReturn(transferForm); given(view.getComponentByReference(TYPE)).willReturn(typeField); given(view.getComponentByReference(TIME)).willReturn(timeField); given(view.getComponentByReference(LOCATION_FROM)).willReturn(locationFromField); given(view.getComponentByReference(LOCATION_TO)).willReturn(locationToField); given(view.getComponentByReference(STAFF)).willReturn(staffField); given(transferForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER, MaterialFlowConstants.MODEL_TRANSFER)) .willReturn(transferDD); given(transferDD.get(1L)).willReturn(null); transferDetailsViewHooks.checkIfTransferHasTransformations(view); verify(typeField, never()).setEnabled(false); verify(timeField, never()).setEnabled(false); verify(locationFromField, never()).setEnabled(false); verify(locationToField, never()).setEnabled(false); verify(staffField, never()).setEnabled(false); } @Test public void shouldReturnWhenCheckIfTransferHasTransformationsAndTransformationsAreNull() { given(view.getComponentByReference(L_FORM)).willReturn(transferForm); given(view.getComponentByReference(TYPE)).willReturn(typeField); given(view.getComponentByReference(TIME)).willReturn(timeField); given(view.getComponentByReference(LOCATION_FROM)).willReturn(locationFromField); given(view.getComponentByReference(LOCATION_TO)).willReturn(locationToField); given(view.getComponentByReference(STAFF)).willReturn(staffField); given(transferForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER, MaterialFlowConstants.MODEL_TRANSFER)) .willReturn(transferDD); given(transferDD.get(1L)).willReturn(transfer); given(transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION)).willReturn(null); given(transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION)).willReturn(null); transferDetailsViewHooks.checkIfTransferHasTransformations(view); verify(typeField, never()).setEnabled(false); verify(timeField, never()).setEnabled(false); verify(locationFromField, never()).setEnabled(false); verify(locationToField, never()).setEnabled(false); verify(staffField, never()).setEnabled(false); } @Test public void shouldDisableFieldsWhenCheckIfTransferHasTransformationsAndTransformationsAreNull() { given(view.getComponentByReference(L_FORM)).willReturn(transferForm); given(view.getComponentByReference(TYPE)).willReturn(typeField); given(view.getComponentByReference(TIME)).willReturn(timeField); given(view.getComponentByReference(LOCATION_FROM)).willReturn(locationFromField); given(view.getComponentByReference(LOCATION_TO)).willReturn(locationToField); given(view.getComponentByReference(STAFF)).willReturn(staffField); given(transferForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER, MaterialFlowConstants.MODEL_TRANSFER)) .willReturn(transferDD); given(transferDD.get(1L)).willReturn(transfer); given(transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION)).willReturn(transformations); given(transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION)).willReturn(transformations); transferDetailsViewHooks.checkIfTransferHasTransformations(view); verify(typeField).setEnabled(false); verify(timeField).setEnabled(false); verify(locationFromField).setEnabled(false); verify(locationToField).setEnabled(false); verify(staffField).setEnabled(false); }
DeliveriesColumnLoaderTSFD { public void addColumnsForDeliveriesTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForDeliveries(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }
@Test public void shouldAddColumnsForDeliveriesTSFD() { deliveriesColumnLoaderTSFD.addColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderService).fillColumnsForDeliveries(Mockito.anyString()); }
DeliveriesColumnLoaderTSFD { public void deleteColumnsForDeliveriesTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForDeliveries(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }
@Test public void shouldDeleteTSFDcolumnsForDeliveries() { deliveriesColumnLoaderTSFD.deleteColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderService).clearColumnsForDeliveries(Mockito.anyString()); }
DeliveriesColumnLoaderTSFD { public void addColumnsForOrdersTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForOrders(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }
@Test public void shouldAddColumnsForOrdersTSFD() { deliveriesColumnLoaderTSFD.addColumnsForOrdersTSFD(); verify(deliveriesColumnLoaderService).fillColumnsForOrders(Mockito.anyString()); }
DeliveriesColumnLoaderTSFD { public void deleteColumnsForOrdersTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForOrders(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }
@Test public void shouldDeleteColumnsForOrdersTSFD() { deliveriesColumnLoaderTSFD.deleteColumnsForOrdersTSFD(); verify(deliveriesColumnLoaderService).clearColumnsForOrders(Mockito.anyString()); }
TechSubcontrForDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantEnable() { deliveriesColumnLoaderTSFD.addColumnsForDeliveriesTSFD(); deliveriesColumnLoaderTSFD.addColumnsForOrdersTSFD(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }
@Test public void shouldMultiTenantEnable() { techSubcontrForDeliveriesOnStartupService.multiTenantEnable(); verify(deliveriesColumnLoaderTSFD).addColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderTSFD).addColumnsForOrdersTSFD(); }
TechSubcontrForDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantDisable() { deliveriesColumnLoaderTSFD.deleteColumnsForDeliveriesTSFD(); deliveriesColumnLoaderTSFD.deleteColumnsForOrdersTSFD(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }
@Test public void shouldMultiTenantDisable() { techSubcontrForDeliveriesOnStartupService.multiTenantDisable(); verify(deliveriesColumnLoaderTSFD).deleteColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderTSFD).deleteColumnsForOrdersTSFD(); }
CostCalculationValidators { public boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation) { Entity technology = costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY); String state = technology.getStringField(TechnologyFields.STATE); if (TechnologyState.DRAFT.getStringValue().equals(state) || TechnologyState.DECLINED.getStringValue().equals(state)) { costCalculation.addError(costCalculationDD.getField(CostCalculationFields.TECHNOLOGY), "costNormsForOperation.messages.fail.incorrectState"); return false; } return true; } boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation); boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation); boolean ifSourceOfMaterialIsFromOrderThenOrderIsNeeded(final DataDefinition costCalculationDD, final Entity costCalculation); }
@Test public void shouldTechnologyHasIncorrectState() { given(costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY)).willReturn(technology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyStateStringValues.DRAFT); boolean result = costCalculationValidators.checkIfTheTechnologyHasCorrectState(costCalculationDD, costCalculation); assertFalse(result); } @Test public void shouldTechnologyHasCorrectState() { given(costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY)).willReturn(technology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyStateStringValues.CHECKED); boolean result = costCalculationValidators.checkIfTheTechnologyHasCorrectState(costCalculationDD, costCalculation); assertTrue(result); }
CostCalculationValidators { public boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation) { String sourceOfMaterialCosts = costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS); String calculateMaterialCostsMode = costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE); if (SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue().equals(sourceOfMaterialCosts) && CalculateMaterialCostsMode.COST_FOR_ORDER.getStringValue().equals(calculateMaterialCostsMode)) { costCalculation.addError(costCalculationDD.getField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE), "costCalculation.messages.optionUnavailable"); return false; } return true; } boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation); boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation); boolean ifSourceOfMaterialIsFromOrderThenOrderIsNeeded(final DataDefinition costCalculationDD, final Entity costCalculation); }
@Test public void shouldReturnFalseWhenCurrencyGlobalIsSelected() throws Exception { given(costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS)).willReturn( SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue()); given(costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE)).willReturn( CalculateMaterialCostsMode.COST_FOR_ORDER.getStringValue()); boolean result = costCalculationValidators.checkIfCurrentGlobalIsSelected(costCalculationDD, costCalculation); assertFalse(result); } @Test public void shouldReturnTrueWhenCalculateMaterialCostsModeIsNominal() throws Exception { given(costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS)).willReturn( SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue()); given(costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE)).willReturn( CalculateMaterialCostsMode.NOMINAL.getStringValue()); boolean result = costCalculationValidators.checkIfCurrentGlobalIsSelected(costCalculationDD, costCalculation); assertTrue(result); }
StaffDetailsHooks { public void enabledIndividualCost(final ViewDefinitionState view) { FieldComponent individual = (FieldComponent) view.getComponentByReference("determinedIndividual"); FieldComponent individualLaborCost = (FieldComponent) view.getComponentByReference("individualLaborCost"); if (individual.getFieldValue() != null && individual.getFieldValue().equals("1")) { individualLaborCost.setEnabled(true); } else { individualLaborCost.setEnabled(false); } individualLaborCost.requestComponentUpdateState(); } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }
@Test public void shouldEnabledFieldWhenCheckBoxIsSelected() throws Exception { String result = "1"; when(view.getComponentByReference("determinedIndividual")).thenReturn(field1); when(view.getComponentByReference("individualLaborCost")).thenReturn(field2); when(field1.getFieldValue()).thenReturn(result); detailsHooks.enabledIndividualCost(view); Mockito.verify(field2).setEnabled(true); } @Test public void shouldDisabledFieldWhenCheckBoxIsSelected() throws Exception { String result = "0"; when(view.getComponentByReference("determinedIndividual")).thenReturn(field1); when(view.getComponentByReference("individualLaborCost")).thenReturn(field2); when(field1.getFieldValue()).thenReturn(result); detailsHooks.enabledIndividualCost(view); Mockito.verify(field2).setEnabled(false); }
StaffDetailsHooks { public void setCurrency(final ViewDefinitionState view) { FieldComponent laborHourlyCostUNIT = (FieldComponent) view.getComponentByReference("individualLaborCostCURRENCY"); FieldComponent laborCostFromWageGroupsUNIT = (FieldComponent) view .getComponentByReference("laborCostFromWageGroupsCURRENCY"); laborHourlyCostUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); laborCostFromWageGroupsUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); laborHourlyCostUNIT.requestComponentUpdateState(); laborCostFromWageGroupsUNIT.requestComponentUpdateState(); } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }
@Test public void shouldFillFieldCurrency() throws Exception { String currency = "PLN"; when(view.getComponentByReference("individualLaborCostCURRENCY")).thenReturn(field1); when(view.getComponentByReference("laborCostFromWageGroupsCURRENCY")).thenReturn(field2); when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); detailsHooks.setCurrency(view); Mockito.verify(field1).setFieldValue(currency); Mockito.verify(field2).setFieldValue(currency); }
StaffDetailsHooks { public void fillFieldAboutWageGroup(final ViewDefinitionState view) { LookupComponent lookup = (LookupComponent) view.getComponentByReference("wageGroup"); Entity wageGroup = lookup.getEntity(); FieldComponent laborCostFromWageGroups = (FieldComponent) view.getComponentByReference("laborCostFromWageGroups"); FieldComponent superiorWageGroups = (FieldComponent) view.getComponentByReference("superiorWageGroups"); if (wageGroup != null) { laborCostFromWageGroups.setFieldValue(wageGroup.getField(LABOR_HOURLY_COST)); superiorWageGroups.setFieldValue(wageGroup.getStringField(SUPERIOR_WAGE_GROUP)); } else { laborCostFromWageGroups.setFieldValue(null); superiorWageGroups.setFieldValue(null); } } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }
@Test public void shouldFillFieldValuesOfSelectedWageGroup() throws Exception { String superiorWageGroup = "1234"; when(view.getComponentByReference("wageGroup")).thenReturn(lookup); when(lookup.getEntity()).thenReturn(wageGroup); when(view.getComponentByReference("laborCostFromWageGroups")).thenReturn(field1); when(view.getComponentByReference("superiorWageGroups")).thenReturn(field2); when(wageGroup.getField(LABOR_HOURLY_COST)).thenReturn(BigDecimal.ONE); when(wageGroup.getStringField(SUPERIOR_WAGE_GROUP)).thenReturn(superiorWageGroup); detailsHooks.fillFieldAboutWageGroup(view); Mockito.verify(field1).setFieldValue(BigDecimal.ONE); Mockito.verify(field2).setFieldValue(superiorWageGroup); }
WageGroupsDetailsHooks { public void setCurrency(final ViewDefinitionState view) { FieldComponent individualLaborCostUNIT = (FieldComponent) view .getComponentByReference(WageGroupFields.LABOR_HOURLY_COST_CURRENCY); individualLaborCostUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); individualLaborCostUNIT.requestComponentUpdateState(); } void setCurrency(final ViewDefinitionState view); }
@Test public void shouldFillFieldWithCurrency() throws Exception { String currency = "pln"; when(view.getComponentByReference("laborHourlyCostCURRENCY")).thenReturn(field); when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); hooks.setCurrency(view); Mockito.verify(field).setFieldValue(currency); }
StaffHooks { public void saveLaborHourlyCost(final DataDefinition dataDefinition, final Entity entity) { boolean individual = entity.getBooleanField(DETERMINED_INDIVIDUAL); if (individual) { entity.setField("laborHourlyCost", entity.getField(INDIVIDUAL_LABOR_COST)); } else { Entity wageGroup = entity.getBelongsToField(WAGE_GROUP); if (wageGroup == null) { entity.setField("laborHourlyCost", null); return; } entity.setField("laborHourlyCost", wageGroup.getField(LABOR_HOURLY_COST)); } } void saveLaborHourlyCost(final DataDefinition dataDefinition, final Entity entity); }
@Test public void shouldSaveIndividualCost() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(true); when(entity.getField(INDIVIDUAL_LABOR_COST)).thenReturn(BigDecimal.ONE); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", BigDecimal.ONE); } @Test public void shouldReturnWhenWageDoesnotExists() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(false); when(entity.getBelongsToField(WAGE_GROUP)).thenReturn(null); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", null); } @Test public void shouldSaveCostFromWageGroup() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(false); when(entity.getBelongsToField(WAGE_GROUP)).thenReturn(wageGroup); when(wageGroup.getField(LABOR_HOURLY_COST)).thenReturn(BigDecimal.TEN); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", BigDecimal.TEN); }
DeliveriesColumnLoaderCNID { public void addColumnsForDeliveriesCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForDeliveries(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }
@Test public void shouldAddColumnsForDeliveriesCNID() { deliveriesColumnLoaderCNID.addColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderService).fillColumnsForDeliveries(Mockito.anyString()); }
DeliveriesColumnLoaderCNID { public void deleteColumnsForDeliveriesCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForDeliveries(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }
@Test public void shouldDeleteColumnsForDeliveriesCNID() { deliveriesColumnLoaderCNID.deleteColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderService).clearColumnsForDeliveries(Mockito.anyString()); }
DeliveriesColumnLoaderCNID { public void addColumnsForOrdersCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForOrders(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }
@Test public void shouldAddColumnsForOrdersCNID() { deliveriesColumnLoaderCNID.addColumnsForOrdersCNID(); verify(deliveriesColumnLoaderService).fillColumnsForOrders(Mockito.anyString()); }
DeliveriesColumnLoaderCNID { public void deleteColumnsForOrdersCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForOrders(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }
@Test public void shouldDeleteColumnsForOrdersCNID() { deliveriesColumnLoaderCNID.deleteColumnsForOrdersCNID(); verify(deliveriesColumnLoaderService).clearColumnsForOrders(Mockito.anyString()); }
OrderedProductHooksCNID { public void updateOrderedProductCatalogNumber(final DataDefinition orderedProductDD, final Entity orderedProduct) { catNumbersInDeliveriesService.updateProductCatalogNumber(orderedProduct); } void updateOrderedProductCatalogNumber(final DataDefinition orderedProductDD, final Entity orderedProduct); }
@Test public void shouldUpdateOrderedProductCatalogNumber() { orderedProductHooksCNID.updateOrderedProductCatalogNumber(orderedProductDD, orderedProduct); verify(catNumbersInDeliveriesService).updateProductCatalogNumber(orderedProduct); }
DeliveredProductHooksCNID { public void updateDeliveredProductCatalogNumber(final DataDefinition deliveredProductDD, final Entity deliveredProduct) { catNumbersInDeliveriesService.updateProductCatalogNumber(deliveredProduct); } void updateDeliveredProductCatalogNumber(final DataDefinition deliveredProductDD, final Entity deliveredProduct); }
@Test public void shouldUpdateDeliveredProductCatalogNumber() { deliveredProductHooksCNID.updateDeliveredProductCatalogNumber(deliveredProductDD, deliveredProduct); verify(catNumbersInDeliveriesService).updateProductCatalogNumber(deliveredProduct); }
DeliveryHooksCNID { public void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery) { catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); } void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); }
@Test public void shouldUpdateOrderedProductsCatalogNumbers() { deliveryHooksCNID.updateOrderedProductsCatalogNumbers(deliveryDD, delivery); verify(catNumbersInDeliveriesService).updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); }
DeliveryHooksCNID { public void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery) { catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, DELIVERED_PRODUCTS); } void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); }
@Test public void shouldUpdateDeliveredProductsCatalogNumbers() { deliveryHooksCNID.updateDeliveredProductsCatalogNumbers(deliveryDD, delivery); verify(catNumbersInDeliveriesService).updateProductsCatalogNumbers(delivery, DELIVERED_PRODUCTS); }
CatNumbersInDeliveriesServiceImpl implements CatNumbersInDeliveriesService { @Override public void updateProductCatalogNumber(final Entity deliveryProduct) { Entity delivery = deliveryProduct.getBelongsToField(DELIVERY); Entity supplier = delivery.getBelongsToField(SUPPLIER); Entity product = deliveryProduct.getBelongsToField(PRODUCT); Entity productCatalogNumber = productCatalogNumbersService.getProductCatalogNumber(product, supplier); if (productCatalogNumber != null) { deliveryProduct.setField(PRODUCT_CATALOG_NUMBER, productCatalogNumber); } } @Override void updateProductCatalogNumber(final Entity deliveryProduct); @Override void updateProductsCatalogNumbers(final Entity delivery, final String productsName); }
@Test public void shouldntUpdateProductCatalogNumberIfEntityIsntSaved() { given(deliveryProduct.getBelongsToField(DELIVERY)).willReturn(delivery); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(null); catNumbersInDeliveriesService.updateProductCatalogNumber(deliveryProduct); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); } @Test public void shouldUpdateProductCatalogNumberIfEntityIsntSaved() { given(deliveryProduct.getBelongsToField(DELIVERY)).willReturn(delivery); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(productCatalogNumber); catNumbersInDeliveriesService.updateProductCatalogNumber(deliveryProduct); verify(deliveryProduct).setField(Mockito.anyString(), Mockito.any(Entity.class)); }
CatNumbersInDeliveriesServiceImpl implements CatNumbersInDeliveriesService { @Override public void updateProductsCatalogNumbers(final Entity delivery, final String productsName) { Entity supplier = delivery.getBelongsToField(SUPPLIER); if ((delivery.getId() != null) && hasSupplierChanged(delivery.getId(), supplier)) { List<Entity> deliveryProducts = delivery.getHasManyField(productsName); if (deliveryProducts != null) { for (Entity deliveryPoduct : deliveryProducts) { Entity product = deliveryPoduct.getBelongsToField(PRODUCT); Entity productCatalogNumber = productCatalogNumbersService.getProductCatalogNumber(product, supplier); if (productCatalogNumber != null) { deliveryPoduct.setField(PRODUCT_CATALOG_NUMBER, productCatalogNumber); deliveryPoduct.getDataDefinition().save(deliveryPoduct); } } } } } @Override void updateProductCatalogNumber(final Entity deliveryProduct); @Override void updateProductsCatalogNumbers(final Entity delivery, final String productsName); }
@Test public void shouldntUpdateProductsCatalogNumbersIfEntityIsntSaved() { Long deliveryId = null; given(delivery.getId()).willReturn(deliveryId); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); verify(deliveryProductDD, never()).save(Mockito.any(Entity.class)); } @Test public void shouldntUpdateProductsCatalogNumbersIfSupplierHasntChanged() { Long deliveryId = 1L; given(delivery.getId()).willReturn(deliveryId); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); given(deliveriesService.getDelivery(deliveryId)).willReturn(existingDelivery); given(existingDelivery.getBelongsToField(SUPPLIER)).willReturn(supplier); catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); verify(deliveryProductDD, never()).save(Mockito.any(Entity.class)); } @Test public void shouldntUpdateProductsCatalogNumbersIfOrderedProductsAreNull() { Long deliveryId = 1L; given(delivery.getId()).willReturn(deliveryId); given(delivery.getBelongsToField(SUPPLIER)).willReturn(null); given(deliveriesService.getDelivery(deliveryId)).willReturn(existingDelivery); given(existingDelivery.getBelongsToField(SUPPLIER)).willReturn(existingSupplier); given(delivery.getHasManyField(ORDERED_PRODUCTS)).willReturn(null); catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); verify(deliveryProductDD, never()).save(Mockito.any(Entity.class)); } @Test public void shouldntUpdateProductsCatalogNumbersIfOrderedProductsArentNull() { Long deliveryId = 1L; given(delivery.getId()).willReturn(deliveryId); given(delivery.getBelongsToField(SUPPLIER)).willReturn(null); given(deliveriesService.getDelivery(deliveryId)).willReturn(existingDelivery); given(existingDelivery.getBelongsToField(SUPPLIER)).willReturn(existingSupplier); deliveryProducts = mockEntityList(Lists.newArrayList(deliveryProduct)); given(delivery.getHasManyField(ORDERED_PRODUCTS)).willReturn(deliveryProducts); given(deliveryProduct.getDataDefinition()).willReturn(deliveryProductDD); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(null); catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); verify(deliveryProductDD, never()).save(Mockito.any(Entity.class)); } @Ignore @Test public void shoulUpdateProductsCatalogNumbersIfOrderedProductsArentNull() { Long deliveryId = 1L; given(delivery.getId()).willReturn(deliveryId); given(delivery.getBelongsToField(SUPPLIER)).willReturn(null); given(deliveriesService.getDelivery(deliveryId)).willReturn(existingDelivery); given(existingDelivery.getBelongsToField(SUPPLIER)).willReturn(existingSupplier); deliveryProducts = mockEntityList(Lists.newArrayList(deliveryProduct)); given(delivery.getHasManyField(ORDERED_PRODUCTS)).willReturn(deliveryProducts); given(deliveryProduct.getDataDefinition()).willReturn(deliveryProductDD); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(productCatalogNumber); catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); verify(deliveryProduct).setField(Mockito.anyString(), Mockito.any(Entity.class)); verify(deliveryProductDD).save(Mockito.any(Entity.class)); }
CatNumbersInDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantEnable() { deliveriesColumnLoaderCNID.addColumnsForDeliveriesCNID(); deliveriesColumnLoaderCNID.addColumnsForOrdersCNID(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }
@Test public void shouldMultiTenantEnable() { catNumbersInDeliveriesOnStartupService.multiTenantEnable(); verify(deliveriesColumnLoaderCNID).addColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderCNID).addColumnsForOrdersCNID(); }
CatNumbersInDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantDisable() { deliveriesColumnLoaderCNID.deleteColumnsForDeliveriesCNID(); deliveriesColumnLoaderCNID.deleteColumnsForOrdersCNID(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }
@Test public void shouldMultiTenantDisable() { catNumbersInDeliveriesOnStartupService.multiTenantDisable(); verify(deliveriesColumnLoaderCNID).deleteColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderCNID).deleteColumnsForOrdersCNID(); }
ProductDetailsListenersO { public final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrders"); String url = "../page/orders/ordersList.html"; view.redirectTo(url, false, true, parameters); } final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldntShowOrdersWithProductMainIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldntShowOrdersWithProductMainIfProductIsSavedAndProductNumberIsNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(null); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldShowOrdersWithProductMainIfProductIsSavedAndProductNumberIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "[" + L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrders"); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
TransferModelHooks { public void copyProductionOrConsumptionDataFromBelongingTransformation(final DataDefinition dd, final Entity transfer) { Entity transformations = transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION); if (transformations == null) { transformations = transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION); if (transformations == null) { return; } else { transfer.setField(TYPE, CONSUMPTION.getStringValue()); transfer.setField(LOCATION_FROM, transformations.getBelongsToField(LOCATION_FROM)); } } else { transfer.setField(TYPE, PRODUCTION.getStringValue()); transfer.setField(LOCATION_TO, transformations.getBelongsToField(LOCATION_TO)); } transfer.setField(TIME, transformations.getField(TIME)); transfer.setField(STAFF, transformations.getBelongsToField(STAFF)); } void copyProductionOrConsumptionDataFromBelongingTransformation(final DataDefinition dd, final Entity transfer); }
@Test public void shouldCopyProductionDataFromBelongingTransformation() { given(transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION)).willReturn(transformation); given(transformation.getField(TIME)).willReturn("1234"); given(transformation.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transformation.getBelongsToField(LOCATION_TO)).willReturn(locationTo); given(transformation.getBelongsToField(STAFF)).willReturn(staff); materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer).setField(TYPE, PRODUCTION.getStringValue()); verify(transfer).setField(TIME, "1234"); verify(transfer).setField(LOCATION_TO, locationTo); verify(transfer).setField(STAFF, staff); } @Test public void shouldCopyConsumptionDataFromBelongingTransformation() { given(transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION)).willReturn(transformation); given(transformation.getField(TIME)).willReturn("1234"); given(transformation.getBelongsToField(LOCATION_TO)).willReturn(locationTo); given(transformation.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transformation.getBelongsToField(STAFF)).willReturn(staff); materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer).setField(TYPE, CONSUMPTION.getStringValue()); verify(transfer).setField(TIME, "1234"); verify(transfer).setField(LOCATION_FROM, locationFrom); verify(transfer).setField(STAFF, staff); } @Test public void shouldNotTriggerCopyingWhenSavingPlainTransfer() { materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer, never()).setField(anyString(), any()); }
ProductDetailsListenersO { public final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrdersPlanning"); String url = "../page/orders/ordersPlanningList.html"; view.redirectTo(url, false, true, parameters); } final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldntShowOrdersWithProductPlannedIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldntShowOrdersWithProductPlannedIfProductIsSavedAndProductNumberIsNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(null); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldShowOrdersWithProductPlannedIfProductIsSavedAndProductNumberIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "[" + L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrdersPlanning"); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
ParametersListenersO { public void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { Long parameterId = (Long) componentState.getFieldValue(); if (parameterId != null) { String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; view.redirectTo(url, false, true); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState, final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldRedirectToOrdersParametersIfParameterIdIsntNull() { Long parameterId = 1L; given(componentState.getFieldValue()).willReturn(parameterId); String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; parametersListenersO.redirectToOrdersParameters(view, componentState, null); verify(view).redirectTo(url, false, true); } @Test public void shouldntRedirectToOrdersParametersIfParameterIdIsNull() { Long parameterId = null; given(componentState.getFieldValue()).willReturn(parameterId); String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; parametersListenersO.redirectToOrdersParameters(view, componentState, null); verify(view, never()).redirectTo(url, false, true); }
ParametersListenersO { public void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState, final ComponentState componentState, final String[] args) { Long dictionaryId = getDictionaryId("reasonTypeOfChangingOrderState"); if (dictionaryId != null) { String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; viewDefinitionState.redirectTo(url, false, true); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState, final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldRedirectToDeviationsDictionaryIfDictionaryIdIsntNull() { Long dictionaryId = 1L; given(dataDefinitionService.get("smartModel", "dictionary")).willReturn(dictionaryDD); given(dictionaryDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(SearchRestrictions.eq("name", "reasonTypeOfChangingOrderState"))).willReturn( searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(dictionary); given(dictionary.getId()).willReturn(dictionaryId); String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; parametersListenersO.redirectToDeviationsDictionary(view, componentState, null); verify(view).redirectTo(url, false, true); } @Test public void shouldntRedirectToDeviationsDictionaryfDictionaryIdIsnull() { Long dictionaryId = null; given(dataDefinitionService.get("smartModel", "dictionary")).willReturn(dictionaryDD); given(dictionaryDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(SearchRestrictions.eq("name", "reasonTypeOfChangingOrderState"))).willReturn( searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(null); String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; parametersListenersO.redirectToDeviationsDictionary(view, componentState, null); verify(view, never()).redirectTo(url, false, true); }
ParametersListenersO { public void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { String componentStateName = componentState.getName(); if (REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); } else if (REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); } else if (REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); } else if (REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState, final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }
@Test public void shouldShowTimeFieldForDelayedEffectiveDateFrom() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); } @Test public void shouldShowTimeFieldForEarlierEffectiveDateFrom() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); } @Test public void shouldShowTimeFieldForDelayedEffectiveDateTo() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); } @Test public void shouldShowTimeFieldForEarlierEffectiveDateTo() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); }
ParametersHooksO { public void showTimeFields(final ViewDefinitionState view) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } void showTimeFields(final ViewDefinitionState view); void hideTabs(final ViewDefinitionState view); }
@Test public void shouldShowTimeFields() { parametersHooksO.showTimeFields(view); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); }
ProductDetailsViewHooksO { public void updateRibbonState(final ViewDefinitionState view) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup orders = (RibbonGroup) window.getRibbon().getGroupByName("orders"); RibbonActionItem showOrdersWithProductMain = (RibbonActionItem) orders.getItemByName("showOrdersWithProductMain"); RibbonActionItem showOrdersWithProductPlanned = (RibbonActionItem) orders.getItemByName("showOrdersWithProductPlanned"); if (product.getId() != null) { updateButtonState(showOrdersWithProductMain, true); updateButtonState(showOrdersWithProductPlanned, true); return; } updateButtonState(showOrdersWithProductMain, false); updateButtonState(showOrdersWithProductPlanned, false); } void updateRibbonState(final ViewDefinitionState view); }
@Test public void shouldntUpdateRibbonStateIfProductIsntSaved() { given(product.getId()).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(orders.getItemByName("showOrdersWithProductMain")).willReturn(showOrdersWithProductMain); given(orders.getItemByName("showOrdersWithProductPlanned")).willReturn(showOrdersWithProductPlanned); productDetailsViewHooksO.updateRibbonState(view); verify(showOrdersWithProductMain).setEnabled(false); verify(showOrdersWithProductPlanned).setEnabled(false); } @Test public void shouldUpdateRibbonStateIfProductIsSaved() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(orders.getItemByName("showOrdersWithProductMain")).willReturn(showOrdersWithProductMain); given(orders.getItemByName("showOrdersWithProductPlanned")).willReturn(showOrdersWithProductPlanned); productDetailsViewHooksO.updateRibbonState(view); verify(showOrdersWithProductMain).setEnabled(true); verify(showOrdersWithProductPlanned).setEnabled(true); }
CommonReasonTypeModelHooks { public void updateDate(final Entity reasonTypeEntity, final DeviationModelDescriber deviationModelDescriber) { if (reasonHasNotBeenSavedYet(reasonTypeEntity) || reasonHasChanged(reasonTypeEntity, deviationModelDescriber)) { reasonTypeEntity.setField(CommonReasonTypeFields.DATE, new Date()); } } void updateDate(final Entity reasonTypeEntity, final DeviationModelDescriber deviationModelDescriber); }
@Test public final void shouldSetCurrentDateOnUpdate() { Date dateBefore = new Date(); stubReasonEntityId(1L); stubFindResults(false); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity).setField(eq(CommonReasonTypeFields.DATE), dateCaptor.capture()); Date capturedDate = dateCaptor.getValue(); Date dateAfter = new Date(); Assert.assertTrue(capturedDate.compareTo(dateBefore) >= 0 && capturedDate.compareTo(dateAfter) <= 0); } @Test public final void shouldSetCurrentDateOnCreate() { Date dateBefore = new Date(); stubReasonEntityId(null); stubFindResults(false); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity).setField(eq(CommonReasonTypeFields.DATE), dateCaptor.capture()); Date capturedDate = dateCaptor.getValue(); Date dateAfter = new Date(); Assert.assertTrue(capturedDate.compareTo(dateBefore) >= 0 && capturedDate.compareTo(dateAfter) <= 0); } @Test public final void shouldNotSetCurrentDateIfTypeFieldValueDidNotChange() { stubReasonEntityId(1L); stubFindResults(true); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity, never()).setField(eq(CommonReasonTypeFields.DATE), any()); }
OrderHooks { public boolean checkOrderDates(final DataDefinition orderDD, final Entity order) { DateRange orderDateRange = orderDatesService.getCalculatedDates(order); Date dateFrom = orderDateRange.getFrom(); Date dateTo = orderDateRange.getTo(); if (dateFrom == null || dateTo == null || dateTo.after(dateFrom)) { return true; } order.addError(orderDD.getField(OrderFields.FINISH_DATE), "orders.validate.global.error.datesOrder"); return false; } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order, final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }
@Test public void shouldReturnTrueForValidOrderDates() throws Exception { DateRange dateRange = new DateRange(new Date(System.currentTimeMillis() - 10000), new Date()); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); boolean result = orderHooks.checkOrderDates(orderDD, order); assertTrue(result); } @Test public void shouldReturnTrueForNullDates() throws Exception { DateRange dateRange = new DateRange(null, null); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); boolean result = orderHooks.checkOrderDates(orderDD, order); assertTrue(result); } @Test public void shouldReturnTrueForNullFromDate() throws Exception { DateRange dateRange = new DateRange(null, new Date()); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); boolean result = orderHooks.checkOrderDates(orderDD, order); assertTrue(result); } @Test public void shouldReturnTrueForNullToDate() throws Exception { DateRange dateRange = new DateRange(new Date(), null); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); boolean result = orderHooks.checkOrderDates(orderDD, order); assertTrue(result); } @Test public void shouldReturnFalseForInvalidOrderDates() throws Exception { DateRange dateRange = new DateRange(new Date(), new Date(System.currentTimeMillis() - 10000)); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); given(orderDD.getField(OrderFields.FINISH_DATE)).willReturn(dateToField); boolean result = orderHooks.checkOrderDates(orderDD, order); assertFalse(result); verify(order).addError(dateToField, "orders.validate.global.error.datesOrder"); } @Test public void shouldReturnFalseForEqualOrderDates() throws Exception { Date currDate = new Date(); DateRange dateRange = new DateRange(currDate, currDate); given(orderDatesService.getCalculatedDates(order)).willReturn(dateRange); given(orderDD.getField(OrderFields.FINISH_DATE)).willReturn(dateToField); boolean result = orderHooks.checkOrderDates(orderDD, order); assertFalse(result); verify(order).addError(dateToField, "orders.validate.global.error.datesOrder"); }
LineChangeoverNormsHooks { public boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm) { String changeoverType = changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE); if (changeoverType.equals(ChangeoverType.FOR_TECHNOLOGY.getStringValue())) { for (String reference : Arrays.asList(FROM_TECHNOLOGY, TO_TECHNOLOGY)) { if (changeoverNorm.getBelongsToField(reference) == null) { changeoverNorm.addError(changeoverNorm.getDataDefinition().getField(reference), L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_FIELD_IS_REQUIRED); return false; } } } else { for (String reference : Arrays.asList(FROM_TECHNOLOGY_GROUP, TO_TECHNOLOGY_GROUP)) { if (changeoverNorm.getBelongsToField(reference) == null) { changeoverNorm.addError(changeoverNorm.getDataDefinition().getField(reference), L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_FIELD_IS_REQUIRED); return false; } } } return true; } boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm); boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm); }
@Test public void shouldReturnErrorWhenRequiredFieldForTechnologyIsNotFill() { given(changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE)).willReturn("01forTechnology"); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY)).willReturn(null); given(changeoverNorm.getDataDefinition()).willReturn(changeoverNormDD); given(changeoverNormDD.getField(FROM_TECHNOLOGY)).willReturn(field); boolean result = hooks.checkRequiredField(changeoverNormDD, changeoverNorm); Assert.isTrue(!result); verify(changeoverNorm).addError(field, L_ERROR); } @Test public void shouldReturnErrorWhenRequiredFieldForTechnologyGroupIsNotFill() throws Exception { given(changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE)).willReturn("02forTechnologyGroup"); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP)).willReturn(fromTechnologyGroup); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP)).willReturn(null); given(changeoverNorm.getDataDefinition()).willReturn(changeoverNormDD); given(changeoverNormDD.getField(TO_TECHNOLOGY_GROUP)).willReturn(field); boolean result = hooks.checkRequiredField(changeoverNormDD, changeoverNorm); Assert.isTrue(!result); verify(changeoverNorm).addError(field, L_ERROR); }
OrderHooks { public boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order) { Entity product = order.getBelongsToField(OrderFields.PRODUCT); if (product == null) { return true; } BigDecimal plannedQuantity = order.getDecimalField(OrderFields.PLANNED_QUANTITY); if (plannedQuantity == null) { order.addError(orderDD.getField(OrderFields.PLANNED_QUANTITY), "orders.validate.global.error.plannedQuantityError"); return false; } else { return true; } } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order, final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }
@Test public void shouldReturnTrueForPlannedQuantityValidationIfThereIsNoProduct() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, null); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertTrue(result); } @Test public void shouldReturnTrueForPlannedQuantityValidation() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, product); stubDecimalField(order, OrderFields.PLANNED_QUANTITY, BigDecimal.ONE); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertTrue(result); } @Test public void shouldReturnFalseForPlannedQuantityValidation() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, product); stubDecimalField(order, OrderFields.PLANNED_QUANTITY, null); given(orderDD.getField(OrderFields.PLANNED_QUANTITY)).willReturn(plannedQuantityField); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertFalse(result); verify(order).addError(plannedQuantityField, "orders.validate.global.error.plannedQuantityError"); }
OrderHooks { public void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order) { order.setField(OrderFields.STATE, OrderState.PENDING.getStringValue()); order.setField(OrderFields.EFFECTIVE_DATE_TO, null); order.setField(OrderFields.EFFECTIVE_DATE_FROM, null); order.setField(OrderFields.CORRECTED_DATE_FROM, null); order.setField(OrderFields.CORRECTED_DATE_TO, null); order.setField(OrderFields.DATE_FROM, order.getDateField(OrderFields.START_DATE)); order.setField(OrderFields.DATE_TO, order.getDateField(OrderFields.FINISH_DATE)); order.setField(OrderFields.DONE_QUANTITY, null); order.setField(OrderFields.WASTES_QUANTITY, null); order.setField(OrderFields.EXTERNAL_NUMBER, null); order.setField(OrderFields.EXTERNAL_SYNCHRONIZED, true); order.setField(OrderFields.COMMENT_REASON_TYPE_CORRECTION_DATE_FROM, null); order.setField(OrderFields.COMMENT_REASON_TYPE_CORRECTION_DATE_TO, null); order.setField(OrderFields.COMMENT_REASON_DEVIATION_EFFECTIVE_END, null); order.setField(OrderFields.COMMENT_REASON_DEVIATION_EFFECTIVE_START, null); order.setField(OrderFields.COMMENT_REASON_TYPE_DEVIATIONS_QUANTITY, null); } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order, final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }
@Test public void shouldClearOrderFieldsOnCopy() throws Exception { Date startDate = new Date(); Date finishDate = new Date(); stubDateField(order, OrderFields.START_DATE, startDate); stubDateField(order, OrderFields.FINISH_DATE, finishDate); orderHooks.clearOrSetSpecyfiedValueOrderFieldsOnCopy(orderDD, order); verify(order).setField(OrderFields.STATE, OrderState.PENDING.getStringValue()); verify(order).setField(OrderFields.EFFECTIVE_DATE_TO, null); verify(order).setField(OrderFields.EFFECTIVE_DATE_FROM, null); verify(order).setField(OrderFields.CORRECTED_DATE_FROM, null); verify(order).setField(OrderFields.CORRECTED_DATE_TO, null); verify(order).setField(OrderFields.DONE_QUANTITY, null); verify(order).setField(OrderFields.DATE_FROM, startDate); verify(order).setField(OrderFields.DATE_TO, finishDate); }
OrderHooks { void setCopyOfTechnology(final Entity order) { if (orderService.isPktEnabled()) { order.setField(OrderFields.TECHNOLOGY, copyTechnology(order).orNull()); } else { Entity prototypeTechnology = order.getBelongsToField(OrderFields.TECHNOLOGY_PROTOTYPE); if (prototypeTechnology != null && TechnologyState.of(prototypeTechnology).compareTo(TechnologyState.ACCEPTED) == 0) { order.setField(OrderFields.TECHNOLOGY, prototypeTechnology); } else { order.setField(OrderFields.TECHNOLOGY, null); order.setField(OrderFields.TECHNOLOGY_PROTOTYPE, null); } } } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order, final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }
@Test public final void shouldNotSetCopyOfTechnology() { given(orderService.isPktEnabled()).willReturn(true); stubBelongsToField(order, OrderFields.TECHNOLOGY, null); orderHooks.setCopyOfTechnology(order); verify(order, never()).setField(eq(OrderFields.TECHNOLOGY), notNull()); } @Test public final void shouldSetCopyOfTechnology() { final String generatedNumber = "NEWLY GENERATED NUM"; given(technologyServiceO.generateNumberForTechnologyInOrder(eq(order), any(Entity.class))).willReturn(generatedNumber); given(orderService.isPktEnabled()).willReturn(true); DataDefinition technologyDD = mock(DataDefinition.class); Entity technology = mockEntity(technologyDD); Entity technologyCopy = mockEntity(technologyDD); given(technologyDD.copy(any(Long[].class))).willReturn(ImmutableList.of(technologyCopy)); given(technologyDD.save(any(Entity.class))).willAnswer(new Answer<Entity>() { @Override public Entity answer(final InvocationOnMock invocation) throws Throwable { return (Entity) invocation.getArguments()[0]; } }); stubBelongsToField(order, OrderFields.TECHNOLOGY, technology); stubStringField(order, OrderFields.ORDER_TYPE, OrderType.WITH_OWN_TECHNOLOGY.getStringValue()); orderHooks.setCopyOfTechnology(order); verify(order).setField(OrderFields.TECHNOLOGY, technologyCopy); verify(order, never()).setField(OrderFields.TECHNOLOGY, technology); verify(technologyCopy).setField(TechnologyFields.NUMBER, generatedNumber); }
OrderDetailsHooks { public void setAndDisableState(final ViewDefinitionState view) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent stateField = (FieldComponent) view.getComponentByReference(OrderFields.STATE); stateField.setEnabled(false); if (orderForm.getEntityId() != null) { return; } stateField.setFieldValue(OrderState.PENDING.getStringValue()); } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology, final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }
@Test public void shouldSetAndDisableState() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(null); orderDetailsHooks.setAndDisableState(view); verify(stateField).setEnabled(false); verify(stateField).setFieldValue(OrderState.PENDING.getStringValue()); } @Test public void shouldDisableState() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(L_ID); orderDetailsHooks.setAndDisableState(view); verify(stateField).setEnabled(false); verify(stateField, never()).setFieldValue(OrderState.PENDING.getStringValue()); }
MaterialsInLocationComponentModelValidators { public boolean checkMaterialFlowComponentUniqueness(final DataDefinition materialsInLocationComponentDD, final Entity materialsInLocationComponent) { Entity location = materialsInLocationComponent.getBelongsToField(LOCATION); Entity materialsInLocation = materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION); if (materialsInLocation == null || location == null) { return false; } SearchResult searchResult = materialsInLocationComponentDD.find().add(SearchRestrictions.belongsTo(LOCATION, location)) .add(SearchRestrictions.belongsTo(MATERIALS_IN_LOCATION, materialsInLocation)).list(); if (searchResult.getTotalNumberOfEntities() == 1 && !searchResult.getEntities().get(0).getId().equals(materialsInLocationComponent.getId())) { materialsInLocationComponent.addError(materialsInLocationComponentDD.getField(LOCATION), "materialFlow.validate.global.error.materialsInLocationDuplicated"); return false; } else { return true; } } boolean checkMaterialFlowComponentUniqueness(final DataDefinition materialsInLocationComponentDD, final Entity materialsInLocationComponent); }
@Test public void shouldReturnFalseWhenCheckMaterialFlowComponentUniquenessAndMaterialsInLocationOrLocationIsNull() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(null); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(null); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertFalse(result); } @Test public void shouldReturnFalseAndAddErrorWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsntUnique() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(location); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(materialsInLocation); given(materialsInLocationComponentDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.list()).willReturn(searchResult); given(searchResult.getTotalNumberOfEntities()).willReturn(1); given(searchResult.getEntities()).willReturn(entities); given(entities.get(0)).willReturn(materialsInLocationComponentOther); given(materialsInLocationComponent.getId()).willReturn(L_ID); given(materialsInLocationComponentOther.getId()).willReturn(L_ID_OTHER); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertFalse(result); Mockito.verify(materialsInLocationComponent).addError(Mockito.eq(materialsInLocationComponentDD.getField(LOCATION)), Mockito.anyString()); } @Test public void shouldReturnTrueWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsUnique() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(location); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(materialsInLocation); given(materialsInLocationComponentDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.list()).willReturn(searchResult); given(searchResult.getTotalNumberOfEntities()).willReturn(0); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertTrue(result); }
OrderDetailsHooks { public void generateOrderNumber(final ViewDefinitionState view) { numberGeneratorService.generateAndInsertNumber(view, OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER, L_FORM, OrderFields.NUMBER); } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology, final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }
@Test public void shouldGenerateOrderNumber() throws Exception { orderDetailsHooks.generateOrderNumber(view); verify(numberGeneratorService).generateAndInsertNumber(view, OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER, L_FORM, OrderFields.NUMBER); }