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

Java tutorial

Introduction

Here is the source code for nc.noumea.mairie.appock.viewmodel.EditStockReferentServiceViewModel.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.core.security.AppUser;
import nc.noumea.mairie.appock.core.utility.AppockUtil;
import nc.noumea.mairie.appock.dto.EntreeSortieStock;
import nc.noumea.mairie.appock.entity.ArticleStock;
import nc.noumea.mairie.appock.services.AuthHelper;
import nc.noumea.mairie.appock.util.StockSpreadsheetExporter;
import nc.noumea.mairie.appock.util.StockSpreadsheetImporter;
import org.apache.commons.collections4.CollectionUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.*;
import org.zkoss.util.media.AMedia;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.event.UploadEvent;
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.Filedownload;
import org.zkoss.zul.Messagebox;

import javax.xml.bind.JAXBException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@VariableResolver(DelegatingVariableResolver.class)
public class EditStockReferentServiceViewModel extends EditStockViewModel implements Serializable {
    private static final long serialVersionUID = 1L;

    private static Logger log = LoggerFactory.getLogger(EditStockReferentServiceViewModel.class);

    @WireVariable
    AuthHelper authHelper;

    @Override
    @Init(superclass = true)
    public void init() {
        AppUser currentUser = authHelper.getCurrentUser();
        setSelectedService(serviceService.findOneAndChargeElementStock(currentUser.getService().getId()));
        refreshListeArticleStock();
    }

    @Command
    public void creeSortieStockReferentService() {
        super.creeSortieStock("ReferentService");
    }

    @GlobalCommand
    public void creeNouvelleSortieStockReferentService(
            @BindingParam("selectedArticleStock") ArticleStock articleStock,
            @BindingParam("quantiteRenseigne") Integer quantiteRenseigne,
            @BindingParam("observation") String observation) {
        super.creeNouvelleSortieStock(articleStock, quantiteRenseigne, observation);
    }

    @GlobalCommand
    public void creeMultipleNouvelleSortieStockReferentService(
            @BindingParam("listeSortieStock") List<EntreeSortieStock> listeSortieStock) {
        super.creeMultipleNouvelleSortieStock(listeSortieStock);
    }

    public boolean isInventaireDemande() {
        if (entity == null) {
            return false;
        }

        return entity.isInventaireDemande();
    }

    @Command
    public void exportStockXlsx() {

        boolean hasError = false;
        String message = null;

        try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
            StockSpreadsheetExporter.exportToXls(authHelper.getCurrentUser().getService(), getListeArticleStock(),
                    catalogueService, out);
            AMedia amedia = new AMedia("inventaire.xlsx", "xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", out.toByteArray());

            Filedownload.save(amedia);

        } catch (JAXBException e) {
            hasError = true;
            message = e.getMessage();
            log.error("An error accored during stock xlsx export : " + e.getMessage(), e);
        } catch (Docx4JException e) {
            hasError = true;
            message = e.getMessage();
            log.error("An error accored during stock xlsx export : " + e.getMessage(), e);
        } catch (IOException e) {
            hasError = true;
            message = e.getMessage();
            log.error("An error accored during stock xlsx export : " + e.getMessage(), e);
        }

        if (hasError) {
            Messagebox.show("Une erreur s'est produite durant l'export Excel.", "Export chou", Messagebox.OK,
                    Messagebox.ERROR);
            return;
        }
    }

    @Command
    public void importStockXlsx(@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;
                }
                importerStockXlsx(media);
                rechargeOngletMonStock();
            }
        }
    }

    private void importerStockXlsx(Media media) {
        try {
            List<String> warnings = StockSpreadsheetImporter.importFromXls(authHelper.getCurrentUser().getService(),
                    stockService, media.getStreamData());
            if (!CollectionUtils.isEmpty(warnings)) {
                Messagebox.show( //
                        "Certaines rfrences ont t ignores :\n"
                                + warnings.stream().collect(Collectors.joining("\n - ", " - ", "")), //
                        "Attention", //
                        Messagebox.OK, //
                        Messagebox.EXCLAMATION);
            }
        } catch (Exception e) {
            log.error("An error accored during stock xlsx import : " + e.getMessage(), e);
            Messagebox.show("Une erreur s'est produite durant l'import Excel.", "Import chou", Messagebox.OK,
                    Messagebox.ERROR);
            return;
        }
        showNotificationStandard("Inventaire import");
    }

    @Command
    @NotifyChange("*")
    public void valideInventaire() {
        Messagebox.show(
                "Confirmez-vous que vous avez ralis un inventaire et mis  jour vos sorties de stocks ?",
                "Confirmation", new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO },
                Messagebox.QUESTION, evt -> {
                    if (evt.getName().equals("onYes")) {
                        AppUser appUser = authHelper.getCurrentUser();
                        entity.setInventaireDemande(false);
                        entity.setDateDernierInventaire(LocalDateTime.now());
                        entity.setInventaireUser(appUser.getNomComplet());
                        stockService.save(entity);
                        refreshListeArticleStock();
                        mailService.sendMailValidationInventaire(appUser.getService());
                        BindUtils.postNotifyChange(null, null, this, "*");
                        showNotificationStandard("Validation de l'inventaire prise en compte");
                    }
                });
    }

    @Command
    @NotifyChange("*")
    public void recherche() {
        refreshListeArticleStock();
    }

    @Command
    @NotifyChange("*")
    public void videRecherche() {
        setTexteRecherche(null);
        refreshListeArticleStock();
    }

    public Integer getMaxLengthClassProperty(String className, String property) throws Exception {
        return AppockUtil.getMaxLengthClassProperty(className, property);
    }
}