@Override
  @Transactional
  public void updateResourcesForReleaseDocuments(final Entity document) {
    Entity warehouse = document.getBelongsToField(DocumentFields.LOCATION_FROM);
    WarehouseAlgorithm warehouseAlgorithm;

    boolean enoughResources = true;

    StringBuilder errorMessage = new StringBuilder();

    Multimap<Long, BigDecimal> quantitiesForWarehouse =
        getQuantitiesInWarehouse(warehouse, getProductsAndPositionsFromDocument(document));

    List<Entity> generatedPositions = Lists.newArrayList();

    for (Entity position : document.getHasManyField(DocumentFields.POSITIONS)) {
      Entity product = position.getBelongsToField(PositionFields.PRODUCT);
      Entity resource = position.getBelongsToField(PositionFields.RESOURCE);

      BigDecimal quantityInWarehouse;

      if (resource != null) {
        warehouse = resource.getBelongsToField(ResourceFields.LOCATION);
        warehouseAlgorithm = WarehouseAlgorithm.MANUAL;
      } else {
        warehouse = document.getBelongsToField(DocumentFields.LOCATION_FROM);
        warehouseAlgorithm =
            WarehouseAlgorithm.parseString(warehouse.getStringField(LocationFieldsMFR.ALGORITHM));
      }

      if (warehouseAlgorithm.equals(WarehouseAlgorithm.MANUAL)) {
        quantityInWarehouse = getQuantityOfProductInWarehouse(warehouse, product, position);
      } else {
        quantityInWarehouse = getQuantityOfProductFromMultimap(quantitiesForWarehouse, product);
      }

      generatedPositions.addAll(updateResources(warehouse, position, warehouseAlgorithm));

      enoughResources = enoughResources && position.isValid();

      if (!position.isValid()) {
        BigDecimal quantity = position.getDecimalField(QUANTITY);

        errorMessage.append(product.getStringField(ProductFields.NAME));
        errorMessage.append(" - ");
        errorMessage.append(numberService.format(quantity.subtract(quantityInWarehouse)));
        errorMessage.append(" ");
        errorMessage.append(product.getStringField(ProductFields.UNIT));
        errorMessage.append(", ");
      }
    }

    if (!enoughResources) {
      addDocumentError(document, warehouse, errorMessage);
    } else {
      deleteReservations(document);
      document.setField(DocumentFields.POSITIONS, generatedPositions);
    }
  }
  @Test
  public final void shouldNotSaveFormAndCorrectedProgressesDueToDailyProgressesValidationErrors() {
    // given
    Long tocId = 1001L;

    Entity pfd1dp1 = mockDailyProgress();
    Entity pfd1dp2 = mockDailyProgress();
    Entity pfd1 = mockProgressForDayEntity(pfd1dp1, pfd1dp2);

    Entity pfd2dp1 = mockDailyProgress();
    Entity pfd2 = mockProgressForDayEntity(pfd2dp1);
    given(pfd2.isValid()).willReturn(false);
    Entity invalidPfd2dp1 = mockDailyProgress();
    given(invalidPfd2dp1.isValid()).willReturn(false);
    given(dataDefinition.save(pfd2dp1)).willReturn(invalidPfd2dp1);

    stubProgressForDaysAdlEntities(pfd1, pfd2);

    stubProgressType(ProgressType.PLANNED);

    Entity technologyOperation = mockEntity(tocId, dataDefinition);
    given(technologyOperation.isValid()).willReturn(true);
    stubTechnologyOperation(technologyOperation);

    given(ppsEntity.isValid()).willReturn(true);

    // when
    progressPerShiftViewSaver.save(view);

    // then
    verify(txStatus, times(4))
        .setRollbackOnly(); // one rollback for each DailyProgress + 1 global rollback
    verifyTocSetupAbsence(technologyOperation);

    verify(dataDefinition).save(pfd1dp1);
    verify(dataDefinition).save(pfd1dp2);
    verify(dataDefinition, never()).save(pfd1);
    verify(pfd1).setField(ProgressForDayFields.CORRECTED, false);
    verify(pfd1).setField(ProgressForDayFields.TECHNOLOGY_OPERATION_COMPONENT, tocId);

    verify(dataDefinition).save(pfd2dp1);
    verify(pfd2).setNotValid();
    verify(dataDefinition, never()).save(pfd2);
    verify(pfd2, never()).setField(ProgressForDayFields.CORRECTED, false);
    verify(pfd2, never()).setField(ProgressForDayFields.TECHNOLOGY_OPERATION_COMPONENT, tocId);

    verify(dataDefinition, never()).save(ppsEntity);

    verify(form)
        .addMessage("qcadooView.message.saveFailedMessage", ComponentState.MessageType.FAILURE);
  }
  @Test
  public final void shouldSaveFormAndCorrectedProgresses() {
    // given
    Long tocId = 1001L;

    Entity pfd1dp1 = mockDailyProgress();
    Entity pfd1dp2 = mockDailyProgress();
    Entity pfd1 = mockProgressForDayEntity(pfd1dp1, pfd1dp2);

    Entity pfd2dp1 = mockDailyProgress();
    Entity pfd2 = mockProgressForDayEntity(pfd2dp1);

    stubProgressForDaysAdlEntities(pfd1, pfd2);

    stubProgressType(ProgressType.CORRECTED);

    Entity technologyOperation = mockEntity(tocId, dataDefinition);
    given(technologyOperation.isValid()).willReturn(true);
    stubTechnologyOperation(technologyOperation);

    given(ppsEntity.isValid()).willReturn(true);

    List<Entity> plannedPfds = Lists.newArrayList(mockEntity(), mockEntity(), mockEntity());
    stubPfdDataProviderFindForoperation(plannedPfds);

    // when
    progressPerShiftViewSaver.save(view);

    // then
    verify(txStatus, times(3)).setRollbackOnly(); // one rollback for each DailyProgress
    List<Entity> expectedPfds =
        Lists.newLinkedList(Iterables.concat(plannedPfds, Lists.newArrayList(pfd1, pfd2)));
    verifyTocSetup(technologyOperation, expectedPfds, true);

    verify(dataDefinition).save(pfd1dp1);
    verify(dataDefinition).save(pfd1dp2);
    verify(dataDefinition).save(pfd1);
    verify(pfd1).setField(ProgressForDayFields.CORRECTED, true);
    verify(pfd1).setField(ProgressForDayFields.TECHNOLOGY_OPERATION_COMPONENT, tocId);

    verify(dataDefinition).save(pfd2dp1);
    verify(dataDefinition).save(pfd2);
    verify(pfd2).setField(ProgressForDayFields.CORRECTED, true);
    verify(pfd2).setField(ProgressForDayFields.TECHNOLOGY_OPERATION_COMPONENT, tocId);

    verify(dataDefinition).save(ppsEntity);

    verify(form).addMessage("qcadooView.message.saveMessage", ComponentState.MessageType.SUCCESS);
  }
  @Override
  @Transactional
  public void moveResourcesForTransferDocument(Entity document) {
    Entity warehouseFrom = document.getBelongsToField(DocumentFields.LOCATION_FROM);
    Entity warehouseTo = document.getBelongsToField(DocumentFields.LOCATION_TO);
    Object date = document.getField(DocumentFields.TIME);

    WarehouseAlgorithm warehouseAlgorithm =
        WarehouseAlgorithm.parseString(warehouseFrom.getStringField(LocationFieldsMFR.ALGORITHM));

    boolean enoughResources = true;

    StringBuilder errorMessage = new StringBuilder();

    Multimap<Long, BigDecimal> quantitiesForWarehouse =
        getQuantitiesInWarehouse(warehouseFrom, getProductsAndPositionsFromDocument(document));

    for (Entity position : document.getHasManyField(DocumentFields.POSITIONS)) {
      Entity product = position.getBelongsToField(PositionFields.PRODUCT);
      BigDecimal quantityInWarehouse;

      if (warehouseAlgorithm.equals(WarehouseAlgorithm.MANUAL)) {
        quantityInWarehouse = getQuantityOfProductInWarehouse(warehouseFrom, product, position);
      } else {
        quantityInWarehouse = getQuantityOfProductFromMultimap(quantitiesForWarehouse, product);
      }

      moveResources(warehouseFrom, warehouseTo, position, date, warehouseAlgorithm);
      enoughResources = enoughResources && position.isValid();

      if (!position.isValid()) {
        BigDecimal quantity = position.getDecimalField(QUANTITY);

        errorMessage.append(product.getStringField(ProductFields.NAME));
        errorMessage.append(" - ");
        errorMessage.append(numberService.format(quantity.subtract(quantityInWarehouse)));
        errorMessage.append(" ");
        errorMessage.append(product.getStringField(ProductFields.UNIT));
        errorMessage.append(", ");
      }
    }

    if (!enoughResources) {
      addDocumentError(document, warehouseFrom, errorMessage);
    } else {
      deleteReservations(document);
    }
  }
  @Test
  public void shouldNotCallAdditinanalFieldValidatorsIfPluginIsSystemDisabled() throws Exception {
    // given
    DataDefinition machineDao =
        dataDefinitionService.get(PLUGIN_MACHINES_NAME, ENTITY_NAME_MACHINE);
    machineDao.save(createMachine("asd"));

    pluginManager.disablePlugin(PLUGIN_MACHINES_NAME);

    DataDefinition productDao =
        dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_PRODUCT);
    DataDefinition componentDao =
        dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_COMPONENT);

    Entity product = createProduct("asd", "asd");
    product = productDao.save(product);

    Entity component = createComponent("name", product, null);
    component.setField("machineDescription", "as");

    // when
    component = componentDao.save(component);

    // then
    Assert.assertTrue(component.isValid());
  }
  @Test
  public final void shouldSaveAndSetOwnerEntity() {
    // given
    given(owner.isValid()).willReturn(true);
    given(savedOwner.isValid()).willReturn(true);
    given(ownerDD.save(owner)).willReturn(savedOwner);

    // when
    stateChangeContext.setOwner(owner);

    // then
    verify(ownerDD).save(owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner);
    verify(stateChangeEntity).setField(describer.getOwnerFieldName(), savedOwner);
    verify(messageService, never())
        .addValidationError(
            Mockito.eq(stateChangeContext),
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.any(String[].class));
    verify(messageService, never())
        .addValidationError(
            Mockito.eq(stateChangeContext),
            Mockito.eq((String) null),
            Mockito.anyString(),
            Mockito.any(String[].class));
    verify(stateChangeEntity, never())
        .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue());
  }
  @Test
  public void shouldNotCallAdditinanalFieldValidatorsIfPluginIsDisabledForCurrentUser()
      throws Exception {
    // given
    DataDefinition machineDao =
        dataDefinitionService.get(PLUGIN_MACHINES_NAME, ENTITY_NAME_MACHINE);
    machineDao.save(createMachine("asd"));

    pluginManager.enablePlugin(PLUGIN_MACHINES_NAME);

    // This should be considered as an anti-pattern. Replacing static fields with mocks in an
    // integration test suite weren't
    // my smartest idea ever..
    PluginStateResolver pluginStateResolver = mock(PluginStateResolver.class);
    PluginUtilsService pluginUtil = new PluginUtilsService(pluginStateResolver);
    pluginUtil.init();
    given(pluginStateResolver.isEnabled(PLUGIN_MACHINES_NAME)).willReturn(false);

    DataDefinition productDao =
        dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_PRODUCT);
    DataDefinition componentDao =
        dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_COMPONENT);

    Entity product = createProduct("asd", "asd");
    product = productDao.save(product);

    Entity component = createComponent("name", product, null);
    component.setField("machineDescription", "as");

    // when
    component = componentDao.save(component);

    // then
    Assert.assertTrue(component.isValid());
  }
  @Test
  public final void shouldNotSaveFormBecauseOfDeviationCausesValidationErrors() {
    // given
    stubProgressType(ProgressType.PLANNED);
    stubTechnologyOperation(null);

    Entity deviationCauseEntity = mockEntity(dataDefinition);
    Entity invalidDeviationCauseEntity = mockEntity(dataDefinition);
    given(invalidDeviationCauseEntity.isValid()).willReturn(false);
    given(dataDefinition.save(deviationCauseEntity)).willReturn(invalidDeviationCauseEntity);

    AwesomeDynamicListComponent deviationCausesAdl = mock(AwesomeDynamicListComponent.class);
    stubViewComponent(CORRECTION_CAUSE_TYPES_ADL_REF, deviationCausesAdl);
    stubHasManyField(
        ppsEntity,
        ProductionPerShiftFields.PLANNED_PROGRESS_CORRECTION_TYPES,
        Lists.newArrayList(deviationCauseEntity));

    // when
    progressPerShiftViewSaver.save(view);

    // then
    verify(txStatus, never()).setRollbackOnly();

    verify(dataDefinition).save(deviationCauseEntity);
    verify(dataDefinition, never()).save(ppsEntity);
    verify(deviationCausesAdl).setFieldValue(Lists.newArrayList(invalidDeviationCauseEntity));
    verify(form)
        .addMessage("qcadooView.message.saveFailedMessage", ComponentState.MessageType.FAILURE);
  }
 private Entity mockProgressForDayEntity(final Entity... dailyProgresses) {
   Entity pfdEntity = mockEntity(dataDefinition);
   stubHasManyField(
       pfdEntity, ProgressForDayFields.DAILY_PROGRESS, Arrays.asList(dailyProgresses));
   given(pfdEntity.isValid()).willReturn(true);
   return pfdEntity;
 }
  @Test
  public final void shouldSaveButNotSetJustInvalidateOwnerEntity() {
    // given
    given(owner.isValid()).willReturn(true);
    given(ownerDD.save(owner)).willReturn(savedOwner);
    given(savedOwner.isValid()).willReturn(false);

    final Map<String, ErrorMessage> fieldErrorsMap = Maps.newHashMap();
    final ErrorMessage fieldErrorMessage = buildErrorMessage(FIELD_1_MESSAGE_1);
    fieldErrorsMap.put(FIELD_1_NAME, fieldErrorMessage);
    given(savedOwner.getErrors()).willReturn(fieldErrorsMap);

    final List<ErrorMessage> globalErrors = Lists.newArrayList();
    final ErrorMessage globalErrorMessage = buildErrorMessage(GLOBAL_MESSAGE_1);
    globalErrors.add(globalErrorMessage);
    given(savedOwner.getGlobalErrors()).willReturn(globalErrors);

    // when
    stateChangeContext.setOwner(owner);

    // then
    verify(ownerDD).save(owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), savedOwner);
    verify(messageService)
        .addValidationError(
            stateChangeContext, FIELD_1_NAME, FIELD_1_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(messageService)
        .addValidationError(stateChangeContext, null, GLOBAL_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(stateChangeEntity)
        .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue());
  }
  @Test
  public final void
      shouldMarkEntityAsInvalidAndSetStateToFailureIfStateChangeEntityIsInvalidAfterSave() {
    // given
    final Entity savedStateChangeEntity = mock(Entity.class);
    given(stateChangeEntity.isValid()).willReturn(true);
    given(savedStateChangeEntity.isValid()).willReturn(true, false);
    given(stateChangeDD.save(stateChangeEntity)).willReturn(savedStateChangeEntity);

    final Map<String, ErrorMessage> fieldErrorsMap = Maps.newHashMap();
    final ErrorMessage fieldErrorMessage = buildErrorMessage(FIELD_1_MESSAGE_1);
    fieldErrorsMap.put(FIELD_1_NAME, fieldErrorMessage);
    given(savedStateChangeEntity.getErrors()).willReturn(fieldErrorsMap);

    final List<ErrorMessage> globalErrors = Lists.newArrayList();
    final ErrorMessage globalErrorMessage = buildErrorMessage(GLOBAL_MESSAGE_1);
    globalErrors.add(globalErrorMessage);
    given(savedStateChangeEntity.getGlobalErrors()).willReturn(globalErrors);

    // when
    stateChangeContext.save();

    // then
    verify(messageService)
        .addValidationError(
            stateChangeContext, FIELD_1_NAME, FIELD_1_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(messageService)
        .addValidationError(stateChangeContext, null, GLOBAL_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(stateChangeEntity).setField(describer.getStatusFieldName(), FAILURE.getStringValue());
  }
Beispiel #12
0
  /**
   * Save document in database and creates resources if document is accepted.
   *
   * @return Created document entity.
   */
  public Entity build() {
    DataDefinition documentDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_DOCUMENT);

    document.setField(DocumentFields.POSITIONS, positions);
    Entity savedDocument = documentDD.save(document);
    if (savedDocument.isValid() && DocumentState.of(document) == DocumentState.ACCEPTED) {
      createResources(savedDocument);
      if (!savedDocument.isValid()) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }
    }

    return savedDocument;
  }
  @Test
  public final void shouldSaveOnlyForm() {
    // given
    stubProgressType(ProgressType.PLANNED);
    stubTechnologyOperation(null);
    given(ppsEntity.isValid()).willReturn(true);

    // when
    progressPerShiftViewSaver.save(view);

    // then
    verify(txStatus, never()).setRollbackOnly();

    verify(dataDefinition).save(ppsEntity);
    verify(form).addMessage("qcadooView.message.saveMessage", ComponentState.MessageType.SUCCESS);
  }
  private void enableAddButton(ViewDefinitionState view) {
    FormComponent form = (FormComponent) view.getComponentByReference(L_FORM);
    Entity multiAssignment = form.getPersistedEntityWithIncludedFormValues();

    GridComponent workersComponent = (GridComponent) view.getComponentByReference("workers");
    WindowComponent window = (WindowComponent) view.getComponentByReference("window");
    RibbonGroup add = (RibbonGroup) window.getRibbon().getGroupByName("add");
    RibbonActionItem addMany = (RibbonActionItem) add.getItemByName("addManyWorkers");
    if (workersComponent.getEntities().isEmpty() || !multiAssignment.isValid()) {
      addMany.setEnabled(false);
      addMany.requestUpdate(true);
    } else {
      addMany.setEnabled(true);
      addMany.requestUpdate(true);
    }
  }
  private Entity performFieldValidationTestOnPart(
      final String fieldName, final Object fieldValue, final boolean shouldPass) {
    DataDefinition partDao = dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_PART);

    pluginManager.enablePlugin(PLUGIN_PRODUCTS_NAME);

    Entity part = createPart("somePart", null);
    part.setField(fieldName, fieldValue);

    // when
    Entity savedPart = partDao.save(part);

    // then
    Assert.assertEquals(shouldPass, savedPart.isValid());

    return savedPart;
  }
  @Test
  public void shouldCallAndPassMaxStringLenFieldValidators() throws Exception {
    // given
    String stringWith300Characters = StringUtils.repeat("a", 300);
    DataDefinition productDao =
        dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_PRODUCT);

    pluginManager.enablePlugin(PLUGIN_PRODUCTS_NAME);

    Entity product = createProduct(stringWith300Characters, "asd");

    // when
    Entity savedProduct = productDao.save(product);

    // then
    Assert.assertTrue(savedProduct.isValid());
    Assert.assertEquals(stringWith300Characters, savedProduct.getStringField("name"));
  }
  @Test
  public final void shouldNotSaveFormBecauseOfValidationErrors() {
    // given
    stubProgressType(ProgressType.PLANNED);
    stubTechnologyOperation(null);
    Entity invalidPpsEntity = mockEntity(dataDefinition);
    given(invalidPpsEntity.isValid()).willReturn(false);
    given(dataDefinition.save(ppsEntity)).willReturn(invalidPpsEntity);

    // when
    progressPerShiftViewSaver.save(view);

    // then
    verify(txStatus, never()).setRollbackOnly();

    verify(dataDefinition).save(ppsEntity);
    verify(form)
        .addMessage("qcadooView.message.saveFailedMessage", ComponentState.MessageType.FAILURE);
  }
  @Test
  public final void
      shouldMarkExistingDatabaseEntityAsInvalidIfConstructorGetInvalidStateChangeEntity() {
    // given
    final Entity existingStateChangeEntity = mock(Entity.class);
    given(stateChangeEntity.isValid()).willReturn(false);
    given(stateChangeEntity.getId()).willReturn(1L);
    given(stateChangeDD.get(Mockito.any(Long.class))).willReturn(existingStateChangeEntity);
    given(existingStateChangeEntity.isValid()).willReturn(true);

    final Map<String, ErrorMessage> fieldErrorsMap = Maps.newHashMap();
    final ErrorMessage fieldErrorMessage = buildErrorMessage(FIELD_1_MESSAGE_1);
    fieldErrorsMap.put(FIELD_1_NAME, fieldErrorMessage);
    given(stateChangeEntity.getErrors()).willReturn(fieldErrorsMap);

    final List<ErrorMessage> globalErrors = Lists.newArrayList();
    final ErrorMessage globalErrorMessage = buildErrorMessage(GLOBAL_MESSAGE_1);
    globalErrors.add(globalErrorMessage);
    given(stateChangeEntity.getGlobalErrors()).willReturn(globalErrors);

    // when
    new StateChangeContextImpl(stateChangeEntity, describer, messageService);

    // then
    verify(messageService)
        .addValidationError(
            Mockito.any(StateChangeContext.class),
            Mockito.eq(FIELD_1_NAME),
            Mockito.eq(FIELD_1_MESSAGE_1));
    verify(messageService)
        .addValidationError(
            Mockito.any(StateChangeContext.class),
            Mockito.eq((String) null),
            Mockito.eq(GLOBAL_MESSAGE_1));
    verify(existingStateChangeEntity)
        .setField(describer.getStatusFieldName(), FAILURE.getStringValue());
  }
 private Entity mockDailyProgress() {
   Entity dailyProgress = mockEntity(dataDefinition);
   given(dailyProgress.isValid()).willReturn(true);
   return dailyProgress;
 }
Beispiel #20
0
 @Override
 public boolean callSaveHook(final Entity entity) {
   return entity.isValid() && callHooks(entity, getSaveHooks());
 }