@Override
  public Set<ImportedOrder> getImportedOrders(final Set<Long> orderIds) {
    Set<ImportedOrder> result = new HashSet<ImportedOrder>();
    for (Long importedOrderId : orderIds) {
      Entity orderEntity =
          dataDefinitionService
              .get(SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_ORDER)
              .get(importedOrderId);

      ImportedOrder order = new ImportedOrder(importedOrderId);

      order.setNumber(orderEntity.getStringField(FIELD_NUMBER));
      order.setDrawDate((Date) orderEntity.getField(FIELD_DRAW_DATE));
      order.setRealizationDate((Date) orderEntity.getField(FIELD_REALIZATION_DATE));

      for (Entity orderProductEntity : orderEntity.getHasManyField("orderProducts")) {

        ImportedProduct orderItemProduct =
            createImportedProduct(orderProductEntity.getBelongsToField("product"), true);
        if (orderItemProduct != null) {
          ImportedOrderItem orderItem = new ImportedOrderItem();
          orderItem.setProduct(orderItemProduct);
          orderItem.setQuantity((BigDecimal) orderProductEntity.getField(FIELD_QUANTITY));
          order.addItem(orderItem);
        }
      }

      result.add(order);
    }

    return result;
  }
  @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;
 }
  public Entity createResource(
      final Entity position,
      final Entity warehouse,
      final Entity resource,
      final BigDecimal quantity,
      Object date) {
    DataDefinition resourceDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_RESOURCE);

    Entity newResource = resourceDD.create();

    if (position != null) {
      Entity document = position.getBelongsToField(PositionFields.DOCUMENT);

      if (document != null) {
        Entity user = document.getBelongsToField(DocumentFields.USER);

        newResource.setField(
            ResourceFields.USER_NAME,
            user.getStringField(_FIRST_NAME) + " " + user.getStringField(L_LAST_NAME));
      }
    }

    newResource.setField(ResourceFields.TIME, date);
    newResource.setField(ResourceFields.LOCATION, warehouse);
    newResource.setField(
        ResourceFields.PRODUCT, resource.getBelongsToField(PositionFields.PRODUCT));
    newResource.setField(ResourceFields.QUANTITY, quantity);
    newResource.setField(ResourceFields.AVAILABLE_QUANTITY, quantity);
    newResource.setField(ResourceFields.RESERVED_QUANTITY, BigDecimal.ZERO);
    newResource.setField(ResourceFields.PRICE, resource.getField(PositionFields.PRICE));
    newResource.setField(ResourceFields.BATCH, resource.getField(PositionFields.BATCH));
    newResource.setField(
        ResourceFields.EXPIRATION_DATE, resource.getField(PositionFields.EXPIRATION_DATE));
    newResource.setField(
        ResourceFields.PRODUCTION_DATE, resource.getField(PositionFields.PRODUCTION_DATE));
    newResource.setField(
        ResourceFields.STORAGE_LOCATION, resource.getField(ResourceFields.STORAGE_LOCATION));
    newResource.setField(
        ResourceFields.ADDITIONAL_CODE, resource.getField(ResourceFields.ADDITIONAL_CODE));
    newResource.setField(ResourceFields.CONVERSION, resource.getField(ResourceFields.CONVERSION));
    newResource.setField(
        ResourceFields.PALLET_NUMBER, resource.getField(ResourceFields.PALLET_NUMBER));
    newResource.setField(
        ResourceFields.TYPE_OF_PALLET, resource.getField(ResourceFields.TYPE_OF_PALLET));
    newResource.setField(ResourceFields.GIVEN_UNIT, resource.getField(ResourceFields.GIVEN_UNIT));

    BigDecimal quantityInAdditionalUnit =
        numberService.setScale(
            quantity.multiply(resource.getDecimalField(ResourceFields.CONVERSION)));

    newResource.setField(ResourceFields.QUANTITY_IN_ADDITIONAL_UNIT, quantityInAdditionalUnit);

    setResourceAttributesFromResource(newResource, resource);

    resourceStockService.addResourceStock(newResource);
    return resourceDD.save(newResource);
  }
  public void fillTitleLabel(final ViewDefinitionState viewDefinitionState) {
    FieldComponent title = (FieldComponent) viewDefinitionState.getComponentByReference("title");
    Entity order =
        dataDefinitionService
            .get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER)
            .get(orderId);
    String number = order.getField("number").toString();
    String name = order.getField("name").toString();

    title.setFieldValue(name + " - " + number);
    title.requestComponentUpdateState();
  }
  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 long getTimestampFromOrder(
      final Entity order, final String dateField, final String correctedField) {
    final Date date = (Date) order.getField(dateField);
    final Date correctedDate = (Date) order.getField(correctedField);

    if (date == null) {
      return 0L;
    }

    if (correctedDate == null) {
      return date.getTime();
    } else {
      return correctedDate.getTime();
    }
  }
 private Date getEffectiveDate(final Entity order, final String effectiveField) {
   Date effectiveDate = (Date) order.getField(effectiveField);
   if (effectiveDate == null) {
     effectiveDate = new Date();
   }
   return effectiveDate;
 }
  public void showCopyOfTechnology(
      final ViewDefinitionState view, final ComponentState state, final String[] args) {
    Long orderId = (Long) state.getFieldValue();

    if (orderId != null) {
      Entity order =
          dataDefinitionService
              .get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER)
              .get(orderId);

      if (OrderType.WITH_PATTERN_TECHNOLOGY
              .getStringValue()
              .equals(order.getField(OrderFields.ORDER_TYPE))
          && (order.getBelongsToField(OrderFields.TECHNOLOGY_PROTOTYPE) == null)) {
        state.addMessage("order.technology.patternTechnology.not.set", MessageType.INFO);

        return;
      }

      Long technologyId = order.getBelongsToField(OrderFields.TECHNOLOGY).getId();
      Map<String, Object> parameters = Maps.newHashMap();
      parameters.put("form.id", technologyId);

      String url = "../page/orders/copyOfTechnologyDetails.html";
      view.redirectTo(url, false, true, parameters);
    }
  }
  @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;
  }
