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;
  }
Example #2
0
  private Entity getExistingOrder(final Entity order) {
    if (order.getId() == null) {
      return null;
    }

    return order.getDataDefinition().get(order.getId());
  }
  @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());
  }
  @Test
  public final void shouldReturnWorkPlan() throws Exception {
    // when
    Entity resultEntity = workPlanService.getWorkPlan(1L);

    // then
    Assert.assertSame(workPlanDD, resultEntity.getDataDefinition());
    Assert.assertEquals(workPlan.getId(), resultEntity.getId());
  }
 @Test
 public void shouldReturnWhenProductQuantitiesFromTechnologyIsnotEmpty() throws Exception {
   // given
   Long orderId = 1L;
   Long technologyId = 2L;
   when(order.getBelongsToField("technology")).thenReturn(technology);
   when(order.getId()).thenReturn(orderId);
   when(orderDD.get(orderId)).thenReturn(order);
   when(technology.getId()).thenReturn(technologyId);
   // when
   orderHooksCNFM.fillOrderOperationProductsInComponents(orderDD, order);
 }
  @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());
  }
  @Override
  protected JSONObject renderContent() throws JSONException {
    JSONObject json = super.renderContent();
    json.put(JSON_TEXT, selectedEntityValue);
    json.put(JSON_CODE, selectedEntityCode);
    json.put(JSON_ACTIVE, selectedEntityActive);
    json.put(JSON_BELONGS_TO_ENTITY_ID, belongsToEntityId);

    if (clearCurrentCodeCode) {
      json.put(JSON_CLEAR_CURRENT_CODE, clearCurrentCodeCode);
    }

    if (autocompleteMatches != null) {
      JSONArray matches = new JSONArray();
      for (Entity entity : autocompleteMatches) {
        JSONObject matchEntity = new JSONObject();
        matchEntity.put("id", entity.getId());
        matchEntity.put("value", ExpressionUtils.getValue(entity, expression, getLocale()));
        matchEntity.put("code", String.valueOf(entity.getField(fieldCode)));
        matchEntity.put("active", entity.isActive());
        matches.put(matchEntity);
      }
      json.put(JSON_AUTOCOMPLETE_MATCHES, matches);
      json.put(JSON_AUTOCOMPLETE_CODE, autocompleteCode);
      json.put(JSON_AUTOCOMPLETE_ENTITIES_NUMBER, autocompleteEntitiesNumber);
    }

    if (criteriaModifierParameter != null && !criteriaModifierParameter.isEmpty()) {
      json.put(JSON_CRITERIA_MODIFIER_PARAMETER, criteriaModifierParameter.toJSON());
    }

    return json;
  }
  @Before
  public final void init() {
    workPlanService = new WorkPlansServiceImpl();

    dataDefinitionService = mock(DataDefinitionService.class);
    TranslationService translationService = mock(TranslationService.class);
    workPlan = mock(Entity.class);
    workPlanDD = mock(DataDefinition.class);

    when(dataDefinitionService.get(
            WorkPlansConstants.PLUGIN_IDENTIFIER, WorkPlansConstants.MODEL_WORK_PLAN))
        .thenReturn(workPlanDD);

    when(translationService.translate(
            Mockito.anyString(), Mockito.any(Locale.class), Mockito.anyString()))
        .thenReturn(TRANSLATED_STRING);

    when(workPlanDD.getName()).thenReturn(WorkPlansConstants.MODEL_WORK_PLAN);
    when(workPlanDD.getPluginIdentifier()).thenReturn(WorkPlansConstants.PLUGIN_IDENTIFIER);
    when(workPlanDD.get(Mockito.anyLong())).thenReturn(workPlan);

    when(workPlan.getDataDefinition()).thenReturn(workPlanDD);
    when(workPlan.getId()).thenReturn(1L);

    ReflectionTestUtils.setField(workPlanService, "dataDefinitionService", dataDefinitionService);
    ReflectionTestUtils.setField(workPlanService, "translationService", translationService);
  }
  @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 void deleteOrderProducts(final Entity orderEntity) {
   for (Entity orrderProductEntity : orderEntity.getHasManyField("orderProducts")) {
     dataDefinitionService
         .get(
             SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_ORDER_PRODUCT)
         .delete(orrderProductEntity.getId());
   }
 }
  @Test
  public void shouldReturnWhenEntityIdIsNull() throws Exception {
    // given
    Mockito.when(order.getId()).thenReturn(null);

    // when
    hooksOTFO.changedProductionLine(dataDefinition, order);
    // then
  }
  @RequestMapping(value = "developReport/hql", method = RequestMethod.POST)
  public ModelAndView executeHql(@RequestParam(L_HQL) final String hql) {
    if (!showReportDevelopment) {
      return new ModelAndView(new RedirectView("/"));
    }

    try {
      List<Entity> entities =
          dataDefinitionService.get("qcadooPlugin", "plugin").find(hql).list().getEntities();

      if (entities.isEmpty()) {
        return new ModelAndView(L_QCADOO_REPORT_HQL)
            .addObject(L_HQL, hql)
            .addObject("isEmpty", true);
      } else {
        DataDefinition dataDefinition = entities.get(0).getDataDefinition();

        List<String> headers = new ArrayList<String>();

        if (!isDynamicDataDefinition(dataDefinition)) {
          headers.add("id");
        }

        headers.addAll(dataDefinition.getFields().keySet());

        List<List<String>> rows = new ArrayList<List<String>>();

        for (Entity entity : entities) {
          List<String> row = new ArrayList<String>();

          if (!isDynamicDataDefinition(dataDefinition)) {
            row.add(String.valueOf(entity.getId()));
          }

          for (String field : dataDefinition.getFields().keySet()) {
            if (entity.getField(field) == null) {
              row.add("");
            } else if (entity.getField(field) instanceof EntityList) {
              row.add("[]");
            } else {
              row.add(String.valueOf(entity.getField(field)));
            }
          }

          rows.add(row);
        }

        return new ModelAndView(L_QCADOO_REPORT_HQL)
            .addObject(L_HQL, hql)
            .addObject("headers", headers)
            .addObject("rows", rows)
            .addObject("isOk", true);
      }
    } catch (Exception e) {
      return showException(L_QCADOO_REPORT_HQL, e).addObject(L_HQL, hql);
    }
  }
 private Entity mockProductComponent(final Long productId) {
   Entity productComponent = mock(Entity.class);
   Entity product = mock(Entity.class);
   given(product.getField("id")).willReturn(productId);
   given(product.getId()).willReturn(productId);
   given(productComponent.getField("product")).willReturn(product);
   given(productComponent.getBelongsToField("product")).willReturn(product);
   given(dataDefinition.get(productId)).willReturn(productComponent);
   return productComponent;
 }
  @Test
  public void shouldCreatetTechnologyInstOperProductInComp() throws Exception {
    // given
    Long orderId = 1L;
    Long technologyId = 2L;
    BigDecimal nominalCost1 = BigDecimal.TEN;
    BigDecimal nominalCost2 = BigDecimal.TEN;

    when(productQuantities.entrySet()).thenReturn(entrySet);
    when(entrySet.iterator()).thenReturn(iterator);
    when(iterator.hasNext()).thenReturn(true, true, false);
    when(iterator.next()).thenReturn(entry1, entry2);

    when(entry1.getKey()).thenReturn(prod1);
    when(entry2.getKey()).thenReturn(prod2);

    when(prod1.getDecimalField("nominalCost")).thenReturn(nominalCost1);
    when(prod2.getDecimalField("nominalCost")).thenReturn(nominalCost2);

    when(order.getBelongsToField("technology")).thenReturn(technology);
    when(order.getId()).thenReturn(orderId);
    when(orderDD.get(orderId)).thenReturn(orderFromDB);
    when(technology.getId()).thenReturn(technologyId);

    when(costNormsForMaterialsService.getProductQuantitiesFromTechnology(technologyId))
        .thenReturn(productQuantities);
    when(techInsOperCompProdInDD.create())
        .thenReturn(techInsOperCompProdIn1, techInsOperCompProdIn2);
    when(techInsOperCompProdIn1.getDataDefinition()).thenReturn(techInsOperCompProdInDD);
    when(techInsOperCompProdIn2.getDataDefinition()).thenReturn(techInsOperCompProdInDD);
    when(techInsOperCompProdInDD.save(techInsOperCompProdIn1))
        .thenReturn(techInsOperCompProdIn1, techInsOperCompProdIn2);
    // when
    orderHooksCNFM.fillOrderOperationProductsInComponents(orderDD, order);

    // then
    Mockito.verify(techInsOperCompProdIn1).setField("order", order);
    Mockito.verify(techInsOperCompProdIn1).setField("product", prod1);
    Mockito.verify(techInsOperCompProdIn1).setField("nominalCost", nominalCost1);
    Mockito.verify(techInsOperCompProdIn2).setField("order", order);
    Mockito.verify(techInsOperCompProdIn2).setField("product", prod2);
    Mockito.verify(techInsOperCompProdIn2).setField("nominalCost", nominalCost2);
  }
