@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());
  }
Пример #2
0
  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);
  }
Пример #3
0
  private Entity generateFormEntity(final ViewDefinitionState view) {
    DataDefinition dd =
        dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT);

    FormComponent form = getForm(view);
    Entity formEntity = form.getEntity();
    GridComponent parentsGrid = (GridComponent) view.getComponentByReference("parents");
    if (parentsGrid.getSelectedEntities().isEmpty()) {
      return null;
    }
    Long productId = parentsGrid.getSelectedEntities().get(0).getId();

    if (productId == null) {
      throw new FormValidationException("basic.productFamiliesTree.noProductSelected");
    }

    Entity product = dd.get(productId);

    List<Entity> tree = productsFamiliesTreeService.getHierarchyProductsTree(product);
    EntityTree entityTree = EntityTreeUtilsService.getDetachedEntityTree(tree);
    formEntity.setId(productId);
    formEntity.setField(PRODUCT_FAMILY_CHILDREN_TREE, entityTree);

    return formEntity;
  }
  @BeforeClass
  public static void init() throws Exception {
    applicationContext = mock(ApplicationContext.class);
    dataAccessService = mock(DataAccessService.class);
    translationService = mock(TranslationService.class);

    dataDefinitionService = new DataDefinitionServiceImpl();

    modelXmlToDefinitionConverter = new ModelXmlToDefinitionConverterImpl();
    setField(modelXmlToDefinitionConverter, "dataDefinitionService", dataDefinitionService);
    setField(modelXmlToDefinitionConverter, "dataAccessService", dataAccessService);
    setField(modelXmlToDefinitionConverter, "applicationContext", applicationContext);
    setField(modelXmlToDefinitionConverter, "translationService", translationService);

    given(applicationContext.getBean(CustomHook.class)).willReturn(new CustomHook());

    modelXmlToClassConverter = new ModelXmlToClassConverterImpl();
    ((ModelXmlToClassConverterImpl) modelXmlToClassConverter)
        .setBeanClassLoader(ClassLoader.getSystemClassLoader());

    dataDefinitions =
        performConvert(
            Utils.FULL_FIRST_ENTITY_XML_RESOURCE,
            Utils.FULL_SECOND_ENTITY_XML_RESOURCE,
            Utils.FULL_THIRD_ENTITY_XML_RESOURCE,
            Utils.OTHER_FIRST_ENTITY_XML_RESOURCE,
            Utils.OTHER_SECOND_ENTITY_XML_RESOURCE);

    for (DataDefinition dd : dataDefinitions.toArray(new DataDefinition[dataDefinitions.size()])) {
      if (dd.getName().equals("firstEntity") && dd.getPluginIdentifier().equals("full")) {
        dataDefinition = (InternalDataDefinition) dd;
      }
    }
  }
Пример #5
0
  /**
   * Creates position with given field values (with the same base and given unit)
   *
   * @param product
   * @param quantity
   * @param price
   * @param batch
   * @param expirationDate
   * @param productionDate
   * @param resource
   * @return Created position entity
   */
  public Entity createPosition(
      final Entity product,
      final BigDecimal quantity,
      final BigDecimal price,
      final String batch,
      final Date productionDate,
      final Date expirationDate,
      final Entity resource) {
    DataDefinition positionDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_POSITION);
    Entity position = positionDD.create();

    position.setField(PositionFields.PRODUCT, product);
    position.setField(PositionFields.QUANTITY, quantity);
    position.setField(PositionFields.GIVEN_QUANTITY, quantity);
    position.setField(PositionFields.GIVEN_UNIT, product.getStringField(ProductFields.UNIT));
    position.setField(PositionFields.PRICE, price);
    position.setField(PositionFields.BATCH, batch);
    position.setField(PositionFields.PRODUCTION_DATE, productionDate);
    position.setField(PositionFields.EXPIRATION_DATE, expirationDate);
    position.setField(PositionFields.RESOURCE, resource);
    return position;
  }
  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;
  }
Пример #7
0
  @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);
  }
 public void setProductAsConverted(final ImportedProduct product) {
   DataDefinition importedProductDataDefinition =
       dataDefinitionService.get(
           SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_PRODUCT);
   Entity importedProduct = importedProductDataDefinition.get(product.getOriginalEntityId());
   importedProduct.setField(FIELD_CONVERTED, "1");
   importedProductDataDefinition.save(importedProduct);
 }
 public void setOrderAsConverted(final ImportedOrder order) {
   DataDefinition importedOrderDataDefinition =
       dataDefinitionService.get(
           SfcSimpleConstants.PLUGIN_IDENTIFIER, SfcSimpleConstants.MODEL_IMPORTED_ORDER);
   Entity importedOrder = importedOrderDataDefinition.get(order.getOriginalEntityId());
   importedOrder.setField(FIELD_CONVERTED, "1");
   importedOrderDataDefinition.save(importedOrder);
 }
  @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);
    }
  }
Пример #11
0
  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);
  }
