@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);
  }
예제 #2
0
  @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;
  }
  private void setAdditionalInfo(
      final StateChangeContext stateChangeContext, final long difference) {
    if (difference == 0L) {
      return;
    }
    final Entity stateChangeEntity = stateChangeContext.getStateChangeEntity();
    final StateChangeEntityDescriber describer = stateChangeContext.getDescriber();
    final OrderState orderState =
        (OrderState) stateChangeContext.getStateEnumValue(describer.getTargetStateFieldName());

    String additionalInfoKey = null;
    if (OrderState.IN_PROGRESS.equals(orderState)) {
      if (difference < 0L) {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooEarly";
      } else {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooLate";
      }
    } else if (OrderState.COMPLETED.equals(orderState)) {
      if (difference < 0L) {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooEarly";
      } else {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooLate";
      }
    } else {
      return;
    }

    final String differenceAsString =
        TimeConverterService.convertTimeToString(String.valueOf(Math.abs(difference)));
    final String additionalInfo =
        translationService.translate(
            additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
    stateChangeEntity.setField(OrderStateChangeFields.ADDITIONAL_INFO, additionalInfo);
    stateChangeContext.save();
  }
예제 #4
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 boolean clearGeneratedOnCopy(final DataDefinition dataDefinition, final Entity entity) {
   entity.setField(L_DATE, null);
   entity.setField(L_GENERATED, false);
   entity.setField(L_FILE_NAME, null);
   entity.setField(L_WORKER, null);
   return true;
 }
예제 #6
0
  @Test
  public final void
      shouldMarkEntityAsInvalidAndSetStateToFailureIfStateChangeEntityIsInvalidAfterSave() {
    // given
    final Entity savedStateChangeEntity = mock(Entity.class);
    given(stateChangeEntity.isValid()).willReturn(true);
    given(savedStateChangeEntity.isValid()).willReturn(true, false);
    given(stateChangeDD.save(stateChangeEntity)).willReturn(savedStateChangeEntity);

    final Map<String, ErrorMessage> fieldErrorsMap = Maps.newHashMap();
    final ErrorMessage fieldErrorMessage = buildErrorMessage(FIELD_1_MESSAGE_1);
    fieldErrorsMap.put(FIELD_1_NAME, fieldErrorMessage);
    given(savedStateChangeEntity.getErrors()).willReturn(fieldErrorsMap);

    final List<ErrorMessage> globalErrors = Lists.newArrayList();
    final ErrorMessage globalErrorMessage = buildErrorMessage(GLOBAL_MESSAGE_1);
    globalErrors.add(globalErrorMessage);
    given(savedStateChangeEntity.getGlobalErrors()).willReturn(globalErrors);

    // when
    stateChangeContext.save();

    // then
    verify(messageService)
        .addValidationError(
            stateChangeContext, FIELD_1_NAME, FIELD_1_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(messageService)
        .addValidationError(stateChangeContext, null, GLOBAL_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(stateChangeEntity).setField(describer.getStatusFieldName(), FAILURE.getStringValue());
  }
  @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");
  }
예제 #8
0
  @Test
  public final void shouldSaveButNotSetJustInvalidateOwnerEntity() {
    // given
    given(owner.isValid()).willReturn(true);
    given(ownerDD.save(owner)).willReturn(savedOwner);
    given(savedOwner.isValid()).willReturn(false);

    final Map<String, ErrorMessage> fieldErrorsMap = Maps.newHashMap();
    final ErrorMessage fieldErrorMessage = buildErrorMessage(FIELD_1_MESSAGE_1);
    fieldErrorsMap.put(FIELD_1_NAME, fieldErrorMessage);
    given(savedOwner.getErrors()).willReturn(fieldErrorsMap);

    final List<ErrorMessage> globalErrors = Lists.newArrayList();
    final ErrorMessage globalErrorMessage = buildErrorMessage(GLOBAL_MESSAGE_1);
    globalErrors.add(globalErrorMessage);
    given(savedOwner.getGlobalErrors()).willReturn(globalErrors);

    // when
    stateChangeContext.setOwner(owner);

    // then
    verify(ownerDD).save(owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), savedOwner);
    verify(messageService)
        .addValidationError(
            stateChangeContext, FIELD_1_NAME, FIELD_1_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(messageService)
        .addValidationError(stateChangeContext, null, GLOBAL_MESSAGE_1, EMPTY_STRING_ARRAY);
    verify(stateChangeEntity)
        .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue());
  }
  @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 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());
  }
