diff --git a/src/main/java/org/sigmah/client/ui/presenter/admin/CategoriesAdminPresenter.java b/src/main/java/org/sigmah/client/ui/presenter/admin/CategoriesAdminPresenter.java index 9a87ae621..efa65f80a 100644 --- a/src/main/java/org/sigmah/client/ui/presenter/admin/CategoriesAdminPresenter.java +++ b/src/main/java/org/sigmah/client/ui/presenter/admin/CategoriesAdminPresenter.java @@ -21,7 +21,6 @@ * . * #L% */ - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -60,6 +59,7 @@ import org.sigmah.shared.servlet.ServletConstants.Servlet; import org.sigmah.shared.servlet.ServletConstants.ServletMethod; import org.sigmah.shared.servlet.ServletUrlBuilder; +import org.sigmah.shared.command.DisableCategoryElements; import com.extjs.gxt.ui.client.Style.Scroll; import com.extjs.gxt.ui.client.event.BaseEvent; @@ -73,625 +73,742 @@ import com.extjs.gxt.ui.client.widget.form.TextField; import com.extjs.gxt.ui.client.widget.grid.Grid; import com.google.gwt.dom.client.Element; +import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Singleton; +import org.sigmah.client.ui.notif.ConfirmCallback; /** * Admin categories Presenter which manages {@link CategoriesAdminView}. - * + * * @author Denis Colliot (dcolliot@ideia.fr) (v2.0) */ @Singleton public class CategoriesAdminPresenter extends AbstractAdminPresenter { - /** - * Description of the view managed by this presenter. - */ - @ImplementedBy(CategoriesAdminView.class) - public static interface View extends AbstractAdminPresenter.View { + /** + * Description of the view managed by this presenter. + */ + @ImplementedBy(CategoriesAdminView.class) + public static interface View extends AbstractAdminPresenter.View { - ListStore getCategoriesStore(); + ListStore getCategoriesStore(); - ListStore getCategoryElementsStore(); + ListStore getCategoryElementsStore(); - Grid getCategoryElementsGrid(); + Grid getCategoryElementsGrid(); - Grid getCategoriesGrid(); + Grid getCategoriesGrid(); - SimpleComboBox getCategoryIcon(); + SimpleComboBox getCategoryIcon(); - TextField getCategoryName(); + TextField getCategoryName(); - Button getAddCategoryElementButton(); + Button getAddCategoryElementButton(); - Button getDeleteCategoryElementButton(); + Button getDeleteCategoryElementButton(); - Button getDeleteCategoryTypeButton(); + Button getDisableCategoryElementButton(); - LoadingMask getGategoriesTypeLoadingMonitor(); + Button getEnableCategoryElementButton(); - LoadingMask getGategoriesElementsLoadingMonitor(); + Button getDeleteCategoryTypeButton(); - Button getAddCategoryTypeButton(); + LoadingMask getGategoriesTypeLoadingMonitor(); - void setCategoryPresenterHandler(CategoryPresenterHandler handler); + LoadingMask getGategoriesElementsLoadingMonitor(); - TextField getName(); + Button getAddCategoryTypeButton(); - ColorField getColorField(); + void setCategoryPresenterHandler(CategoryPresenterHandler handler); - Button getImportCategoryTypeButton(); + TextField getName(); - } + ColorField getColorField(); - public static interface CategoryPresenterHandler { + Boolean getisdisable(); - void onClickHandler(CategoryTypeDTO categoryTypeDTO); + Button getImportCategoryTypeButton(); - void onSelectHandler(CategoryTypeDTO categoryTypeDTO); + } - } + public static interface CategoryPresenterHandler { - private CategoryTypeDTO currentCategoryType; + void onClickHandler(CategoryTypeDTO categoryTypeDTO); - /** - * Presenters's initialization. - * - * @param view - * Presenter's view interface. - * @param injector - * Injected client injector. - */ - @Inject - protected CategoriesAdminPresenter(View view, Injector injector) { - super(view, injector); - } + void onSelectHandler(CategoryTypeDTO categoryTypeDTO); - /** - * {@inheritDoc} - */ - @Override - public Page getPage() { - return Page.ADMIN_CATEGORIES; - } + } - /** - * {@inheritDoc} - */ - @Override - public void onBind() { + private CategoryTypeDTO currentCategoryType; - /** - * *************** Category Panel ************************* - */ + /** + * Presenters's initialization. + * + * @param view Presenter's view interface. + * @param injector Injected client injector. + */ + @Inject + protected CategoriesAdminPresenter(View view, Injector injector) { + super(view, injector); + } - // ADD CATEGORY + /** + * {@inheritDoc} + */ + @Override + public Page getPage() { + return Page.ADMIN_CATEGORIES; + } - createCategoryButtonListener(); + /** + * {@inheritDoc} + */ + @Override + public void onBind() { - // Delete Category + /** + * *************** Category Panel ************************* + */ + // ADD CATEGORY + createCategoryButtonListener(); - deleteCategoryButtonListener(); + // Delete Category + deleteCategoryButtonListener(); // Import Category + importCategoryButtonListener(); - importCategoryButtonListener(); - - /** - * ****************** Category Element Panel ***************** - */ - + /** + * ****************** Category Element Panel ***************** + */ // ADD ELEMENT CATEGORY - - createCategoryElementListener(); + createCategoryElementListener(); // DELETE ELEMENT CATEGORY + deleteCategoryElementListener(); - deleteCategoryElementListener(); + //Disable category elements + disableCategoryElementListener(); + //Enable category elements + enableCategoryElementListener(); - /** - * ************* Presenter Handler ******************* - */ + /** + * ************* Presenter Handler ******************* + */ + view.setCategoryPresenterHandler(new CategoryPresenterHandler() { - view.setCategoryPresenterHandler(new CategoryPresenterHandler() { + /** + * show Category Elements + */ + @Override + public void onSelectHandler(CategoryTypeDTO categoryTypeDTO) { + currentCategoryType = categoryTypeDTO; - /** - * show Category Elements - */ - @Override - public void onSelectHandler(CategoryTypeDTO categoryTypeDTO) { - currentCategoryType = categoryTypeDTO; - view.getCategoryElementsGrid().show(); - view.getCategoryElementsStore().removeAll(); - for (CategoryElementDTO categoryElementDTO : categoryTypeDTO.getCategoryElementsDTO()) { - view.getCategoryElementsStore().add(categoryElementDTO); - } - view.getCategoryElementsStore().commitChanges(); - view.getAddCategoryElementButton().enable(); + view.getCategoryElementsGrid().show(); + view.getCategoryElementsStore().removeAll(); + for (CategoryElementDTO categoryElementDTO : categoryTypeDTO.getCategoryElementsDTO()) { + view.getCategoryElementsStore().add(categoryElementDTO); + } + view.getCategoryElementsStore().commitChanges(); + view.getAddCategoryElementButton().enable(); - } + } - /** - * Export Category - */ - @Override - public void onClickHandler(CategoryTypeDTO categoryTypeDTO) { + /** + * Export Category + */ + @Override + public void onClickHandler(CategoryTypeDTO categoryTypeDTO) { - final ServletUrlBuilder urlBuilder = - new ServletUrlBuilder(injector.getAuthenticationProvider(), injector.getPageManager(), Servlet.EXPORT, ServletMethod.EXPORT_MODEL_CATEGORY); + final ServletUrlBuilder urlBuilder + = new ServletUrlBuilder(injector.getAuthenticationProvider(), injector.getPageManager(), Servlet.EXPORT, ServletMethod.EXPORT_MODEL_CATEGORY); - urlBuilder.addParameter(RequestParameter.ID, categoryTypeDTO.getId()); + urlBuilder.addParameter(RequestParameter.ID, categoryTypeDTO.getId()); - ClientUtils.launchDownload(urlBuilder.toString()); + ClientUtils.launchDownload(urlBuilder.toString()); - } - }); + } + }); // Handler + registerHandler(eventBus.addHandler(UpdateEvent.getType(), new UpdateHandler() { - registerHandler(eventBus.addHandler(UpdateEvent.getType(), new UpdateHandler() { + @Override + public void onUpdate(final UpdateEvent event) { - @Override - public void onUpdate(final UpdateEvent event) { + if (event.concern(UpdateEvent.CATEGORY_MODEL_IMPORT)) { - if (event.concern(UpdateEvent.CATEGORY_MODEL_IMPORT)) { + refreshCategoryTypePanel(); + } + } + })); + } - refreshCategoryTypePanel(); - } - } - })); - } + private void importCategoryButtonListener() { - private void importCategoryButtonListener() { + view.getImportCategoryTypeButton().addListener(Events.Select, new Listener() { - view.getImportCategoryTypeButton().addListener(Events.Select, new Listener() { + @Override + public void handleEvent(ButtonEvent be) { + eventBus.navigateRequest(Page.IMPORT_MODEL.requestWith(RequestParameter.TYPE, AdminUtil.ADMIN_CATEGORY_MODEL)); + } + }); - @Override - public void handleEvent(ButtonEvent be) { - eventBus.navigateRequest(Page.IMPORT_MODEL.requestWith(RequestParameter.TYPE, AdminUtil.ADMIN_CATEGORY_MODEL)); - } - }); + } - } + private void deleteCategoryElementListener() { - private void deleteCategoryElementListener() { + view.getDeleteCategoryElementButton().addListener(Events.OnClick, new Listener() { - view.getDeleteCategoryElementButton().addListener(Events.OnClick, new Listener() { + @Override + public void handleEvent(ButtonEvent be) { + onDeleteCategoryElement(view.getCategoryElementsGrid().getSelectionModel().getSelectedItems()); + } - @Override - public void handleEvent(ButtonEvent be) { - onDeleteCategoryElement(view.getCategoryElementsGrid().getSelectionModel().getSelectedItems()); - } + }); + } - }); - } + private void disableCategoryElementListener() { + view.getDisableCategoryElementButton().addListener(Events.OnClick, new Listener() { - /** - * Method to delete a element under a category Firstly,get all project models for verifying if the selected category - * elements are being used by one or more project models. If being used, a category element should not be deleted. - * - * @param selectedItems - * The selected categories - */ - private void onDeleteCategoryElement(final List selectedItems) { + @Override + public void handleEvent(final ButtonEvent event) { + onDisableCategoryElement(view.getCategoryElementsGrid().getSelectionModel().getSelectedItems()); + } + }); + } - // Check if there is at least one item selected - if (ClientUtils.isEmpty(selectedItems)) { - N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.selectCategoryElementToDelete()); - return; - } + private void enableCategoryElementListener() { + view.getEnableCategoryElementButton().addListener(Events.OnClick, new Listener() { - dispatch.execute(new GetProjectModels(ProjectModelDTO.Mode.ALL, ProjectModelStatus.values()), new CommandResultHandler>() { + @Override + public void handleEvent(final ButtonEvent event) { + onEnableCategoryElement(view.getCategoryElementsGrid().getSelectionModel().getSelectedItems()); + } + }); + } - @Override - public void onCommandFailure(final Throwable arg0) { + /** + * Method to delete a element under a category Firstly,get all project + * models for verifying if the selected category elements are being used by + * one or more project models. If being used, a category element should not + * be deleted. + * + * @param selectedItems The selected categories + */ + private void onDeleteCategoryElement(final List selectedItems) { - N10N.error(I18N.CONSTANTS.error(), I18N.CONSTANTS.deleteCategoryGetProjectModelsError()); + // Check if there is at least one item selected + if (ClientUtils.isEmpty(selectedItems)) { + N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.selectCategoryElementToDelete()); + return; + } - } + dispatch.execute(new GetProjectModels(ProjectModelDTO.Mode.ALL, ProjectModelStatus.values()), new CommandResultHandler>() { - @Override - public void onCommandSuccess(final ListResult result) { + @Override + public void onCommandFailure(final Throwable arg0) { - deleteCategoryElementVerify(selectedItems, result.getList()); + N10N.error(I18N.CONSTANTS.error(), I18N.CONSTANTS.deleteCategoryGetProjectModelsError()); - } - }, view.getGategoriesElementsLoadingMonitor()); - } + } - private void createCategoryElementListener() { - - view.getAddCategoryElementButton().addListener(Events.OnClick, new Listener() { - - @Override - public void handleEvent(ButtonEvent be) { - if (view.getName().getValue() != null - && !view.getName().getValue().isEmpty() - && view.getCategoryElementsStore().findModel("label", view.getName().getValue()) == null) { - - Map newCategoryElementProperties = new HashMap(); - newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_ELEMENT_NAME, view.getName().getValue()); - newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_ELEMENT_COLOR, view.getColorField().getValue()); - newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_TYPE, currentCategoryType); - - dispatch.execute(new CreateEntity("CategoryElement", newCategoryElementProperties), new CommandResultHandler() { - - @Override - public void onCommandFailure(Throwable caught) { - N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardCreationFailureF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); - } - - @Override - public void onCommandSuccess(CreateResult result) { - if (result != null && result.getEntity() != null) { - view.getCategoryElementsStore().add((CategoryElementDTO) result.getEntity()); - view.getCategoryElementsStore().commitChanges(); - List elements = null; - if (currentCategoryType.getCategoryElementsDTO() == null) { - elements = new ArrayList(); - } else { - elements = currentCategoryType.getCategoryElementsDTO(); - } - elements.add((CategoryElementDTO) result.getEntity()); - currentCategoryType.setCategoryElementsDTO(elements); - view.getCategoriesStore().update(currentCategoryType); - view.getCategoriesStore().commitChanges(); - view.getName().clear(); - N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); - } else { - N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardCreationNullF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); - } - } - }); - } else { - N10N.warn("", I18N.CONSTANTS.adminStandardInvalidValues()); - } - } - }); - } + @Override + public void onCommandSuccess(final ListResult result) { - /** - * add category button listener - */ - private void createCategoryButtonListener() { - - view.getAddCategoryTypeButton().addListener(Events.OnClick, new Listener() { - - @Override - public void handleEvent(BaseEvent be) { - - if (view.getCategoryName().getValue() != null - && view.getCategoryIcon().getValue() != null - && view.getCategoriesStore().findModel("label", view.getCategoryName().getValue()) == null) { - - Map newCategoryTypeProperties = new HashMap(); - - newCategoryTypeProperties.put(AdminUtil.PROP_CATEGORY_TYPE_ICON, CategoryIcon.getIcon(view.getCategoryIcon().getValue().getValue())); - newCategoryTypeProperties.put(AdminUtil.PROP_CATEGORY_TYPE_NAME, view.getCategoryName().getValue()); - - dispatch.execute(new CreateEntity("CategoryType", newCategoryTypeProperties), new CommandResultHandler() { - - @Override - public void onCommandFailure(Throwable caught) { - N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardCreationFailureF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); - } - - @Override - public void onCommandSuccess(CreateResult result) { - if (result != null && result.getEntity() != null) { - - view.getCategoriesStore().add((CategoryTypeDTO) result.getEntity()); - view.getCategoriesStore().commitChanges(); - - N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); - - List selectedCategory = new ArrayList(); - selectedCategory.add((CategoryTypeDTO) result.getEntity()); // Focus and scroll to the new created - // category - int rowIndex = view.getCategoriesStore().indexOf((CategoryTypeDTO) result.getEntity()); - Element addedRow = view.getCategoriesGrid().getView().getRow(rowIndex); - view.getCategoriesGrid().getSelectionModel().setSelection(selectedCategory); - addedRow.setScrollTop(addedRow.getScrollTop()); - addedRow.scrollIntoView(); - - view.getCategoryName().clear(); - view.getCategoryIcon().clearSelections(); - - } else { - N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), - I18N.MESSAGES.adminStandardCreationNullF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); - } - } - }); - } else { - N10N.warn("", I18N.CONSTANTS.adminStandardInvalidValues()); - } - }; - }); - } + deleteCategoryElementVerify(selectedItems, result.getList()); - /** - * Delete Category Button Listener - */ - public void deleteCategoryButtonListener() { - - view.getDeleteCategoryTypeButton().addListener(Events.OnClick, new Listener() { - - @Override - public void handleEvent(ButtonEvent be) { - onDeleteCategory(view.getCategoriesGrid().getSelectionModel().getSelectedItems()); - } - - }); - - } - - /** - * Method to delete a category. Firstly,get all project models for verifying if there is one or more in the selected - * categories who are being used by one or more project models. If being used, a category should not be deleted. - * - * @param selectedItems - * The selected categories - */ - protected void onDeleteCategory(final List selectedItems) { - - // Check if there is at least one item selected - if (selectedItems == null || selectedItems.size() == 0) { - N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.selectCategoryToDelete()); - return; - } - - GetProjectModels cmdGetProjectModels = new GetProjectModels(ProjectModelDTO.Mode.ALL, ProjectModelStatus.values()); - - dispatch.execute(cmdGetProjectModels, new CommandResultHandler>() { + } + }, view.getGategoriesElementsLoadingMonitor()); + } - @Override - public void onCommandFailure(Throwable arg0) { + private void onDisableCategoryElement(final List selection) { - N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.deleteCategoryGetProjectModelsError()); + final StringBuilder fields = new StringBuilder(); - } + for (CategoryElementDTO s : selection) { - @Override - public void onCommandSuccess(ListResult result) { + if (fields.length() > 0) { + fields.append(", "); + } + fields.append(s.getLabel()); + } - deleteCategoryVerify(selectedItems, result.getList()); + dispatch.execute(new DisableCategoryElements(selection, true), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + N10N.error(I18N.CONSTANTS.error(), I18N.MESSAGES.flexibleElementDisableError(fields.toString())); + } - } - }, view.getGategoriesTypeLoadingMonitor()); + @Override + public void onSuccess(VoidResult result) { + // update view + for (CategoryElementDTO element : selection) { + // + element.setisDisabled(true); + //view.getCategoryElementsStore().remove(element); + view.getCategoryElementsStore().update(element); + } + + // Feedback + N10N.infoNotif(I18N.CONSTANTS.infoConfirmation(), + I18N.CONSTANTS.adminDisableCategoryElementsConfirm()); + } + }); + + } + + private void onEnableCategoryElement(final List selection) { + + final StringBuilder fields = new StringBuilder(); + final List elementNames = new ArrayList(); + + for (final CategoryElementDTO element : selection) { + elementNames.add(element.getLabel()); + } + + for (CategoryElementDTO s : selection) { + + if (fields.length() > 0) { + fields.append(", "); + } + fields.append(s.getLabel()); + } + + N10N.confirmation(I18N.CONSTANTS.enable(), I18N.CONSTANTS.adminCategoryElementEnableConfirm(), elementNames, new ConfirmCallback() { + + @Override + public void onAction() { + + dispatch.execute(new DisableCategoryElements(selection, false), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + N10N.error(I18N.CONSTANTS.error(), I18N.MESSAGES.flexibleElementDisableError(fields.toString())); + } + + @Override + public void onSuccess(VoidResult result) { + // update view + for (CategoryElementDTO element : selection) { + element.setisDisabled(false); + view.getCategoryElementsStore().update(element); + } + + // Feedback + N10N.infoNotif(I18N.CONSTANTS.infoConfirmation(), + I18N.CONSTANTS.adminEnableCategoryElementsConfirm()); + } + }); + } + }); + + } + + private void createCategoryElementListener() { + + view.getAddCategoryElementButton().addListener(Events.OnClick, new Listener() { + + @Override + public void handleEvent(ButtonEvent be) { + if (view.getName().getValue() != null + && !view.getName().getValue().isEmpty() + && view.getCategoryElementsStore().findModel("label", view.getName().getValue()) == null) { + + final List elementNames = new ArrayList(); + + elementNames.add(view.getName().getValue()); + + N10N.confirmation(I18N.CONSTANTS.categoryElements(), I18N.CONSTANTS.adminCategoryElementEnableConfirm(), elementNames, new ConfirmCallback() { + + @Override + public void onAction() { + + Map newCategoryElementProperties = new HashMap(); + newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_ELEMENT_NAME, view.getName().getValue()); + newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_ELEMENT_COLOR, view.getColorField().getValue()); + newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_ELEMENT_ISDISABLED, false); + newCategoryElementProperties.put(AdminUtil.PROP_CATEGORY_TYPE, currentCategoryType); + + dispatch.execute(new CreateEntity("CategoryElement", newCategoryElementProperties), new CommandResultHandler() { + + @Override + public void onCommandFailure(Throwable caught) { + N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardCreationFailureF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); + } + + @Override + public void onCommandSuccess(CreateResult result) { + if (result != null && result.getEntity() != null) { + view.getCategoryElementsStore().add((CategoryElementDTO) result.getEntity()); + view.getCategoryElementsStore().commitChanges(); + List elements = null; + if (currentCategoryType.getCategoryElementsDTO() == null) { + elements = new ArrayList(); + } else { + elements = currentCategoryType.getCategoryElementsDTO(); + } + elements.add((CategoryElementDTO) result.getEntity()); + currentCategoryType.setCategoryElementsDTO(elements); + view.getCategoriesStore().update(currentCategoryType); + view.getCategoriesStore().commitChanges(); + view.getName().clear(); + N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); + } else { + N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardCreationNullF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + currentCategoryType.getLabel() + "'")); + } + } + }); + } + }); + } else { + N10N.warn("", I18N.CONSTANTS.adminStandardInvalidValues()); + } + } + }); + } + + /** + * add category button listener + */ + private void createCategoryButtonListener() { + + view.getAddCategoryTypeButton().addListener(Events.OnClick, new Listener() { + + @Override + public void handleEvent(BaseEvent be) { + + if (view.getCategoryName().getValue() != null + && view.getCategoryIcon().getValue() != null + && view.getCategoriesStore().findModel("label", view.getCategoryName().getValue()) == null) { + + Map newCategoryTypeProperties = new HashMap(); + + newCategoryTypeProperties.put(AdminUtil.PROP_CATEGORY_TYPE_ICON, CategoryIcon.getIcon(view.getCategoryIcon().getValue().getValue())); + newCategoryTypeProperties.put(AdminUtil.PROP_CATEGORY_TYPE_NAME, view.getCategoryName().getValue()); + + dispatch.execute(new CreateEntity("CategoryType", newCategoryTypeProperties), new CommandResultHandler() { + + @Override + public void onCommandFailure(Throwable caught) { + N10N.warn(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardCreationFailureF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); + } + + @Override + public void onCommandSuccess(CreateResult result) { + if (result != null && result.getEntity() != null) { + + view.getCategoriesStore().add((CategoryTypeDTO) result.getEntity()); + view.getCategoriesStore().commitChanges(); + + N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); + + List selectedCategory = new ArrayList(); + selectedCategory.add((CategoryTypeDTO) result.getEntity()); // Focus and scroll to the new created + // category + int rowIndex = view.getCategoriesStore().indexOf((CategoryTypeDTO) result.getEntity()); + Element addedRow = view.getCategoriesGrid().getView().getRow(rowIndex); + view.getCategoriesGrid().getSelectionModel().setSelection(selectedCategory); + addedRow.setScrollTop(addedRow.getScrollTop()); + addedRow.scrollIntoView(); + + view.getCategoryName().clear(); + view.getCategoryIcon().clearSelections(); + + } else { + N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), + I18N.MESSAGES.adminStandardCreationNullF(I18N.CONSTANTS.adminCategoryTypeStandard() + " '" + view.getCategoryName().getValue() + "'")); + } + } + }); + } else { + N10N.warn("", I18N.CONSTANTS.adminStandardInvalidValues()); + } + } + ; + } + + ); } /** - * Method to verify the deletion action. If the verification passes, try to delete a category, or show a alert window. - * - * @param selectedItems - * The selected categories - * @param allProjectModelsList - * The list of all project models - */ - private void deleteCategoryVerify(final List selectedItems, List allProjectModelsList) { - - // A List to store DeletionError object - List deletionErrorList = new ArrayList(); - - // Check - for (ProjectModelDTO projectModelDTO : allProjectModelsList) { - List allElements = new ArrayList(); - allElements = projectModelDTO.getAllElements(); - - for (FlexibleElementDTO e : allElements) { - if (e.getElementType() == ElementTypeEnum.QUESTION) { - QuestionElementDTO questionElement = (QuestionElementDTO) e; - - if (questionElement.getCategoryType() != null && selectedItems.contains(questionElement.getCategoryType())) { - deletionErrorList.add(new DeletionError(questionElement.getCategoryType().getLabel(), projectModelDTO.getName(), questionElement.getLabel())); - } - - } - } - - } - - // If the category is used by project models,show an alert window - if (deletionErrorList.size() > 0) { - - // Create a dialog window to show error message - final Dialog errorDialog = new Dialog(); - errorDialog.setHeadingHtml(I18N.CONSTANTS.deletionError()); - errorDialog.setButtons(Dialog.CANCEL); - errorDialog.setScrollMode(Scroll.AUTO); - errorDialog.setHideOnButtonClick(true); - errorDialog.setModal(true); - errorDialog.setWidth(500); - errorDialog.setHeight(250); - - String errorText = ""; - for (DeletionError error : deletionErrorList) { - errorText = errorText + I18N.MESSAGES.categoryBeingUsed(error.getCategoryTypeName(), error.getProjectModelName(), error.getFieldName()) + "
"; - - } - errorDialog.addText(errorText); - errorDialog.show(); - - } - - // Else, try to delete - else { - - List ids = new ArrayList(); - String names = ""; - for (CategoryTypeDTO s : selectedItems) { - ids.add(s.getId()); - names = s.getLabel() + ", " + names; - } - - final String toDelete = names; - final DeleteCategories deactivate = new DeleteCategories(selectedItems, null); - dispatch.execute(deactivate, new CommandResultHandler() { - - @Override - public void onCommandFailure(Throwable caught) { - N10N.warn(I18N.CONSTANTS.error(), I18N.MESSAGES.entityDeleteEventError(toDelete)); - } - - @Override - public void onCommandSuccess(VoidResult result) { - for (CategoryTypeDTO model : selectedItems) { - view.getCategoriesStore().remove(model); - view.getCategoryElementsStore().removeAll(); - view.getCategoriesStore().commitChanges(); - } - view.getCategoriesStore().commitChanges(); - view.getAddCategoryElementButton().disable(); - N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard())); - } - }); - - } - - } - - /** - * Method to verify the deletion action. If the verification passes, try to delete a category element, or show a alert - * window. - * - * @param selectedItems - * The selected category elements - * @param allProjectModelsList - * The list of all project models + * Delete Category Button Listener */ - protected void deleteCategoryElementVerify(final List selectedItems, List allProjectModelsList) { - - // Get the parent CategoryTypeDTO object, they have the same parent CategoryTypeDTO object - CategoryTypeDTO parentCategoryTypeDTO = selectedItems.get(0).getParentCategoryDTO(); - - // A List to store DeletionError object - List deletionErrorList = new ArrayList(); - - // Check - for (ProjectModelDTO projectModelDTO : allProjectModelsList) { - List allElements = new ArrayList(); - allElements = projectModelDTO.getAllElements(); - - for (FlexibleElementDTO e : allElements) { - if (e.getElementType() == ElementTypeEnum.QUESTION) { - QuestionElementDTO questionElement = (QuestionElementDTO) e; - - if (questionElement.getCategoryType() != null && parentCategoryTypeDTO.getId().equals(questionElement.getCategoryType().getId())) { - // Add a deletion error object - deletionErrorList.add(new DeletionError(parentCategoryTypeDTO.getLabel(), projectModelDTO.getName(), questionElement.getLabel())); - } - - } - } - - } - - // If the category is used by project models,show an alert window - if (deletionErrorList.size() > 0) { - // Create a dialog window to show error message - final Dialog errorDialog = new Dialog(); - errorDialog.setHeadingHtml(I18N.CONSTANTS.deletionError()); - errorDialog.setButtons(Dialog.CANCEL); - errorDialog.setScrollMode(Scroll.AUTO); - errorDialog.setHideOnButtonClick(true); - errorDialog.setModal(true); - errorDialog.setHeight(250); - errorDialog.setWidth(500); - - String errorText = ""; - for (DeletionError error : deletionErrorList) { - errorText = errorText + I18N.MESSAGES.categoryBeingUsed(error.getCategoryTypeName(), error.getProjectModelName(), error.getFieldName()) + "
"; - - } - errorDialog.addText(errorText); - errorDialog.show(); - return; - } - - // Else, try to delete - else { - List ids = new ArrayList(); - String names = ""; - for (CategoryElementDTO s : selectedItems) { - ids.add(s.getId()); - names = s.getLabel() + ", " + names; - } - - final String toDelete = names; - final DeleteCategories deactivate = new DeleteCategories(null, selectedItems); - dispatch.execute(deactivate, new CommandResultHandler() { - - @Override - public void onCommandFailure(Throwable caught) { - N10N.warn(I18N.CONSTANTS.error(), I18N.MESSAGES.entityDeleteEventError(toDelete), null); - } - - @Override - public void onCommandSuccess(VoidResult result) { - - List elements = currentCategoryType.getCategoryElementsDTO(); - for (CategoryElementDTO model : selectedItems) { - view.getCategoryElementsStore().remove(model); - elements.remove(model); - } - view.getCategoryElementsStore().commitChanges(); - - currentCategoryType.setCategoryElementsDTO(elements); - view.getCategoriesStore().update(currentCategoryType); - view.getCategoriesStore().commitChanges(); - } - }); - } - - } + public void deleteCategoryButtonListener() { - /** - * {@inheritDoc} - */ - @Override - public void onPageRequest(final PageRequest request) { + view.getDeleteCategoryTypeButton().addListener(Events.OnClick, new Listener() { - // clear view - view.getCategoryName().clear(); - view.getCategoryIcon().clearSelections(); - view.getName().clear(); + @Override + public void handleEvent(ButtonEvent be) { + onDeleteCategory(view.getCategoriesGrid().getSelectionModel().getSelectedItems()); + } - // load category - refreshCategoryTypePanel(); + }); - } + } - /** - * Load category - */ - public void refreshCategoryTypePanel() { + /** + * Method to delete a category. Firstly,get all project models for verifying + * if there is one or more in the selected categories who are being used by + * one or more project models. If being used, a category should not be + * deleted. + * + * @param selectedItems The selected categories + */ + protected void onDeleteCategory(final List selectedItems) { - dispatch.execute(new GetCategories(), new CommandResultHandler>() { + // Check if there is at least one item selected + if (selectedItems == null || selectedItems.size() == 0) { + N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.selectCategoryToDelete()); + return; + } + + GetProjectModels cmdGetProjectModels = new GetProjectModels(ProjectModelDTO.Mode.ALL, ProjectModelStatus.values()); + + dispatch.execute(cmdGetProjectModels, new CommandResultHandler>() { + + @Override + public void onCommandFailure(Throwable arg0) { - @Override - public void onCommandFailure(Throwable arg0) { - N10N.warn(I18N.CONSTANTS.adminboard(), I18N.CONSTANTS.adminProblemLoading()); - } + N10N.warn(I18N.CONSTANTS.error(), I18N.CONSTANTS.deleteCategoryGetProjectModelsError()); - @Override - public void onCommandSuccess(ListResult result) { + } - if (result.getList() != null && !result.getList().isEmpty()) { - view.getCategoriesStore().removeAll(); - view.getCategoriesStore().add(result.getList()); - view.getCategoriesStore().commitChanges(); - } + @Override + public void onCommandSuccess(ListResult result) { + + deleteCategoryVerify(selectedItems, result.getList()); + + } + }, view.getGategoriesTypeLoadingMonitor()); + + } + + /** + * Method to verify the deletion action. If the verification passes, try to + * delete a category, or show a alert window. + * + * @param selectedItems The selected categories + * @param allProjectModelsList The list of all project models + */ + private void deleteCategoryVerify(final List selectedItems, List allProjectModelsList) { + + // A List to store DeletionError object + List deletionErrorList = new ArrayList(); + + // Check + for (ProjectModelDTO projectModelDTO : allProjectModelsList) { + List allElements = new ArrayList(); + allElements = projectModelDTO.getAllElements(); + + for (FlexibleElementDTO e : allElements) { + if (e.getElementType() == ElementTypeEnum.QUESTION) { + QuestionElementDTO questionElement = (QuestionElementDTO) e; - } - }, view.getGategoriesTypeLoadingMonitor()); - } + if (questionElement.getCategoryType() != null && selectedItems.contains(questionElement.getCategoryType())) { + deletionErrorList.add(new DeletionError(questionElement.getCategoryType().getLabel(), projectModelDTO.getName(), questionElement.getLabel())); + } + + } + } + + } + + // If the category is used by project models,show an alert window + if (deletionErrorList.size() > 0) { + + // Create a dialog window to show error message + final Dialog errorDialog = new Dialog(); + errorDialog.setHeadingHtml(I18N.CONSTANTS.deletionError()); + errorDialog.setButtons(Dialog.CANCEL); + errorDialog.setScrollMode(Scroll.AUTO); + errorDialog.setHideOnButtonClick(true); + errorDialog.setModal(true); + errorDialog.setWidth(500); + errorDialog.setHeight(250); + + String errorText = ""; + for (DeletionError error : deletionErrorList) { + errorText = errorText + I18N.MESSAGES.categoryBeingUsed(error.getCategoryTypeName(), error.getProjectModelName(), error.getFieldName()) + "
"; + + } + errorDialog.addText(errorText); + errorDialog.show(); + + } // Else, try to delete + else { + + List ids = new ArrayList(); + String names = ""; + for (CategoryTypeDTO s : selectedItems) { + ids.add(s.getId()); + names = s.getLabel() + ", " + names; + } + + final String toDelete = names; + final DeleteCategories deactivate = new DeleteCategories(selectedItems, null); + dispatch.execute(deactivate, new CommandResultHandler() { + + @Override + public void onCommandFailure(Throwable caught) { + N10N.warn(I18N.CONSTANTS.error(), I18N.MESSAGES.entityDeleteEventError(toDelete)); + } + + @Override + public void onCommandSuccess(VoidResult result) { + for (CategoryTypeDTO model : selectedItems) { + view.getCategoriesStore().remove(model); + view.getCategoryElementsStore().removeAll(); + view.getCategoriesStore().commitChanges(); + } + view.getCategoriesStore().commitChanges(); + view.getAddCategoryElementButton().disable(); + N10N.infoNotif(I18N.CONSTANTS.adminCategoryTypeCreationBox(), I18N.MESSAGES.adminStandardUpdateSuccessF(I18N.CONSTANTS.adminCategoryTypeStandard())); + } + }); + + } + + } + + /** + * Method to verify the deletion action. If the verification passes, try to + * delete a category element, or show a alert window. + * + * @param selectedItems The selected category elements + * @param allProjectModelsList The list of all project models + */ + protected void deleteCategoryElementVerify(final List selectedItems, List allProjectModelsList) { + + // Get the parent CategoryTypeDTO object, they have the same parent CategoryTypeDTO object + CategoryTypeDTO parentCategoryTypeDTO = selectedItems.get(0).getParentCategoryDTO(); + + // A List to store DeletionError object + List deletionErrorList = new ArrayList(); + + // Check + for (ProjectModelDTO projectModelDTO : allProjectModelsList) { + List allElements = new ArrayList(); + allElements = projectModelDTO.getAllElements(); + + for (FlexibleElementDTO e : allElements) { + if (e.getElementType() == ElementTypeEnum.QUESTION) { + QuestionElementDTO questionElement = (QuestionElementDTO) e; + + if (questionElement.getCategoryType() != null && parentCategoryTypeDTO.getId().equals(questionElement.getCategoryType().getId())) { + // Add a deletion error object + deletionErrorList.add(new DeletionError(parentCategoryTypeDTO.getLabel(), projectModelDTO.getName(), questionElement.getLabel())); + } + + } + } + + } + + // If the category is used by project models,show an alert window + if (deletionErrorList.size() > 0) { + // Create a dialog window to show error message + final Dialog errorDialog = new Dialog(); + errorDialog.setHeadingHtml(I18N.CONSTANTS.deletionError()); + errorDialog.setButtons(Dialog.CANCEL); + errorDialog.setScrollMode(Scroll.AUTO); + errorDialog.setHideOnButtonClick(true); + errorDialog.setModal(true); + errorDialog.setHeight(250); + errorDialog.setWidth(500); + + String errorText = ""; + for (DeletionError error : deletionErrorList) { + errorText = errorText + I18N.MESSAGES.categoryBeingUsed(error.getCategoryTypeName(), error.getProjectModelName(), error.getFieldName()) + "
"; + + } + errorDialog.addText(errorText); + errorDialog.show(); + return; + } // Else, try to delete + else { + List ids = new ArrayList(); + String names = ""; + for (CategoryElementDTO s : selectedItems) { + ids.add(s.getId()); + names = s.getLabel() + ", " + names; + } + + final String toDelete = names; + final DeleteCategories deactivate = new DeleteCategories(null, selectedItems); + dispatch.execute(deactivate, new CommandResultHandler() { + + @Override + public void onCommandFailure(Throwable caught) { + N10N.warn(I18N.CONSTANTS.error(), I18N.MESSAGES.entityDeleteEventError(toDelete), null); + } + + @Override + public void onCommandSuccess(VoidResult result) { + + List elements = currentCategoryType.getCategoryElementsDTO(); + for (CategoryElementDTO model : selectedItems) { + view.getCategoryElementsStore().remove(model); + elements.remove(model); + + } + view.getCategoryElementsStore().commitChanges(); + + currentCategoryType.setCategoryElementsDTO(elements); + view.getCategoriesStore().update(currentCategoryType); + view.getCategoriesStore().commitChanges(); + } + }); + } + + } + + /** + * {@inheritDoc} + */ + @Override + public void onPageRequest(final PageRequest request) { + + // clear view + view.getCategoryName().clear(); + view.getCategoryIcon().clearSelections(); + view.getName().clear(); + + // load category + refreshCategoryTypePanel(); + + } + + /** + * Load category + */ + public void refreshCategoryTypePanel() { + + dispatch.execute(new GetCategories(), new CommandResultHandler>() { + + @Override + public void onCommandFailure(Throwable arg0) { + N10N.warn(I18N.CONSTANTS.adminboard(), I18N.CONSTANTS.adminProblemLoading()); + } + + @Override + public void onCommandSuccess(ListResult result) { + + if (result.getList() != null && !result.getList().isEmpty()) { + view.getCategoriesStore().removeAll(); + view.getCategoriesStore().add(result.getList()); + view.getCategoriesStore().commitChanges(); + } + + } + }, view.getGategoriesTypeLoadingMonitor()); + } } diff --git a/src/main/java/org/sigmah/client/ui/view/admin/CategoriesAdminView.java b/src/main/java/org/sigmah/client/ui/view/admin/CategoriesAdminView.java index 5c761cd4f..08cda0ed3 100644 --- a/src/main/java/org/sigmah/client/ui/view/admin/CategoriesAdminView.java +++ b/src/main/java/org/sigmah/client/ui/view/admin/CategoriesAdminView.java @@ -50,6 +50,7 @@ import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction; +import com.extjs.gxt.ui.client.widget.form.Field; import com.extjs.gxt.ui.client.widget.form.SimpleComboBox; import com.extjs.gxt.ui.client.widget.form.TextField; import com.extjs.gxt.ui.client.widget.grid.ColumnConfig; @@ -61,6 +62,8 @@ import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.inject.Singleton; +import org.sigmah.client.ui.widget.form.Forms; +import org.sigmah.client.util.ColumnProviders; /** * {@link CategoriesAdminPresenter}'s view implementation. @@ -79,8 +82,11 @@ public class CategoriesAdminView extends AbstractView implements CategoriesAdmin private Grid categoryElementsGrid; private Button addCategoryElementButton; private Button deleteCategoryElementButton; + private Button disableCategoryElementButton; + private Button enableCategoryElementButton; private TextField name; private ColorField colorField; + private Boolean isdisable; private ContentPanel categoryElementsPanel; /** * Category Panel @@ -142,9 +148,29 @@ public Object render(CategoryElementDTO model, String property, ColumnData confi configs.add(column); column = new ColumnConfig(); + + column.setId("label"); column.setWidth(400); column.setHeaderHtml(I18N.CONSTANTS.adminCategoryElementLabel()); + column.setRenderer(new GridCellRenderer() { + + @Override + public Object render(CategoryElementDTO model, String property, ColumnData config, int rowIndex, int colIndex, ListStore store, + Grid grid) { + final String label; + label = model.getLabel(); + if(model.getisDisabled()) { + return model.renderDisabled(label); + } + else { + return model.renderText(label); + } + + + } + + }); configs.add(column); ColumnModel cm = new ColumnModel(configs); @@ -309,6 +335,14 @@ private ToolBar categoryElementToolBar() { deleteCategoryElementButton = new Button(I18N.CONSTANTS.delete(), IconImageBundle.ICONS.delete()); toolbar.add(deleteCategoryElementButton); + + disableCategoryElementButton = new Button(I18N.CONSTANTS.disable(), IconImageBundle.ICONS.disable()); + + toolbar.add(disableCategoryElementButton); + + enableCategoryElementButton =new Button(I18N.CONSTANTS.enable(), IconImageBundle.ICONS.checked()); + + toolbar.add(enableCategoryElementButton); return toolbar; } @@ -351,6 +385,16 @@ public Button getAddCategoryElementButton() { public Button getDeleteCategoryElementButton() { return deleteCategoryElementButton; } + + @Override + public Button getDisableCategoryElementButton() { + return disableCategoryElementButton; + } + + @Override + public Button getEnableCategoryElementButton() { + return enableCategoryElementButton; + } @Override public Button getDeleteCategoryTypeButton() { @@ -386,6 +430,11 @@ public TextField getName() { public ColorField getColorField() { return colorField; } + + @Override + public Boolean getisdisable() { + return false; + } @Override public Button getImportCategoryTypeButton() { diff --git a/src/main/java/org/sigmah/client/util/AdminUtil.java b/src/main/java/org/sigmah/client/util/AdminUtil.java index bb103f60d..4f1ce8cd1 100644 --- a/src/main/java/org/sigmah/client/util/AdminUtil.java +++ b/src/main/java/org/sigmah/client/util/AdminUtil.java @@ -117,6 +117,7 @@ public final class AdminUtil { public static final String PROP_CATEGORY_ELEMENT = "NewCategoryElement"; public static final String PROP_CATEGORY_ELEMENT_NAME = "NewCategoryElementName"; public static final String PROP_CATEGORY_ELEMENT_COLOR = "NewCategoryElementColor"; + public static final String PROP_CATEGORY_ELEMENT_ISDISABLED = "isdisabled"; public static final String PROP_PM_NAME = "ProjectModelName"; public static final String PROP_PM_USE = "ProjectModelUse"; diff --git a/src/main/java/org/sigmah/offline/dao/ProjectAsyncDAO.java b/src/main/java/org/sigmah/offline/dao/ProjectAsyncDAO.java index 3b3f1f4f1..0fabe99e9 100644 --- a/src/main/java/org/sigmah/offline/dao/ProjectAsyncDAO.java +++ b/src/main/java/org/sigmah/offline/dao/ProjectAsyncDAO.java @@ -509,12 +509,13 @@ public void onRequestSuccess(OrgUnitDTO result) { private Set getCategoryElements(ValueResult valueResult, QuestionElementDTO questionElement) { if (valueResult != null && valueResult.isValueDefined()) { - if(questionElement.getMultiple() == null || !questionElement.getMultiple()) { + + if(questionElement.getMultiple() == null || !questionElement.getMultiple()) { final String idChoice = valueResult.getValueObject(); - for (final QuestionChoiceElementDTO choice : questionElement.getChoices()) { + for (final CategoryElementDTO choice : questionElement.getCategoryType().getCategoryElementsDTO()) { if (idChoice.equals(String.valueOf(choice.getId()))) { - return Collections.singleton(choice.getCategoryElement()); + return Collections.singleton(choice); } } } else { @@ -522,9 +523,9 @@ private Set getCategoryElements(ValueResult valueResult, Que final Set elements = new HashSet(); - for (final QuestionChoiceElementDTO choice : questionElement.getChoices()) { + for (final CategoryElementDTO choice : questionElement.getCategoryType().getCategoryElementsDTO()) { if (selectedChoicesId.contains(choice.getId())) { - elements.add(choice.getCategoryElement()); + elements.add(choice); } } diff --git a/src/main/java/org/sigmah/server/domain/category/CategoryElement.java b/src/main/java/org/sigmah/server/domain/category/CategoryElement.java index 01cc8226d..8c9665969 100644 --- a/src/main/java/org/sigmah/server/domain/category/CategoryElement.java +++ b/src/main/java/org/sigmah/server/domain/category/CategoryElement.java @@ -1,27 +1,27 @@ -package org.sigmah.server.domain.category; - -/* - * #%L - * Sigmah - * %% - * Copyright (C) 2010 - 2016 URD - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . - * #L% - */ - +package org.sigmah.server.domain.category; + +/* + * #%L + * Sigmah + * %% + * Copyright (C) 2010 - 2016 URD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * . + * #L% + */ + import java.util.Objects; import javax.persistence.Column; @@ -72,7 +72,10 @@ public class CategoryElement extends AbstractEntityId { @NotNull @Size(max = EntityConstants.CATEGORY_ELEMENT_COLOR_HEX_MAX_LENGTH) private String color; - + + @Column(name = EntityConstants.IS_DISABLED, nullable = false) + @NotNull + private Boolean isdisabled = false; // -------------------------------------------------------------------------------- // // FOREIGN KEYS. @@ -194,4 +197,15 @@ public Organization getOrganization() { public void setOrganization(Organization organization) { this.organization = organization; } + + public boolean getisDisabled() { + if(isdisabled == null){ + return false; + } + return isdisabled; + } + + public void setisDisabled(boolean isdisabled) { + this.isdisabled = isdisabled; + } } diff --git a/src/main/java/org/sigmah/server/domain/util/EntityConstants.java b/src/main/java/org/sigmah/server/domain/util/EntityConstants.java index 3fbcfb5f7..6491b8868 100644 --- a/src/main/java/org/sigmah/server/domain/util/EntityConstants.java +++ b/src/main/java/org/sigmah/server/domain/util/EntityConstants.java @@ -272,6 +272,7 @@ private EntityConstants() { public static final String CATEGORY_ELEMENT_COLUMN_ID = "id_category_element"; public static final String CATEGORY_ELEMENT_COLUMN_COLOR_HEX = "color_hex"; public static final String CATEGORY_ELEMENT_COLUMN_LABEL = "label"; + public static final String IS_DISABLED = "isdisabled"; public static final int CATEGORY_ELEMENT_COLOR_HEX_MAX_LENGTH = 6; diff --git a/src/main/java/org/sigmah/server/handler/DisableCategoryElementsHandler.java b/src/main/java/org/sigmah/server/handler/DisableCategoryElementsHandler.java new file mode 100644 index 000000000..36b629648 --- /dev/null +++ b/src/main/java/org/sigmah/server/handler/DisableCategoryElementsHandler.java @@ -0,0 +1,65 @@ +package org.sigmah.server.handler; + +/* + * #%L + * Sigmah + * %% + * Copyright (C) 2010 - 2016 URD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * . + * #L% + */ +import com.google.inject.persist.Transactional; +import java.util.List; +import org.sigmah.shared.command.DisableCategoryElements; +import org.sigmah.shared.dto.category.CategoryElementDTO; +import org.sigmah.server.dispatch.impl.UserDispatch; +import org.sigmah.server.domain.category.CategoryElement; +import org.sigmah.server.handler.base.AbstractCommandHandler; +import org.sigmah.shared.command.DisableFlexibleElements; +import org.sigmah.shared.command.result.VoidResult; +import org.sigmah.shared.dispatch.CommandException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Handler for the command {@link DisableCategoryElements}. + * + * @author Nikita Jibhkate (niksj1996@@gmail.com) + */ +public class DisableCategoryElementsHandler extends AbstractCommandHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(DisableCategoryElementsHandler.class); + + @Override + protected VoidResult execute(DisableCategoryElements command, UserDispatch.UserExecutionContext context) throws CommandException { + if (command.getCategoryElements() != null) { + setDisabled(command.getCategoryElements(), command.isDisable()); + } + return null; + } + + @Transactional + protected void setDisabled(List elements, boolean disabled) { + for (CategoryElementDTO categoryElementDTO : elements) { + final CategoryElement categoryElement = em().find(CategoryElement.class, categoryElementDTO.getId()); + //flexibleElement.setDisabledDate(disabled ? new Date() : null); + categoryElement.setisDisabled(disabled); + em().merge(categoryElement); + + LOGGER.debug("DisableFlexibleElementsHandler flexibleElement {} name {}.", categoryElementDTO.getId(), categoryElementDTO.getLabel()); + } + } +} diff --git a/src/main/java/org/sigmah/server/handler/util/ProjectMapper.java b/src/main/java/org/sigmah/server/handler/util/ProjectMapper.java index f7edf6c6b..7946dfd5d 100644 --- a/src/main/java/org/sigmah/server/handler/util/ProjectMapper.java +++ b/src/main/java/org/sigmah/server/handler/util/ProjectMapper.java @@ -219,19 +219,19 @@ public ProjectDTO map(final Project project, final boolean mapChildren) { List values = ValueResultUtils.splitValuesAsInteger(value.getValue()); if (!values.isEmpty()) { - final TypedQuery choicesQuery = - em().createQuery("SELECT c FROM QuestionChoiceElement c WHERE c.id IN (:ids)", QuestionChoiceElement.class); + final TypedQuery choicesQuery = + em().createQuery("SELECT c FROM CategoryElement c WHERE c.id IN (:ids)", CategoryElement.class); choicesQuery.setParameter("ids", ValueResultUtils.splitValuesAsInteger(value.getValue())); - for (final QuestionChoiceElement choice : choicesQuery.getResultList()) { + for (final CategoryElement choice : choicesQuery.getResultList()) { - final CategoryType parent = choice.getCategoryElement().getParentType(); + final CategoryType parent = choice.getParentType(); final CategoryTypeDTO parentDTO = new CategoryTypeDTO(); parentDTO.setId(parent.getId()); parentDTO.setLabel(parent.getLabel()); parentDTO.setIcon(parent.getIcon()); - final CategoryElement element = choice.getCategoryElement(); + final CategoryElement element = choice; final CategoryElementDTO elementDTO = new CategoryElementDTO(); elementDTO.setId(element.getId()); elementDTO.setLabel(element.getLabel()); diff --git a/src/main/java/org/sigmah/server/inject/CommandHandlerModule.java b/src/main/java/org/sigmah/server/inject/CommandHandlerModule.java index af8f0343a..fe17ad082 100644 --- a/src/main/java/org/sigmah/server/inject/CommandHandlerModule.java +++ b/src/main/java/org/sigmah/server/inject/CommandHandlerModule.java @@ -59,6 +59,7 @@ protected void configureHandlers() { bindHandler(CopyLogFrame.class, CopyLogFrameHandler.class); bindHandler(DeactivateUsers.class, DeactivateUsersHandler.class); bindHandler(DisableFlexibleElements.class, DisableFlexibleElementsHandler.class); + bindHandler(DisableCategoryElements.class, DisableCategoryElementsHandler.class); bindHandler(DeleteCategories.class, DeleteCategoriesHandler.class); bindHandler(DeleteFlexibleElements.class, DeleteFlexibleElementsHandler.class); bindHandler(Delete.class, DeleteHandler.class); diff --git a/src/main/java/org/sigmah/server/security/impl/AccessRights.java b/src/main/java/org/sigmah/server/security/impl/AccessRights.java index 5a2f0338a..0142da38f 100644 --- a/src/main/java/org/sigmah/server/security/impl/AccessRights.java +++ b/src/main/java/org/sigmah/server/security/impl/AccessRights.java @@ -138,6 +138,7 @@ final class AccessRights { sperm(commandToken(CopyLogFrame.class), GrantType.AUTHENTICATED_ONLY, GlobalPermissionEnum.EDIT_LOGFRAME); sperm(commandToken(DeactivateUsers.class), GrantType.AUTHENTICATED_ONLY, GlobalPermissionEnum.MANAGE_USERS); sperm(commandToken(DisableFlexibleElements.class), GrantType.AUTHENTICATED_ONLY); + sperm(commandToken(DisableCategoryElements.class), GrantType.AUTHENTICATED_ONLY); sperm(commandToken(DeleteCategories.class), GrantType.AUTHENTICATED_ONLY); sperm(commandToken(DeleteFlexibleElements.class), GrantType.AUTHENTICATED_ONLY); sperm(commandToken(Delete.class), GrantType.AUTHENTICATED_ONLY); diff --git a/src/main/java/org/sigmah/shared/command/DisableCategoryElements.java b/src/main/java/org/sigmah/shared/command/DisableCategoryElements.java new file mode 100644 index 000000000..af67fc1ee --- /dev/null +++ b/src/main/java/org/sigmah/shared/command/DisableCategoryElements.java @@ -0,0 +1,59 @@ +package org.sigmah.shared.command; + +/* + * #%L + * Sigmah + * %% + * Copyright (C) 2010 - 2016 URD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * . + * #L% + */ + +import java.util.List; +import org.sigmah.shared.command.base.Command; + +import org.sigmah.shared.command.result.VoidResult; +import org.sigmah.shared.dto.category.CategoryElementDTO; + +/** + * Enable or disable category elements. + * + * @author Nikita Jibhkate (niksj1996@gmail.com) + */ +public class DisableCategoryElements implements Command { + //private static final long serialVersionUID = 3902096705358448566L; + + private List categoryElements; + private boolean disable; + + protected DisableCategoryElements() { + // Serialization. + } + + public DisableCategoryElements(List categoryElements, boolean disable) { + this.categoryElements = categoryElements; + this.disable = disable; + } + + public List getCategoryElements() { + return categoryElements; + } + + public boolean isDisable() { + return disable; + } + +} diff --git a/src/main/java/org/sigmah/shared/dto/category/CategoryElementDTO.java b/src/main/java/org/sigmah/shared/dto/category/CategoryElementDTO.java index 7691f0b23..cca2e973d 100644 --- a/src/main/java/org/sigmah/shared/dto/category/CategoryElementDTO.java +++ b/src/main/java/org/sigmah/shared/dto/category/CategoryElementDTO.java @@ -36,6 +36,9 @@ public class CategoryElementDTO extends AbstractModelDataEntityDTO { * Serial version UID. */ private static final long serialVersionUID = 7879245182808843730L; + + private static final String STYLE_LABEL_SMALL = "label-small"; + /** * {@inheritDoc} @@ -89,5 +92,32 @@ public void setIconHtml(String iconHtml) { public String getIconHtml() { return get("iconHtml"); } + + public boolean getisDisabled() { + return get("isdisabled"); + } + + public void setisDisabled(boolean isdisabled) { + set("isdisabled", isdisabled); + } + + public String renderDisabled(final String value) { + + // Renders direct HTML to improve performances. + final StringBuilder builder = new StringBuilder(); + builder.append("
"); + builder.append(value != null ? String.valueOf(value) : "").append("
"); + return builder.toString(); + } + + public String renderText(final String value) { + + // Renders direct HTML to improve performances. + final StringBuilder builder = new StringBuilder(); + builder.append("
"); + builder.append(value != null ? String.valueOf(value) : "").append("
"); + + return builder.toString(); + } } diff --git a/src/main/java/org/sigmah/shared/dto/element/QuestionElementDTO.java b/src/main/java/org/sigmah/shared/dto/element/QuestionElementDTO.java index 539355fbb..2fcb08a83 100644 --- a/src/main/java/org/sigmah/shared/dto/element/QuestionElementDTO.java +++ b/src/main/java/org/sigmah/shared/dto/element/QuestionElementDTO.java @@ -1,28 +1,26 @@ -package org.sigmah.shared.dto.element; - -/* - * #%L - * Sigmah - * %% - * Copyright (C) 2010 - 2016 URD - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . - * #L% - */ - - +package org.sigmah.shared.dto.element; + +/* + * #%L + * Sigmah + * %% + * Copyright (C) 2010 - 2016 URD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * . + * #L% + */ import java.util.ArrayList; import java.util.List; @@ -32,6 +30,7 @@ import org.sigmah.client.ui.widget.HistoryTokenText; import org.sigmah.shared.command.result.ValueResult; import org.sigmah.shared.dto.category.CategoryTypeDTO; +import org.sigmah.shared.dto.category.CategoryElementDTO; import org.sigmah.shared.dto.element.event.RequiredValueEvent; import org.sigmah.shared.dto.element.event.ValueEvent; import org.sigmah.shared.dto.history.HistoryTokenListDTO; @@ -61,432 +60,725 @@ /** * QuestionElementDTO. - * + * * @author Denis Colliot (dcolliot@ideia.fr) (v2.0) * @author Renato Almeida (renatoaf.ufcg@gmail.com) */ public class QuestionElementDTO extends FlexibleElementDTO { - /** - * Serial version UID. - */ - private static final long serialVersionUID = 8520711106031085130L; - - /** - * DTO corresponding entity name. - */ - public static final String ENTITY_NAME = "element.QuestionElement"; - - // DTO attributes keys. - public static final String CHOICES = "choices"; - public static final String MULTIPLE = "multiple"; - public static final String CATEGORY_TYPE = "categoryType"; - public static final String QUALITY_CRITERION = "qualityCriterion"; - - /** - * {@inheritDoc} - */ - @Override - public String getEntityName() { - return ENTITY_NAME; - } - - // Question choices list - public List getChoices() { - return get(CHOICES); - } - - public void setChoices(List choices) { - set(CHOICES, choices); - } - - // Question multiple mode - public Boolean getMultiple() { - return get(MULTIPLE); - } - - public void setMultiple(Boolean multiple) { - set(MULTIPLE, multiple); - } - - // Question category type - public CategoryTypeDTO getCategoryType() { - return get(CATEGORY_TYPE); - } - - public void setCategoryType(CategoryTypeDTO categoryType) { - set(CATEGORY_TYPE, categoryType); - } - - // Question quality criterion - public QualityCriterionDTO getQualityCriterion() { - return get(QUALITY_CRITERION); - } - - public void setQualityCriterion(QualityCriterionDTO qualityCriterion) { - set(QUALITY_CRITERION, qualityCriterion); - } - - /** - * {@inheritDoc} - */ - @Override - protected Component getComponent(ValueResult valueResult, boolean enabled) { - final boolean canEdit = enabled && userCanPerformChangeType(ValueEventChangeType.EDIT); - - // Question's component. - final Component component; - - // Creates choices store. - final ListStore store = new ListStore(); - store.add(getChoices()); - - // Creates the listener of selection changes. - final ComboBoxSelectionListener listener = new ComboBoxSelectionListener(); - - // Selection. - List selectedChoices = Collections.emptyList(); - - // Single selection case. - if (!Boolean.TRUE.equals(getMultiple())) { - - final ComboBox comboBox = new ComboBox(); - comboBox.setEmptyText(I18N.CONSTANTS.flexibleElementQuestionEmptyChoice()); - - comboBox.setStore(store); - comboBox.setFieldLabel(getLabel()); - comboBox.setDisplayField(LABEL); - comboBox.setValueField(ID); - comboBox.setLabelSeparator(""); - comboBox.setTriggerAction(TriggerAction.ALL); - comboBox.setEditable(false); - comboBox.setAllowBlank(true); - - if (getCategoryType() != null) { - - for (final QuestionChoiceElementDTO choiceDTO : store.getModels()) { - if (choiceDTO.getCategoryElement() != null) { - choiceDTO.getCategoryElement().setIconHtml(CategoryIconProvider.getIconHtml(choiceDTO.getCategoryElement(), false)); - } - } - - comboBox.setTemplate(CategoryIconProvider.getComboboxIconTemplate()); - } - - if (valueResult != null && valueResult.isValueDefined()) { - - final String idChoice = valueResult.getValueObject(); - - for (QuestionChoiceElementDTO choiceDTO : getChoices()) { - if (idChoice.equals(String.valueOf(choiceDTO.getId()))) { - comboBox.setValue(choiceDTO); - selectedChoices = Collections.singletonList(choiceDTO); - break; - } - } - } - - // Listens to the selection changes. - comboBox.addSelectionChangedListener(listener); - - comboBox.setEnabled(enabled); - - component = comboBox; - } - // Multiple selection case. - else { - - // Selection model. - final CheckBoxSelectionModel selectionModel = new CheckBoxSelectionModel(); - selectionModel.setSelectionMode(SelectionMode.MULTI); - selectionModel.addListener(Events.SelectionChange, listener); - - // Defines grid column model. - final ColumnConfig labelColumn = new ColumnConfig(); - labelColumn.setId(LABEL); - labelColumn.setHeaderText(I18N.CONSTANTS.flexibleElementQuestionMutiple()); - labelColumn.setWidth(500); - if (getCategoryType() != null) { - labelColumn.setRenderer(new GridCellRenderer() { - - @Override - public Object render(QuestionChoiceElementDTO model, String property, ColumnData config, int rowIndex, int colIndex, - ListStore store, Grid grid) { - - final com.google.gwt.user.client.ui.Grid panel = new com.google.gwt.user.client.ui.Grid(1, 2); - panel.setCellPadding(0); - panel.setCellSpacing(0); - - panel.setWidget(0, 0, CategoryIconProvider.getIcon(model.getCategoryElement())); - panel.setText(0, 1, (String) model.get(property)); - - final Element element = panel.getCellFormatter().getElement(0, 1); - element.getStyle().setPaddingTop(1, Unit.PX); - element.getStyle().setPaddingLeft(5, Unit.PX); - - return panel; - } - }); - } - - // Visible columns. - final ColumnConfig[] columnConfigs = canEdit ? - new ColumnConfig[] {selectionModel.getColumn(), labelColumn} : - new ColumnConfig[] {labelColumn}; - - // Grid used as a list box. - final FlexibleGrid multipleQuestion = new FlexibleGrid(store, selectionModel, columnConfigs); - multipleQuestion.setAutoExpandColumn(LABEL); - multipleQuestion.setVisibleElementsCount(5); - - final ContentPanel contentPanel = new ContentPanel(); - contentPanel.setHeaderVisible(true); - contentPanel.setBorders(true); - contentPanel.setHeadingText(getLabel()); - contentPanel.setTopComponent(null); - contentPanel.add(multipleQuestion); - - // Selects the already selected choices. - if (valueResult != null && valueResult.isValueDefined()) { - - final HashSet selectedChoicesId = new HashSet(ValueResultUtils.splitValuesAsInteger(valueResult.getValueObject())); - selectedChoices = new ArrayList(); - - for (final QuestionChoiceElementDTO choiceDTO : getChoices()) { - if (selectedChoicesId.contains(choiceDTO.getId())) { - selectedChoices.add(choiceDTO); - } - } - - selectionModel.select(selectedChoices, false); - } - - component = contentPanel; - } - - // If the component is a category and/or a quality criterion. - if (getCategoryType() != null) { - - if (getQualityCriterion() != null) { - component.setToolTip(I18N.MESSAGES.flexibleElementQuestionCategory(getCategoryType().getLabel()) - + "
" - + I18N.MESSAGES.flexibleElementQuestionQuality(getQualityCriterion().getInfo())); - } else { - component.setToolTip(I18N.MESSAGES.flexibleElementQuestionCategory(getCategoryType().getLabel())); - } - - } else if (getQualityCriterion() != null) { - component.setToolTip(I18N.MESSAGES.flexibleElementQuestionQuality(getQualityCriterion().getInfo())); - } - - // Remove disabled options (not selected) - for (QuestionChoiceElementDTO choice : getChoices()) { - if (choice.isDisabled() && !selectedChoices.contains(choice)) { - store.remove(choice); - } + /** + * Serial version UID. + */ + private static final long serialVersionUID = 8520711106031085130L; + + /** + * DTO corresponding entity name. + */ + public static final String ENTITY_NAME = "element.QuestionElement"; + + // DTO attributes keys. + public static final String CHOICES = "choices"; + public static final String MULTIPLE = "multiple"; + public static final String CATEGORY_TYPE = "categoryType"; + public static final String QUALITY_CRITERION = "qualityCriterion"; + + /** + * {@inheritDoc} + */ + @Override + public String getEntityName() { + return ENTITY_NAME; + } + + // Question choices list + public List getChoices() { + return get(CHOICES); + } + + public void setChoices(List choices) { + set(CHOICES, choices); + } + + // Question multiple mode + public Boolean getMultiple() { + return get(MULTIPLE); + } + + public void setMultiple(Boolean multiple) { + set(MULTIPLE, multiple); + } + + // Question category type + public CategoryTypeDTO getCategoryType() { + return get(CATEGORY_TYPE); + } + + public void setCategoryType(CategoryTypeDTO categoryType) { + set(CATEGORY_TYPE, categoryType); + } + + // Question quality criterion + public QualityCriterionDTO getQualityCriterion() { + return get(QUALITY_CRITERION); + } + + public void setQualityCriterion(QualityCriterionDTO qualityCriterion) { + set(QUALITY_CRITERION, qualityCriterion); + } + + /** + * {@inheritDoc} + */ + @Override + protected Component getComponent(ValueResult valueResult, boolean enabled) { + + if (getCategoryType() == null) { + + final boolean canEdit = enabled && userCanPerformChangeType(ValueEventChangeType.EDIT); + + // Question's component. + final Component component; + + // Creates choices store. + final ListStore store1 = new ListStore(); + store1.add(getChoices()); + + // Creates the listener of selection changes. + final ComboBoxSelectionListener listener = new ComboBoxSelectionListener(); + + // Selection. + List selectedChoices = Collections.emptyList(); + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + + final ComboBox comboBox = new ComboBox(); + comboBox.setEmptyText(I18N.CONSTANTS.flexibleElementQuestionEmptyChoice()); + + comboBox.setStore(store1); + comboBox.setFieldLabel(getLabel()); + comboBox.setDisplayField(LABEL); + comboBox.setValueField(ID); + comboBox.setLabelSeparator(""); + comboBox.setTriggerAction(TriggerAction.ALL); + comboBox.setEditable(false); + comboBox.setAllowBlank(true); + + if (getCategoryType() != null) { + + for (final QuestionChoiceElementDTO choiceDTO : store1.getModels()) { + if (choiceDTO.getCategoryElement() != null) { + choiceDTO.getCategoryElement().setIconHtml(CategoryIconProvider.getIconHtml(choiceDTO.getCategoryElement(), false)); + } + } + + comboBox.setTemplate(CategoryIconProvider.getComboboxIconTemplate()); + } + + if (valueResult != null && valueResult.isValueDefined()) { + + final String idChoice = valueResult.getValueObject(); + + for (QuestionChoiceElementDTO choiceDTO : getChoices()) { + if (idChoice.equals(String.valueOf(choiceDTO.getId()))) { + comboBox.setValue(choiceDTO); + selectedChoices = Collections.singletonList(choiceDTO); + break; + } + } + } + + // Listens to the selection changes. + comboBox.addSelectionChangedListener(listener); + + comboBox.setEnabled(enabled); + + component = comboBox; + } // Multiple selection case. + else { + + // Selection model. + final CheckBoxSelectionModel selectionModel = new CheckBoxSelectionModel(); + selectionModel.setSelectionMode(SelectionMode.MULTI); + selectionModel.addListener(Events.SelectionChange, listener); + + // Defines grid column model. + final ColumnConfig labelColumn = new ColumnConfig(); + labelColumn.setId(LABEL); + labelColumn.setHeaderText(I18N.CONSTANTS.flexibleElementQuestionMutiple()); + labelColumn.setWidth(500); + if (getCategoryType() != null) { + labelColumn.setRenderer(new GridCellRenderer() { + + @Override + public Object render(QuestionChoiceElementDTO model, String property, ColumnData config, int rowIndex, int colIndex, + ListStore store, Grid grid) { + + final com.google.gwt.user.client.ui.Grid panel = new com.google.gwt.user.client.ui.Grid(1, 2); + panel.setCellPadding(0); + panel.setCellSpacing(0); + + panel.setWidget(0, 0, + CategoryIconProvider.getIcon(model.getCategoryElement())); + panel.setText(0, 1, (String) model.get(property)); + + final Element element + = panel.getCellFormatter().getElement(0, 1); + element.getStyle().setPaddingTop(1, + Unit.PX); + element.getStyle().setPaddingLeft(5, + Unit.PX); + + return panel; + } + }); + } + + // Visible columns. + final ColumnConfig[] columnConfigs = canEdit + ? new ColumnConfig[]{selectionModel.getColumn(), + labelColumn} + : new ColumnConfig[]{labelColumn}; + + // Grid used as a list box. + final FlexibleGrid multipleQuestion + = new FlexibleGrid(store1, selectionModel, columnConfigs); + multipleQuestion.setAutoExpandColumn(LABEL); + multipleQuestion.setVisibleElementsCount(5); + + final ContentPanel contentPanel = new ContentPanel(); + contentPanel.setHeaderVisible(true); + contentPanel.setBorders(true); + contentPanel.setHeadingText(getLabel()); + contentPanel.setTopComponent(null); + contentPanel.add(multipleQuestion); + + // Selects the already selected choices. + if (valueResult != null && valueResult.isValueDefined()) { + + final HashSet selectedChoicesId = new HashSet(ValueResultUtils.splitValuesAsInteger(valueResult.getValueObject())); + selectedChoices = new ArrayList(); + + for (final QuestionChoiceElementDTO choiceDTO : getChoices()) { + if (selectedChoicesId.contains(choiceDTO.getId())) { + selectedChoices.add(choiceDTO); + } + } + + selectionModel.select(selectedChoices, false); + } + + component = contentPanel; + } + + // If the component is a category and/or a quality criterion. + if (getQualityCriterion() != null) { + component.setToolTip(I18N.MESSAGES.flexibleElementQuestionQuality(getQualityCriterion().getInfo())); + } + + // Remove disabled options (not selected) + for (QuestionChoiceElementDTO choice : getChoices()) { + if (choice.isDisabled() && !selectedChoices.contains(choice)) { + store1.remove(choice); + } + } + + return component; + } //*********************************************************************************************** + //when (categorytype!=null) + + else { + + final boolean canEdit = enabled && userCanPerformChangeType(ValueEventChangeType.EDIT); + + // Question's component. + final Component component; + + // Creates choices store. + final ListStore store2 = new ListStore(); + for (CategoryElementDTO choice : getCategoryType().getCategoryElementsDTO()) { + if (!choice.getisDisabled()) { + store2.add(choice); + } + } + + // Creates the listener of selection changes. + final ComboBoxCateSelectionListener listener = new ComboBoxCateSelectionListener(); + + // Selection. + List selectedChoices = Collections.emptyList(); + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + + final ComboBox comboBox = new ComboBox(); + + comboBox.setEmptyText(I18N.CONSTANTS.flexibleElementQuestionEmptyChoice()); + + comboBox.setStore(store2); + comboBox.setFieldLabel(getLabel()); + comboBox.setDisplayField(LABEL); + comboBox.setValueField(ID); + comboBox.setLabelSeparator(""); + comboBox.setTriggerAction(TriggerAction.ALL); + comboBox.setEditable(false); + comboBox.setAllowBlank(true); + + if (getCategoryType() != null) { + + for (final CategoryElementDTO choiceDTO : store2.getModels()) { + if (choiceDTO != null) { + CategoryIconProvider.getIcon(choiceDTO); + choiceDTO.setIconHtml(CategoryIconProvider.getIconHtml(choiceDTO, false)); + } + //store2.add(choiceDTO); + } + comboBox.setTemplate(CategoryIconProvider.getComboboxIconTemplate()); + } + + if (valueResult != null && valueResult.isValueDefined()) { + + final String idChoice = valueResult.getValueObject(); + + for (CategoryElementDTO choiceDTO : getCategoryType().getCategoryElementsDTO()) { + if (idChoice.equals(String.valueOf(choiceDTO.getId()))) { + comboBox.setValue(choiceDTO); + selectedChoices = Collections.singletonList(choiceDTO); + break; + } + } + } + + // Listens to the selection changes. + comboBox.addSelectionChangedListener(listener); + + comboBox.setEnabled(enabled); + + component = comboBox; + } // Multiple selection case. + else { + + // Selection model. + final CheckBoxSelectionModel selectionModel + = new CheckBoxSelectionModel(); + selectionModel.setSelectionMode(SelectionMode.MULTI); + selectionModel.addListener(Events.SelectionChange, listener); + + // Defines grid column model. + final ColumnConfig labelColumn = new ColumnConfig(); + labelColumn.setId(LABEL); + labelColumn.setHeaderText(I18N.CONSTANTS.flexibleElementQuestionMutiple()); + labelColumn.setWidth(500); + if (getCategoryType() != null) { + labelColumn.setRenderer(new GridCellRenderer() { + + @Override + public Object render(CategoryElementDTO model, + String property, ColumnData config, int rowIndex, int colIndex, + ListStore store, Grid grid) { + + final com.google.gwt.user.client.ui.Grid panel = new com.google.gwt.user.client.ui.Grid(1, 2); + panel.setCellPadding(0); + panel.setCellSpacing(0); + + panel.setWidget(0, 0, + CategoryIconProvider.getIcon(model)); + panel.setText(0, 1, (String) model.get(property)); + + final Element element + = panel.getCellFormatter().getElement(0, 1); + element.getStyle().setPaddingTop(1, + Unit.PX); + element.getStyle().setPaddingLeft(5, + Unit.PX); + + return panel; + } + }); + } + + // Visible columns. + final ColumnConfig[] columnConfigs = canEdit + ? new ColumnConfig[]{selectionModel.getColumn(), + labelColumn} + : new ColumnConfig[]{labelColumn}; + + // Grid used as a list box. + final FlexibleGrid multipleQuestion = new FlexibleGrid(store2, selectionModel, columnConfigs); + multipleQuestion.setAutoExpandColumn(LABEL); + multipleQuestion.setVisibleElementsCount(5); + + final ContentPanel contentPanel = new ContentPanel(); + contentPanel.setHeaderVisible(true); + contentPanel.setBorders(true); + contentPanel.setHeadingText(getLabel()); + contentPanel.setTopComponent(null); + contentPanel.add(multipleQuestion); + + // Selects the already selected choices. + if (valueResult != null && valueResult.isValueDefined()) { + + final HashSet selectedChoicesId = new HashSet(ValueResultUtils.splitValuesAsInteger(valueResult.getValueObject())); + selectedChoices = new ArrayList(); + + for (final CategoryElementDTO choiceDTO : getCategoryType().getCategoryElementsDTO()) { + if (selectedChoicesId.contains(choiceDTO.getId())) { + selectedChoices.add(choiceDTO); + } + } + + selectionModel.select(selectedChoices, false); + } + + component = contentPanel; + } + + // If the component is a category and/or a quality criterion. + if (getCategoryType() != null) { + + if (getQualityCriterion() != null) { + component.setToolTip(I18N.MESSAGES.flexibleElementQuestionCategory(getCategoryType().getLabel()) + + "
" + + I18N.MESSAGES.flexibleElementQuestionQuality(getQualityCriterion().getInfo())); + } else { + component.setToolTip(I18N.MESSAGES.flexibleElementQuestionCategory(getCategoryType().getLabel())); + } + + } else if (getQualityCriterion() != null) { + component.setToolTip(I18N.MESSAGES.flexibleElementQuestionQuality(getQualityCriterion().getInfo())); + } + + // Remove disabled options (not selected) + /*for (CategoryElementDTO choice : getCateChoices()) { + if (choice.isDisabled() && !selectedChoices.contains(choice)) { + store.remove(choice); + } + }*/ + return component; + } + + } + + @Override + public boolean isCorrectRequiredValue(ValueResult result) { + + if (result == null || !result.isValueDefined()) { + return false; + } + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + try { + final String value = result.getValueObject(); + return value != null && !"".equals(value); + } catch (ClassCastException e) { + return false; + } + } // Multiple selection case. + else { + final List selectedChoicesId + = ValueResultUtils.splitValuesAsInteger(result.getValueObject()); + return selectedChoicesId != null && selectedChoicesId.size() > 0; + } + } + + /** + * Basic selection changes listener implementation to fire value changes + * events of the current flexible element. + * + * @author tmi + */ + private class ComboBoxSelectionListener extends + SelectionChangedListener { + + @Override + public void selectionChanged(SelectionChangedEvent se) { + + String value = null; + final boolean isValueOn; + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + + // Gets the selected choice. + final QuestionChoiceElementDTO choice = se.getSelectedItem(); + + // Checks if the choice isn't the default empty choice. + isValueOn = choice != null && choice.getId() != null + && choice.getId() != -1; + + if (choice != null) { + value = String.valueOf(choice.getId()); + } + } // Multiple selection case. + else { + + // Gets the selected choices. + final List choices + = se.getSelection(); + + isValueOn = choices != null && choices.size() != 0; + + if (choices != null) { + value = ValueResultUtils.mergeValues(choices); + } + } + + if (value != null) { + // Fires value change event. + handlerManager.fireEvent(new ValueEvent(QuestionElementDTO.this, value)); + } + + // Required element ? + if (getValidates()) { + handlerManager.fireEvent(new RequiredValueEvent(isValueOn)); + } + } + + } + + private class ComboBoxCateSelectionListener extends + SelectionChangedListener { + + @Override + public void selectionChanged(SelectionChangedEvent se) { + + String value = null; + final boolean isValueOn; + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + + // Gets the selected choice. + final CategoryElementDTO choice = se.getSelectedItem(); + + // Checks if the choice isn't the default empty choice. + isValueOn = choice != null && choice.getId() != null + && choice.getId() != -1; + + if (choice != null) { + value = String.valueOf(choice.getId()); + } + } // Multiple selection case. + else { + + // Gets the selected choices. + final List choices = se.getSelection(); + + isValueOn = choices != null && choices.size() != 0; + + if (choices != null) { + value = ValueResultUtils.mergeValues(choices); + } + } + + if (value != null) { + // Fires value change event. + handlerManager.fireEvent(new ValueEvent(QuestionElementDTO.this, value)); + } + + // Required element ? + if (getValidates()) { + handlerManager.fireEvent(new RequiredValueEvent(isValueOn)); + } + } + + } + + private String toLabel(String value) { + if (getCategoryType() != null) { + CategoryElementDTO singleChoice; + + try { + singleChoice = pickCateChoice(Integer.valueOf(value)); + + } catch (NumberFormatException e) { + GWT.log("Value is not an id: '" + value + "'.", e); + + // Searching for the element. + singleChoice = pickCateChoice(value); + } + + if (singleChoice != null) { + return singleChoice.getLabel(); + } else { + return ""; + } + + } else { + QuestionChoiceElementDTO singleChoice; + + try { + singleChoice = pickChoice(Integer.valueOf(value)); + + } catch (NumberFormatException e) { + GWT.log("Value is not an id: '" + value + "'.", e); + + // Searching for the element. + singleChoice = pickChoice(value); + } + + if (singleChoice != null) { + return singleChoice.getLabel(); + } else { + return ""; + } + } + } + + private List toLabels(String values) { + if (getCategoryType() != null) { + final ArrayList labels = new ArrayList(); + + try { + final List selectedChoicesId = ValueResultUtils.splitValuesAsInteger(values); + + for (final Integer id : selectedChoicesId) { + final CategoryElementDTO choice = pickCateChoice(id.intValue()); + if (choice != null) { + labels.add(choice.getLabel()); + } + } + } catch (NumberFormatException e) { + GWT.log("Values is not an array of ids:'" + values + "'.", e); + + final String valuesAsString = (String) values; + final String[] labelArray = valuesAsString.trim().split("-"); + for (final String label : labelArray) { + final String trimmedLabel = label.trim(); + if (!trimmedLabel.isEmpty()) { + labels.add(trimmedLabel); + } + } + } + + return labels; + } else { + final ArrayList labels = new ArrayList(); + + try { + final List selectedChoicesId = ValueResultUtils.splitValuesAsInteger(values); + + for (final Integer id : selectedChoicesId) { + final QuestionChoiceElementDTO choice = pickChoice(id.intValue()); + if (choice != null) { + labels.add(choice.getLabel()); + } + } + } catch (NumberFormatException e) { + GWT.log("Values is not an array of ids:'" + values + "'.", e); + + final String valuesAsString = (String) values; + final String[] labelArray = valuesAsString.trim().split("-"); + for (final String label : labelArray) { + final String trimmedLabel = label.trim(); + if (!trimmedLabel.isEmpty()) { + labels.add(trimmedLabel); + } + } + } + + return labels; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Object renderHistoryToken(HistoryTokenListDTO token) { + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + return new HistoryTokenText(toLabel(token.getTokens().get(0).getValue())); + } // Multiple selection case. + else { + return new HistoryTokenText(toLabels(token.getTokens().get(0).getValue())); + } + } + + @Override + public String toHTML(String value) { + if (value == null || value.length() == 0) { + return ""; + } + + final StringBuilder htmlBuilder = new StringBuilder(); + + // Single selection case. + if (!Boolean.TRUE.equals(getMultiple())) { + htmlBuilder.append(toLabel(value)); + } // Multiple selection case. + else { + for (final String entry : toLabels(value)) { + htmlBuilder.append(" -").append(entry).append("
"); + } + } + + return htmlBuilder.toString(); + } + + /** + * Select a choice among the list of the choices. + * + * @param id The wanted choice's id. + * @return The choice if it exists, null otherwise. + */ + private QuestionChoiceElementDTO pickChoice(int id) { + + if (getChoices() != null) { + for (final QuestionChoiceElementDTO choice : getChoices()) { + if (choice.getId().equals(id)) { + return choice; + } + } + } + + return null; + } + + private CategoryElementDTO pickCateChoice(int id) { + + if (getCategoryType().getCategoryElementsDTO() != null) { + for (final CategoryElementDTO choice : getCategoryType().getCategoryElementsDTO()) { + if (choice.getId().equals(id)) { + return choice; + } + } + } + + return null; + } + + /** + * Select a choice among the list of the choices. + * + * @param label The wanted choice's label. + * @return The choice if it exists, null otherwise. + */ + private QuestionChoiceElementDTO pickChoice(final String label) { + + if (getChoices() != null) { + for (final QuestionChoiceElementDTO choice : getChoices()) { + if (choice.getLabel().equals(label)) { + return choice; + } + } + } + + return null; + } + + private CategoryElementDTO pickCateChoice(final String label) { + + if (getCategoryType().getCategoryElementsDTO() != null) { + for (final CategoryElementDTO choice : getCategoryType().getCategoryElementsDTO()) { + if (choice.getLabel().equals(label)) { + return choice; + } + } } - return component; - } - - @Override - public boolean isCorrectRequiredValue(ValueResult result) { - - if (result == null || !result.isValueDefined()) { - return false; - } - - // Single selection case. - if (!Boolean.TRUE.equals(getMultiple())) { - try { - final String value = result.getValueObject(); - return value != null && !"".equals(value); - } catch (ClassCastException e) { - return false; - } - } - // Multiple selection case. - else { - final List selectedChoicesId = ValueResultUtils.splitValuesAsInteger(result.getValueObject()); - return selectedChoicesId != null && selectedChoicesId.size() > 0; - } - } - - /** - * Basic selection changes listener implementation to fire value changes events of the current flexible element. - * - * @author tmi - */ - private class ComboBoxSelectionListener extends SelectionChangedListener { - - @Override - public void selectionChanged(SelectionChangedEvent se) { - - String value = null; - final boolean isValueOn; - - // Single selection case. - if (!Boolean.TRUE.equals(getMultiple())) { - - // Gets the selected choice. - final QuestionChoiceElementDTO choice = se.getSelectedItem(); - - // Checks if the choice isn't the default empty choice. - isValueOn = choice != null && choice.getId() != null && choice.getId() != -1; - - if (choice != null) { - value = String.valueOf(choice.getId()); - } - } - // Multiple selection case. - else { - - // Gets the selected choices. - final List choices = se.getSelection(); - - isValueOn = choices != null && choices.size() != 0; - - if (choices != null) { - value = ValueResultUtils.mergeValues(choices); - } - } - - if (value != null) { - // Fires value change event. - handlerManager.fireEvent(new ValueEvent(QuestionElementDTO.this, value)); - } - - // Required element ? - if (getValidates()) { - handlerManager.fireEvent(new RequiredValueEvent(isValueOn)); - } - } - - } - - private String toLabel(String value) { - QuestionChoiceElementDTO singleChoice; - - try { - singleChoice = pickChoice(Integer.valueOf(value)); - - } catch (NumberFormatException e) { - GWT.log("Value is not an id: '" + value + "'.", e); - - // Searching for the element. - singleChoice = pickChoice(value); - } - - if (singleChoice != null) { - return singleChoice.getLabel(); - } else { - return ""; - } - } - - private List toLabels(String values) { - final ArrayList labels = new ArrayList(); - - try { - final List selectedChoicesId = ValueResultUtils.splitValuesAsInteger(values); - - for (final Integer id : selectedChoicesId) { - final QuestionChoiceElementDTO choice = pickChoice(id.intValue()); - if (choice != null) { - labels.add(choice.getLabel()); - } - } - } catch (NumberFormatException e) { - GWT.log("Values is not an array of ids:'" + values + "'.", e); - - final String valuesAsString = (String) values; - final String[] labelArray = valuesAsString.trim().split("-"); - for (final String label : labelArray) { - final String trimmedLabel = label.trim(); - if (!trimmedLabel.isEmpty()) { - labels.add(trimmedLabel); - } - } - } - - return labels; - } - - /** - * {@inheritDoc} - */ - @Override - public Object renderHistoryToken(HistoryTokenListDTO token) { - - // Single selection case. - if (!Boolean.TRUE.equals(getMultiple())) { - return new HistoryTokenText(toLabel(token.getTokens().get(0).getValue())); - } - // Multiple selection case. - else { - return new HistoryTokenText(toLabels(token.getTokens().get(0).getValue())); - } - } - - @Override - public String toHTML(String value) { - if(value == null || value.length() == 0) { - return ""; - } - - final StringBuilder htmlBuilder = new StringBuilder(); - - // Single selection case. - if (!Boolean.TRUE.equals(getMultiple())) { - htmlBuilder.append(toLabel(value)); - } - // Multiple selection case. - else { - for(final String entry : toLabels(value)) { - htmlBuilder.append(" -").append(entry).append("
"); - } - } - - return htmlBuilder.toString(); - } - - /** - * Select a choice among the list of the choices. - * - * @param id - * The wanted choice's id. - * @return The choice if it exists, null otherwise. - */ - private QuestionChoiceElementDTO pickChoice(int id) { - - if (getChoices() != null) { - for (final QuestionChoiceElementDTO choice : getChoices()) { - if (choice.getId().equals(id)) { - return choice; - } - } - } - - return null; - } - - /** - * Select a choice among the list of the choices. - * - * @param label - * The wanted choice's label. - * @return The choice if it exists, null otherwise. - */ - private QuestionChoiceElementDTO pickChoice(final String label) { - - if (getChoices() != null) { - for (final QuestionChoiceElementDTO choice : getChoices()) { - if (choice.getLabel().equals(label)) { - return choice; - } - } - } - - return null; - } + return null; + } } diff --git a/src/main/resources/org/sigmah/client/i18n/UIConstants.properties b/src/main/resources/org/sigmah/client/i18n/UIConstants.properties index dd875c832..260ad322f 100644 --- a/src/main/resources/org/sigmah/client/i18n/UIConstants.properties +++ b/src/main/resources/org/sigmah/client/i18n/UIConstants.properties @@ -1664,10 +1664,14 @@ adminDeleteLayoutGroupsConfirm=The selected groups have been deleted. adminDeleteLayoutGroups=Delete selected groups enable=Enable disable=Disable +categoryElements=CategoryElements adminFlexibleEnableFlexibleElements=Enable selected fields adminFlexibleDisableFlexibleElements=Disable selected fields adminFlexibleEnableFlexibleElementsConfirm=The selected fields have been enabled. adminFlexibleDisableFlexibleElementsConfirm=The selected fields have been disabled. +adminEnableCategoryElementsConfirm=The selected category elements have been enabled. +adminDisableCategoryElementsConfirm=The selected category elements have been disabled. +adminCategoryElementEnableConfirm=Do you wish to automatically add this category item as new personalized choice in all fields already using this category? adminOneModelMaintenanceAttention=Warning adminOneModelMaintenanceAlert=Be aware that during the maintenance period, modifications will not be allowed on any project/organisational unit created from this model. adminOneModelMaintenanceTitle=Modification of an "Available and Used" model