Search in sources :

Example 41 with ViewDefinitionState

use of com.qcadoo.view.api.ViewDefinitionState in project mes by qcadoo.

the class WarehouseIssueDetailsListeners method fillProductsToIssue.

public void fillProductsToIssue(final ViewDefinitionState view, final ComponentState state, final String[] args) {
    FormComponent issueForm = (FormComponent) view.getComponentByReference(QcadooViewConstants.L_FORM);
    FieldComponent collectionProductsField = (FieldComponent) view.getComponentByReference(WarehouseIssueFields.COLLECTION_PRODUCTS);
    LookupComponent operation = (LookupComponent) view.getComponentByReference(WarehouseIssueFields.TECHNOLOGY_OPERATION_COMPONENT);
    LookupComponent division = (LookupComponent) view.getComponentByReference(WarehouseIssueFields.DIVISION);
    Long warehouseIssueId = issueForm.getEntityId();
    Entity toc = operation.getEntity();
    Entity divisionEntity = division.getEntity();
    List<Entity> createdProducts = warehouseIssueService.fillProductsToIssue(warehouseIssueId, CollectionProducts.fromStringValue(collectionProductsField.getFieldValue().toString()), toc, divisionEntity);
    if (createdProducts != null) {
        List<Entity> invalidProducts = createdProducts.stream().filter(productToIssue -> !productToIssue.isValid()).collect(Collectors.toList());
        if (invalidProducts.isEmpty()) {
            view.addMessage("productFlowThruDivision.issue.downloadedProducts", ComponentState.MessageType.SUCCESS);
        } else {
            Multimap<String, String> errors = ArrayListMultimap.create();
            for (Entity productToIssue : invalidProducts) {
                String number = productToIssue.getBelongsToField(ProductsToIssueFields.PRODUCT).getStringField(ProductFields.NUMBER);
                Map<String, ErrorMessage> errorMessages = productToIssue.getErrors();
                errorMessages.entrySet().stream().forEach(entry -> errors.put(entry.getValue().getMessage(), number));
                productToIssue.getGlobalErrors().stream().forEach(error -> errors.put(error.getMessage(), number));
            }
            view.addMessage("productFlowThruDivision.issue.downloadedProductsError", ComponentState.MessageType.INFO, false);
            for (String message : errors.keySet()) {
                String translatedMessage = translationService.translate(message, LocaleContextHolder.getLocale());
                String products = errors.get(message).stream().collect(Collectors.joining(", "));
                if ((translatedMessage + products).length() < 255) {
                    view.addMessage("productFlowThruDivision.issue.downloadedProductsErrorMessages", ComponentState.MessageType.FAILURE, false, translatedMessage, products);
                }
            }
        }
    } else {
        view.addMessage("productFlowThruDivision.issue.noProductsToDownload", ComponentState.MessageType.INFO);
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) java.util(java.util) DataDefinitionService(com.qcadoo.model.api.DataDefinitionService) ProductsToIssueFields(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.constans.ProductsToIssueFields) IssueFields(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.constans.IssueFields) ComponentState(com.qcadoo.view.api.ComponentState) QcadooViewConstants(com.qcadoo.view.constants.QcadooViewConstants) Autowired(org.springframework.beans.factory.annotation.Autowired) OrderFields(com.qcadoo.mes.orders.constants.OrderFields) ProductionLineFields(com.qcadoo.mes.productionLines.constants.ProductionLineFields) Multimap(com.google.common.collect.Multimap) OrdersConstants(com.qcadoo.mes.orders.constants.OrdersConstants) DateUtils(com.qcadoo.localization.api.utils.DateUtils) BigDecimal(java.math.BigDecimal) ErrorMessage(com.qcadoo.model.api.validators.ErrorMessage) ViewDefinitionState(com.qcadoo.view.api.ViewDefinitionState) WarehouseIssueService(com.qcadoo.mes.productFlowThruDivision.service.WarehouseIssueService) Service(org.springframework.stereotype.Service) FormComponent(com.qcadoo.view.api.components.FormComponent) WarehouseIssueFields(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.constans.WarehouseIssueFields) WarehouseIssueHooks(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.hooks.WarehouseIssueHooks) WarehouseIssueParameterService(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.WarehouseIssueParameterService) TranslationService(com.qcadoo.localization.api.TranslationService) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) DataDefinition(com.qcadoo.model.api.DataDefinition) GridComponent(com.qcadoo.view.api.components.GridComponent) Entity(com.qcadoo.model.api.Entity) CollectionProducts(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.constans.CollectionProducts) FieldComponent(com.qcadoo.view.api.components.FieldComponent) WarehouseIssueDetailHooks(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.hooks.WarehouseIssueDetailHooks) NumberService(com.qcadoo.model.api.NumberService) LookupComponent(com.qcadoo.view.api.components.LookupComponent) ProductFields(com.qcadoo.mes.basic.constants.ProductFields) ProductFlowThruDivisionConstants(com.qcadoo.mes.productFlowThruDivision.constants.ProductFlowThruDivisionConstants) IssueDetailsHooks(com.qcadoo.mes.productFlowThruDivision.warehouseIssue.hooks.IssueDetailsHooks) FormComponent(com.qcadoo.view.api.components.FormComponent) Entity(com.qcadoo.model.api.Entity) LookupComponent(com.qcadoo.view.api.components.LookupComponent) FieldComponent(com.qcadoo.view.api.components.FieldComponent) ErrorMessage(com.qcadoo.model.api.validators.ErrorMessage)

