@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 BigDecimal getQuantityOfProductInWarehouse(
      final Entity warehouse, final Entity product, Entity position) {
    BigDecimal quantity = BigDecimal.ZERO;

    Entity resource = position.getBelongsToField(PositionFields.RESOURCE);
    Entity reservation = reservationsService.getReservationForPosition(position);
    if (resource != null) {
      quantity = resource.getDecimalField(ResourceFields.AVAILABLE_QUANTITY);
    } else {
      List<Entity> resources =
          dataDefinitionService
              .get(
                  MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
                  MaterialFlowResourcesConstants.MODEL_RESOURCE)
              .find()
              .add(SearchRestrictions.belongsTo(ResourceFields.LOCATION, warehouse))
              .add(SearchRestrictions.belongsTo(ResourceFields.PRODUCT, product))
              .list()
              .getEntities();

      for (Entity res : resources) {
        quantity = quantity.add(res.getDecimalField(ResourceFields.AVAILABLE_QUANTITY));
      }
    }

    if (reservation != null) {
      quantity = quantity.add(reservation.getDecimalField(ReservationFields.QUANTITY));
    }
    return quantity;
  }
  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;
  }
  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");
    }
  }
Exemple #5
0
 private Entity findMainAddressTypeDictionaryItem(final Entity addressType) {
   return getDictionaryItemDD()
       .find()
       .add(SearchRestrictions.belongsTo(DictionaryItemFields.DICTIONARY, addressType))
       .add(SearchRestrictions.eq(DictionaryItemFields.TECHNICAL_CODE, L_MAIN))
       .setMaxResults(1)
       .uniqueResult();
 }
Exemple #6
0
 private Entity findMainAddress(final Entity company, final String addressType) {
   return getAddressDD()
       .find()
       .add(SearchRestrictions.belongsTo(AddressFields.COMPANY, company))
       .add(SearchRestrictions.eq(AddressFields.ADDRESS_TYPE, addressType))
       .setMaxResults(1)
       .uniqueResult();
 }
 @Override
 public void addRestriction(final SearchCriteriaBuilder searchBuilder) {
   searchBuilder
       .add(SearchRestrictions.isNull(PARENT))
       .add(
           SearchRestrictions.eq(
               ProductFields.ENTITY_TYPE,
               ProductFamilyElementType.PRODUCTS_FAMILY.getStringValue()));
 }
 private SearchCriteriaBuilder getSearchCriteriaForResourceForProductAndWarehouse(
     final Entity product, final Entity warehouse) {
   return dataDefinitionService
       .get(
           MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
           MaterialFlowResourcesConstants.MODEL_RESOURCE)
       .find()
       .add(SearchRestrictions.belongsTo(ResourceFields.LOCATION, warehouse))
       .add(SearchRestrictions.belongsTo(ResourceFields.PRODUCT, product))
       .add(SearchRestrictions.gt(ResourceFields.AVAILABLE_QUANTITY, BigDecimal.ZERO));
 }
Exemple #9
0
 private Entity findAddressTypeDictionary() {
   return getDictionaryDD()
       .find()
       .add(SearchRestrictions.eq(DictionaryFields.NAME, L_ADDRESS_TYPE))
       .setMaxResults(1)
       .uniqueResult();
 }
 public Entity findDictionaryItemByTechnicalCode(final String technicalCode) {
   return dataDefinitionService
       .get("qcadooModel", "dictionaryItem")
       .find()
       .add(SearchRestrictions.eq(TECHNICAL_CODE, technicalCode))
       .uniqueResult();
 }
 protected Entity findDictionaryItemByName(final String name) {
   return dataDefinitionService
       .get("qcadooModel", "dictionaryItem")
       .find()
       .add(SearchRestrictions.eq(NAME, name))
       .uniqueResult();
 }
 private Entity getCompany(final String number) {
   return dataDefinitionService
       .get(SamplesConstants.BASIC_PLUGIN_IDENTIFIER, SamplesConstants.BASIC_MODEL_COMPANY)
       .find()
       .add(SearchRestrictions.eq("number", number))
       .uniqueResult();
 }
