ar.com.informaticaorion.sasha.beans.CollectionsBean.java Source code

Java tutorial

Introduction

Here is the source code for ar.com.informaticaorion.sasha.beans.CollectionsBean.java

Source

package ar.com.informaticaorion.sasha.beans;

import ar.com.informaticaorion.sasha.enums.ImputationType;
import ar.com.informaticaorion.sasha.enums.ProfitCenter;
import ar.com.informaticaorion.sasha.enums.ReservationUse;
import ar.com.informaticaorion.sasha.enums.ValueType;
import ar.com.informaticaorion.sasha.model.Collection;
import ar.com.informaticaorion.sasha.model.*;
import ar.com.informaticaorion.sasha.persistence.CollectionsJPA;
import ar.com.informaticaorion.tools.classes.CustomSession;
import ar.com.informaticaorion.tools.classes.GenericDataModel;
import ar.com.informaticaorion.tools.exceptions.DbSaveException;
import ar.com.informaticaorion.tools.exceptions.DbSelectException;
import ar.com.informaticaorion.tools.exceptions.OpenModuleException;
import ar.com.informaticaorion.tools.helper.Funciones;
import ar.com.informaticaorion.tools.interfaces.IGenericForDataModel;
import static ch.lambdaj.Lambda.*;
import java.io.Serializable;
import java.util.*;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.ArrayUtils;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isIn;
import org.hibernate.Transaction;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleSelectEvent;
import org.primefaces.event.UnselectEvent;

@Named("collectionsBean")
@ConversationScoped
public class CollectionsBean extends BaseAbmApp implements Serializable {

    // Inject

    @Inject
    private CollectionsJPA collectionsJPA;

    // Private Fields

    private GenericDataModel ticketsDataModel;
    private Ticket[] ticketsSelected = new Ticket[0];

    // Constructors

    public CollectionsBean() {
        this.setAbmClass(Collection.class);
        this.setAbmPrefix("collections");
        this.setAbmTitle(Funciones.getResource("collections"));
    }

    // Getters & Setters

    public Collection getCollectionActivo() {
        return (Collection) this.getAbmItemActivo();
    }

    public GenericDataModel getTicketsDataModel() {
        return ticketsDataModel;
    }

    public Ticket[] getTicketsSelected() {
        return ticketsSelected;
    }

    public void setTicketsSelected(Ticket[] ticketsSelected) {
        this.ticketsSelected = ticketsSelected;
    }

    // Methods

    @Override
    public void doOpenModule() throws OpenModuleException {
        super.doOpenModule();
        try {
            this.listsBean.refreshClubMembers(this.getModuleBean().getSession());
            this.listsBean.refreshBanks(this.getModuleBean().getSession());
            this.listsBean.refreshBankAccounts(this.getModuleBean().getSession());
            this.listsBean.refreshPunishments(this.getModuleBean().getSession());
            this.listsBean.refreshLicensors(this.getModuleBean().getSession());
            this.listsBean.refreshCollectionsConcepts(this.getModuleBean().getSession());
        } catch (DbSelectException e) {
            throw new OpenModuleException(e.getMessage());
        }
    }

    @Override
    public Comparator getAbmItemsComparator() {
        return new Collection.CollectionComparator();
    };

    public void onChangeClubMember() {
        this.ticketsDataModel = new GenericDataModel(new ArrayList<IGenericForDataModel>());
        if (this.getCollectionActivo().getClubMember() != null)
            this.ticketsDataModel = new GenericDataModel((List) this.getTicketsPending());
        if (!ArrayUtils.isEmpty(this.ticketsSelected))
            this.ticketsSelected = new Ticket[0];
    }

    private List<Ticket> getTicketsPending() {
        //        try {
        //            this.getBaseJPA().refresh(this.getBaseSessionKeepAlive(),this.getCollectionActivo().getClubMember());
        //        } catch (DbSelectException e) {
        //            this.raiseFacesErrorMessage(e);
        //        }                    
        List<Ticket> tickets = new ArrayList<>(this.getCollectionActivo().getClubMember().getTicketsPending());
        if (this.getCollectionActivo().getLicensor() == null) {
            tickets = filter(having(on(Ticket.class).isLicensed(), equalTo(false)), tickets);
        } else {
            tickets = filter(having(on(Ticket.class).isLicensed(), equalTo(true)), tickets);
            tickets = filter(having(on(Ticket.class).getActivity(),
                    isIn(this.getCollectionActivo().getLicensor().getActivitiesAsList())), tickets);
        }
        return tickets;
    }

    public boolean allowTicketSelection(Ticket ticket) {
        if (this.getCollectionActivo() != null) {
            if (this.getCollectionActivo().getLicensor() == null) {
                if (ticket.isLicensed())
                    return false;
            } else {
                if (!ticket.isLicensed())
                    return false;
                if (!this.getCollectionActivo().getLicensor().getActivities().contains(ticket.getActivity()))
                    return false;
            }
        }
        return true;
    }

