be.fgov.minfin.webForm.backing.FondsDetCdcBean.java Source code

Java tutorial

Introduction

Here is the source code for be.fgov.minfin.webForm.backing.FondsDetCdcBean.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package be.fgov.minfin.webForm.backing;

import be.fgov.minfin.ccff.fwk.logging.api.Logger;
import be.fgov.minfin.ccff.fwk.logging.api.LoggerFactory;
import be.fgov.minfin.ccff.fwk.mail.api.exceptions.MailException;
import be.fgov.minfin.webForm.entity.Email;
import be.fgov.minfin.webForm.entity.Sujet;
import be.fgov.minfin.webForm.util.FediamIdentityUtil;
import be.fgov.minfin.webForm.util.MailHelper;
import be.fgov.minfin.webForm.util.NNUtil;
import be.fgov.minfin.webForm.util.Partie;
import be.fgov.minfin.webForm.util.UploadedAttachment;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.primefaces.util.Constants;

/**
 *
 * @author gbeurnea
 */
@ManagedBean(name = "fondsDetCdcBean")
@ViewScoped
public class FondsDetCdcBean extends WebFormBean implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(FondsDetCdcBean.class);

    private boolean visibleConfirm = false;
    private String nomCompte;
    private String numCompte;
    private String proprietaires;
    private int nbDossiers;
    private String choix;
    private boolean fichierTelecharge = false;
    private String filename;
    private List<Partie> partiesConcernees;
    private String montantTotal = "0";
    private boolean mailEnvoye = false;

    @ManagedProperty(value = "#{authentificationCdcBean}")
    private AuthentificationCdcBean authentificationCdcBean;

    @PostConstruct
    public void init() {
        partiesConcernees = new ArrayList<Partie>();
    }

    public void cleanPartie(int index) {
        Partie partie = partiesConcernees.get(index);

        partie.setCodepostal(null);
        partie.setMail(null);
        partie.setNom(null);
        partie.setNnr(null);
        partie.setNomSociete(null);
        partie.setNumrue(null);
        partie.setNumtel(null);
        partie.setPrenom(null);
        partie.setRue(null);
        partie.setPays(null);
        partie.setUpdatePersonBelge(false);
        partie.setVille(null);
    }

    public void ajoutPersonne() {
        partiesConcernees.clear();
        for (int i = 0; i < nbDossiers; i++) {
            Partie personne = new Partie();
            partiesConcernees.add(personne);
        }
    }

    // Methode qui check le NNR
    public void checkNNR(FacesContext context, UIComponent component, Object value) {
        Application app = FacesContext.getCurrentInstance().getApplication();
        ResourceBundle bundle = app.getResourceBundle(FacesContext.getCurrentInstance(), "CdcMessages");
        Date date;
        try {
            NNUtil nnUtil = new NNUtil();
            String nnr = (String) value;
            String anneeNnr = nnr.substring(0, 1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (Integer.valueOf(anneeNnr) > 17) {
                date = sdf.parse("19" + anneeNnr + "-" + nnr.substring(2, 3) + "-" + nnr.substring(4, 5));
            } else {
                date = sdf.parse("20" + anneeNnr + "-" + nnr.substring(2, 3) + "-" + nnr.substring(4, 5));
            }

            boolean valid = nnUtil.checkNN((String) value, date);
            if (valid == false) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        bundle.getString("liquiacte.idenf.nnr.valid"), ""));
            }
        } catch (Exception e) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    bundle.getString("liquiacte.idenf.nnr.valid"), ""));
        }
    }

    /*
    Check Sitran si personne belge et affecte les diffrents attributs  la partie concerne
     */
    public void checkSitranPersonneBelge(int index) {
        Partie partie = partiesConcernees.get(index);

        String nnr = partie.getNnr();
        try {
            FediamIdentityUtil fediam = new FediamIdentityUtil(nnr);
            partie.setNom(fediam.getLastName());
            partie.setPrenom(fediam.getFirstName());
            partie.setRue(fediam.getStreet());
            partie.setNumrue(fediam.getNumStreet());
            partie.setCodepostal(fediam.getZip());
            partie.setVille(fediam.getCity());
            partie.setPays(fediam.getPays());
            partie.setMail(null);
            partie.setNumtel(null);
            partie.setUpdatePersonBelge(true);
        } catch (IOException e) {

        }
    }

    /*
    Vrifie si le comte bancaire est correcte
     */
    public void checkDigit(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Application app = FacesContext.getCurrentInstance().getApplication();
        ResourceBundle bundle = app.getResourceBundle(FacesContext.getCurrentInstance(), "CdcMessages");
        IBANCheckDigit ibancheck = new IBANCheckDigit();
        String numComptAValider = (String) value;
        if (ibancheck.isValid(numComptAValider) == false) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    bundle.getString("liquiacte.numcompte.error"), ""));
        }
    }

    public StreamedContent download() {
        InputStream stream = FacesContext.getCurrentInstance().getExternalContext()
                .getResourceAsStream("/resources/excel/template_fonds_detenu.xlsx");
        StreamedContent file = new DefaultStreamedContent(stream,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "template_fonds_detenu.xlsx");
        return file;
    }

    /*
    Gre l'upload du composant Primefaces
     */
    public void handleFileUpload(FileUploadEvent event) throws ValidatorException {
        Application app = FacesContext.getCurrentInstance().getApplication();
        ResourceBundle bundle = app.getResourceBundle(FacesContext.getCurrentInstance(), "CdcMessages");
        if (super.attachments.size() < 1) {
            UploadedFile file = event.getFile();
            UploadedAttachment attachment = new UploadedAttachment();
            filename = file.getFileName();
            attachment.setName(file.getFileName());
            attachment.setLength((int) file.getSize());
            attachment.setData(file.getContents());
            attachment.setContentType(file.getContentType());
            super.attachments.add(attachment);
            FacesMessage msg = new FacesMessage(bundle.getString("cantonnement.upload.success.partun") + " "
                    + file.getFileName() + " " + bundle.getString("cantonnement.upload.success.parttwo"));
            FacesContext.getCurrentInstance().addMessage("uploadfile", msg);
        } else {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Vous ne pouvez uploader qu'un seul fichier !", "");
            FacesContext.getCurrentInstance().addMessage("uploadfile", msg);
        }
    }

    public void calculMontantTotal() {
        double montantEnDouble = 0;
        for (int i = 0; i < partiesConcernees.size(); i++) {
            if (partiesConcernees.get(i).getMontant() != null) {
                String montant = partiesConcernees.get(i).getMontant().replaceAll(",", ".");
                montantEnDouble = montantEnDouble + Double.valueOf(montant);
            }
        }

        montantTotal = String.valueOf(montantEnDouble);
    }

    public void sendEmail() {
        Application app = FacesContext.getCurrentInstance().getApplication();
        ResourceBundle bundle = app.getResourceBundle(FacesContext.getCurrentInstance(), "CdcMessages");

        String bodyEmail = null;
        Sujet sujet = new Sujet();
        sujet.setIdSujet(255);
        sujet = this.webFormManager.findSujetById(sujet);
        if (sujet != null) {
            String language = this.getLanguage();
            StringBuilder messageEmail = new StringBuilder();
            MailHelper mailhelper = new MailHelper();
            //Ajoute la communication structure au mail
            messageEmail.append("Donnes communiques pour l'ouverture du dossier :\n");
            //Ajoute la partie authentification au message
            String idenf = mailhelper.getCorpsIdenf(this.authentificationCdcBean);
            messageEmail.append(idenf);
            // Formulaire Liquidation en un acte !!!!!
            messageEmail.append(
                    "\n###################### Type de dossier : Fonds de dtenus librs ou inconnu #####################")
                    .append("\nNom du titulaire du compte : ").append(this.nomCompte)
                    .append("\nNumro de compte de versement : ").append(this.numCompte)
                    .append("\nIdentification du/des propritaires : ").append(this.proprietaires)
                    .append("\nNombre de dossiers  transmettre  la CDC : ").append(this.nbDossiers)
                    .append("\nVous avez choisi de : ");
            if (this.choix.equals("excel")) {
                messageEmail.append("Transmettre une liste Excel").append("\nNom du fichier joint : ")
                        .append(this.filename);
            } else {
                messageEmail.append("Complter le formulaire");
                // Pour chaque partie
                for (int i = 0; i < partiesConcernees.size(); i++) {
                    messageEmail.append(("\n\n---- Personne " + i + 1 + " ----\n")).append("\nNationalit : ")
                            .append(partiesConcernees.get(i).getNationalite()).append("\nNumro national : ")
                            .append(partiesConcernees.get(i).getNnr()).append("\nNom : ")
                            .append(partiesConcernees.get(i).getNom()).append("\nPrnom : ")
                            .append(partiesConcernees.get(i).getPrenom()).append("\nRue : ")
                            .append(partiesConcernees.get(i).getRue()).append("\nNumro : ")
                            .append(partiesConcernees.get(i).getNumrue()).append("\nCode postal : ")
                            .append(partiesConcernees.get(i).getCodepostal()).append("\nVille : ")
                            .append(partiesConcernees.get(i).getVille()).append("\nPays : ")
                            .append(partiesConcernees.get(i).getPays()).append("\nMontant : ")
                            .append(partiesConcernees.get(i).getMontant());
                }
            }
            messageEmail.append("\n\nMontant total : ").append(this.montantTotal + " EUR");
            List emailList = sujet.getEmailList();
            if (emailList != null) {
                for (int i = 0; i < emailList.size(); i++) {
                    Email emailTmp = (Email) emailList.get(i);
                    String emailTo = this.webFormUtil.getPropertyValue((Object) emailTmp, "email", language);
                    emailTmp.setEmail(emailTo);
                    bodyEmail = "Nouvelle demande d'ouverture d'un dossier de Fonds de dtenus librs ou inconnus";
                    try {
                        if (authentificationCdcBean.getMail2() != null) {
                            this.webFormUtil.sendMail(emailTmp.getEmail(), bodyEmail, messageEmail.toString(),
                                    this.authentificationCdcBean.getMail2(), super.attachments);
                        } else {
                            this.webFormUtil.sendMail(emailTmp.getEmail(), bodyEmail, messageEmail.toString(),
                                    this.authentificationCdcBean.getMail(), super.attachments);
                        }
                        this.mailEnvoye = true;

                    } catch (MailException e) {
                        this.sousStatus = "email";
                        logger.error("Erreur dans la mthode sendMail");
                        FacesMessage msg = new FacesMessage(bundle.getString("liquiacte.mail.error"));
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                    }
                }
                // Si le mail est envoy  la CDC, on envoi au client !
                if (mailEnvoye == true) {
                    StringBuilder messageClient = new StringBuilder();
                    messageClient.append("Donnes communiques pour l'ouverture du dossier :\n");
                    //Ajoute la partie authentification au message
                    messageClient.append(idenf);
                    // Formulaire Liquidation en un acte !!!!!
                    messageClient.append(
                            "\n###################### Type de dossier : Fonds de dtenus librs ou inconnu #####################")
                            .append("\nNom du titulaire du compte : ").append(this.nomCompte)
                            .append("\nNumro de compte de versement : ").append(this.numCompte)
                            .append("\nIdentification du/des propritaires : ").append(this.proprietaires)
                            .append("\nNombre de dossiers  transmettre  la CDC : ").append(this.nbDossiers)
                            .append("\nVous avez choisi de : ");
                    if (this.choix.equals("excel")) {
                        messageClient.append("Transmettre une liste Excel").append("\nNom du fichier joint : ")
                                .append(this.filename);
                    } else {
                        messageClient.append("Complter le formulaire");
                        // Pour chaque partie
                        for (int i = 0; i < partiesConcernees.size(); i++) {
                            messageClient.append(("\n\n---- Personne " + i + 1 + " ----\n"));
                            if (partiesConcernees.get(i).isUpdatePersonBelge()) {
                                messageClient.append("\nLa personne au numro national "
                                        + partiesConcernees.get(i).getNnr() + " a bien t trouve");
                            } else {
                                messageClient.append("\nNationalit : ")
                                        .append(partiesConcernees.get(i).getNationalite())
                                        .append("\nNumro national : ").append(partiesConcernees.get(i).getNnr())
                                        .append("\nNom : ").append(partiesConcernees.get(i).getNom())
                                        .append("\nPrnom : ").append(partiesConcernees.get(i).getPrenom())
                                        .append("\nRue : ").append(partiesConcernees.get(i).getRue())
                                        .append("\nNumro : ").append(partiesConcernees.get(i).getNumrue())
                                        .append("\nCode postal : ").append(partiesConcernees.get(i).getCodepostal())
                                        .append("\nVille : ").append(partiesConcernees.get(i).getVille())
                                        .append("\nPays : ").append(partiesConcernees.get(i).getPays());

                            }
                            messageClient.append("\nMontant : ").append(partiesConcernees.get(i).getMontant());
                        }
                    }
                    messageClient.append("\n\nMontant total : ").append(this.montantTotal + " EUR");

                    bodyEmail = bundle.getString("liquiacte.bodymail");
                    try {
                        if (authentificationCdcBean.getMail2() != null) {
                            this.webFormUtil.sendMail(this.authentificationCdcBean.getMail2(), bodyEmail,
                                    messageClient.toString(), "depots.tresorerie@minfin.fed.be");
                        } else {
                            this.webFormUtil.sendMail(this.authentificationCdcBean.getMail(), bodyEmail,
                                    messageClient.toString(), "depots.tresorerie@minfin.fed.be");
                        }
                        FacesMessage msg = new FacesMessage(bundle.getString("liquiacte.validfinal"));
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        RequestContext.getCurrentInstance().execute("window.scrollTo(0,0);");
                        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
                    } catch (MailException e) {
                        this.sousStatus = "email";
                        logger.error("Erreur dans la mthode sendMail");
                        FacesMessage msg = new FacesMessage(bundle.getString("liquiacte.mail.error"));
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                    }
                }

            } else {
                logger.error("emailList = null ******************");
                FacesMessage msg = new FacesMessage(bundle.getString("liquiacte.mail.error"));
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        } else {
            logger.error("emailList = null ******************");
            FacesMessage msg = new FacesMessage(bundle.getString("liquiacte.mail.error"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }

    }

    /*
    Affiche la page de confirmation
     */
    public void afficheConfirm() {
        this.visibleConfirm = !this.visibleConfirm;
    }

    public AuthentificationCdcBean getAuthentificationCdcBean() {
        return authentificationCdcBean;
    }

    public void setAuthentificationCdcBean(AuthentificationCdcBean authentificationCdcBean) {
        this.authentificationCdcBean = authentificationCdcBean;
    }

    public boolean isVisibleConfirm() {
        return visibleConfirm;
    }

    public void setVisibleConfirm(boolean visibleConfirm) {
        this.visibleConfirm = visibleConfirm;
    }

    public String getNomCompte() {
        return nomCompte;
    }

    public void setNomCompte(String nomCompte) {
        this.nomCompte = nomCompte;
    }

    public String getNumCompte() {
        return numCompte;
    }

    public void setNumCompte(String numCompte) {
        this.numCompte = numCompte;
    }

    public String getProprietaires() {
        return proprietaires;
    }

    public void setProprietaires(String proprietaires) {
        this.proprietaires = proprietaires;
    }

    public int getNbDossiers() {
        return nbDossiers;
    }

    public void setNbDossiers(int nbDossiers) {
        this.nbDossiers = nbDossiers;
    }

    public String getChoix() {
        return choix;
    }

    public void setChoix(String choix) {
        this.choix = choix;
    }

    public boolean isFichierTelecharge() {
        return fichierTelecharge;
    }

    public void setFichierTelecharge(boolean fichierTelecharge) {
        this.fichierTelecharge = fichierTelecharge;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public ArrayList<UploadedAttachment> getAttachments() {
        return super.attachments;
    }

    public void removeFileUpload(int index) {
        super.attachments.remove(index);
    }

    public String getMontantTotal() {
        return montantTotal;
    }

    public void setMontantTotal(String montantTotal) {
        this.montantTotal = montantTotal;
    }

    public List<Partie> getPartiesConcernees() {
        return partiesConcernees;
    }

    public void setPartiesConcernees(List<Partie> partiesConcernees) {
        this.partiesConcernees = partiesConcernees;
    }

    public boolean isMailEnvoye() {
        return mailEnvoye;
    }

    public void setMailEnvoye(boolean mailEnvoye) {
        this.mailEnvoye = mailEnvoye;
    }

}