public void checkIfExistsFinalRecord(final StateChangeContext stateChangeContext) {
    final Entity productionTracking = stateChangeContext.getOwner();
    final Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER);
    final String typeOfProductionRecording =
        order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING);

    final SearchCriteriaBuilder searchBuilder = productionTracking.getDataDefinition().find();
    searchBuilder.add(
        SearchRestrictions.eq(
            ProductionTrackingFields.STATE, ProductionTrackingStateStringValues.ACCEPTED));
    searchBuilder.add(SearchRestrictions.belongsTo(ProductionTrackingFields.ORDER, order));
    searchBuilder.add(SearchRestrictions.eq(ProductionTrackingFields.LAST_TRACKING, true));

    if (productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)) {
      searchBuilder.add(
          SearchRestrictions.belongsTo(
              ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT,
              productionTracking.getBelongsToField(
                  ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT)));
    }

    if (searchBuilder.list().getTotalNumberOfEntities() != 0) {
      stateChangeContext.addValidationError(
          "productionCounting.productionTracking.messages.error.finalExists");
    }
  }
    public void autompleteSearch(final String[] args) {
      if ((belongsToFieldDefinition == null || belongsToEntityId != null)) {
        SearchCriteriaBuilder searchCriteriaBuilder = getDataDefinition().find();

        if (StringUtils.hasText(currentCode)) {
          searchCriteriaBuilder.add(
              SearchRestrictions.ilike(fieldCode, currentCode, SearchMatchMode.ANYWHERE));
        }

        if (belongsToFieldDefinition != null
            && belongsToEntityId != null
            && belongsToFieldDefinition.getType() instanceof BelongsToType) {
          BelongsToType type = (BelongsToType) belongsToFieldDefinition.getType();
          searchCriteriaBuilder.add(
              SearchRestrictions.belongsTo(
                  belongsToFieldDefinition.getName(),
                  type.getDataDefinition().get(belongsToEntityId)));
        }

        if (getDataDefinition().isActivable()) {
          if (oldSelectedEntityId == null) {
            searchCriteriaBuilder.add(SearchRestrictions.eq("active", true));
          } else {
            searchCriteriaBuilder.add(
                SearchRestrictions.or(
                    SearchRestrictions.eq("active", true),
                    SearchRestrictions.idEq(oldSelectedEntityId)));
          }
        }

        searchCriteriaBuilder.addOrder(SearchOrders.asc(fieldCode));

        if (criteriaModifier != null) {
          criteriaModifier.modifyCriteria(searchCriteriaBuilder, criteriaModifierParameter);
        }

        SearchResult results = searchCriteriaBuilder.list();

        autocompleteEntitiesNumber = results.getTotalNumberOfEntities();

        if (results.getTotalNumberOfEntities() > 25) {
          autocompleteMatches = new LinkedList<Entity>();
        } else {
          autocompleteMatches = results.getEntities();
        }
      } else {
        autocompleteMatches = new LinkedList<Entity>();
      }

      autocompleteCode = currentCode;
      requestRender();
    }
  @Test
  public void shouldReturnFalseWhenEntityWithGivenProductAndCompanyDoesExistsInDB()
      throws Exception {
    // given
    SearchCriterion criterion1 =
        SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER));
    SearchCriterion criterion2 =
        SearchRestrictions.belongsTo(PRODUCT, entity.getBelongsToField(PRODUCT));

    given(entity.getId()).willReturn(null);
    given(criteria.add(criterion1)).willReturn(criteria);
    given(criteria.add(criterion2)).willReturn(criteria);
    given(criteria.list()).willReturn(searchResult);
    given(searchResult.getEntities()).willReturn(productCatalogNumbers);
    given(productCatalogNumbers.isEmpty()).willReturn(false);
    // when
    boolean result =
        productCatalogNumbersHooks.checkIfExistsCatalogNumberWithProductAndCompany(
            dataDefinition, entity);
    // then
    Assert.assertFalse(result);
    Mockito.verify(entity)
        .addGlobalError(
            "productCatalogNumbers.productCatalogNumber.validationError.alreadyExistsProductForCompany");
  }
  public boolean checkIfCustomTranslationIsUnique(
      final DataDefinition customTranslationDD, final Entity customTranslation) {
    String pluginIdentifier = customTranslation.getStringField(PLUGIN_IDENTIFIER);
    String locale = customTranslation.getStringField(LOCALE);
    String key = customTranslation.getStringField(KEY);

    SearchCriteriaBuilder searchCriteriaBuilder =
        customTranslationDD
            .find()
            .add(SearchRestrictions.eq(PLUGIN_IDENTIFIER, pluginIdentifier))
            .add(SearchRestrictions.eq(LOCALE, locale))
            .add(SearchRestrictions.eq(KEY, key));

    if (customTranslation.getId() != null) {
      searchCriteriaBuilder.add(SearchRestrictions.ne("id", customTranslation.getId()));
    }

    SearchResult searchResult = searchCriteriaBuilder.list();

    if (!searchResult.getEntities().isEmpty()) {
      customTranslation.addError(
          customTranslationDD.getField(KEY),
          "customTranslation.customTranslation.error.customTranslationIsntUnique");

      return false;
    }

    return true;
  }
  @Test
  public void
      shouldReturnFalseAndAddErrorWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsntUnique() {
    // given
    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);

    // when
    boolean result =
        materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness(
            materialsInLocationComponentDD, materialsInLocationComponent);

    // then
    assertFalse(result);

    Mockito.verify(materialsInLocationComponent)
        .addError(
            Mockito.eq(materialsInLocationComponentDD.getField(LOCATION)), Mockito.anyString());
  }
 @Override
 public void addRestriction(final SearchCriteriaBuilder searchBuilder) {
   searchBuilder
       .add(SearchRestrictions.isNull(PARENT))
       .add(
           SearchRestrictions.eq(
               ProductFields.ENTITY_TYPE,
               ProductFamilyElementType.PRODUCTS_FAMILY.getStringValue()));
 }
  @Test
  public final void shouldReturnOrdersById() throws Exception {
    // given
    Entity order1 = mock(Entity.class);
    when(order1.getId()).thenReturn(1L);

    Entity order2 = mock(Entity.class);
    when(order2.getId()).thenReturn(2L);

    Entity order3 = mock(Entity.class);
    when(order3.getId()).thenReturn(3L);

    @SuppressWarnings("unchecked")
    Iterator<Long> iterator = mock(Iterator.class);
    when(iterator.hasNext()).thenReturn(true, true, true, true, false);
    when(iterator.next()).thenReturn(1L, 2L, 3L, 4L);

    @SuppressWarnings("unchecked")
    Set<Long> selectedOrderIds = mock(Set.class);
    when(selectedOrderIds.iterator()).thenReturn(iterator);
    when(selectedOrderIds.size()).thenReturn(4);

    SearchCriteriaBuilder criteria = mock(SearchCriteriaBuilder.class);
    when(criteria.add(Mockito.any(SearchCriterion.class))).thenReturn(criteria);

    SearchResult result = mock(SearchResult.class);
    when(criteria.list()).thenReturn(result);

    when(result.getTotalNumberOfEntities()).thenReturn(3);
    when(result.getEntities()).thenReturn(Lists.newArrayList(order1, order2, order3));

    DataDefinition orderDD = mock(DataDefinition.class);
    when(orderDD.find()).thenReturn(criteria);

    when(dataDefinitionService.get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER))
        .thenReturn(orderDD);

    // when
    List<Entity> resultList = workPlanService.getSelectedOrders(selectedOrderIds);

    // then
    Assert.assertEquals(3, resultList.size());

    Assert.assertNotNull(resultList.get(0));
    Assert.assertSame(1L, resultList.get(0).getId());

    Assert.assertNotNull(resultList.get(1));
    Assert.assertSame(2L, resultList.get(1).getId());

    Assert.assertNotNull(resultList.get(2));
    Assert.assertSame(3L, resultList.get(2).getId());
  }
