nc.noumea.mairie.appock.viewmodel.EditCatalogueViewModel.java Source code

Java tutorial

Introduction

Here is the source code for nc.noumea.mairie.appock.viewmodel.EditCatalogueViewModel.java

Source

package nc.noumea.mairie.appock.viewmodel;

/*-
 * #%L
 * Logiciel de Gestion des approvisionnements et des stocks des fournitures administratives de la Mairie de Nouma
 * %%
 * Copyright (C) 2017 Mairie de Nouma, Nouvelle-Caldonie
 * %%
 * 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
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import nc.noumea.mairie.appock.controller.MainController;
import nc.noumea.mairie.appock.core.utility.AppockUtil;
import nc.noumea.mairie.appock.core.viewmodel.AbstractEditViewModel;
import nc.noumea.mairie.appock.entity.*;
import nc.noumea.mairie.appock.enums.EtatCatalogue;
import nc.noumea.mairie.appock.enums.TypeCatalogueNode;
import nc.noumea.mairie.appock.repositories.*;
import nc.noumea.mairie.appock.services.*;
import nc.noumea.mairie.appock.util.CatalogueTreeModel;
import nc.noumea.mairie.appock.util.CatalogueTreeNode;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.orm.jpa.JpaSystemException;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.*;
import org.zkoss.image.AImage;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import org.zkoss.zul.*;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@VariableResolver(DelegatingVariableResolver.class)
public class EditCatalogueViewModel extends AbstractEditViewModel<Catalogue> implements Serializable {
    private static final long serialVersionUID = 1L;

    @WireVariable
    CatalogueRepository catalogueRepository;

    @WireVariable
    FamilleRepository familleRepository;

    @WireVariable
    SousFamilleRepository sousFamilleRepository;

    @WireVariable
    ArticleCatalogueRepository articleCatalogueRepository;

    @WireVariable
    ArticleCatalogueService articleCatalogueService;

    @WireVariable
    ConfigService configService;

    @WireVariable
    CatalogueService catalogueService;

    @WireVariable
    MarcheRepository marcheRepository;

    @WireVariable
    SousMarcheRepository sousMarcheRepository;

    @WireVariable
    TypeColisageRepository typeColisageRepository;

    @WireVariable
    PanierService panierService;

    @WireVariable
    FournisseurRepository fournisseurRepository;

    @WireVariable
    FamilleService familleService;

    @WireVariable
    SousFamilleService sousFamilleService;

    @WireVariable
    ExportExcelService exportExcelService;

    private TreeModel<CatalogueTreeNode> catalogueTree;

    private TreeitemRenderer<CatalogueTreeNode> catalogueTreeitemRenderer;

    private CatalogueTreeNode selectedCatalogueTreeNode;

    private Famille popupCreateFamille, popupEditFamille = new Famille();

    private SousFamille popupCreateSousFamille, popupEditSousFamille = new SousFamille();

    private ArticleCatalogue popupCreateArticleCatalogue, popupEditArticleCatalogue = new ArticleCatalogue();

    private ListModelList<ArticleCatalogue> listeArticleCatalogue;

    /**
     * popup visible ou non
     */
    private boolean popupCreateFamilleVisible, popupCreateSousFamilleVisible, popupCreateArticleCatalogueVisible,
            popupEditFamilleVisible, popupEditSousFamilleVisible, popupEditArticleCatalogueVisible;

    @Init(superclass = true)
    public void init() throws IOException {
        initCatalogueTreeModel();
    }

    @AfterCompose
    public void afterCompose(@ContextParam(ContextType.VIEW) Component view) {
        Selectors.wireComponents(view, this, false);
    }

    public TreeModel<CatalogueTreeNode> getCatalogueTree() {
        return catalogueTree;
    }

    public void setCatalogueTree(TreeModel<CatalogueTreeNode> catalogueTree) {
        this.catalogueTree = catalogueTree;
    }

    public Famille getPopupCreateFamille() {
        return popupCreateFamille;
    }

    public void setPopupCreateFamille(Famille popupCreateFamille) {
        this.popupCreateFamille = popupCreateFamille;
    }

    public boolean isPopupCreateFamilleVisible() {
        return popupCreateFamilleVisible;
    }

    public void setPopupCreateFamilleVisible(boolean popupCreateFamilleVisible) {
        this.popupCreateFamilleVisible = popupCreateFamilleVisible;
    }

    public CatalogueTreeNode getSelectedCatalogueTreeNode() {
        return selectedCatalogueTreeNode;
    }

    public void setSelectedCatalogueTreeNode(CatalogueTreeNode selectedCatalogueTreeNode) {
        this.selectedCatalogueTreeNode = selectedCatalogueTreeNode;
    }

    public boolean isPopupCreateSousFamilleVisible() {
        return popupCreateSousFamilleVisible;
    }

    public void setPopupCreateSousFamilleVisible(boolean popupCreateSousFamilleVisible) {
        this.popupCreateSousFamilleVisible = popupCreateSousFamilleVisible;
    }

    public SousFamille getPopupCreateSousFamille() {
        return popupCreateSousFamille;
    }

    public void setPopupCreateSousFamille(SousFamille popupCreateSousFamille) {
        this.popupCreateSousFamille = popupCreateSousFamille;
    }

    public Famille getPopupEditFamille() {
        return popupEditFamille;
    }

    public void setPopupEditFamille(Famille popupEditFamille) {
        this.popupEditFamille = popupEditFamille;
    }

    public SousFamille getPopupEditSousFamille() {
        return popupEditSousFamille;
    }

    public void setPopupEditSousFamille(SousFamille popupEditSousFamille) {
        this.popupEditSousFamille = popupEditSousFamille;
    }

    public boolean isPopupEditFamilleVisible() {
        return popupEditFamilleVisible;
    }

    public void setPopupEditFamilleVisible(boolean popupEditFamilleVisible) {
        this.popupEditFamilleVisible = popupEditFamilleVisible;
    }

    public boolean isPopupEditSousFamilleVisible() {
        return popupEditSousFamilleVisible;
    }

    public void setPopupEditSousFamilleVisible(boolean popupEditSousFamilleVisible) {
        this.popupEditSousFamilleVisible = popupEditSousFamilleVisible;
    }

    public ArticleCatalogue getPopupCreateArticleCatalogue() {
        return popupCreateArticleCatalogue;
    }

    public void setPopupCreateArticleCatalogue(ArticleCatalogue popupCreateArticleCatalogue) {
        this.popupCreateArticleCatalogue = popupCreateArticleCatalogue;
    }

    public ArticleCatalogue getPopupEditArticleCatalogue() {
        return popupEditArticleCatalogue;
    }

    public void setPopupEditArticleCatalogue(ArticleCatalogue popupEditArticleCatalogue) {
        this.popupEditArticleCatalogue = popupEditArticleCatalogue;
    }

    public boolean isPopupCreateArticleCatalogueVisible() {
        return popupCreateArticleCatalogueVisible;
    }

    public void setPopupCreateArticleCatalogueVisible(boolean popupCreateArticleCatalogueVisible) {
        this.popupCreateArticleCatalogueVisible = popupCreateArticleCatalogueVisible;
    }

    public boolean isPopupEditArticleCatalogueVisible() {
        return popupEditArticleCatalogueVisible;
    }

    public void setPopupEditArticleCatalogueVisible(boolean popupEditArticleCatalogueVisible) {
        this.popupEditArticleCatalogueVisible = popupEditArticleCatalogueVisible;
    }

    public ListModelList<ArticleCatalogue> getListeArticleCatalogue() {
        return listeArticleCatalogue;
    }

    public void setListeArticleCatalogue(ListModelList<ArticleCatalogue> listeArticleCatalogue) {
        this.listeArticleCatalogue = listeArticleCatalogue;
    }

    @Override
    @Command
    @NotifyChange("entity")
    public void update() {
        List<Catalogue> listeCatalogueWithSameLibelle = catalogueRepository.findAllByLibelle(entity.getLibelle());
        if (!CollectionUtils.isEmpty(listeCatalogueWithSameLibelle)) {
            Catalogue catalogue = listeCatalogueWithSameLibelle.get(0);
            if (!AppockUtil.sameIdAndNotNull(catalogue.getId(), entity.getId())) {
                showErrorPopup("Le libell " + entity.getLibelle() + " est dj utilis");
                return;
            }
        }
        super.update();
    }

    @Override
    protected String getMessageNotificationEnregistre() {
        return "Catalogue enregistr";
    }

    private void initCatalogueTreeModel() throws IOException {
        setCatalogueTree(new CatalogueTreeModel(getCatalogueTreeRoot()));
    }

    private CatalogueTreeNode getCatalogueTreeRoot() throws IOException {
        return catalogueService.getCatalogueTreeRoot(this.entity, false, false, false, null);
    }

    public TreeitemRenderer<CatalogueTreeNode> getCatalogueTreeitemRenderer() {
        if (catalogueTreeitemRenderer == null) {
            catalogueTreeitemRenderer = new TreeitemRenderer<CatalogueTreeNode>() {
                @Override
                public void render(Treeitem treeitem, CatalogueTreeNode catalogueTreeNode, int i) throws Exception {
                    Treerow dataRow = new Treerow();
                    dataRow.setParent(treeitem);
                    treeitem.setValue(catalogueTreeNode);
                    treeitem.setOpen(true);

                    Treecell treecellLabel = new Treecell(catalogueTreeNode.getLibelle());
                    dataRow.appendChild(treecellLabel);
                    dataRow.addEventListener(Events.ON_CLICK, event -> {
                        CatalogueTreeNode selectedNodeValue = ((Treeitem) event.getTarget().getParent()).getValue();
                        setSelectedCatalogueTreeNode(selectedNodeValue);

                        if (selectedNodeValue.getTypeCatalogueNode() == TypeCatalogueNode.FAMILLE) {
                            List<ArticleCatalogue> result = new ArrayList<>();
                            for (SousFamille sousFamille : ((Famille) selectedNodeValue.getEntity())
                                    .getListeSousFamille()) {
                                result.addAll(sousFamille.getListeArticleCatalogue());
                            }
                            setListeArticleCatalogue(new ListModelList<>(result));
                            notifyChange("listeArticleCatalogue");
                        } else if (selectedNodeValue.getTypeCatalogueNode() == TypeCatalogueNode.SOUS_FAMILLE) {
                            setListeArticleCatalogue(new ListModelList<>(
                                    ((SousFamille) selectedNodeValue.getEntity()).getListeArticleCatalogue()));
                            notifyChange("listeArticleCatalogue");
                        }
                    });
                    dataRow.addEventListener(Events.ON_DOUBLE_CLICK, event -> {
                        CatalogueTreeNode selectedNodeValue = ((Treeitem) event.getTarget().getParent()).getValue();
                        setSelectedCatalogueTreeNode(selectedNodeValue);
                        // @formatter:off
                        switch (selectedNodeValue.getTypeCatalogueNode()) {
                        case FAMILLE:
                            editFamille();
                            notifyChange(new String[] { "popupEditFamille", "popupEditFamilleVisible" });
                            break;
                        case SOUS_FAMILLE:
                            editSousFamille();
                            notifyChange(new String[] { "popupEditSousFamille", "popupEditSousFamilleVisible" });
                            break;
                        default:
                            break;
                        }
                        // @formatter:on
                    });

                    Treecell treecellNombreArticle = new Treecell(
                            String.valueOf(catalogueTreeNode.getNombreArticleCatalogue()));
                    dataRow.appendChild(treecellNombreArticle);

                    if (!entity.isArchive()) {
                        Treecell treecellDelete = new Treecell();
                        Button buttonDelete = new Button();
                        buttonDelete.setIconSclass("z-icon-trash");
                        buttonDelete.addEventListener(Events.ON_CLICK, event -> {
                            CatalogueTreeNode selectedNodeValue = ((Treeitem) event.getTarget().getParent()
                                    .getParent().getParent()).getValue();
                            deleteFamilleSousFamille(selectedNodeValue);

                        });
                        treecellDelete.appendChild(buttonDelete);
                        dataRow.appendChild(treecellDelete);
                    }
                }
            };
        }

        return catalogueTreeitemRenderer;
    }

    public void setCatalogueTreeitemRenderer(TreeitemRenderer<CatalogueTreeNode> catalogueTreeitemRenderer) {
        this.catalogueTreeitemRenderer = catalogueTreeitemRenderer;
    }

    public void deleteFamilleSousFamille(CatalogueTreeNode catalogueTreeNode) {
        // @formatter:off
        switch (catalogueTreeNode.getTypeCatalogueNode()) {
        case FAMILLE:
            Messagebox.show(
                    "Voulez-vous vraiment supprimer cette famille ainsi que toutes les sous-famille et tous les articles qui lui sont rattachs ?",
                    "Suppression", new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO },
                    Messagebox.QUESTION, evt -> {
                        if (evt.getName().equals("onYes")) {
                            try {
                                familleRepository.delete((Famille) catalogueTreeNode.getEntity());
                                rechargeOnglet();
                                showNotificationStandard("Famille supprime");
                            } catch (JpaSystemException e) {
                                Messagebox.show(
                                        "Impossible de supprimer cette famille car un de ses lments est utilis dans l'application",
                                        "Suppression refuse", Messagebox.OK, Messagebox.ERROR);
                                return;
                            }
                        }
                    });
            break;
        case SOUS_FAMILLE:
            Messagebox.show(
                    "Voulez-vous vraiment supprimer cette sous-famille ainsi que tous les articles qui lui sont rattachs ?",
                    "Suppression", new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO },
                    Messagebox.QUESTION, evt -> {
                        if (evt.getName().equals("onYes")) {
                            try {
                                sousFamilleRepository.delete((SousFamille) catalogueTreeNode.getEntity());
                                rechargeOnglet();
                                showNotificationStandard("Sous-famille supprime");
                            } catch (JpaSystemException e) {
                                Messagebox.show(
                                        "Impossible de supprimer cette sous-famille car un de ses lments est utilis dans l'application",
                                        "Suppression refuse", Messagebox.OK, Messagebox.ERROR);
                                return;
                            }
                        }
                    });
            break;
        default:
            break;
        }
        // @formatter:on
    }

    @Command
    @NotifyChange({ "popupCreateFamille", "popupCreateFamilleVisible" })
    public void createFamille() {
        this.popupCreateFamille = new Famille();
        this.setPopupCreateFamilleVisible(true);
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupCreateFamilleVisible" })
    public void addFamille() {
        if (showErrorPopup(this.popupCreateFamille)) {
            return;
        }

        Famille famille = familleService.findByLibelleAndCatalogue(this.popupCreateFamille.getLibelle(),
                this.entity);
        if (famille != null) {
            Messagebox.show("Cette famille existe dj", "Cration refuse", Messagebox.OK,
                    Messagebox.INFORMATION);
            return;
        }

        this.popupCreateFamille.setCatalogue(this.entity);
        this.entity.getListeFamille().add(this.popupCreateFamille);
        this.setPopupCreateFamilleVisible(false);
        this.update();

        this.rechargeOnglet();
    }

    @Command
    @NotifyChange("popupCreateFamilleVisible")
    public void cancelCreateFamille(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupCreateFamilleVisible = false;
    }

    @Command
    @NotifyChange({ "popupCreateSousFamille", "popupCreateSousFamilleVisible" })
    public void createSousFamille() {
        if (selectedCatalogueTreeNode == null
                || selectedCatalogueTreeNode.getTypeCatalogueNode() != TypeCatalogueNode.FAMILLE) {
            Messagebox.show("Vous devez slectionner une famille afin de pouvoir lui ajouter une sous-famille",
                    "Cration refuse", Messagebox.OK, Messagebox.INFORMATION);
            return;
        }

        this.popupCreateSousFamille = new SousFamille();
        this.popupCreateSousFamille.setFamille((Famille) selectedCatalogueTreeNode.getEntity());
        this.setPopupCreateSousFamilleVisible(true);
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupCreateSousFamilleVisible" })
    public void addSousFamille() {
        if (showErrorPopup(this.popupCreateSousFamille)) {
            return;
        }

        SousFamille sousFamille = sousFamilleService
                .findByLibelleAndCatalogue(this.popupCreateSousFamille.getLibelle(), this.entity);
        if (sousFamille != null) {
            Messagebox.show("Cette sous-famille existe dj dans ce catalogue", "Cration refuse",
                    Messagebox.OK, Messagebox.INFORMATION);
            return;
        }

        this.popupCreateSousFamille.setFamille((Famille) selectedCatalogueTreeNode.getEntity());
        for (Famille famille : this.entity.getListeFamille()) {
            if (famille.equals(selectedCatalogueTreeNode.getEntity())) {
                famille.getListeSousFamille().add(this.popupCreateSousFamille);
            }
        }
        this.setPopupCreateSousFamilleVisible(false);
        this.update();

        this.rechargeOnglet();
    }

    @Command
    @NotifyChange("popupCreateSousFamilleVisible")
    public void cancelCreateSousFamille(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupCreateSousFamilleVisible = false;
    }

    @Command
    public void editFamille() {
        this.popupEditFamille = new Famille();
        this.popupEditFamille = (Famille) this.selectedCatalogueTreeNode.getEntity();
        this.setPopupEditFamilleVisible(true);
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupEditFamilleVisible" })
    public void updateFamille() {
        if (showErrorPopup(this.popupEditFamille)) {
            return;
        }

        Famille famille = familleService.findByLibelleAndCatalogue(this.popupEditFamille.getLibelle(), this.entity);
        if (famille != null && !famille.equals(this.popupEditFamille)) {
            Messagebox.show("Cette famille existe dj", "Cration refuse", Messagebox.OK,
                    Messagebox.INFORMATION);
            return;
        }

        this.setPopupEditFamilleVisible(false);
        familleRepository.save(this.popupEditFamille);

        this.rechargeOnglet();
    }

    @Command
    @NotifyChange("popupEditFamilleVisible")
    public void cancelEditFamille(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupEditFamilleVisible = false;
    }

    @Command
    public void editSousFamille() {
        this.popupEditSousFamille = new SousFamille();
        this.popupEditSousFamille = (SousFamille) this.selectedCatalogueTreeNode.getEntity();
        this.setPopupEditSousFamilleVisible(true);
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupEditSousFamilleVisible" })
    public void updateSousFamille() {
        if (showErrorPopup(this.popupEditSousFamille)) {
            return;
        }

        SousFamille sousFamille = sousFamilleService
                .findByLibelleAndCatalogue(this.popupEditSousFamille.getLibelle(), this.entity);
        if (sousFamille != null && !sousFamille.equals(this.popupEditSousFamille)) {
            Messagebox.show("Cette sous-famille existe dj dans ce catalogue", "Cration refuse",
                    Messagebox.OK, Messagebox.INFORMATION);
            return;
        }

        this.setPopupEditSousFamilleVisible(false);
        sousFamilleRepository.save(this.popupEditSousFamille);

        this.rechargeOnglet();
    }

    @Command
    @NotifyChange("popupEditSousFamilleVisible")
    public void cancelEditSousFamille(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupEditSousFamilleVisible = false;
    }

    @Command
    @NotifyChange({ "popupCreateArticleCatalogue", "popupCreateArticleCatalogueVisible" })
    public void createArticleCatalogue() {
        if (selectedCatalogueTreeNode == null
                || selectedCatalogueTreeNode.getTypeCatalogueNode() != TypeCatalogueNode.SOUS_FAMILLE) {
            Messagebox.show("Vous devez slectionner une sous-famille afin de pouvoir lui ajouter un article",
                    "Cration refuse", Messagebox.OK, Messagebox.INFORMATION);
            return;
        }

        this.popupCreateArticleCatalogue = new ArticleCatalogue();
        this.popupCreateArticleCatalogue.setSousFamille((SousFamille) selectedCatalogueTreeNode.getEntity());
        this.setPopupCreateArticleCatalogueVisible(true);
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupCreateArticleCatalogueVisible" })
    public void addArticleCatalogue() throws IOException {
        if (showErrorPopup(this.popupCreateArticleCatalogue)) {
            return;
        }

        if (this.popupCreateArticleCatalogue.getPhotoSrc() != null) {
            byte[] content = java.util.Base64.getDecoder()
                    .decode(this.popupCreateArticleCatalogue.getPhotoSrc().split(",")[1].getBytes("UTF-8"));
            this.popupCreateArticleCatalogue.setPhotoArticleCatalogue(
                    catalogueService.savePhotoArticleCatalogue(content, "import_fichier"));
        }

        this.popupCreateArticleCatalogue.setSousFamille((SousFamille) selectedCatalogueTreeNode.getEntity());
        for (Famille famille : this.entity.getListeFamille()) {
            for (SousFamille sousFamille : famille.getListeSousFamille()) {
                if (sousFamille.equals(selectedCatalogueTreeNode.getEntity())) {
                    sousFamille.getListeArticleCatalogue().add(this.popupCreateArticleCatalogue);
                }
            }
        }

        // Avec la regexp de lien qui est indiqu, lors d'un vidage de l'input, a met  blanc et pas  null
        if (org.apache.commons.lang.StringUtils.isBlank(this.popupCreateArticleCatalogue.getLienFournisseur())) {
            this.popupCreateArticleCatalogue.setLienFournisseur(null);
        }

        this.setPopupCreateArticleCatalogueVisible(false);
        this.update();

        this.rechargeOnglet();
    }

    @Command
    @NotifyChange("popupCreateArticleCatalogueVisible")
    public void cancelCreateArticleCatalogue(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupCreateArticleCatalogueVisible = false;
    }

    @Command
    @NotifyChange({ "popupEditArticleCatalogue", "popupEditArticleCatalogueVisible" })
    public void editArticleCatalogue(@BindingParam("articleCatalogue") ArticleCatalogue articleCatalogue)
            throws IOException {

        if (entity.isArchive()) {
            return;
        }

        this.popupEditArticleCatalogue = articleCatalogue;
        initialisePhotoArticleCatalogue(this.popupEditArticleCatalogue);
        this.setPopupEditArticleCatalogueVisible(true);
    }

    private void initialisePhotoArticleCatalogue(ArticleCatalogue articleCatalogue) throws IOException {
        if (articleCatalogue.getPhotoArticleCatalogue() != null) {
            File fichierPhotoArticleCatalogue = catalogueService
                    .getFilePieceJointe(articleCatalogue.getPhotoArticleCatalogue());
            byte[] bytes = Files.readAllBytes(fichierPhotoArticleCatalogue.toPath());
            articleCatalogue.setPhotoSrc(("data:" + AppockUtil.getMimeType(bytes) + ";base64,")
                    + StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false)));
        }
    }

    @Command
    @NotifyChange({ "catalogueTree", "popupEditArticleCatalogueVisible" })
    public void updateArticleCatalogue() throws IOException {
        if (showErrorPopup(this.popupEditArticleCatalogue) || entity.isArchive()) {
            return;
        }

        ArticleCatalogue oldArticleCatalogue = articleCatalogueRepository
                .findOne(popupEditArticleCatalogue.getId());

        // Avec la regexp de lien qui est indiqu, lors d'un vidage de l'input, a met  blanc et pas  null
        if (org.apache.commons.lang.StringUtils.isBlank(this.popupEditArticleCatalogue.getLienFournisseur())) {
            this.popupEditArticleCatalogue.setLienFournisseur(null);
        }

        if (oldArticleCatalogue.isActif() && !this.popupEditArticleCatalogue.isActif()) {
            // L'article vient d'tre dsactiv
            Messagebox.show("Voulez-vous vraiment dsactiver cet article ?", "Dsactivation",
                    new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO }, Messagebox.QUESTION,
                    evt -> {
                        if (evt.getName().equals("onYes")) {
                            articleCatalogueService.gereDesactivationArticleCatalogue(popupEditArticleCatalogue);
                            setPopupEditArticleCatalogueVisible(false);
                            updateArticleCatalogue(oldArticleCatalogue, popupEditArticleCatalogue);
                            rechargeOnglet();
                        }
                    });
        } else {
            this.setPopupEditArticleCatalogueVisible(false);
            updateArticleCatalogue(oldArticleCatalogue, this.popupEditArticleCatalogue);
            this.rechargeOnglet();
        }
    }

    @Command
    @NotifyChange({ "popupCreateArticleCatalogue" })
    public void deletePhotoArticleCataloguePourCreation() {
        this.popupCreateArticleCatalogue.setPhotoSrc(null);
        this.popupCreateArticleCatalogue.setPhotoArticleCatalogue(null);
    }

    @Command
    @NotifyChange({ "popupEditArticleCatalogue" })
    public void deletePhotoArticleCataloguePourEdition() {
        this.popupEditArticleCatalogue.setPhotoSrc(null);
        this.popupEditArticleCatalogue.setPhotoArticleCatalogue(null);
    }

    private void updateArticleCatalogue(ArticleCatalogue oldArticleCatalogue,
            ArticleCatalogue articleCatalogueToUpdate) throws IOException {
        initialisePhotoArticleCatalogue(oldArticleCatalogue);
        if (oldArticleCatalogue.getPhotoSrc() != null && articleCatalogueToUpdate.getPhotoSrc() != null) {
            if (!oldArticleCatalogue.getPhotoSrc().equals(articleCatalogueToUpdate.getPhotoSrc())) {
                byte[] content = java.util.Base64.getDecoder()
                        .decode(articleCatalogueToUpdate.getPhotoSrc().split(",")[1].getBytes("UTF-8"));
                articleCatalogueToUpdate.setPhotoArticleCatalogue(
                        catalogueService.savePhotoArticleCatalogue(content, "import_fichier"));
            }
        }

        articleCatalogueRepository.save(popupEditArticleCatalogue);
    }

    @Command
    @NotifyChange("popupEditArticleCatalogueVisible")
    public void cancelEditArticleCatalogue(@ContextParam(ContextType.TRIGGER_EVENT) Event event) {
        event.stopPropagation();
        this.rechargeOnglet();
        this.popupEditArticleCatalogueVisible = false;
    }

    @Command
    public void importCatalogue(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) throws IOException {
        UploadEvent upEvent = null;
        Object objUploadEvent = ctx.getTriggerEvent();
        if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
            upEvent = (UploadEvent) objUploadEvent;
        }
        if (upEvent != null) {
            Media media = upEvent.getMedia();
            if (media != null) {
                if (!media.getFormat().equals("xlsx")) {
                    Messagebox.show("Vous devez importer un fichier Excel 2007 (.xlsx)");
                    return;
                }
                byte[] contenu = media.getByteData();
                Integer tailleMaxPieceJointeEnMo = configService.getTailleMaxPieceJointeEnMo();
                double tailleFichierEnMo = contenu.length / (1024.0 * 1024.0);

                if (tailleMaxPieceJointeEnMo != null && tailleFichierEnMo > tailleMaxPieceJointeEnMo) {
                    Messagebox.show("Pice trop grande, le fichier fait "
                            + AppockUtil.formatteAvec2ChiffreApresVirgule(tailleFichierEnMo, false)
                            + " Mo, et la limite est de " + tailleMaxPieceJointeEnMo + "Mo");
                    return;
                }

                List<String> messages = catalogueService.importCatalogue(media, this.entity);
                Map params = new HashMap();
                params.put("width", 600);
                Messagebox.show(messages.stream().collect(Collectors.joining("\n")), //
                        "Rsultat d'import", //
                        new Messagebox.Button[] { Messagebox.Button.OK }, //
                        null, null, null, null, //
                        params);

                this.rechargeOnglet();
                showNotificationStandard("Catalogue import");
            }
        }
    }

    @Command
    @NotifyChange("popupCreateArticleCatalogue")
    public void importPhotoArticleCataloguePourCreation(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
            throws IOException {
        this.popupCreateArticleCatalogue.setPhotoSrc(importPhotoArticleCatalogue(ctx));
    }

    @Command
    @NotifyChange("popupEditArticleCatalogue")
    public void importPhotoArticleCataloguePourEdition(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
            throws IOException {
        this.popupEditArticleCatalogue.setPhotoSrc(importPhotoArticleCatalogue(ctx));
    }

    private String importPhotoArticleCatalogue(BindContext ctx) throws IOException {
        UploadEvent upEvent = null;
        Object objUploadEvent = ctx.getTriggerEvent();
        if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
            upEvent = (UploadEvent) objUploadEvent;
        }
        if (upEvent != null) {
            Media media = upEvent.getMedia();
            if (media == null || !(media instanceof AImage)) {
                Messagebox.show("Vous devez importer une image");
                return null;
            }

            byte[] contenu = media.getByteData();
            Integer tailleMaxPieceJointeEnMo = configService.getTailleMaxPieceJointeEnMo();
            double tailleFichierEnMo = contenu.length / (1024.0 * 1024.0);

            if (tailleMaxPieceJointeEnMo != null && tailleFichierEnMo > tailleMaxPieceJointeEnMo) {
                Messagebox.show("Pice trop grande, le fichier fait "
                        + AppockUtil.formatteAvec2ChiffreApresVirgule(tailleFichierEnMo, false)
                        + " Mo, et la limite est de " + tailleMaxPieceJointeEnMo + "Mo");
                return null;
            }

            contenu = AppockUtil.scale(contenu, 80, 80);

            return ("data:" + AppockUtil.getMimeType(contenu) + ";base64,")
                    + StringUtils.newStringUtf8(Base64.encodeBase64(contenu, false));
        }

        return null;
    }

    /**
     * @return la liste des marchs proposs sur cration d'un catalogue
     */
    public List<Marche> getListeMarche() {
        List<Marche> result = marcheRepository.findAllByOrderByLibelle();
        result.add(0, null);
        return result;
    }

    public List<SousMarche> getListeSousMarche() {
        List<SousMarche> listeSousMarche = sousMarcheRepository
                .findAllByMarcheOrderByLibelle(this.entity.getMarche());
        listeSousMarche.add(0, null);
        return listeSousMarche;
    }

    public List<TypeColisage> getListeTypeColisage() {
        return typeColisageRepository.findAllByOrderByLibelle();
    }

    @Command
    public void deleteArticleCatalogue(@BindingParam("articleCatalogue") ArticleCatalogue articleCatalogue) {
        Messagebox.show("Voulez-vous vraiment supprimer cet article ?", "Suppression",
                new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO }, Messagebox.QUESTION,
                evt -> {
                    if (evt.getName().equals("onYes")) {
                        try {
                            SousFamille sousFamille = articleCatalogue.getSousFamille();
                            sousFamille.removeArticleCatalogue(articleCatalogue);
                            sousFamilleRepository.save(sousFamille);
                            rechargeOnglet();
                            notifyChange("entity");
                            showNotificationStandard("Article supprim");
                        } catch (JpaSystemException e) {
                            Messagebox.show(
                                    "Vous ne pouvez pas supprimer cet article car il est utilis dans l'application",
                                    "Suppression refuse", Messagebox.OK, Messagebox.ERROR);
                            initSetup(entity);
                            notifyChange("entity");
                            return;
                        }
                    }
                });
    }

    @Command
    public void activeCatalogue() {

        if (catalogueRepository.findFirstByEtatCatalogue(EtatCatalogue.ACTIF) != null) {
            Messagebox.show("Impossible d'activer ce catalogue car il existe dj un catalogue actif",
                    "Un seul catalogue actif autoris", Messagebox.OK, Messagebox.ERROR);
            return;
        }

        Messagebox.show("Voulez-vous activer ce catalogue ?", "Activation",
                new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO }, Messagebox.QUESTION,
                evt -> {
                    if (evt.getName().equals("onYes")) {
                        entity.setEtatCatalogue(EtatCatalogue.ACTIF);
                        catalogueRepository.save(entity);
                        rechargeOnglet();
                        notifyChange("entity");
                        showNotificationStandard("Catalogue activ");
                    }
                });
    }

    @Command
    public void archiveCatalogue() {
        Messagebox.show("Voulez-vous archiver ce catalogue ?", "Archivage",
                new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO }, Messagebox.QUESTION,
                evt -> {
                    if (evt.getName().equals("onYes")) {
                        entity.setEtatCatalogue(EtatCatalogue.ARCHIVE);
                        catalogueRepository.save(entity);
                        panierService.videTousPanier();
                        rechargeOnglet(panierService.findOrCreateByCurrentService(), "/layout/panier.zul",
                                MainController.TITRE_PANIER);
                        rechargeOnglet();
                        notifyChange("entity");
                        showNotificationStandard("Catalogue archiv");
                    }
                });
    }

    public List<Fournisseur> getListeFournisseur() {
        List<Fournisseur> result = fournisseurRepository.findAllByOrderByNom();
        result.add(0, null);

        return result;
    }

    @Command
    @NotifyChange("popupEditArticleCatalogue")
    public void onChangeMarchePopupEdit() {
        this.popupEditArticleCatalogue.setFournisseur(null);
    }

    @Command
    public void exportCatalogue() throws IOException {
        exportExcelService.exportCatalogue(entity);
    }

    @Command
    public void delete() {
        super.delete("Voulez-vous vraiment supprimer ce catalogue ?");
    }
}