Пример #12
0
  @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());
  }
  @Before
  public void init() {
    super.init();

    progressPerShiftViewSaver = new ProgressPerShiftViewSaver();
    ReflectionTestUtils.setField(
        progressPerShiftViewSaver, "progressForDayDataProvider", progressForDayDataProvider);

    given(dataDefinition.save(any(Entity.class)))
        .willAnswer(
            new Answer<Entity>() {

              @Override
              public Entity answer(final InvocationOnMock invocation) throws Throwable {
                return (Entity) invocation.getArguments()[0];
              }
            });

    ppsEntity = mockEntity(dataDefinition);
    stubHasManyField(
        ppsEntity,
        ProductionPerShiftFields.PLANNED_PROGRESS_CORRECTION_TYPES,
        Collections.<Entity>emptyList());

    form = mockForm(ppsEntity);

    stubViewComponent("progressForDays", progressForDaysAdl);
    stubViewComponent("form", form);

    stubTransactionStatus();
  }
  @Test
  public final void shouldNotSaveFormBecauseOfDeviationCausesValidationErrors() {
    // given
    stubProgressType(ProgressType.PLANNED);
    stubTechnologyOperation(null);

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

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

    // when
    progressPerShiftViewSaver.save(view);

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

    verify(dataDefinition).save(deviationCauseEntity);
    verify(dataDefinition, never()).save(ppsEntity);
    verify(deviationCausesAdl).setFieldValue(Lists.newArrayList(invalidDeviationCauseEntity));
    verify(form)
        .addMessage("qcadooView.message.saveFailedMessage", ComponentState.MessageType.FAILURE);
  }
Пример #15
0
  @Test
  public final void shouldGetPpsForOrderReturnNullIfPpsDoesNotExists() {
    // given
    Long givenOrderId = 1L;

    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(null);

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

    // then
    Assert.assertNull(resultPpsId);
  }
  private Entity performFieldValidationTestOnPart(
      final String fieldName, final Object fieldValue, final boolean shouldPass) {
    DataDefinition partDao = dataDefinitionService.get(PLUGIN_PRODUCTS_NAME, ENTITY_NAME_PART);

    pluginManager.enablePlugin(PLUGIN_PRODUCTS_NAME);

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

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

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

    return savedPart;
  }
  @Test
  public final void shouldBuildDataDefinitionWithFieldWhichIsAllowedToBeBothCopyableAndUnique() {
    // when
    DataDefinition convertedDataDefinition =
        performConvert(Utils.UNIQUE_COPYABLE_ENTITY_XML_RESOURCE).iterator().next();

    // then
    for (String fieldName : Lists.newArrayList("stringField", "textField")) {
      FieldDefinition fieldDefinition = convertedDataDefinition.getField(fieldName);
      assertNotNull(String.format("Field '%s' is missing", fieldName), fieldDefinition);
      assertTrue(
          String.format("Field '%s' should be unique", fieldName), fieldDefinition.isUnique());
      assertTrue(
          String.format("Field '%s' should be copyable", fieldName),
          fieldDefinition.getType().isCopyable());
    }
  }
Пример #18
0
  /**
   * Save document in database and creates resources if document is accepted.
   *
   * @return Created document entity.
   */
  public Entity build() {
    DataDefinition documentDD =
        dataDefinitionService.get(
            MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
            MaterialFlowResourcesConstants.MODEL_DOCUMENT);

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

    return savedDocument;
  }
Пример #19
0
 public Entity createDocument(
     UserService userService, NumberGeneratorService numberGeneratorService) {
   DataDefinition documentDD =
       dataDefinitionService.get(
           MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
           MaterialFlowResourcesConstants.MODEL_DOCUMENT);
   Entity document = documentDD.create();
   document.setField(DocumentFields.TIME, new Date());
   document.setField(DocumentFields.USER, userService.getCurrentUserEntity().getId());
   document.setField(DocumentFields.STATE, DocumentState.DRAFT.getStringValue());
   document.setField(
       DocumentFields.NUMBER,
       numberGeneratorService.generateNumber(
           MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
           MaterialFlowResourcesConstants.MODEL_DOCUMENT));
   document.setField(DocumentFields.POSITIONS, Lists.newArrayList());
   return document;
 }
  private List<String> getPluginIdentifiersFromView(final ViewDefinitionState viewDefinitionState) {

    List<String> pluginIdentifiers = new LinkedList<String>();
    GridComponent grid = (GridComponent) viewDefinitionState.getComponentByReference("grid");

    Preconditions.checkState(grid.getSelectedEntitiesIds().size() > 0, "No record selected");

    DataDefinition pluginDataDefinition =
        dataDefinitionService.get(
            QcadooPluginConstants.PLUGIN_IDENTIFIER, QcadooPluginConstants.MODEL_PLUGIN);
    for (Long entityId : grid.getSelectedEntitiesIds()) {
      Entity pluginEntity = pluginDataDefinition.get(entityId);

      pluginIdentifiers.add(pluginEntity.getStringField("identifier"));
    }

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

    pluginManager.enablePlugin(PLUGIN_PRODUCTS_NAME);

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

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

    // then
    Assert.assertTrue(savedProduct.isValid());
    Assert.assertEquals(stringWith300Characters, savedProduct.getStringField("name"));
  }