Example #15
0
  public Optional<Entity> getMainAddress(final Entity company) {
    if (company.getId() != null) {
      String addressType = getMainAddressType();

      if (StringUtils.isNotEmpty(addressType)) {
        return Optional.ofNullable(findMainAddress(company, addressType));
      }
    }

    return Optional.empty();
  }
  @Test
  public void shouldReturnWhenProductionLineIsThisSame() throws Exception {
    // given
    Long orderId = 1L;
    when(entity.getId()).thenReturn(orderId);
    when(dataDefinition.get(orderId)).thenReturn(order);
    when(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).thenReturn(orderProdLine);
    when(entity.getBelongsToField(OrderFields.PRODUCTION_LINE)).thenReturn(orderProdLine);

    // when
    hooksOTFO.changedProductionLine(dataDefinition, entity);
    // then
  }
 @Test
 public void shouldApplyCurrentCurrency() throws Exception {
   // given
   FieldComponent field = mock(FieldComponent.class);
   Long currencyId = 1L;
   when(view.getComponentByReference("currency")).thenReturn(field);
   when(currencyService.getCurrentCurrency()).thenReturn(currency);
   when(currency.getId()).thenReturn(currencyId);
   // when
   currencyViewService.applyCurrentCurrency(view);
   // then
   Mockito.verify(field).setFieldValue(currencyId);
 }
  private GanttChartItem getItemForOrder(
      final Entity order, final GanttChartScale scale, final Locale locale) {
    Date from = (Date) order.getField("dateFrom");
    Date to = (Date) order.getField("dateTo");

    if (order.getField("effectiveDateFrom") != null) {
      long diff = to.getTime() - from.getTime();
      from = (Date) order.getField("effectiveDateFrom");
      to = new Date(from.getTime() + diff);
    }

    return scale.createGanttChartItem(
        "", getOrderDescription(order, locale), order.getId(), from, to);
  }
  private Entity getBasicProductionCounting(
      final Entity trackingOperationProductComponent, final List<Entity> basicProductionCountings) {
    Entity product = trackingOperationProductComponent.getBelongsToField(L_PRODUCT);

    for (Entity basicProductionCounting : basicProductionCountings) {
      if (basicProductionCounting
          .getBelongsToField(BasicProductionCountingFields.PRODUCT)
          .getId()
          .equals(product.getId())) {
        return basicProductionCounting;
      }
    }

    throw new IllegalStateException("No basic production counting found for product");
  }