Beispiel #8
0
  @Override
  public long count(final SearchCriterion criterion) {
    final String countAlias = "count";
    SearchCriteriaBuilder scb = find();
    if (criterion != null) {
      scb.add(criterion);
    }
    scb.setProjection(alias(rowCount(), countAlias));
    scb.addOrder(asc(countAlias));

    Entity countProjection = scb.setMaxResults(1).uniqueResult();
    return (Long) countProjection.getField(countAlias);
  }
 private void addOrdersToOrderGroup(final Entity orderGroup) {
   List<Entity> orders;
   SearchCriteriaBuilder searchBuilder =
       dataDefinitionService.get(L_ORDERS_PLUGIN_IDENTIFIER, L_ORDERS_MODEL_ORDER).find();
   int ordersLeft =
       searchBuilder
           .add(SearchRestrictions.isNull(ORDER_GROUP_LITERAL))
           .list()
           .getTotalNumberOfEntities();
   if (ordersLeft >= 0) {
     orders =
         searchBuilder
             .add(SearchRestrictions.isNull(ORDER_GROUP_LITERAL))
             .setMaxResults(10)
             .list()
             .getEntities();
     for (Entity order : orders) {
       order.setField(ORDER_GROUP_LITERAL, orderGroup);
       order.setField("doneQuantity", RANDOM.nextInt(10) + 1);
       order.getDataDefinition().save(order);
     }
   }
 }
  @Before
  public void init() {
    hooksOTFO = new OrderHooksOTFO();
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(SearchRestrictions.class);
    ReflectionTestUtils.setField(hooksOTFO, "dataDefinitionService", dataDefinitionService);

    when(dataDefinitionService.get(
            OperationalTasksConstants.PLUGIN_IDENTIFIER,
            OperationalTasksConstants.MODEL_OPERATIONAL_TASK))
        .thenReturn(operationalTasksDD);
    when(operationalTasksDD.find()).thenReturn(builder);
    SearchCriterion criterion = SearchRestrictions.belongsTo("order", order);
    when(builder.add(criterion)).thenReturn(builder);
    when(builder.list()).thenReturn(result);
  }
  @Test
  public void shouldReturnTrueWhenEntityWithGivenNumberAndCompanyDoesnotExistsInDB()
      throws Exception {
    // given
    SearchCriterion criterion1 =
        SearchRestrictions.eq(CATALOG_NUMBER, entity.getStringField(CATALOG_NUMBER));
    SearchCriterion criterion2 =
        SearchRestrictions.belongsTo(ProductCatalogNumberFields.COMPANY, company);

    given(entity.getId()).willReturn(null);
    given(criteria.add(criterion1)).willReturn(criteria);
    given(criteria.add(criterion2)).willReturn(criteria);
    given(criteria.list()).willReturn(searchResult);
    given(searchResult.getEntities()).willReturn(productCatalogNumbers);
    given(productCatalogNumbers.isEmpty()).willReturn(true);
    // when
    boolean result =
        productCatalogNumbersHooks.checkIfExistsCatalogNumberWithNumberAndCompany(
            dataDefinition, entity);
    // then
    Assert.assertTrue(result);
  }
  @Test
  public void
      shouldReturnTrueWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsUnique() {
    // given
    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);

    // when
    boolean result =
        materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness(
            materialsInLocationComponentDD, materialsInLocationComponent);

    // then
    assertTrue(result);
  }
  private List<Entity> getResourcesForLocationAndProductFEFO(
      final Entity warehouse,
      final Entity product,
      final Entity additionalCode,
      final Entity position) {
    List<Entity> resources = Lists.newArrayList();

    if (additionalCode != null) {
      SearchCriteriaBuilder scb =
          getSearchCriteriaForResourceForProductAndWarehouse(product, warehouse);

      if (!StringUtils.isEmpty(product.getStringField(ProductFields.ADDITIONAL_UNIT))) {
        scb.add(
            SearchRestrictions.eq(
                PositionFields.CONVERSION, position.getDecimalField(PositionFields.CONVERSION)));
      } else {
        scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
      }

      resources =
          scb.add(SearchRestrictions.belongsTo(ResourceFields.ADDITIONAL_CODE, additionalCode))
              .addOrder(SearchOrders.asc(ResourceFields.EXPIRATION_DATE))
              .list()
              .getEntities();

      scb = getSearchCriteriaForResourceForProductAndWarehouse(product, warehouse);

      if (!StringUtils.isEmpty(product.getStringField(ProductFields.ADDITIONAL_UNIT))) {
        scb.add(
            SearchRestrictions.eq(
                PositionFields.CONVERSION, position.getDecimalField(PositionFields.CONVERSION)));
      } else {
        scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
      }

      resources.addAll(
          scb.add(
                  SearchRestrictions.or(
                      SearchRestrictions.isNull(ResourceFields.ADDITIONAL_CODE),
                      SearchRestrictions.ne("additionalCode.id", additionalCode.getId())))
              .addOrder(SearchOrders.asc(ResourceFields.EXPIRATION_DATE))
              .list()
              .getEntities());
    }

    if (resources.isEmpty()) {
      SearchCriteriaBuilder scb =
          getSearchCriteriaForResourceForProductAndWarehouse(product, warehouse);

      if (!StringUtils.isEmpty(product.getStringField(ProductFields.ADDITIONAL_UNIT))) {
        scb.add(
            SearchRestrictions.eq(
                PositionFields.CONVERSION, position.getDecimalField(PositionFields.CONVERSION)));
      } else {
        scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
      }

      resources =
          scb.addOrder(SearchOrders.asc(ResourceFields.EXPIRATION_DATE)).list().getEntities();
    }

    return resources;
  }
  public Multimap<Long, BigDecimal> getQuantitiesInWarehouse(
      final Entity warehouse, Multimap<Entity, Entity> productsAndPositions) {
    Multimap<Long, BigDecimal> result = ArrayListMultimap.create();

    String algorithm = warehouse.getStringField(LocationFieldsMFR.ALGORITHM);

    for (Map.Entry<Entity, Entity> productAndPosition : productsAndPositions.entries()) {
      Entity resource = productAndPosition.getValue().getBelongsToField(PositionFields.RESOURCE);

      if (algorithm.equalsIgnoreCase(WarehouseAlgorithm.MANUAL.getStringValue())
          && resource != null) {
        result.put(
            productAndPosition.getKey().getId(),
            resource.getDecimalField(ResourceFields.AVAILABLE_QUANTITY));
      } else {
        Entity additionalCode =
            productAndPosition.getValue().getBelongsToField(PositionFields.ADDITIONAL_CODE);
        BigDecimal conversion =
            productAndPosition.getValue().getDecimalField(PositionFields.CONVERSION);
        Entity reservation =
            reservationsService.getReservationForPosition(productAndPosition.getValue());
        List<Entity> resources = Lists.newArrayList();

        if (additionalCode != null) {
          SearchCriteriaBuilder scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources =
              scb.add(SearchRestrictions.belongsTo(ResourceFields.ADDITIONAL_CODE, additionalCode))
                  .list()
                  .getEntities();

          scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources.addAll(
              scb.add(
                      SearchRestrictions.or(
                          SearchRestrictions.isNull(ResourceFields.ADDITIONAL_CODE),
                          SearchRestrictions.ne("additionalCode.id", additionalCode.getId())))
                  .list()
                  .getEntities());
        }

        if (resources.isEmpty()) {
          SearchCriteriaBuilder scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources = scb.list().getEntities();
        }

        BigDecimal reservedQuantity = BigDecimal.ZERO;
        if (reservation != null) {
          reservedQuantity = reservation.getDecimalField(ReservationFields.QUANTITY);
        }
        if (result.containsKey(productAndPosition.getKey().getId())) {
          BigDecimal currentQuantity =
              result
                  .get(productAndPosition.getKey().getId())
                  .stream()
                  .reduce(reservedQuantity, BigDecimal::add);

          result.put(
              productAndPosition.getKey().getId(),
              (resources
                      .stream()
                      .map(res -> res.getDecimalField(ResourceFields.AVAILABLE_QUANTITY))
                      .reduce(BigDecimal.ZERO, BigDecimal::add))
                  .add(currentQuantity));
        } else {
          result.put(
              productAndPosition.getKey().getId(),
              resources
                  .stream()
                  .map(res -> res.getDecimalField(ResourceFields.AVAILABLE_QUANTITY))
                  .reduce(reservedQuantity, BigDecimal::add));
        }
      }
    }

    return result;
  }