Example 42 with ViewDefinitionState

use of com.qcadoo.view.api.ViewDefinitionState in project mes by qcadoo.

the class RemoveTOCService method removeOnlySelectedOperation.

@Transactional
public boolean removeOnlySelectedOperation(final Entity tocToDelete, final ViewDefinitionState view) {
    List<Entity> usageInProductStructureTree = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_PRODUCT_STRUCTURE_TREE_NODE).find().add(SearchRestrictions.belongsTo(ProductStructureTreeNodeFields.OPERATION, tocToDelete)).list().getEntities();
    if (!usageInProductStructureTree.isEmpty()) {
        view.addMessage("technologies.technologyDetails.window.treeTab.technologyTree.error.cannotDeleteOperationUsedInProductStructureTree", ComponentState.MessageType.FAILURE, false, usageInProductStructureTree.stream().map(e -> e.getBelongsToField(ProductStructureTreeNodeFields.MAIN_TECHNOLOGY).getStringField(TechnologyFields.NUMBER)).distinct().collect(Collectors.joining(", ")));
        return false;
    }
    final Entity parent = tocToDelete.getBelongsToField(TechnologyOperationComponentFields.PARENT);
    final List<Entity> operationsToRewrite = tocToDelete.getHasManyField(TechnologyOperationComponentFields.CHILDREN);
    if (parent == null) {
        if (operationsToRewrite.size() > 1) {
            view.addMessage("technologies.technologyDetails.window.treeTab.technologyTree.error.cannotDeleteRoot", ComponentState.MessageType.FAILURE);
            return false;
        } else if (operationsToRewrite.size() == 1) {
            return createNewRoot(operationsToRewrite.get(0), tocToDelete, view);
        } else {
            deleteOldToc(tocToDelete);
            return true;
        }
    }
    final Optional<Entity> mainOutProductComponentToDelete = technologyService.tryGetMainOutputProductComponent(tocToDelete);
    final List<Entity> originalInProducts = tocToDelete.getHasManyField(TechnologyOperationComponentFields.OPERATION_PRODUCT_IN_COMPONENTS);
    List<Entity> newInProducts = Lists.newArrayList();
    for (Entity toc : operationsToRewrite) {
        Optional<Entity> mainOutProductComponent = technologyService.tryGetMainOutputProductComponent(toc);
        if (mainOutProductComponent.isPresent()) {
            Optional<Entity> maybeInProductComponent = getInProductComponentFromProductComponent(originalInProducts, mainOutProductComponent.get());
            if (maybeInProductComponent.isPresent()) {
                Entity inProductComponent = maybeInProductComponent.get();
                newInProducts.add(inProductComponent);
            }
        }
        setNewParent(toc, parent);
    }
    if (!rewriteInProductComponents(parent, newInProducts, mainOutProductComponentToDelete, view)) {
        view.addMessage("technologies.technologyDetails.window.treeTab.technologyTree.error.cannotRewriteProducts", ComponentState.MessageType.FAILURE);
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return false;
    }
    deleteOldToc(tocToDelete);
    return true;
}
Also used : DataDefinitionService(com.qcadoo.model.api.DataDefinitionService) SearchRestrictions(com.qcadoo.model.api.search.SearchRestrictions) ComponentState(com.qcadoo.view.api.ComponentState) Autowired(org.springframework.beans.factory.annotation.Autowired) UnitConversionItemFieldsB(com.qcadoo.mes.basic.constants.UnitConversionItemFieldsB) UnitConversionService(com.qcadoo.model.api.units.UnitConversionService) TechnologyService(com.qcadoo.mes.technologies.TechnologyService) Collectors(java.util.stream.Collectors) DataDefinition(com.qcadoo.model.api.DataDefinition) BigDecimal(java.math.BigDecimal) List(java.util.List) com.qcadoo.mes.technologies.constants(com.qcadoo.mes.technologies.constants) Entity(com.qcadoo.model.api.Entity) ViewDefinitionState(com.qcadoo.view.api.ViewDefinitionState) Lists(com.google.common.collect.Lists) PossibleUnitConversions(com.qcadoo.model.api.units.PossibleUnitConversions) Service(org.springframework.stereotype.Service) TransactionAspectSupport(org.springframework.transaction.interceptor.TransactionAspectSupport) Optional(java.util.Optional) ProductFields(com.qcadoo.mes.basic.constants.ProductFields) Transactional(org.springframework.transaction.annotation.Transactional) Entity(com.qcadoo.model.api.Entity) Transactional(org.springframework.transaction.annotation.Transactional)