    public void onSelectAllTickets(ToggleSelectEvent event) {
        for (Ticket ticket : this.getTicketsPending()) {
            if (event.isSelected()) {
                ticket.setApplied(ticket.getBalance());
            } else {
                ticket.setApplied(0);
            }
        }
        this.generateImputations();
    }

    public void onSelectTicket(SelectEvent event) {
        Ticket ticket = (Ticket) event.getObject();
        ticket.setPunishmentAmount(this.getPunishmentAmount(ticket));
        ticket.setApplied(ticket.getBalance());
        this.generateImputations();
    }

    public void onUnselectTicket(UnselectEvent event) {
        Ticket ticket = (Ticket) event.getObject();
        ticket.setPunishmentAmount(0);
        ticket.setApplied(0);
        this.generateImputations();
    }

    public void onChangeApplied() {
        this.generateImputations();
    }

    public float getTotalTickets() {
        float totalApplied = 0;
        for (Ticket ticket : this.getTicketSelectedAsList()) {
            totalApplied += ticket.getApplied();
        }
        return totalApplied;
    }

    public void onAddCash() {
        this.addValue(ValueType.CASH);
    }

    public void onAddThirdPartyCheck() {
        this.addValue(ValueType.THIRDPARTYCHECK);
    }

    public void onAddCreditInBankAccount() {
        this.addValue(ValueType.CREDITINBANKACCOUNT);
    }

    private void addValue(ValueType type) {
        CollectionValue cv = new CollectionValue();
        cv.setCollection(this.getCollectionActivo());
        cv.setType(type);
        if (cv.getAllowBankAccount())
            if (this.listsBean.getBankAccounts().size() == 1)
                cv.setBankAccount((BankAccount) this.listsBean.getBankAccounts().get(0));
        if ((this.getTotalTickets() + this.getCollectionActivo().getTotalImputationsManual()) > this
                .getCollectionActivo().getTotalValues())
            cv.setAmount((this.getTotalTickets() + this.getCollectionActivo().getTotalImputationsManual())
                    - this.getCollectionActivo().getTotalValues());
        this.getCollectionActivo().getValues().add(cv);
    }

    public List<Ticket> getTicketSelectedAsList() {
        if (this.ticketsSelected.length > 0)
            return Arrays.asList(this.ticketsSelected);
        return new ArrayList<>();
    }

    public void onDeleteValue(CollectionValue collectionValue) {
        this.getCollectionActivo().getValues().remove(collectionValue);
    }

    public void generateImputations() {
        this.generateImputations(this.getCollectionActivo(), this.getTicketSelectedAsList());
    }

    public void generateImputations(Collection collection, List<Ticket> tickets) {
        for (Iterator<CollectionImputation> it = collection.getImputations().iterator(); it.hasNext();) {
            CollectionImputation imputation = it.next();
            if (imputation.getType() == ImputationType.AUTOMATIC)
                it.remove();
        }
        for (Ticket ticket : tickets) {
            CollectionImputation imputation = new CollectionImputation();
            imputation.setCollection(collection);
            imputation.setType(ImputationType.AUTOMATIC);
            if (ticket.getProfitCenter() == ProfitCenter.MEMBERSHIPFEE) {
                imputation.setConcept(ticket.getClubMember().getCategory().getCollectionConcept());
            }
            if (ticket.getProfitCenter() == ProfitCenter.RENT) {
                if (ticket.getReservation().getRentConcept().getCollectionConcept() != null) {
                    imputation.setConcept(ticket.getReservation().getRentConcept().getCollectionConcept());
                } else {
                    if (ticket.getReservation().getUse() == ReservationUse.RENT)
                        imputation.setConcept(ticket.getReservation().getRentSpace().getCollectionConceptRent());
                    if (ticket.getReservation().getUse() == ReservationUse.LESSON)
                        imputation.setConcept(ticket.getReservation().getRentSpace().getCollectionConceptLesson());
                }
            }
            if (ticket.getProfitCenter() == ProfitCenter.ACTIVITY) {
                imputation.setConcept(ticket.getActivity().getCollectionConcept());
            }
            if (ticket.getProfitCenter() == ProfitCenter.ARTICLE) {
                for (TicketItem ticketItem : ticket.getItems()) {
                    imputation.setConcept(ticketItem.getArticle().getCategory().getCollectionConcept());
                    if (ticketItem.getArticle().getCollectionConcept() != null)
                        imputation.setConcept(ticketItem.getArticle().getCollectionConcept());
                }
            }
            imputation.setAmount(ticket.getApplied());
            collection.getImputations().add(imputation);
        }
    }

    public void onDeleteImputation(CollectionImputation collectionImputation) {
        this.getCollectionActivo().getImputations().remove(collectionImputation);
    }

    @Override
    public void abmOnBeforeSelfValidation(Object obj, boolean isInserting) {
        Collection collection = Collection.class.cast(obj);
        if (isInserting) {
            collection.getTickets().clear();
            for (Ticket ticket : this.getTicketSelectedAsList()) {
                CollectionTicket collectionTicket = new CollectionTicket();
                collectionTicket.setCollection(collection);
                collectionTicket.setTicket(ticket);
                collectionTicket.setAmount(ticket.getApplied());
                collection.getTickets().add(collectionTicket);
            }
        }
    }