Пример #22
0
  @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);
  }
  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);

    DataDefinition materialCostsComponentDD = mock(DataDefinition.class);
    given(materialCostsComponentDD.create()).willReturn(createdEntity);

    DataDefinitionService dataDefinitionService = mock(DataDefinitionService.class);
    given(
            dataDefinitionService.get(
                CostNormsForMaterialsConstants.PLUGIN_IDENTIFIER,
                CostNormsForMaterialsConstants.MODEL_TECHNOLOGY_INST_OPER_PRODUCT_IN_COMP))
        .willReturn(materialCostsComponentDD);

    orderMaterialCostsEntityBuilder = new OrderMaterialCostsEntityBuilderImpl();

    ReflectionTestUtils.setField(
        orderMaterialCostsEntityBuilder, "dataDefinitionService", dataDefinitionService);
  }
 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;
 }
Пример #25
0
  @Test
  public final void shouldGenerateWorkPlanEntity() throws Exception {
    // given
    Entity emptyWorkPlan = mock(Entity.class);
    when(workPlanDD.create()).thenReturn(emptyWorkPlan);
    when(workPlanDD.save(emptyWorkPlan)).thenReturn(emptyWorkPlan);
    when(emptyWorkPlan.getDataDefinition()).thenReturn(workPlanDD);

    Entity order = mock(Entity.class);

    @SuppressWarnings("unchecked")
    Iterator<Entity> iterator = mock(Iterator.class);
    when(iterator.hasNext()).thenReturn(true, true, true, false);
    when(iterator.next()).thenReturn(order);

    @SuppressWarnings("unchecked")
    List<Entity> orders = mock(List.class);
    when(orders.iterator()).thenReturn(iterator);
    when(orders.size()).thenReturn(3);
    when(orders.get(Mockito.anyInt())).thenReturn(order);

    @SuppressWarnings("rawtypes")
    ArgumentCaptor<List> listArgCaptor = ArgumentCaptor.forClass(List.class);
    ArgumentCaptor<String> stringArgCaptor = ArgumentCaptor.forClass(String.class);

    // when
    workPlanService.generateWorkPlanEntity(orders);

    // then
    verify(emptyWorkPlan, times(1)).setField(Mockito.eq("orders"), listArgCaptor.capture());
    @SuppressWarnings("unchecked")
    List<Entity> resultOrders = listArgCaptor.getValue();
    Assert.assertEquals(orders.size(), resultOrders.size());
    Assert.assertSame(order, resultOrders.get(0));
    Assert.assertSame(order, resultOrders.get(1));
    Assert.assertSame(order, resultOrders.get(2));

    verify(emptyWorkPlan, times(1)).setField(Mockito.eq("name"), stringArgCaptor.capture());
    Assert.assertEquals(TRANSLATED_STRING, stringArgCaptor.getValue());

    verify(emptyWorkPlan, times(1)).setField(Mockito.eq("type"), stringArgCaptor.capture());
    Assert.assertEquals(WorkPlanType.NO_DISTINCTION.getStringValue(), stringArgCaptor.getValue());
  }
Пример #26
0
  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);
  }
Пример #27
0
 @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 void shouldNotCallAdditinanalFieldValidatorsIfPluginIsSystemDisabled() throws Exception {
    // given
    DataDefinition machineDao =
        dataDefinitionService.get(PLUGIN_MACHINES_NAME, ENTITY_NAME_MACHINE);
    machineDao.save(createMachine("asd"));

    pluginManager.disablePlugin(PLUGIN_MACHINES_NAME);

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

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

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

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

    // then
    Assert.assertTrue(component.isValid());
  }
  @Test
  public void shouldNotCallAdditinanalFieldValidatorsIfPluginIsDisabledForCurrentUser()
      throws Exception {
    // given
    DataDefinition machineDao =
        dataDefinitionService.get(PLUGIN_MACHINES_NAME, ENTITY_NAME_MACHINE);
    machineDao.save(createMachine("asd"));

    pluginManager.enablePlugin(PLUGIN_MACHINES_NAME);

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

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

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

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

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

    // then
    Assert.assertTrue(component.isValid());
  }
Пример #30
0
  @Test
  public void shouldReturnCompanyProductsFamilyWhenGetCompanyProductsFamily() {
    // given
    Long companyProductsFamilyId = 1L;

    given(companyProductsFamilyDD.get(companyProductsFamilyId)).willReturn(companyProductsFamily);

    // when
    Entity result = deliveriesService.getCompanyProductsFamily(companyProductsFamilyId);

    // then
    assertEquals(companyProductsFamily, result);
  }