Example 43 with ViewDefinitionState

use of com.qcadoo.view.api.ViewDefinitionState in project qcadoo by qcadoo.

the class ExportToCsvController method generateCsv.

@Monitorable(threshold = 500)
@ResponseBody
@RequestMapping(value = { L_CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generateCsv(@PathVariable(L_PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier, @PathVariable(L_VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body, final Locale locale, @RequestHeader("User-Agent") final String userAgent) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference(QcadooViewConstants.L_GRID);
        if (grid == null) {
            JSONArray args = body.getJSONObject("event").getJSONArray("args");
            if (args.length() > 0) {
                grid = (GridComponent) state.getComponentByReference(args.getString(0));
            }
        }
        List<String> columns = getColumns(grid);
        List<String> columnNames = getColumnNames(grid, columns);
        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }
        File file = exportToCsv.createExportFile(columns, columnNames, rows, grid.getName());
        boolean openInNewWindow = !StringUtils.isNoneBlank(userAgent) || (!userAgent.contains("Chrome") && !userAgent.contains("Safari")) || userAgent.contains("Edge");
        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", openInNewWindow, false);
        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
Also used : GridComponent(com.qcadoo.view.api.components.GridComponent) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ViewDefinitionState(com.qcadoo.view.api.ViewDefinitionState) Map(java.util.Map) File(java.io.File) Monitorable(com.qcadoo.model.api.aop.Monitorable)

Example 44 with ViewDefinitionState

use of com.qcadoo.view.api.ViewDefinitionState in project qcadoo by qcadoo.

the class ExportToPdfController method generatePdf.

@Monitorable(threshold = 500)
@ResponseBody
@RequestMapping(value = { L_CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generatePdf(@PathVariable(L_PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier, @PathVariable(L_VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body, final Locale locale, @RequestHeader("User-Agent") final String userAgent) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference(QcadooViewConstants.L_GRID);
        if (grid == null) {
            JSONArray args = body.getJSONObject("event").getJSONArray("args");
            if (args.length() > 0) {
                grid = (GridComponent) state.getComponentByReference(args.getString(0));
            }
        }
        Document document = new Document(PageSize.A4.rotate());
        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream);
        pdfWriter.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        document.addTitle("export.pdf");
        pdfHelper.addMetaData(document);
        pdfWriter.createXmpMetadata();
        document.open();
        String title = translationService.translate(pluginIdentifier + "." + viewName + ".window.mainTab." + grid.getName() + ".header", locale);
        Date generationDate = new Date();
        pdfHelper.addDocumentHeader(document, "", title, translationService.translate("qcadooReport.commons.generatedBy.label", locale), generationDate);
        List<String> columns = getColumns(grid);
        List<String> columnNames = getColumnNames(grid, columns);
        PdfPTable pdfTable = pdfHelper.createTableWithHeader(columnNames.size(), columnNames, false);
        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }
        addPdfTableCells(pdfTable, rows, columns, viewName);
        document.add(pdfTable);
        document.close();
        boolean openInNewWindow = !StringUtils.isNoneBlank(userAgent) || (!userAgent.contains("Chrome") && !userAgent.contains("Safari")) || userAgent.contains("Edge");
        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", openInNewWindow, false);
        return crudService.renderView(state);
    } catch (JSONException | FileNotFoundException | DocumentException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) GridComponent(com.qcadoo.view.api.components.GridComponent) JSONArray(org.json.JSONArray) FileNotFoundException(java.io.FileNotFoundException) JSONException(org.json.JSONException) PdfPageNumbering(com.qcadoo.report.api.pdf.PdfPageNumbering) ViewDefinitionState(com.qcadoo.view.api.ViewDefinitionState) Document(com.lowagie.text.Document) Date(java.util.Date) PdfPTable(com.lowagie.text.pdf.PdfPTable) FileOutputStream(java.io.FileOutputStream) DocumentException(com.lowagie.text.DocumentException) File(java.io.File) Map(java.util.Map) Monitorable(com.qcadoo.model.api.aop.Monitorable)

Example 45 with ViewDefinitionState

use of com.qcadoo.view.api.ViewDefinitionState in project qcadoo by qcadoo.

the class GridComponentStateTest method init.

@Before
public void init() throws Exception {
    JSONObject jsonContent = new JSONObject();
    jsonContent.put(GridComponentState.JSON_SELECTED_ENTITY_ID, 13L);
    jsonContent.put(GridComponentState.JSON_MULTISELECT_MODE, false);
    JSONObject jsonSelected = new JSONObject();
    jsonSelected.put("13", true);
    jsonContent.put(GridComponentState.JSON_SELECTED_ENTITIES, jsonSelected);
    jsonContent.put(GridComponentState.JSON_BELONGS_TO_ENTITY_ID, 1L);
    jsonContent.put(GridComponentState.JSON_FIRST_ENTITY, 60);
    jsonContent.put(GridComponentState.JSON_MAX_ENTITIES, 30);
    jsonContent.put(GridComponentState.JSON_FILTERS_ENABLED, true);
    JSONArray jsonOrder = new JSONArray();
    jsonOrder.put(ImmutableMap.of("column", "asd", "direction", "asc"));
    jsonContent.put(GridComponentState.JSON_ORDER, jsonOrder);
    JSONObject jsonFilters = new JSONObject();
    jsonFilters.put("asd", "test");
    jsonFilters.put("qwe", "test2");
    jsonContent.put(GridComponentState.JSON_FILTERS, jsonFilters);
    json = new JSONObject(Collections.singletonMap(AbstractComponentState.JSON_CONTENT, jsonContent));
    Entity entity = mock(Entity.class);
    given(entity.getField("name")).willReturn("text");
    viewDefinitionState = mock(ViewDefinitionState.class);
    productDataDefinition = mock(DataDefinition.class, RETURNS_DEEP_STUBS);
    substituteDataDefinition = mock(DataDefinition.class, "substituteDataDefinition");
    HasManyType substitutesFieldType = mock(HasManyType.class);
    given(substitutesFieldType.getDataDefinition()).willReturn(substituteDataDefinition);
    given(substitutesFieldType.getJoinFieldName()).willReturn("product");
    substitutesFieldDefinition = mock(FieldDefinition.class);
    given(substitutesFieldDefinition.getType()).willReturn(substitutesFieldType);
    given(substitutesFieldDefinition.getName()).willReturn("substitutes");
    given(substitutesFieldDefinition.getDataDefinition()).willReturn(substituteDataDefinition);
    substituteCriteria = mock(SearchCriteriaBuilder.class);
    given(substituteDataDefinition.getPluginIdentifier()).willReturn("plugin");
    given(substituteDataDefinition.getName()).willReturn("substitute");
    given(substituteDataDefinition.find()).willReturn(substituteCriteria);
    given(productDataDefinition.getPluginIdentifier()).willReturn("plugin");
    given(productDataDefinition.getName()).willReturn("product");
    given(productDataDefinition.getField("substitutes")).willReturn(substitutesFieldDefinition);
    columns = new LinkedHashMap<String, GridComponentColumn>();
    TranslationService translationService = mock(TranslationService.class);
    given(translationService.translate(Mockito.anyString(), Mockito.any(Locale.class))).willReturn("i18n");
    given(translationService.translate(Mockito.anyString(), Mockito.anyString(), Mockito.any(Locale.class))).willReturn("i18n");
    given(translationService.translate(Mockito.anyString(), Mockito.any(Locale.class))).willReturn("i18n");
    GridComponentPattern pattern = mock(GridComponentPattern.class);
    given(pattern.getColumns()).willReturn(columns);
    given(pattern.getBelongsToFieldDefinition()).willReturn(substitutesFieldDefinition);
    given(pattern.isActivable()).willReturn(false);
    given(pattern.isWeakRelation()).willReturn(false);
    ApplicationContext applicationContext = mock(ApplicationContext.class);
    setField(pattern, "applicationContext", applicationContext);
    SecurityRolesService securityRolesService = mock(SecurityRolesService.class);
    given(applicationContext.getBean(SecurityRolesService.class)).willReturn(securityRolesService);
    grid = new GridComponentState(productDataDefinition, pattern);
    grid.setDataDefinition(substituteDataDefinition);
    grid.setTranslationService(translationService);
    new ExpressionServiceImpl().init();
}
Also used : Locale(java.util.Locale) Entity(com.qcadoo.model.api.Entity) DefaultEntity(com.qcadoo.model.internal.DefaultEntity) FieldDefinition(com.qcadoo.model.api.FieldDefinition) JSONArray(org.json.JSONArray) GridComponentColumn(com.qcadoo.view.internal.components.grid.GridComponentColumn) ViewDefinitionState(com.qcadoo.view.api.ViewDefinitionState) Matchers.anyString(org.mockito.Matchers.anyString) DataDefinition(com.qcadoo.model.api.DataDefinition) HasManyType(com.qcadoo.model.api.types.HasManyType) SearchCriteriaBuilder(com.qcadoo.model.api.search.SearchCriteriaBuilder) ApplicationContext(org.springframework.context.ApplicationContext) GridComponentPattern(com.qcadoo.view.internal.components.grid.GridComponentPattern) JSONObject(org.json.JSONObject) TranslationService(com.qcadoo.localization.api.TranslationService) GridComponentState(com.qcadoo.view.internal.components.grid.GridComponentState) SecurityRolesService(com.qcadoo.security.api.SecurityRolesService) ExpressionServiceImpl(com.qcadoo.model.internal.ExpressionServiceImpl) Before(org.junit.Before)

Aggregations

ViewDefinitionState (com.qcadoo.view.api.ViewDefinitionState)50 Autowired (org.springframework.beans.factory.annotation.Autowired)35 QcadooViewConstants (com.qcadoo.view.constants.QcadooViewConstants)32 Service (org.springframework.stereotype.Service)31 ComponentState (com.qcadoo.view.api.ComponentState)29 Collectors (java.util.stream.Collectors)28 Entity (com.qcadoo.model.api.Entity)27 Lists (com.google.common.collect.Lists)25 GridComponent (com.qcadoo.view.api.components.GridComponent)25 DataDefinitionService (com.qcadoo.model.api.DataDefinitionService)24 FormComponent (com.qcadoo.view.api.components.FormComponent)23 BigDecimal (java.math.BigDecimal)21 List (java.util.List)21 Maps (com.google.common.collect.Maps)18 Map (java.util.Map)18 DataDefinition (com.qcadoo.model.api.DataDefinition)16 ProductFields (com.qcadoo.mes.basic.constants.ProductFields)15 SearchRestrictions (com.qcadoo.model.api.search.SearchRestrictions)13 FieldComponent (com.qcadoo.view.api.components.FieldComponent)11 Objects (java.util.Objects)11