예제 #11
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;
  }
 private Entity mockProgressForDayEntity(final Entity... dailyProgresses) {
   Entity pfdEntity = mockEntity(dataDefinition);
   stubHasManyField(
       pfdEntity, ProgressForDayFields.DAILY_PROGRESS, Arrays.asList(dailyProgresses));
   given(pfdEntity.isValid()).willReturn(true);
   return pfdEntity;
 }
  @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());
  }
예제 #14
0
  private Entity getExistingOrder(final Entity order) {
    if (order.getId() == null) {
      return null;
    }

    return order.getDataDefinition().get(order.getId());
  }
  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);
    }
  }
 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);
 }
 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());
   }
 }
 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);
 }
예제 #19
0
 private void addWorkPlanComponent(final Entity workPlan, final List<Entity> orders) {
   if (orders == null || orders.isEmpty()) {
     return;
   }
   List<Entity> existingOrders = workPlan.getManyToManyField("orders");
   existingOrders.addAll(orders);
   workPlan.setField("orders", existingOrders);
 }
예제 #20
0
  private void generateNumber(final Entity palletNumber) {
    String number = palletNumber.getStringField(PalletNumberFields.NUMBER);

    if (StringUtils.isEmpty(number)) {
      number = palletNumberGenerator.generate();
    }

    palletNumber.setField(PalletNumberFields.NUMBER, number);
  }
예제 #21
0
  private void generateDictionaryItem(final String name) {
    Entity dictionary = getDictionaryByName(name);

    Entity item = dataDefinitionService.get("qcadooModel", "dictionaryItem").create();
    item.setField("dictionary", dictionary);
    item.setField(L_NAME, generateString(CHARS_ONLY, 8));

    dataDefinitionService.get("qcadooModel", "dictionaryItem").save(item);
  }
  @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);
    }
  }
예제 #23
0
  private void setResourceAttributesFromPosition(final Entity resource, final Entity position) {
    List<Entity> attributes = position.getHasManyField(PositionFields.ATRRIBUTE_VALUES);

    for (Entity attribute : attributes) {
      attribute.setField(AttributeValueFields.RESOURCE, resource);
    }

    resource.setField(ResourceFields.ATRRIBUTE_VALUES, attributes);
  }
  public void changeActiveState(
      final DataDefinition customTranslationDD, final Entity customTranslation) {
    String pluginIdentifier = customTranslation.getStringField(PLUGIN_IDENTIFIER);
    String translation = customTranslation.getStringField(CUSTOM_TRANSLATION);

    if (pluginStateResolver.isEnabled(pluginIdentifier)) {
      customTranslation.setField(ACTIVE, (translation != null));
    }
  }
예제 #25
0
  @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());
  }
  private void setOrderDoneQuantity(final Entity productionTracking) {
    Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER);

    order.setField(
        OrderFields.DONE_QUANTITY,
        basicProductionCountingService.getProducedQuantityFromBasicProductionCountings(order));

    order.getDataDefinition().save(order);
  }
  @Test
  public void shouldCallAndFailDefaultMaxStringLenFieldValidators() throws Exception {
    // given
    String stringWith300Characters = StringUtils.repeat("a", 300);

    // when & then
    Entity savedPart = performFieldValidationTestOnPart("name", stringWith300Characters, false);
    Assert.assertEquals(
        "qcadooView.validate.field.error.invalidLength", savedPart.getError("name").getMessage());
  }
 private String getOrderDescription(final Entity order, final Locale locale) {
   return order.getStringField("number")
       + " - "
       + order.getStringField("name")
       + "<br/>"
       + translationService.translate("orders.order.state.label", locale)
       + ": "
       + translationService.translate(
           "orders.order.state.value." + order.getStringField("state"), locale);
 }
예제 #29
0
  @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 updateCache(
      final DataDefinition customTranslationDD, final Entity customTranslation) {
    boolean active = customTranslation.getBooleanField(ACTIVE);

    String key = customTranslation.getStringField(KEY);
    String locale = customTranslation.getStringField(LOCALE);
    String translation = (active) ? customTranslation.getStringField(CUSTOM_TRANSLATION) : null;

    customTranslationCacheService.manageCustomTranslation(key, locale, translation);
  }