Example #20
0
  private Entity copyTechnology(final Entity order, final Entity technologyPrototype) {
    Entity copyOfTechnology = getTechnologyDD().create();

    String number = generateNumberForTechnologyInOrder(order, technologyPrototype);

    copyOfTechnology =
        copyOfTechnology.getDataDefinition().copy(technologyPrototype.getId()).get(0);

    copyOfTechnology.setField(TechnologyFields.NUMBER, number);
    copyOfTechnology.setField(TechnologyFields.TECHNOLOGY_PROTOTYPE, technologyPrototype);
    copyOfTechnology.setField(
        TechnologyFields.TECHNOLOGY_TYPE, TechnologyType.WITH_PATTERN_TECHNOLOGY.getStringValue());

    copyOfTechnology = copyOfTechnology.getDataDefinition().save(copyOfTechnology);
    changeTechnologyState(copyOfTechnology, TechnologyStateStringValues.CHECKED);
    return copyOfTechnology;
  }
  @Test
  public void shouldChangedProdLineWhenProdLineIsNullify() throws Exception {
    // given
    Long orderId = 1L;
    when(entity.getId()).thenReturn(orderId);
    when(dataDefinition.get(orderId)).thenReturn(order);
    when(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).thenReturn(orderProdLine);
    when(entity.getBelongsToField(OrderFields.PRODUCTION_LINE)).thenReturn(null);
    EntityList tasks = mockEntityList(Lists.newArrayList(task1));

    when(result.getEntities()).thenReturn(tasks);
    // when
    hooksOTFO.changedProductionLine(dataDefinition, entity);
    // then

    Mockito.verify(task1).setField(OrderFields.PRODUCTION_LINE, null);
  }