Exemple #11
0
  @Test
  public final void shouldGetPpsForOrderReturnExistingPpsId() {
    // given
    Long givenOrderId = 1L;
    Long expectedPpsId = 50L;

    given(
            dataDefinitionService.get(
                ProductionPerShiftConstants.PLUGIN_IDENTIFIER,
                ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT))
        .willReturn(dataDefinition);
    SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class);
    given(
            dataDefinition.find(
                "select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId"))
        .willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId)))
        .willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.uniqueResult()).willReturn(entity);
    given(entity.getField("ppsId")).willReturn(expectedPpsId);

    // when
    final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId);

    // then
    Assert.assertEquals(expectedPpsId, resultPpsId);
  }
  protected void addCompany(final Map<String, String> values) {
    Entity company =
        dataDefinitionService
            .get(SamplesConstants.BASIC_PLUGIN_IDENTIFIER, SamplesConstants.BASIC_MODEL_COMPANY)
            .create();

    LOG.debug(
        "id: "
            + values.get("id")
            + "number: "
            + values.get("number")
            + " companyFullName "
            + values.get("companyfullname")
            + " tax "
            + values.get("tax")
            + " street "
            + values.get("street")
            + " house "
            + values.get("house")
            + " flat "
            + values.get("flat")
            + " zipCode "
            + values.get("zipcode")
            + " city "
            + values.get("city")
            + " state "
            + values.get("state")
            + " country "
            + values.get("country")
            + " email "
            + values.get(EMAIL)
            + " website "
            + values.get("website")
            + " phone "
            + values.get("phone")
            + " owner "
            + values.get("owner"));

    company.setField("number", values.get("number"));
    company.setField(NAME, values.get(NAME));
    company.setField("tax", values.get("tax"));
    company.setField("street", values.get("street"));
    company.setField("house", values.get("house"));
    company.setField("flat", values.get("flat"));
    company.setField("zipCode", values.get("zipcode"));
    company.setField("city", values.get("city"));
    company.setField("state", values.get("state"));
    company.setField("country", values.get("country"));
    company.setField(EMAIL, values.get(EMAIL));
    company.setField("website", values.get("website"));
    company.setField("phone", values.get("phone"));
    company.setField("owner", values.get("owner"));

    if (LOG.isDebugEnabled()) {
      LOG.debug("Add test company item {company=" + company.getField(NAME) + "}");
    }

    company.getDataDefinition().save(company);
  }
 public String generateNumber(final Entity product) {
   String numberPrefix = product.getField(ProductFields.NUMBER) + "-";
   return numberGeneratorService.generateNumberWithPrefix(
       TechnologiesConstants.PLUGIN_IDENTIFIER,
       TechnologiesConstants.MODEL_TECHNOLOGY,
       3,
       numberPrefix);
 }
  private Entity addOperationComponent(
      final Entity technology,
      final Entity parent,
      final Entity operation,
      final int productsComponentsQuantity) {
    Preconditions.checkNotNull(technology, "Technology entity is null");
    Entity operationComponent =
        dataDefinitionService
            .get(L_TECHNOLOGIES_PLUGIN_IDENTIFIER, "technologyOperationComponent")
            .create();

    int productInComponentQuantity = RANDOM.nextInt(productsComponentsQuantity);
    int productOutComponentQuantity = productsComponentsQuantity - productInComponentQuantity;

    operationComponent.setField(
        L_NAME, "operationComponent" + generateString(CHARS_AND_DIGITS, 15));
    operationComponent.setField(L_NUMBER, generateString(CHARS_AND_DIGITS, 20));
    operationComponent.setField(L_TECHNOLOGY_MODEL_TECHNOLOGY, technology);
    operationComponent.setField("parent", parent);
    operationComponent.setField(L_TECHNOLOGY_MODEL_OPERATION, operation);
    operationComponent.setField("entityType", L_TECHNOLOGY_MODEL_OPERATION);
    operationComponent.setField(L_TPZ, operation.getField(L_TPZ));
    operationComponent.setField(L_TJ, operation.getField(L_TJ));
    operationComponent.setField("machineUtilization", operation.getField("machineUtilization"));
    operationComponent.setField("laborUtilization", operation.getField("laborUtilization"));
    operationComponent.setField("productionInOneCycle", operation.getField("productionInOneCycle"));
    operationComponent.setField(
        L_NEXT_OPERATION_AFTER_PRODUCED_TYPE,
        operation.getField(L_NEXT_OPERATION_AFTER_PRODUCED_TYPE));
    operationComponent.setField("nextOperationAfterProducedQuantity", "0");
    operationComponent.setField("timeNextOperation", operation.getField("timeNextOperation"));

    operationComponent = operationComponent.getDataDefinition().save(operationComponent);
    List<Entity> listOut = new LinkedList<Entity>();
    Entity productOut = null;
    for (int i = 0; i < productOutComponentQuantity; i++) {
      productOut = getRandomProduct();

      while (listOut.contains(productOut)) {
        productOut = getRandomProduct();
      }
      listOut.add(productOut);
      generateAndAddOperationProductOutComponent(
          operationComponent, new BigDecimal(RANDOM.nextInt(50) + 5), productOut);
    }
    List<Entity> listIn = new LinkedList<Entity>();
    Entity productIn = null;
    for (int i = 0; i < productInComponentQuantity; i++) {
      productIn = getRandomProduct();

      while (listIn.contains(productIn)) {
        productIn = getRandomProduct();
      }
      listIn.add(productIn);
      generateAndAddOperationProductInComponent(
          operationComponent, new BigDecimal(RANDOM.nextInt(50) + 5), productIn);
    }

    return operationComponent;
  }
  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;
  }
  @Override
  @Transactional
  public void createResourcesForReceiptDocuments(final Entity document) {
    Entity warehouse = document.getBelongsToField(DocumentFields.LOCATION_TO);
    Object date = document.getField(DocumentFields.TIME);

    for (Entity position : document.getHasManyField(DocumentFields.POSITIONS)) {
      createResource(document, warehouse, position, date);
    }
  }
  public void setGenerateButtonState(
      final ViewDefinitionState state,
      final Locale locale,
      final String plugin,
      final String entityName) {
    WindowComponent window = (WindowComponent) state.getComponentByReference("window");
    FormComponent form = (FormComponent) state.getComponentByReference("form");
    RibbonActionItem generateButton =
        window.getRibbon().getGroupByName("generate").getItemByName("generate");
    RibbonActionItem deleteButton =
        window.getRibbon().getGroupByName("actions").getItemByName("delete");

    if (form.getEntityId() == null) {
      generateButton.setMessage("recordNotCreated");
      generateButton.setEnabled(false);
      deleteButton.setMessage(null);
      deleteButton.setEnabled(false);
    } else {

      Entity simpleMaterialBalanceEntity =
          dataDefinitionService.get(plugin, entityName).get(form.getEntityId());

      if (simpleMaterialBalanceEntity.getField(L_GENERATED) == null) {
        simpleMaterialBalanceEntity.setField(L_GENERATED, "0");
      }

      if ("1".equals(simpleMaterialBalanceEntity.getField(L_GENERATED))) {
        generateButton.setMessage("orders.ribbon.message.recordAlreadyGenerated");
        generateButton.setEnabled(false);
        deleteButton.setMessage("orders.ribbon.message.recordAlreadyGenerated");
        deleteButton.setEnabled(false);
      } else {
        generateButton.setMessage(null);
        generateButton.setEnabled(true);
        deleteButton.setMessage(null);
        deleteButton.setEnabled(true);
      }
    }
    generateButton.requestUpdate(true);
    deleteButton.requestUpdate(true);
    window.requestRibbonRender();
  }
  public void checkDoneCalculate(final ViewDefinitionState viewDefinitionState) {
    FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference("form");
    Entity order =
        dataDefinitionService
            .get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER)
            .get(orderId);

    Integer realizationTime = (Integer) order.getField("realizationTime");
    if (realizationTime == null) {
      form.addMessage("orders.order.report.realizationTime", MessageType.INFO, false);
    }
  }
  protected void addDictionaryItems(final Map<String, String> values) {
    Entity dictionary = getDictionaryByName(values.get(NAME));

    Entity item = dataDefinitionService.get("qcadooModel", "dictionaryItem").create();
    item.setField("dictionary", dictionary);
    item.setField(NAME, values.get("item"));
    item.setField("description", values.get("description"));

    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Add test dictionary item {dictionary="
              + dictionary.getField(NAME)
              + ", item="
              + item.getField(NAME)
              + ", description="
              + item.getField("description")
              + "}");
    }

    item.getDataDefinition().save(item);
  }
 public boolean isRealizationTimeGenerated(final ViewDefinitionState viewDefinitionState) {
   FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference("form");
   if (form.getEntityId() == null) {
     return false;
   }
   Entity order =
       dataDefinitionService
           .get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER)
           .get(form.getEntityId());
   Integer realizationTime = (Integer) order.getField("realizationTime");
   return !(realizationTime == null || realizationTime == 0);
 }
  void applyTimeNormsFromGivenSource(
      final ViewDefinitionState view, final Entity source, final Iterable<String> fields) {
    checkArgument(source != null, "source entity is null");
    FieldComponent component = null;

    for (String fieldName : fields) {
      component = (FieldComponent) view.getComponentByReference(fieldName);
      component.setFieldValue(source.getField(fieldName));
    }

    if (source.getField(NEXT_OPERATION_AFTER_PRODUCED_TYPE) == null) {
      view.getComponentByReference(NEXT_OPERATION_AFTER_PRODUCED_TYPE).setFieldValue("01all");
    }

    if (source.getField(PRODUCTION_IN_ONE_CYCLE) == null) {
      view.getComponentByReference(PRODUCTION_IN_ONE_CYCLE).setFieldValue("1");
    }

    if (source.getField(NEXT_OPERATION_AFTER_PRODUCED_QUANTITY) == null) {
      view.getComponentByReference(NEXT_OPERATION_AFTER_PRODUCED_QUANTITY).setFieldValue("0");
    }
  }