Exemple #13
0
  public Entity getDefaultTechnology(final Entity product) {
    SearchResult searchResult =
        getTechnologyDD()
            .find()
            .setMaxResults(1)
            .add(SearchRestrictions.eq(TechnologyFields.MASTER, true))
            .add(SearchRestrictions.eq("active", true))
            .add(SearchRestrictions.belongsTo(TechnologyFields.PRODUCT, product))
            .list();

    if (searchResult.getTotalNumberOfEntities() == 1) {
      return searchResult.getEntities().get(0);
    } else {
      return null;
    }
  }
 private Entity getDefaultTechnologyForProduct(final Entity product) {
   if (product == null) {
     return null;
   }
   List<Entity> technologies =
       dataDefinitionService
           .get(L_TECHNOLOGIES_PLUGIN_IDENTIFIER, L_TECHNOLOGY_MODEL_TECHNOLOGY)
           .find()
           .add(SearchRestrictions.belongsTo(L_BASIC_MODEL_PRODUCT, product))
           .add(SearchRestrictions.eq("master", true))
           .setMaxResults(1)
           .list()
           .getEntities();
   if (technologies.isEmpty()) {
     return null;
   }
   return technologies.get(0);
 }
  private boolean checkIfUsedQuantitiesWereFilled(
      final Entity productionTracking, final String modelName) {
    final SearchCriteriaBuilder searchBuilder =
        productionTracking
            .getHasManyField(modelName)
            .find()
            .add(SearchRestrictions.isNotNull(L_USED_QUANTITY));

    return (searchBuilder.list().getTotalNumberOfEntities() != 0);
  }
  protected void addParameters(final Map<String, String> values) {
    LOG.info("Adding parameters");
    Entity params = parameterService.getParameter();

    Entity currency =
        dataDefinitionService
            .get(SamplesConstants.BASIC_PLUGIN_IDENTIFIER, SamplesConstants.BASIC_MODEL_CURRENCY)
            .find()
            .add(SearchRestrictions.eq("alphabeticCode", values.get("code")))
            .uniqueResult();

    params.setField("currency", currency);
    params.setField("unit", values.get("unit"));
    params.setField("company", getCompany(values.get("owner")));

    if (isEnabledOrEnabling("productionCounting")) {
      params.setField("registerQuantityInProduct", true);
      params.setField("registerQuantityOutProduct", true);
      params.setField("registerProductionTime", true);
      params.setField("justOne", false);
      params.setField("allowToClose", false);
      params.setField("autoCloseOrder", false);
    }

    if (isEnabledOrEnabling("qualityControls")) {
      params.setField("checkDoneOrderForQuality", false);
      params.setField("autoGenerateQualityControl", false);
    }

    if (isEnabledOrEnabling("genealogies")) {
      params.setField("batchForDoneOrder", "01none");
    }

    if (isEnabledOrEnabling("advancedGenealogy")) {
      params.setField("batchNumberUniqueness", "01globally");
    }

    if (isEnabledOrEnabling("advancedGenealogyForOrders")) {
      params.setField("trackingRecordForOrderTreatment", "01duringProduction");
      params.setField("batchNumberRequiredInputProducts", false);
    }

    if (isEnabledOrEnabling("materialRequirements")) {
      params.setField("inputProductsRequiredForType", "01startOrder");
    }

    if (isEnabledOrEnabling("materialFlowResources")) {
      params.setField("changeDateWhenTransferToWarehouseType", "01never");
    }

    params.getDataDefinition().save(params);
  }
  @Override
  @Transactional
  public Map<String, List<GanttChartItem>> resolve(
      final GanttChartScale scale, final JSONObject context, final Locale locale) {
    List<Entity> orders =
        dataDefinitionService
            .get("orders", "order")
            .find()
            .add(SearchRestrictions.ne("state", "04completed"))
            .add(SearchRestrictions.lt("dateFrom", scale.getDateTo()))
            .add(SearchRestrictions.gt("dateTo", scale.getDateFrom()))
            .list()
            .getEntities();

    List<GanttChartItem> items = new ArrayList<GanttChartItem>();

    for (Entity order : orders) {
      items.add(getItemForOrder(order, scale, locale));
    }

    return Collections.singletonMap("", items);
  }
 public Entity getExistingOrder(final ParsedOrder order) {
   SearchCriteriaBuilder ordersBuilder =
       dataDefinitionService
           .get(SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_ORDER)
           .find()
           .add(SearchRestrictions.eq(FIELD_NUMBER, order.getField(FIELD_NUMBER)))
           .setMaxResults(1);
   SearchResult existingOrders = ordersBuilder.list();
   if (existingOrders.getTotalNumberOfEntities() > 0) {
     return existingOrders.getEntities().get(0);
   }
   return null;
 }
  @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);
  }
 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);
     }
   }
 }
 protected String getRandomDictionaryItem(final String dictionaryName) {
   Entity dictionary = getDictionaryByName(dictionaryName);
   SearchCriteriaBuilder searchBuilder =
       dataDefinitionService
           .get("qcadooModel", "dictionaryItem")
           .find()
           .add(SearchRestrictions.belongsTo("dictionary", dictionary));
   int total = searchBuilder.list().getTotalNumberOfEntities();
   return searchBuilder
       .setMaxResults(1)
       .setFirstResult(RANDOM.nextInt(total))
       .uniqueResult()
       .getField(NAME)
       .toString();
 }
 public Entity getExistingProduct(final ParsedProduct productEntity) {
   SearchCriteriaBuilder productBuilder =
       dataDefinitionService
           .get(SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_PRODUCT)
           .find()
           .add(
               SearchRestrictions.eq(
                   FIELD_IDENTIFICATION_CODE, productEntity.getIdentificationCode()))
           .setMaxResults(1);
   SearchResult existingProducts = productBuilder.list();
   if (existingProducts.getTotalNumberOfEntities() > 0) {
     return existingProducts.getEntities().get(0);
   }
   return null;
 }
  @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);
  }
  private BigDecimal convertToGivenUnit(BigDecimal quantity, Entity product, String givenUnit) {
    String baseUnit = product.getStringField(ProductFields.UNIT);

    if (!baseUnit.equals(givenUnit)) {
      PossibleUnitConversions unitConversions =
          unitConversionService.getPossibleConversions(
              baseUnit,
              searchCriteriaBuilder ->
                  searchCriteriaBuilder.add(
                      SearchRestrictions.belongsTo(UnitConversionItemFieldsB.PRODUCT, product)));

      if (unitConversions.isDefinedFor(givenUnit)) {
        return unitConversions.convertTo(quantity, givenUnit);
      }
    }

    return quantity;
  }
    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();
    }
  private void generateAndAddUser() {
    Entity user = dataDefinitionService.get("qcadooSecurity", "user").create();

    user.setField("userName", generateString(CHARS_ONLY, RANDOM.nextInt(4) + 3));
    user.setField("email", generateRandomEmail());
    user.setField("firstname", generateString(CHARS_ONLY, RANDOM.nextInt(4) + 3));
    user.setField("lastname", generateString(CHARS_ONLY, RANDOM.nextInt(4) + 3));

    Entity group =
        dataDefinitionService
            .get("qcadooSecurity", "group")
            .find()
            .add(SearchRestrictions.eq(L_NAME, "Admin"))
            .setMaxResults(1)
            .uniqueResult();
    user.setField("group", group);

    user.setField("password", "123");
    user.setField("passwordConfirmation", "123");
    user.setField("enabled", true);

    dataDefinitionService.get("qcadooSecurity", "user").save(user);
  }
  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;
  }
  private void scheduleOrder(final Long orderId) {
    Entity order =
        dataDefinitionService
            .get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER)
            .get(orderId);

    if (order == null) {
      return;
    }

    Entity technology = order.getBelongsToField(OrderFields.TECHNOLOGY);

    if (technology == null) {
      return;
    }

    DataDefinition technologyOperationComponentDD =
        dataDefinitionService.get(
            TechnologiesConstants.PLUGIN_IDENTIFIER,
            TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT);

    List<Entity> operations =
        technologyOperationComponentDD
            .find()
            .add(
                SearchRestrictions.belongsTo(
                    TechnologyOperationComponentFields.TECHNOLOGY, technology))
            .list()
            .getEntities();

    Date orderStartDate = order.getDateField(OrderFields.START_DATE);
    for (Entity operation : operations) {
      Entity techOperCompTimeCalculation =
          operation.getBelongsToField(
              TechnologyOperationComponentFieldsTNFO.TECH_OPER_COMP_TIME_CALCULATION);

      if (techOperCompTimeCalculation == null) {
        continue;
      }

      Integer offset =
          techOperCompTimeCalculation.getIntegerField(
              TechOperCompTimeCalculationsFields.OPERATION_OFF_SET);
      Integer duration =
          techOperCompTimeCalculation.getIntegerField(
              TechOperCompTimeCalculationsFields.EFFECTIVE_OPERATION_REALIZATION_TIME);

      techOperCompTimeCalculation.setField(
          TechOperCompTimeCalculationsFields.EFFECTIVE_DATE_FROM, null);
      techOperCompTimeCalculation.setField(
          TechOperCompTimeCalculationsFields.EFFECTIVE_DATE_TO, null);

      if (offset == null || duration == null) {
        continue;
      }

      if (duration.equals(0)) {
        duration = duration + 1;
      }

      Date dateFrom = shiftsService.findDateToForOrder(orderStartDate, offset);
      if (dateFrom == null) {
        continue;
      }

      Date dateTo = shiftsService.findDateToForOrder(orderStartDate, offset + duration);
      if (dateTo == null) {
        continue;
      }

      techOperCompTimeCalculation.setField(
          TechOperCompTimeCalculationsFields.EFFECTIVE_DATE_FROM, dateFrom);
      techOperCompTimeCalculation.setField(
          TechOperCompTimeCalculationsFields.EFFECTIVE_DATE_TO, dateTo);

      techOperCompTimeCalculation.getDataDefinition().save(techOperCompTimeCalculation);
    }
  }
  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;
  }