Example #22
0
  public String generateAddressNumber(final Entity company) {
    String addressNumber = "";

    Long greatestNumber = 0L;

    if (company.getId() != null) {
      Collection<Entity> numberProjections = getNumbersProjection(company);

      Collection<Long> numericValues = extractNumericValues(numberProjections);

      if (!numericValues.isEmpty()) {
        greatestNumber = Ordering.natural().max(numericValues);
      }
    }

    addressNumber = generateNumber(company, greatestNumber + 1);

    return addressNumber;
  }
  private ImportedProduct createImportedProduct(
      final Entity productEntity, final boolean isOrderConversion) {
    ImportedProduct product = new ImportedProduct(productEntity.getId());

    if ("02service".equals(productEntity.getField(FIELD_TYPE))) {
      return null;
    } else if (isOrderConversion || "04set".equals(productEntity.getField(FIELD_TYPE))) {
      product.setTypeOfMaterial("03finalProduct");
    } else {
      product.setTypeOfMaterial("01component");
    }

    product.setNumber(productEntity.getStringField(FIELD_IDENTIFICATION_CODE));
    product.setName(productEntity.getStringField(FIELD_NAME));
    product.setEan(productEntity.getStringField("ean"));
    product.setUnit(productEntity.getStringField(FIELD_UNIT));

    return product;
  }
Example #24
0
  private String buildQuery(final Entity company) {
    String query = "";

    if (company != null) {
      Map<String, String> placeholderValues = Maps.newHashMap();

      placeholderValues.put("NUMBER_FIELD", AddressFields.NUMBER);
      placeholderValues.put("PREFIX", createPrefix(company));
      placeholderValues.put("NUM_PROJECTION_ALIAS", L_NUM_PROJECTION_ALIAS);
      placeholderValues.put("COMPANY_FIELD", AddressFields.COMPANY);
      placeholderValues.put("COMPANY_VALUE", company.getId().toString());

      StrSubstitutor substitutor = new StrSubstitutor(placeholderValues, "${", "}");

      query = substitutor.replace(L_GET_NUMBERS_QUERY_TEMPLATE).toString();
    }

    return query;
  }
  private void checkIfProductionLineFilled(
      DataDefinition multiAssignmentToShiftDD, Entity multiAssignmentToShift) {
    if (multiAssignmentToShift.getId() != null) {
      String occupationType =
          multiAssignmentToShift.getStringField(MultiAssignmentToShiftFields.OCCUPATION_TYPE);

      Entity dictionaryItem = findDictionaryItemByName(occupationType);

      String technicalCode = dictionaryItem.getStringField(TECHNICAL_CODE);

      if (technicalCode != null && technicalCode.equals(WORK_ON_LINE.getStringValue())) {
        if (multiAssignmentToShift.getBelongsToField(MultiAssignmentToShiftFields.PRODUCTION_LINE)
            == null) {
          multiAssignmentToShift.addError(
              multiAssignmentToShiftDD.getField(MultiAssignmentToShiftFields.PRODUCTION_LINE),
              "assignmentToShift.staffAssignmentToShift.productionLine.isEmpty");
        }
      }
    }
  }
  private void setResourceAttributesFromResource(final Entity resource, final Entity baseResource) {
    List<Entity> attributes = baseResource.getHasManyField(ResourceFields.ATRRIBUTE_VALUES);

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

    DataDefinition attributeDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_ATTRIBUTE_VALUE);

    for (Entity attribute : attributes) {
      List<Entity> newAttribute = attributeDD.copy(attribute.getId());

      newAttribute.get(0).setField(AttributeValueFields.RESOURCE, resource);

      newAttributes.addAll(newAttribute);
    }

    resource.setField(ResourceFields.ATRRIBUTE_VALUES, newAttributes);
  }
  @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);
  }