Exemple #22
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 addOrderSeries(final Map<String, Object> model, final HSSFSheet sheet) {
   int rowNum = 1;
   Map<Entity, List<Entity>> productOrders =
       qualityControlsReportService.getQualityOrdersForProduct(
           qualityControlsReportService.getOrderSeries(model, "qualityControlsForUnit"));
   productOrders = SortUtil.sortMapUsingComparator(productOrders, new EntityNumberComparator());
   for (Entry<Entity, List<Entity>> entry : productOrders.entrySet()) {
     List<Entity> orders = entry.getValue();
     Collections.sort(orders, new EntityNumberComparator());
     for (Entity order : orders) {
       HSSFRow row = sheet.createRow(rowNum++);
       row.createCell(0)
           .setCellValue(
               entry.getKey() == null ? "" : entry.getKey().getField("number").toString());
       row.createCell(1).setCellValue(order.getField("number").toString());
       row.createCell(2)
           .setCellValue(
               numberService
                   .setScale((BigDecimal) order.getField("controlledQuantity"))
                   .doubleValue());
       row.createCell(3)
           .setCellValue(
               numberService
                   .setScale((BigDecimal) order.getField("rejectedQuantity"))
                   .doubleValue());
       row.createCell(4)
           .setCellValue(
               numberService
                   .setScale((BigDecimal) order.getField("acceptedDefectsQuantity"))
                   .doubleValue());
     }
   }
   sheet.autoSizeColumn((short) 0);
   sheet.autoSizeColumn((short) 1);
   sheet.autoSizeColumn((short) 2);
   sheet.autoSizeColumn((short) 3);
   sheet.autoSizeColumn((short) 4);
 }
  @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);
    }
  }
 private void refresh() {
   Long entityId = getFieldValueWithoutSearching();
   if (entityId == null) {
     selectedEntityCode = "";
     selectedEntityValue = "";
     selectedEntityActive = true;
     return;
   }
   Entity entity = getDataDefinition().get(entityId);
   if (entity == null) {
     setFieldValueWithoutRefreshing(null);
     selectedEntityCode = "";
     selectedEntityValue = "";
     selectedEntityActive = true;
   } else {
     selectedEntityCode = String.valueOf(entity.getField(fieldCode));
     selectedEntityValue = ExpressionUtils.getValue(entity, expression, getLocale());
     selectedEntityActive = entity.isActive();
   }
 }
  public void setGridGenerateButtonState(
      final ViewDefinitionState state,
      final Locale locale,
      final String plugin,
      final String entityName) {
    WindowComponent window = (WindowComponent) state.getComponentByReference("window");
    GridComponent grid = (GridComponent) state.getComponentByReference("grid");
    RibbonActionItem deleteButton =
        window.getRibbon().getGroupByName("actions").getItemByName("delete");

    if (grid.getSelectedEntitiesIds() == null || grid.getSelectedEntitiesIds().size() == 0) {
      deleteButton.setMessage(null);
      deleteButton.setEnabled(false);
    } else {
      boolean canDelete = true;
      for (Long entityId : grid.getSelectedEntitiesIds()) {
        Entity simpleMaterialBalanceEntity =
            dataDefinitionService.get(plugin, entityName).get(entityId);

        if ((Boolean) simpleMaterialBalanceEntity.getField(L_GENERATED)) {
          canDelete = false;
          break;
        }
      }
      if (canDelete) {
        deleteButton.setMessage(null);
        deleteButton.setEnabled(true);
      } else {
        deleteButton.setMessage("orders.ribbon.message.selectedRecordAlreadyGenerated");
        deleteButton.setEnabled(false);
      }
    }

    deleteButton.requestUpdate(true);
    window.requestRibbonRender();
  }
 private Date getEffectiveDate(final Entity order, final String effectiveField) {
   return (Date) order.getField(effectiveField);
 }
  public Entity createResource(
      final Entity document, final Entity warehouse, final Entity position, final Object date) {
    DataDefinition resourceDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_RESOURCE);

    Entity product = position.getBelongsToField(PositionFields.PRODUCT);
    Entity resource = resourceDD.create();
    Entity user = document.getBelongsToField(DocumentFields.USER);

    resource.setField(
        ResourceFields.USER_NAME,
        user.getStringField(_FIRST_NAME) + " " + user.getStringField(L_LAST_NAME));
    resource.setField(ResourceFields.TIME, date);
    resource.setField(ResourceFields.LOCATION, warehouse);
    resource.setField(ResourceFields.PRODUCT, position.getBelongsToField(PositionFields.PRODUCT));
    resource.setField(ResourceFields.QUANTITY, position.getField(PositionFields.QUANTITY));
    resource.setField(ResourceFields.RESERVED_QUANTITY, BigDecimal.ZERO);
    resource.setField(
        ResourceFields.AVAILABLE_QUANTITY, position.getDecimalField(PositionFields.QUANTITY));
    resource.setField(ResourceFields.PRICE, position.getField(PositionFields.PRICE));
    resource.setField(ResourceFields.BATCH, position.getField(PositionFields.BATCH));
    resource.setField(
        ResourceFields.EXPIRATION_DATE, position.getField(PositionFields.EXPIRATION_DATE));
    resource.setField(
        ResourceFields.PRODUCTION_DATE, position.getField(PositionFields.PRODUCTION_DATE));
    resource.setField(
        ResourceFields.STORAGE_LOCATION, position.getField(PositionFields.STORAGE_LOCATION));
    resource.setField(
        ResourceFields.ADDITIONAL_CODE, position.getField(PositionFields.ADDITIONAL_CODE));
    resource.setField(
        ResourceFields.PALLET_NUMBER, position.getField(PositionFields.PALLET_NUMBER));
    resource.setField(
        ResourceFields.TYPE_OF_PALLET, position.getField(PositionFields.TYPE_OF_PALLET));
    resource.setField(ResourceFields.WASTE, position.getField(PositionFields.WASTE));

    if (StringUtils.isEmpty(product.getStringField(ProductFields.ADDITIONAL_UNIT))) {
      resource.setField(ResourceFields.GIVEN_UNIT, product.getField(ProductFields.UNIT));
      resource.setField(
          ResourceFields.QUANTITY_IN_ADDITIONAL_UNIT, position.getField(PositionFields.QUANTITY));
      resource.setField(ResourceFields.CONVERSION, BigDecimal.ONE);
    } else {
      resource.setField(ResourceFields.GIVEN_UNIT, position.getField(PositionFields.GIVEN_UNIT));
      resource.setField(
          ResourceFields.QUANTITY_IN_ADDITIONAL_UNIT,
          position.getField(PositionFields.GIVEN_QUANTITY));
      resource.setField(ResourceFields.CONVERSION, position.getField(PositionFields.CONVERSION));
    }

    setResourceAttributesFromPosition(resource, position);

    resourceStockService.addResourceStock(resource);
    return resourceDD.save(resource);
  }
 @Override
 public int compare(final Entity o1, final Entity o2) {
   return ((Integer) o1.getField(FIELD_ORDER_NUMBER))
       .compareTo((Integer) o1.getField(FIELD_ORDER_NUMBER));
 }
  private List<Entity> updateResources(
      Entity warehouse, Entity position, WarehouseAlgorithm warehouseAlgorithm) {
    DataDefinition positionDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_POSITION);

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

    Entity product = position.getBelongsToField(PositionFields.PRODUCT);

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

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

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

      Entity newPosition = positionDD.create();

      newPosition.setField(
          PositionFields.PRODUCT, position.getBelongsToField(PositionFields.PRODUCT));
      newPosition.setField(
          PositionFields.GIVEN_QUANTITY, position.getDecimalField(PositionFields.GIVEN_QUANTITY));
      newPosition.setField(
          PositionFields.GIVEN_UNIT, position.getStringField(PositionFields.GIVEN_UNIT));
      newPosition.setField(PositionFields.PRICE, resource.getField(ResourceFields.PRICE));
      newPosition.setField(PositionFields.BATCH, resource.getField(ResourceFields.BATCH));
      newPosition.setField(
          PositionFields.PRODUCTION_DATE, resource.getField(ResourceFields.PRODUCTION_DATE));
      newPosition.setField(
          PositionFields.EXPIRATION_DATE, resource.getField(ResourceFields.EXPIRATION_DATE));
      newPosition.setField(PositionFields.RESOURCE, resource);
      newPosition.setField(
          PositionFields.STORAGE_LOCATION, resource.getField(ResourceFields.STORAGE_LOCATION));
      newPosition.setField(
          PositionFields.ADDITIONAL_CODE, resource.getField(ResourceFields.ADDITIONAL_CODE));
      newPosition.setField(PositionFields.CONVERSION, position.getField(PositionFields.CONVERSION));
      newPosition.setField(
          PositionFields.PALLET_NUMBER, resource.getField(ResourceFields.PALLET_NUMBER));
      newPosition.setField(
          PositionFields.TYPE_OF_PALLET, resource.getField(ResourceFields.TYPE_OF_PALLET));
      // newPosition.setField(PositionFields.GIVEN_UNIT,
      // resource.getField(ResourceFields.GIVEN_UNIT));

      setPositionAttributesFromResource(newPosition, resource);

      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);
        }

        newPosition.setField(
            PositionFields.QUANTITY, numberService.setScale(resourceAvailableQuantity));

        BigDecimal givenResourceQuantity = convertToGivenUnit(resourceAvailableQuantity, position);

        newPosition.setField(
            PositionFields.GIVEN_QUANTITY, numberService.setScale(givenResourceQuantity));

        newPositions.add(newPosition);

        if (BigDecimal.ZERO.compareTo(quantity) == 0) {
          return newPositions;
        }
      } else {
        resourceQuantity = resourceQuantity.subtract(quantity, numberService.getMathContext());
        resourceAvailableQuantity =
            resourceAvailableQuantity.subtract(quantity, numberService.getMathContext());
        if (position.getBelongsToField(PositionFields.RESOURCE) != null
            && reservationsService.reservationsEnabledForDocumentPositions()) {
          BigDecimal reservedQuantity =
              resource
                  .getDecimalField(ResourceFields.RESERVED_QUANTITY)
                  .subtract(quantity, numberService.getMathContext());
          resource.setField(ResourceFields.RESERVED_QUANTITY, reservedQuantity);
        }
        BigDecimal resourceConversion = resource.getDecimalField(ResourceFields.CONVERSION);
        BigDecimal quantityInAdditionalUnit = resourceQuantity.multiply(resourceConversion);

        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);
        newPosition.setField(PositionFields.QUANTITY, numberService.setScale(quantity));

        BigDecimal givenQuantity = convertToGivenUnit(quantity, position);

        newPosition.setField(PositionFields.GIVEN_QUANTITY, numberService.setScale(givenQuantity));
        newPositions.add(newPosition);

        return newPositions;
      }
    }

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

    return Lists.newArrayList(position);
  }