    @Override
    public void abmOnBeforeSave(Object obj, boolean isInserting) {
        Collection collection = Collection.class.cast(obj);
        if (isInserting) {
            collection.setCollectionDate(new Date());
            try {
                for (Ticket ticket : this.getTicketSelectedAsList()) {
                    if (ticket.getPunishmentAmount() != 0)
                        this.getAbmJPA().updateAbmItem(this.getModuleBean().getSession(), false, Ticket.class,
                                ticket);
                }
            } catch (DbSaveException e) {
                this.raiseFacesErrorMessage(e);
            }
        }
    }

    @Override
    public void abmOnAfterSave(Object obj, boolean isInserting) throws DbSaveException {
        Collection collection = Collection.class.cast(obj);
        if (isInserting) {
            try {
                this.collectionsJPA.assignNumberToCollection(this.getModuleBean().getSession(), collection);
            } catch (DbSaveException e) {
                throw e;
            }
        }
    }

    public boolean allowEditTicket(Ticket ticket) {
        if (!this.getTicketSelectedAsList().contains(ticket))
            return false;
        if (!this.listsBean.getPunishments(ticket.getProfitCenter(), ticket.getActivity()).isEmpty())
            return false;
        return true;
    }

    public void onAddImputation() {
        CollectionImputation collectionImputation = new CollectionImputation();
        collectionImputation.setCollection(this.getCollectionActivo());
        collectionImputation.setType(ImputationType.MANUAL);
        this.getCollectionActivo().getImputations().add(collectionImputation);
    }

    private int getDelay(Ticket ticket) {
        DateTime dtCollectionDate = new DateTime(this.getCollectionActivo().getCollectionDate());
        DateTime dtTicketDueDate = new DateTime(ticket.getDueDate());
        int delay = Days
                .daysBetween(dtTicketDueDate.withTimeAtStartOfDay(), dtCollectionDate.withTimeAtStartOfDay())
                .getDays();
        return delay;
    }

    private Punishment getPunishment(Ticket ticket) {
        Punishment punishment = null;
        for (Punishment pnsh : (List<Punishment>) this.listsBean.getPunishments(ticket.getProfitCenter(),
                ticket.getActivity())) {
            if (pnsh.isValid(this.getDelay(ticket)))
                punishment = pnsh;
        }
        return punishment;
    }

    private float getPunishmentAmount(Ticket ticket) {
        float punishmentAmount = 0;
        Punishment punishment = this.getPunishment(ticket);
        if (punishment != null)
            punishmentAmount = ((ticket.getTotalItems() * punishment.getAliquot()) / 100);
        return punishmentAmount;
    }

    public boolean allowAnnull(Collection collection) {
        if (collection.getAnnulled())
            return false;
        if (collection.getToEndConsumer())
            return false;
        if (this.mainBean.getEnvironment().getClosedTreasuryDate() != null)
            if (collection.getCollectionDate().before(this.mainBean.getEnvironment().getClosedTreasuryDate()))
                return false;
        return true;
    }

    public void annullCollection(Collection collection) {
        Transaction tx = this.moduleBean.getCustomSessionProvider().beginTransaction();
        try {
            this.annullCollection(this.moduleBean.getSession(), collection);
            this.moduleBean.getCustomSessionProvider().commitTransaction(tx);
        } catch (DbSaveException e) {
            this.moduleBean.getCustomSessionProvider().rollbackTransaction(tx);
            this.raiseFacesErrorMessage(e);
        }
    }

    public void annullCollection(CustomSession customSession, Collection collection) throws DbSaveException {
        collection.setAnnulled(true);
        try {
            this.getAbmJPA().updateAbmItem(customSession, false, Collection.class, collection);
        } catch (DbSaveException e) {
            throw e;
        }
    }

    public void buildCollection(CustomSession customSession, Ticket ticket) throws DbSaveException {
        List<Ticket> tickets = new ArrayList<>();
        tickets.add(ticket);
        ticket.setApplied(ticket.getBalance());
        Collection collection = new Collection();
        collection.setClubMember(ticket.getClubMember());
        collection.setDescription("-");
        CollectionTicket collectionTicket = new CollectionTicket();
        collectionTicket.setCollection(collection);
        collectionTicket.setTicket(ticket);
        collectionTicket.setAmount(ticket.getApplied());
        collection.getTickets().add(collectionTicket);
        CollectionValue collectionValue = new CollectionValue();
        collectionValue.setCollection(collection);
        collectionValue.setType(ValueType.CASH);
        collectionValue.setAmount(ticket.getApplied());
        collection.getValues().add(collectionValue);
        this.generateImputations(collection, tickets);
        try {
            this.getAbmJPA().saveAbmItem(customSession, false, Collection.class, collection);
        } catch (DbSaveException e) {
            throw e;
        }
        try {
            this.collectionsJPA.assignNumberToCollection(customSession, collection);
        } catch (DbSaveException e) {
            throw e;
        }
    }

}