Example #28
0
  private void generateAndAddTechnology(final Entity product) {
    Entity technology =
        dataDefinitionService.get(TECHNOLOGIES_PLUGIN, L_TECHNOLOGY_MODEL_TECHNOLOGY).create();

    Entity defaultTechnology = getDefaultTechnologyForProduct(product);

    String number = generateString(DIGITS_ONLY, RANDOM.nextInt(40) + 5);

    technology.setField("master", defaultTechnology == null);
    technology.setField(L_NAME, getNameFromNumberAndPrefix("Technology-", number));
    technology.setField(L_NUMBER, number);
    technology.setField(L_BASIC_MODEL_PRODUCT, product);
    technology.setField(STATE_L, "01draft");
    technology.setField("batchRequired", true);
    technology.setField("postFeatureRequired", false);
    technology.setField("otherFeatureRequired", false);
    technology.setField("shiftFeatureRequired", false);
    technology.setField("minimalQuantity", RANDOM.nextInt(40) + 10);
    technology.setField("technologyBatchRequired", false);

    technology.setField("qualityControlType", "02forUnit");
    technology.setField("unitSamplingNr", "123");
    technology.setField("qualityControlInstruction", "asd23");

    technology =
        dataDefinitionService
            .get(TECHNOLOGIES_PLUGIN, L_TECHNOLOGY_MODEL_TECHNOLOGY)
            .save(technology);
    generateAndAddTechnologyOperationComponent(technology);

    treeNumberingService.generateNumbersAndUpdateTree(
        dataDefinitionService.get(L_TECHNOLOGIES_PLUGIN_IDENTIFIER, "technologyOperationComponent"),
        L_TECHNOLOGY_MODEL_TECHNOLOGY,
        technology.getId());

    technology.setField(STATE_L, "02accepted");
    dataDefinitionService.get(TECHNOLOGIES_PLUGIN, L_TECHNOLOGY_MODEL_TECHNOLOGY).save(technology);
  }
  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;
  }
  private void moveResources(
      Entity warehouseFrom,
      Entity warehouseTo,
      Entity position,
      Object date,
      WarehouseAlgorithm warehouseAlgorithm) {
    Entity product = position.getBelongsToField(PositionFields.PRODUCT);

    List<Entity> resources =
        getResourcesForWarehouseProductAndAlgorithm(
            warehouseFrom, product, position, warehouseAlgorithm);

    BigDecimal quantity = position.getDecimalField(PositionFields.QUANTITY);

    resourceStockService.removeResourceStock(product, warehouseFrom, quantity);
    for (Entity resource : resources) {
      BigDecimal resourceQuantity = resource.getDecimalField(QUANTITY);

      BigDecimal resourceAvailableQuantity =
          resource.getDecimalField(ResourceFields.AVAILABLE_QUANTITY);
      if (quantity.compareTo(resourceAvailableQuantity) >= 0) {
        quantity = quantity.subtract(resourceAvailableQuantity, numberService.getMathContext());
        if (resourceQuantity.compareTo(resourceAvailableQuantity) <= 0) {
          resource.getDataDefinition().delete(resource.getId());
        } else {
          BigDecimal newResourceQuantity = resourceQuantity.subtract(resourceAvailableQuantity);
          BigDecimal resourceConversion = resource.getDecimalField(ResourceFields.CONVERSION);
          BigDecimal quantityInAdditionalUnit = newResourceQuantity.multiply(resourceConversion);
          resource.setField(ResourceFields.AVAILABLE_QUANTITY, BigDecimal.ZERO);
          resource.setField(ResourceFields.QUANTITY, newResourceQuantity);
          resource.setField(
              ResourceFields.QUANTITY_IN_ADDITIONAL_UNIT,
              numberService.setScale(quantityInAdditionalUnit));
          resource.getDataDefinition().save(resource);
        }

        createResource(position, warehouseTo, resource, resourceAvailableQuantity, date);

        if (BigDecimal.ZERO.compareTo(quantity) == 0) {
          return;
        }
      } else {
        resourceQuantity = resourceQuantity.subtract(quantity, numberService.getMathContext());
        resourceAvailableQuantity =
            resourceAvailableQuantity.subtract(quantity, numberService.getMathContext());
        String givenUnit = resource.getStringField(ResourceFields.GIVEN_UNIT);
        BigDecimal quantityInAdditionalUnit =
            convertToGivenUnit(resourceQuantity, product, givenUnit);

        resource.setField(
            ResourceFields.QUANTITY_IN_ADDITIONAL_UNIT,
            numberService.setScale(quantityInAdditionalUnit));
        resource.setField(ResourceFields.QUANTITY, numberService.setScale(resourceQuantity));
        resource.setField(ResourceFields.AVAILABLE_QUANTITY, resourceAvailableQuantity);

        resource.getDataDefinition().save(resource);

        createResource(position, warehouseTo, resource, quantity, date);

        return;
      }
    }

    position.addError(
        position.getDataDefinition().getField(PositionFields.QUANTITY),
        "materialFlow.error.position.quantity.notEnough");
  }