com.accounting.office.PayRollManagedBean.java Source code

Java tutorial

Introduction

Here is the source code for com.accounting.office.PayRollManagedBean.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 com.accounting.office;

import com.accounting.commonutils.HelperUtil;
import static com.accounting.commonutils.HelperUtil.getLoggedInOffice;
import static com.accounting.commonutils.HelperUtil.getLoggedInUser;
import com.accounting.entities.account.AccMaster;
import com.accounting.entities.account.EmployeeMaster;
import com.accounting.entities.office.PayHeads;
import com.accounting.entities.office.SalaryPosting;
import com.accounting.entities.parameters.AppData;
import com.accounting.dto.DataTableColumn;
import com.accounting.dto.SalaryPostingDTO;
import com.accounting.ejb.exceptions.ClientException;
import com.accounting.entities.office.PayheadDerivedCondition;
import com.accounting.jasperbean.JasperReportBean;
import com.accounting.sessions.account.AccMasterSession;
import com.accounting.sessions.account.EmployeeSessionBean;
import com.accounting.sessions.inventory.AppDataSession;
import com.accounting.sessions.inventory.PayrollTransactionBean;
import com.accounting.util.JsfUtil;
import com.accounting.utils.KeyConstants;
import com.accounting.utils.NepaliDateConverter;
import com.accounting.utils.PageNameEnum;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.primefaces.context.RequestContext;

/**
 *
 * @author hasmat
 */
@ManagedBean
@SessionScoped
public class PayRollManagedBean {

    @EJB
    private AccMasterSession accMasterSession;
    @EJB
    private EmployeeSessionBean employeeSessionBean;
    @EJB
    private AppDataSession appDataSession;
    @EJB
    private PayrollTransactionBean payrollTransactionBean;
    private PayHeads payHeads;
    private boolean insertMode, editRender;
    private List<AccMaster> accMasterList, accMasterList2;
    private List<PayHeads> payHeadsList, payHeadsListTemp;
    private List<SalaryPostingDTO> salaryDTO;
    private int stage;
    private final NepaliDateConverter ndc;
    private List<AppData> nepaliMonthList, nepaliYearList;
    private List<AppData> employeeGroupList;
    private AppData selectedYear, selectedMonth;
    private AppData selectedYearTemp, selectedMonthTemp, selectedGroup;
    private AccMaster accMaster;
    private String remark;
    private List<Object[]> payHeadsValueList;
    private List<DataTableColumn> dataTableColumns;
    private List<SalaryPosting> postings;
    private EmployeeMaster selectedEmployeeMaster;
    private String tranDate;

    public PayRollManagedBean() {
        ndc = new NepaliDateConverter();
    }

    @PostConstruct
    public void init() {

        String lastDayOfMonth = ndc.lastDayOfMonth().toString();
        String[] str = ndc.currentNepaliDate().split("-");
        tranDate = str[0] + "-" + str[1] + "-" + lastDayOfMonth;
        tranDate = NepaliDateConverter.formatNepaliDate(tranDate);
        nepaliMonthList = appDataSession.returnAppDataByDataType(KeyConstants.NEPALIMONTH);
        nepaliYearList = appDataSession.returnNepaliYear(KeyConstants.NEPALIYEAR, HelperUtil.getLoggedInOfficeID());
    }

    public String redirectToSalaryPosting() {

        selectedGroup = null;
        accMaster = null;

        payHeadsValueList = new ArrayList<Object[]>();

        accMasterList = new ArrayList<AccMaster>();
        accMasterList.addAll(accMasterSession.retrieveAccMasterByGlSubCodeAndOffice(KeyConstants.CASH,
                HelperUtil.getLoggedInOfficeID()));
        accMasterList.addAll(accMasterSession.retrieveAccMasterByGlSubCodeAndOffice(KeyConstants.BANK,
                HelperUtil.getLoggedInOfficeID()));
        accMasterList.addAll(accMasterSession.retrieveAccMasterByAccOwnerId(KeyConstants.OFFICEOWNER,
                HelperUtil.getLoggedInOfficeID()));

        employeeGroupList = employeeSessionBean.returnEmployeeGroupByOffice(HelperUtil.getLoggedInOffice().getId());

        String curYear = ndc.currentNepaliYear(new Date());
        AppData curY = appDataSession.retrieveAppDataByDataDescNative(curYear, HelperUtil.getLoggedInOfficeID());
        if (curY == null) {

            curY = new AppData();
            curY.setDelFlag(false);
            curY.setOfficeId(HelperUtil.getLoggedInOffice().getId());
            curY.setAppDataCode(KeyConstants.NEPALIYEAR);
            curY.setAppDataDesc(curYear);

            appDataSession.persist(curY);
        }
        selectedYear = curY;
        setSelectedMonth(appDataSession.retrieveAppDataByDataDescNative(ndc.currentNepaliMonthInWords(new Date()),
                HelperUtil.getLoggedInOfficeID()));

        loadEmployeesToSalaryPay();

        return "salaryPosting.xhtml?faces-redirect=true";
    }

    public String redirectToSalaryPostingReport() {
        showXLS = false;
        selectedYear = null;
        selectedGroup = null;
        accMaster = null;
        payHeadsValueList = new ArrayList<Object[]>();
        stage = 1;
        accMasterList = accMasterSession.retrieveAccMasterByAccOwnerId(KeyConstants.OFFICEOWNER,
                HelperUtil.getLoggedInOfficeID());
        employeeGroupList = employeeSessionBean.returnEmployeeGroupByOffice(HelperUtil.getLoggedInOffice().getId());

        setSelectedMonth(appDataSession.retrieveAppDataByDataDescNative(ndc.currentNepaliMonthInWords(new Date()),
                HelperUtil.getLoggedInOfficeID()));

        return "salaryPostingReport.xhtml?faces-redirect=true";
    }

    public void loadEmployeesToSalaryPay() {

        if (selectedYear == null) {
            JsfUtil.addErrorMessage("Please select year.");
            return;
        } else if (selectedMonth == null) {
            JsfUtil.addErrorMessage("Please select month.");
            return;
        }

        remark = "Salary Posting for  " + selectedYear.getAppDataDesc() + "/" + selectedMonth.getAppDataDesc();

        List<EmployeeMaster> employeeList = null;
        if (selectedGroup == null) {
            employeeList = employeeSessionBean.returnAllEmployeeGroupByOffice(HelperUtil.getLoggedInOfficeID());
        } else {
            employeeList = employeeSessionBean.returnAllEmployeeGroupByGroup(HelperUtil.getLoggedInOfficeID(),
                    selectedGroup.getId());
        }

        if (employeeList.isEmpty()) {
            JsfUtil.addErrorMessage("No employee found.");
            return;
        }

        dataTableColumns = new ArrayList<DataTableColumn>();
        dataTableColumns.add(new DataTableColumn("EMPLOYEE", "Employee", true));

        positiveIndexT = 0;
        negativeIndexT = 0;
        boolean dataFound = false;

        payHeadsList = appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.EARNING);

        if (!payHeadsList.isEmpty()) {
            dataFound = true;
            for (PayHeads p : payHeadsList) {
                dataTableColumns
                        .add(new DataTableColumn(p.getPayHead().toUpperCase(), p.getPayHead().toLowerCase(), p));
            }
            dataTableColumns.add(new DataTableColumn("Total Earning", "Total Earning", true));
        }
        positiveIndexT = payHeadsList.size() + 1;

        payHeadsList = appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.DEDUCTION);

        if (!payHeadsList.isEmpty()) {
            dataFound = true;
            for (PayHeads p : payHeadsList) {
                dataTableColumns
                        .add(new DataTableColumn(p.getPayHead().toUpperCase(), p.getPayHead().toLowerCase(), p));
            }
            dataTableColumns.add(new DataTableColumn("Total Deduction", "Total Deduction", true));
        }
        negativeIndexT = positiveIndexT + payHeadsList.size() + 1;

        if (!dataFound) {
            JsfUtil.addErrorMessage("Pay head not found. Please setup payhead first!");
            return;
        }

        payHeadsValueList = new ArrayList<Object[]>();

        for (EmployeeMaster e : employeeList) {
            if (employeeSessionBean.returnSalaryPostingForSpecificMonth(HelperUtil.getLoggedInOfficeID(),
                    selectedYear.getId(), selectedMonth.getId(), e.getId()).isEmpty()) {
                Object[] str = new Object[dataTableColumns.size() + 2];
                str[0] = e;
                payHeadsValueList.add(str);
            }
        }
        if (payHeadsValueList.isEmpty()) {
            JsfUtil.addErrorMessage("Employees salary already saved for this month.");
        }
        selectedYearTemp = appDataSession.findAppData(selectedYear.getId());
        selectedMonthTemp = appDataSession.findAppData(selectedMonth.getId());
    }

    private int positiveIndexT, negativeIndexT;

    public void deleteSalaryPosting(Object[] obj) {
        try {
            payrollTransactionBean.deleteSalaryPosting(selectedYearTemp, selectedMonthTemp, obj);
            payHeadsValueList.remove(obj);

            JsfUtil.addSuccessMessage("Salary Post Remove Successful.");
        } catch (ClientException ex) {
            HelperUtil.showErrorMessage(ex.getMessage());
        }
    }

    public void editSalaryPosting(Object[] obj) {
        postings = new ArrayList<SalaryPosting>();

        payHeadsList = new ArrayList<PayHeads>();
        payHeadsList.addAll(appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.EARNING));
        payHeadsList.addAll(appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.DEDUCTION));

        selectedEmployeeMaster = (EmployeeMaster) obj[0];

        setAccMaster(employeeSessionBean.returnCrAccMasterFromSalaryPosting(HelperUtil.getLoggedInOfficeID(),
                selectedYearTemp.getId(), selectedMonthTemp.getId(), selectedEmployeeMaster.getId()));

        if (accMaster == null) {
            JsfUtil.addErrorMessage("System Error!!!");
            System.out.println("***************POSSIBLE HACK******************");
            return;
        }

        for (PayHeads p : payHeadsList) {

            SalaryPosting sp = employeeSessionBean.returnSalaryPostingByEmployeePayHeadTime(
                    HelperUtil.getLoggedInOfficeID(), selectedYearTemp.getId(), selectedMonthTemp.getId(),
                    selectedEmployeeMaster.getId(), p.getId());

            if (sp == null) {
                sp = new SalaryPosting();

                sp.setDelFlg(false);
                sp.setEmployId(selectedEmployeeMaster);
                sp.setPayHeadsId(p);
                sp.setAmount(calculateDerivedAmount(selectedEmployeeMaster, p));
                sp.setCreatedBy(HelperUtil.getLoggedInUserID());
                sp.setCreatedDateNp(new NepaliDateConverter().convertToNepaliDate(new Date()));
                sp.setCreatedDate(new Date());
                sp.setOfficeId(HelperUtil.getLoggedInOffice());
                sp.setYearId(selectedYearTemp);
                sp.setMonthId(selectedMonthTemp);
                sp.setCrAccmasterId(accMaster);
            }
            postings.add(sp);
        }
        stage = 2;
    }

    @ManagedProperty(value = "#{jasperReportBean}")
    JasperReportBean jasperReportBean;

    public void printSalaryPosting(Object[] obj, ActionEvent event) {

        Map params = new HashMap();

        EmployeeMaster em = (EmployeeMaster) obj[0];
        params.put("officeName", HelperUtil.getLoggedInOffice().getName());
        params.put("employeeName", em.getEmployeeName());
        params.put("salaryDate", selectedYearTemp.getAppDataDesc() + "-" + selectedMonthTemp.getAppDataDesc());
        params.put("currentDate", ndc.convertToNepaliDate(new Date()));
        params.put("generatedBy", getLoggedInUser().getName());

        List<SalaryPostingDTO> list = new ArrayList<SalaryPostingDTO>();

        for (int i = 1; i < dataTableColumns.size(); i++) {
            SalaryPostingDTO s = new SalaryPostingDTO();
            s.setPayHead(dataTableColumns.get(i).getHeader());
            s.setAmount((Double) obj[i]);
            list.add(s);
        }
        SalaryPostingDTO s = new SalaryPostingDTO();
        s.setPayHead("Net Paid");
        s.setAmount((Double) obj[positiveIndexT] - (Double) obj[negativeIndexT]);
        list.add(s);

        try {
            JRBeanCollectionDataSource beancoldatasrc = new JRBeanCollectionDataSource(list);
            jasperReportBean.exportReportToPDF(event, beancoldatasrc, params, "SalaryPosting");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void updateSalaryPost() {
        try {
            payrollTransactionBean.updateSalaryPosting(postings, selectedYearTemp, selectedMonthTemp);
            JsfUtil.addSuccessMessage("Salary updated successfully.");
            payHeadsValueList = new ArrayList<Object[]>();

            stage = 1;
        } catch (ClientException ex) {
            HelperUtil.showErrorMessage(ex.getMessage());
        }
    }

    public void saveSalaryPosting() {

        if (accMaster == null) {
            JsfUtil.addErrorMessage("Cr Account Required.");
            return;
        } else if (remark == null || remark.isEmpty()) {
            JsfUtil.addErrorMessage("Remark Required.");
            return;
        }
        try {
            payrollTransactionBean.saveSalaryPosting(payHeadsValueList, dataTableColumns, selectedYearTemp,
                    selectedMonthTemp, tranDate, accMaster, remark);
            JsfUtil.addSuccessMessage("Salary posted successfully.");
            loadEmployeesToSalaryPay();

        } catch (ClientException ex) {
            HelperUtil.showErrorMessage(ex.getMessage());
        }
    }

    public void ajaxDerivedAmountCalculationEdit() {

        double earningAmount = 0;
        double deductionAmount = 0;

        double earningAmountFromDerivedNonSlab = 0;
        double deductionAmountFromDerivedNonSlab = 0;

        for (SalaryPosting sp : postings) {

            if (sp.getAmount() != null && sp.getAmount() > 0) {
                PayHeads p = sp.getPayHeadsId();

                if (p.getPayHeadType().equals(KeyConstants.EARNING)
                        && p.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    earningAmount += sp.getAmount();

                } else if (p.getPayHeadType().equals(KeyConstants.DEDUCTION)
                        && p.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    deductionAmount += sp.getAmount();
                }
            }
        }

        for (SalaryPosting sp : postings) {
            PayHeads p = sp.getPayHeadsId();

            if (p.getCalculationType().equals(KeyConstants.DERIVED)) {
                if (p.getPayHeadId() != null) {

                    for (SalaryPosting sa : postings) {

                        if (sa.getPayHeadsId().getId().equals(p.getPayHeadId().getId())) {
                            if (sa.getAmount() != null && sa.getAmount() > 0) {

                                double d = sa.getAmount();
                                boolean found = false;

                                List<PayheadDerivedCondition> temp = appDataSession
                                        .returnPayheadConditionByPayheadId(p.getId());
                                for (PayheadDerivedCondition dc : temp) {

                                    if (d >= dc.getMonthlyAmountFrom() && d <= dc.getMonthlyAmountTo()) {
                                        if (dc.getType().equals(KeyConstants.FLAT)) {
                                            sp.setAmount(dc.getValue());

                                        } else {
                                            d = d * (dc.getValue() / 100.f);
                                            String s = new DecimalFormat("##.##").format(d);
                                            sp.setAmount(Double.valueOf(s));

                                        }
                                        found = true;
                                    }
                                    if (found) {
                                        break;
                                    }
                                }
                                if (!found) {
                                    sp.setAmount(0.0);
                                }
                                if (p.getPayHeadType().equals(KeyConstants.EARNING)) {
                                    earningAmountFromDerivedNonSlab = earningAmountFromDerivedNonSlab
                                            + sp.getAmount();
                                } else {
                                    deductionAmountFromDerivedNonSlab = deductionAmountFromDerivedNonSlab
                                            + sp.getAmount();
                                }
                            }
                        }
                    }
                }
            }
        }

        for (SalaryPosting sp : postings) {
            PayHeads p = sp.getPayHeadsId();

            if (p.getCalculationType().equals(KeyConstants.DERIVED)) {
                if (p.getPayHeadId() == null) {

                    double d1 = earningAmountFromDerivedNonSlab + earningAmount;
                    double d2 = deductionAmountFromDerivedNonSlab + deductionAmount;

                    double earning = d1 - d2;
                    boolean found = false;

                    List<PayheadDerivedCondition> temp = appDataSession
                            .returnPayheadConditionByPayheadId(p.getId());
                    for (PayheadDerivedCondition dc : temp) {

                        if (earning >= dc.getMonthlyAmountFrom() && earning <= dc.getMonthlyAmountTo()) {

                            if (dc.getType().equals(KeyConstants.FLAT)) {
                                sp.setAmount(dc.getValue());

                            } else {
                                double d = earning * (dc.getValue() / 100.f);
                                String s = new DecimalFormat("##.##").format(d);
                                sp.setAmount(Double.valueOf(s));
                            }
                            found = true;
                        }
                        if (found) {
                            break;
                        }
                    }
                    if (!found) {
                        sp.setAmount(0.0);
                    }
                }
            }
        }
    }

    public void ajaxCalculationTypeDerive() {
        if (payHeads.getCalculationType().equals(KeyConstants.DERIVED)) {
            if (payHeadsList.isEmpty()) {
                JsfUtil.addErrorMessage("No payHeads found to be derived from");
                payHeads.setCalculationType(null);
                return;
            }
        }
        if (conditionsList == null || conditionsList.isEmpty()) {
            conditionsList.add(new PayheadDerivedCondition());
        }
    }

    public double calculateDerivedAmount(EmployeeMaster em, PayHeads payHeadToCheck) {

        double finalAmount = 0;
        double earningAmount = 0;
        double deductionAmount = 0;

        List<SalaryPosting> splist = employeeSessionBean.returnSalaryPostingForSpecificMonth(
                HelperUtil.getLoggedInOfficeID(), selectedYearTemp.getId(), selectedMonthTemp.getId(), em.getId());

        for (SalaryPosting sp : splist) {
            if (sp.getAmount() != null && sp.getAmount() > 0) {

                PayHeads ph = sp.getPayHeadsId();

                if (ph.getPayHeadType().equals(KeyConstants.EARNING)
                        && ph.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    earningAmount += sp.getAmount();
                } else if (ph.getPayHeadType().equals(KeyConstants.DEDUCTION)
                        && ph.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    deductionAmount += sp.getAmount();
                }
            }
        }

        if (payHeadToCheck.getCalculationType().equals(KeyConstants.DERIVED)) {

            if (payHeadToCheck.getPayHeadId() == null) {

                double earning = earningAmount - deductionAmount;
                boolean found = false;

                List<PayheadDerivedCondition> temp = appDataSession
                        .returnPayheadConditionByPayheadId(payHeadToCheck.getId());
                for (PayheadDerivedCondition dc : temp) {

                    if (earning >= payHeadToCheck.getAmountFrom() && earning <= payHeadToCheck.getAmountTo()) {

                        if (payHeadToCheck.getType().equals(KeyConstants.FLAT)) {
                            finalAmount = payHeadToCheck.getValue();

                        } else {
                            double total = earning * (payHeadToCheck.getValue() / 100.f);
                            String s = new DecimalFormat("##.##").format(total);
                            finalAmount = Double.valueOf(s);
                        }
                        found = true;
                    }
                    if (found) {
                        break;
                    }
                }
                if (!found) {
                    finalAmount = 0.0;
                }
            } else {

                for (SalaryPosting sp : splist) {
                    if (sp.getPayHeadsId().getId().equals(payHeadToCheck.getPayHeadId().getId())) {

                        double total = sp.getAmount();
                        boolean found = false;

                        List<PayheadDerivedCondition> temp = appDataSession
                                .returnPayheadConditionByPayheadId(payHeadToCheck.getId());
                        for (PayheadDerivedCondition dc : temp) {

                            if (total >= payHeadToCheck.getAmountFrom() && total <= payHeadToCheck.getAmountTo()) {
                                if (payHeadToCheck.getType().equals(KeyConstants.FLAT)) {
                                    finalAmount = payHeadToCheck.getValue();

                                } else {
                                    total = total * (payHeadToCheck.getValue() / 100.f);
                                    String s = new DecimalFormat("##.##").format(total);
                                    finalAmount = Double.valueOf(s);

                                }
                                found = true;
                            }
                            if (found) {
                                break;
                            }
                        }
                        if (!found) {
                            finalAmount = 0.0;
                        }
                    }
                }
            }
        }
        return finalAmount;
    }

    public void ajaxDerivedAmountCalculation(Object[] obj) {

        double earningAmount = 0;
        double deductionAmount = 0;

        double earningAmountFinal = 0;
        double deductionAmountFinal = 0;

        for (int i = 1; i < dataTableColumns.size(); i++) {

            if (obj[i] != null && !dataTableColumns.get(i).isHideInput()) {
                PayHeads p = dataTableColumns.get(i).getPayHeads();

                if (p.getPayHeadType().equals(KeyConstants.EARNING)
                        && p.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    earningAmount += Double.parseDouble(obj[i].toString());

                } else if (p.getPayHeadType().equals(KeyConstants.DEDUCTION)
                        && p.getCalculationType().equals(KeyConstants.USERDEFINED)) {
                    deductionAmount += Double.parseDouble(obj[i].toString());
                }
            }
        }

        for (int i = 1; i < dataTableColumns.size(); i++) {
            if (!dataTableColumns.get(i).isHideInput()) {

                PayHeads p = dataTableColumns.get(i).getPayHeads();
                if (p.getCalculationType().equals(KeyConstants.DERIVED)) {

                    if (p.getPayHeadId() != null) {
                        for (int j = 1; j < dataTableColumns.size(); j++) {

                            if (!dataTableColumns.get(j).isHideInput()) {
                                if (dataTableColumns.get(j).getPayHeads().getId()
                                        .equals(p.getPayHeadId().getId())) {

                                    if (obj[j] != null) {
                                        double d = Double.parseDouble(obj[j].toString());

                                        List<PayheadDerivedCondition> temp = appDataSession
                                                .returnPayheadConditionByPayheadId(p.getId());
                                        for (PayheadDerivedCondition dc : temp) {

                                            if (d >= dc.getMonthlyAmountFrom() && d <= dc.getMonthlyAmountTo()) {
                                                if (dc.getType().equals(KeyConstants.FLAT)) {
                                                    obj[i] = dc.getValue();
                                                } else {
                                                    d = d * (dc.getValue() / 100.f);
                                                    String s = new DecimalFormat("##.##").format(d);
                                                    d = Double.valueOf(s);
                                                    obj[i] = d;
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    if (obj[i] == null) {
                                        obj[i] = 0;
                                    }
                                    if (p.getPayHeadType().equals(KeyConstants.EARNING)) {
                                        earningAmountFinal = earningAmountFinal + Double.valueOf(obj[i].toString());
                                    } else {
                                        deductionAmountFinal = deductionAmountFinal
                                                + Double.valueOf(obj[i].toString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        double earningAmountFromDerivedNonSlab = earningAmountFinal;
        double deductionAmountFromDerivedNonSlab = deductionAmountFinal;

        for (int i = 1; i < dataTableColumns.size(); i++) {
            if (!dataTableColumns.get(i).isHideInput()) {

                PayHeads p = dataTableColumns.get(i).getPayHeads();

                if (p.getCalculationType().equals(KeyConstants.DERIVED)) {
                    if (p.getPayHeadId() == null) {

                        double d1 = earningAmountFromDerivedNonSlab + earningAmount;
                        double d2 = deductionAmountFromDerivedNonSlab + deductionAmount;

                        double earning = d1 - d2;

                        List<PayheadDerivedCondition> temp = appDataSession
                                .returnPayheadConditionByPayheadId(p.getId());
                        for (PayheadDerivedCondition dc : temp) {

                            if (earning >= dc.getMonthlyAmountFrom() && earning <= dc.getMonthlyAmountTo()) {

                                if (dc.getType().equals(KeyConstants.FLAT)) {
                                    obj[i] = dc.getValue();

                                } else {
                                    double d = earning * (dc.getValue() / 100.f);
                                    String s = new DecimalFormat("##.##").format(d);
                                    d = Double.valueOf(s);
                                    obj[i] = d;
                                }
                                break;
                            }
                        }
                        if (obj[i] == null) {
                            obj[i] = 0;
                        }
                        if (p.getPayHeadType().equals(KeyConstants.EARNING)) {
                            earningAmountFinal = earningAmountFinal + Double.valueOf(obj[i].toString());
                        } else {
                            deductionAmountFinal = deductionAmountFinal + Double.valueOf(obj[i].toString());
                        }
                    }
                }
            }
        }
        obj[positiveIndexT] = HelperUtil.round((earningAmountFinal + earningAmount), 2);
        obj[negativeIndexT] = HelperUtil.round((deductionAmountFinal + deductionAmount), 2);
    }

    public void searchEmployeeSalaryPost() {

        if (selectedYear == null) {
            JsfUtil.addErrorMessage("Please select year.");
            return;
        } else if (selectedMonth == null) {
            JsfUtil.addErrorMessage("Please select month.");
            return;
        }

        List<EmployeeMaster> employeeList = null;
        if (selectedGroup == null) {
            employeeList = employeeSessionBean.returnAllEmployeeGroupByOffice(HelperUtil.getLoggedInOfficeID());
        } else {
            employeeList = employeeSessionBean.returnAllEmployeeGroupByGroup(HelperUtil.getLoggedInOfficeID(),
                    selectedGroup.getId());
        }

        if (employeeList.isEmpty()) {
            JsfUtil.addErrorMessage("No employee found.");
            return;
        }

        dataTableColumns = new ArrayList<DataTableColumn>();
        dataTableColumns.add(new DataTableColumn("EMPLOYEE", "Employee", true));

        payHeadsList = appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.EARNING);
        if (!payHeadsList.isEmpty()) {
            for (PayHeads p : payHeadsList) {
                dataTableColumns
                        .add(new DataTableColumn(p.getPayHead().toUpperCase(), p.getPayHead().toLowerCase(), p));
            }
            dataTableColumns.add(new DataTableColumn("Total Earning", "Total Earning", true));
        }

        positiveIndexT = payHeadsList.size() + 1;

        payHeadsList = appDataSession.returnPayHeadsByTypeAndOffice(HelperUtil.getLoggedInOfficeID(),
                KeyConstants.DEDUCTION);
        if (!payHeadsList.isEmpty()) {
            for (PayHeads p : payHeadsList) {
                dataTableColumns
                        .add(new DataTableColumn(p.getPayHead().toUpperCase(), p.getPayHead().toLowerCase(), p));
            }
            dataTableColumns.add(new DataTableColumn("Total Deduction", "Total Deduction", true));
        }

        negativeIndexT = positiveIndexT + payHeadsList.size() + 1;

        payHeadsValueList = new ArrayList<Object[]>();

        for (EmployeeMaster e : employeeList) {
            if (!employeeSessionBean.returnSalaryPostingForSpecificMonth(HelperUtil.getLoggedInOfficeID(),
                    selectedYear.getId(), selectedMonth.getId(), e.getId()).isEmpty()) {

                Object[] str = new Object[dataTableColumns.size()];
                str[0] = e;
                int i = 0;

                for (DataTableColumn data : dataTableColumns) {
                    if (!data.isHideInput()) {
                        SalaryPosting posting = employeeSessionBean.returnSalaryPostingByEmployeePayHeadTime(
                                HelperUtil.getLoggedInOfficeID(), selectedYear.getId(), selectedMonth.getId(),
                                e.getId(), data.getPayHeads().getId());
                        if (posting != null) {
                            str[i] = posting.getAmount();
                        }
                    }
                    i++;
                }
                payHeadsValueList.add(str);
            }
        }
        if (payHeadsValueList.isEmpty()) {
            JsfUtil.addErrorMessage("No Record Found.");
            return;
        }

        for (Object[] obj : payHeadsValueList) {

            double earningAmount = 0;
            double deductionAmount = 0;

            for (int i = 1; i < dataTableColumns.size(); i++) {
                if (obj[i] != null && !dataTableColumns.get(i).isHideInput()) {

                    PayHeads p = dataTableColumns.get(i).getPayHeads();

                    if (p.getPayHeadType().equals(KeyConstants.EARNING)) {
                        earningAmount += (Double) obj[i];

                    } else if (p.getPayHeadType().equals(KeyConstants.DEDUCTION)) {
                        deductionAmount += (Double) obj[i];
                    }
                }
            }
            obj[positiveIndexT] = earningAmount;
            obj[negativeIndexT] = deductionAmount;
        }

        selectedYearTemp = appDataSession.findAppData(selectedYear.getId());
        selectedMonthTemp = appDataSession.findAppData(selectedMonth.getId());
        showXLS = true;
    }

    public String redirectToPayHeads() {

        HelperUtil.setPageName(PageNameEnum.PAYHEADSETUP);
        stage = 1;

        accMasterList = accMasterSession.retrieveAccMasterListByNatureIdAndOffice(KeyConstants.ACCNATUREEXPENDITURE,
                HelperUtil.getLoggedInOfficeID());
        accMasterList2 = accMasterSession.retrieveAccMasterListByNatureIdAndOffice(
                KeyConstants.ACCNATURELIABILITIES, HelperUtil.getLoggedInOfficeID());
        payHeadsList = appDataSession.returnPayHeadsByOffice(HelperUtil.getLoggedInOfficeID());

        return "payHeads.xhtml?faces-redirect=true";
    }

    private List<PayheadDerivedCondition> conditionsList;

    public String createNewPayHeadClicked() {
        stage = 2;

        payHeads = new PayHeads();
        payHeads.setPayHeadType(KeyConstants.EARNING);
        payHeads.setType(KeyConstants.FLAT);

        insertMode = true;
        editRender = false;
        payHeads.setPayHeadType("Earning");

        conditionsList = new ArrayList<PayheadDerivedCondition>();
        conditionsList.add(new PayheadDerivedCondition());

        payHeadsListTemp = new ArrayList<PayHeads>(payHeadsList);
        /*
         * Yo Method ma return nachaine ho but nagarda payhead form ma value flush hudaina. like if you enter some value and left some
         * required value empty and there is validation error. Now if you cancel the form and again click create new, the values 
         * are not flushed. But with this redirect return the values are flushed.
         */
        return "payHeads.xhtml?faces-redirect=true";
    }

    public void addNewCondition() {
        conditionsList.add(new PayheadDerivedCondition());
    }

    public void removeExistingCondition(PayheadDerivedCondition p) {

        System.out.println("p " + p);
        if (p.getId() != null) {
            p.setDelFlg(true);

            appDataSession.merge(p);
            conditionsList.remove(p);

        } else {
            p.setDelFlg(true);

            List<PayheadDerivedCondition> temp = new ArrayList<PayheadDerivedCondition>(conditionsList);
            conditionsList.clear();

            for (PayheadDerivedCondition pd : temp) {
                if (pd.getDelFlg() != null && pd.getDelFlg()) {
                } else {
                    conditionsList.add(new PayheadDerivedCondition());
                }
            }
        }
    }

    public void editPayHeads(PayHeads ph) {
        payHeads = appDataSession.findPayHeads(ph.getId());
        conditionsList = appDataSession.returnPayheadConditionByPayheadId(ph.getId());

        payHeadsListTemp = new ArrayList<PayHeads>(payHeadsList);
        payHeadsListTemp.remove(ph);

        insertMode = true;
        editRender = true;
        stage = 2;
    }

    public void showDerivedDataDialogClicked(PayHeads p) {
        conditionsList = appDataSession.returnPayheadConditionByPayheadId(p.getId());
        RequestContext.getCurrentInstance().execute("PF('DerivedConditionsDialog').show();");
    }

    public void removePayHeads(PayHeads ph) {

        if (!appDataSession.returnSalaryPostByPayHead(ph.getId(), HelperUtil.getLoggedInOfficeID()).isEmpty()) {
            JsfUtil.addErrorMessage("PayHead found with amounts. Please remove the amount first from salary post.");
            return;
        }

        ph.setDelFlg(true);
        appDataSession.merge(ph);
        appDataSession.updateSalaryPostDeleteByPayHead(ph.getId(), HelperUtil.getLoggedInOfficeID());

        payHeadsList.remove(ph);

        JsfUtil.addSuccessMessage("PayHead Remove Successful.");
    }

    public void backBtnClicked() {
        insertMode = true;
    }

    public void cancelBtnClicked() {
        stage = 1;
    }

    public void cancelBtnClickedFromPayHead() {
        stage = 1;
    }

    public boolean payHeadsValidation() {

        boolean validationFailed = false;

        if (appDataSession.returnPayHeadsForDuplicateChecking(editRender, payHeads,
                HelperUtil.getLoggedInOfficeID()) != null) {
            JsfUtil.addErrorMessage("PayHead already exists.");
            validationFailed = true;
        }

        if (payHeads.getCalculationType().equals(KeyConstants.DERIVED)) {

            if (conditionsList.isEmpty()) {
                JsfUtil.addErrorMessage("Derivation Table Found Empty.");
                validationFailed = true;
            }
            int i = 1;
            for (PayheadDerivedCondition pd : conditionsList) {
                if (pd.getMonthlyAmountFrom() > pd.getMonthlyAmountTo()
                        || pd.getMonthlyAmountFrom().equals(pd.getMonthlyAmountTo())) {

                    JsfUtil.addErrorMessage(
                            "Amount From must be smaller than Amount To at index " + i + " of the table.");
                    validationFailed = true;
                }
                i++;
            }

            if (payHeads.getCalculationType().equals(KeyConstants.DERIVED)) {
                if (payHeads.getPayHeadId() != null
                        && payHeads.getPayHeadId().getCalculationType().equals(KeyConstants.DERIVED)) {
                    JsfUtil.addErrorMessage(
                            "PayHead to be derived from must have calculation type 'User Defined'.");
                    validationFailed = true;
                }
            }

            if (conditionsList.size() > 1) {
                Set<String> set = new HashSet<String>();
                for (PayheadDerivedCondition p : conditionsList) {
                    set.add(p.getMonthlyAmountFrom() + "-" + p.getMonthlyAmountTo());
                }
                if (set.size() != conditionsList.size()) {
                    JsfUtil.addErrorMessage("Duplicate Amount Range Found.");
                    validationFailed = true;
                }
            }
        }
        return validationFailed;
    }

    public void savePayHead() {

        if (payHeadsValidation()) {
            return;
        }

        payHeads.setCreatedBy(HelperUtil.getLoggedInUserID());
        payHeads.setCreatedDate(new Date());
        payHeads.setDelFlg(false);
        payHeads.setOfficeId(HelperUtil.getLoggedInOffice());
        accMasterSession.persistObject(payHeads);

        if (payHeads.getCalculationType().equals(KeyConstants.DERIVED)) {
            for (PayheadDerivedCondition dc : conditionsList) {
                dc.setDelFlg(false);
                dc.setPayheadIdParent(payHeads.getId());
                accMasterSession.persistObject(dc);
            }
        }

        payHeadsList.add(payHeads);
        stage = 1;

        JsfUtil.addSuccessMessage("PayHead Save Successful.");
    }

    public void updatePayHead() {

        if (payHeadsValidation()) {
            return;
        }

        if (payHeads.getCalculationType().equals(KeyConstants.USERDEFINED)) {
            payHeads.setPayHeadId(null);
            if (conditionsList != null && !conditionsList.isEmpty()) {

                for (PayheadDerivedCondition dc : conditionsList) {
                    dc.setDelFlg(true);
                    appDataSession.merge(dc);
                }
            }
        } else {
            for (PayheadDerivedCondition dc : conditionsList) {
                if (dc.getId() == null) {
                    dc.setDelFlg(false);
                    dc.setPayheadIdParent(payHeads.getId());
                    appDataSession.persist(dc);
                } else {
                    appDataSession.merge(dc);
                }
            }
        }
        appDataSession.merge(payHeads);
        payHeadsList.set(payHeadsList.indexOf(payHeads), payHeads);

        stage = 1;
        JsfUtil.addSuccessMessage("PayHead Save Successful.");
    }

    //    public void handleKeyEvent() {
    //        System.out.println("salary posting date");
    //    loadEmployeesToSalaryPay();
    ////        remark = "Salary Posting for  " + selectedYear.getAppDataDesc() + "/" + selectedMonth.getAppDataDesc();
    //    
    //    }
    public PayHeads getPayHeads() {
        return payHeads;
    }

    public void setPayHeads(PayHeads payHeads) {
        this.payHeads = payHeads;
    }

    public boolean isInsertMode() {
        return insertMode;
    }

    public void setInsertMode(boolean insertMode) {
        this.insertMode = insertMode;
    }

    public List<AccMaster> getAccMasterList() {
        return accMasterList;
    }

    public void setAccMasterList(List<AccMaster> accMasterList) {
        this.accMasterList = accMasterList;
    }

    public int getStage() {
        return stage;
    }

    public void setStage(int stage) {
        this.stage = stage;
    }

    public boolean isEditRender() {
        return editRender;
    }

    public void setEditRender(boolean editRender) {
        this.editRender = editRender;
    }

    public List<Object[]> getPayHeadsValueList() {
        return payHeadsValueList;
    }

    public void setPayHeadsValueList(List<Object[]> payHeadsValueList) {
        this.payHeadsValueList = payHeadsValueList;
    }

    public List<DataTableColumn> getDataTableColumns() {
        return dataTableColumns;
    }

    public void setDataTableColumns(List<DataTableColumn> dataTableColumns) {
        this.dataTableColumns = dataTableColumns;
    }

    public List<AppData> getNepaliMonthList() {
        return nepaliMonthList;
    }

    public void setNepaliMonthList(List<AppData> nepaliMonthList) {
        this.nepaliMonthList = nepaliMonthList;
    }

    public List<AppData> getNepaliYearList() {
        return nepaliYearList;
    }

    public void setNepaliYearList(List<AppData> nepaliYearList) {
        this.nepaliYearList = nepaliYearList;
    }

    public List<AppData> getEmployeeGroupList() {
        return employeeGroupList;
    }

    public void setEmployeeGroupList(List<AppData> employeeGroupList) {
        this.employeeGroupList = employeeGroupList;
    }

    public AppData getSelectedYear() {
        return selectedYear;
    }

    public void setSelectedYear(AppData selectedYear) {
        this.selectedYear = selectedYear;
    }

    public AppData getSelectedMonth() {
        return selectedMonth;
    }

    public void setSelectedMonth(AppData selectedMonth) {
        this.selectedMonth = selectedMonth;
    }

    public AppData getSelectedGroup() {
        return selectedGroup;
    }

    public void setSelectedGroup(AppData selectedGroup) {
        this.selectedGroup = selectedGroup;
    }

    public AccMaster getAccMaster() {
        return accMaster;
    }

    public void setAccMaster(AccMaster accMaster) {
        this.accMaster = accMaster;
    }

    public List<SalaryPosting> getPostings() {
        return postings;
    }

    public void setPostings(List<SalaryPosting> postings) {
        this.postings = postings;
    }

    public EmployeeMaster getSelectedEmployeeMaster() {
        return selectedEmployeeMaster;
    }

    public void setSelectedEmployeeMaster(EmployeeMaster selectedEmployeeMaster) {
        this.selectedEmployeeMaster = selectedEmployeeMaster;
    }

    public AppData getSelectedYearTemp() {
        return selectedYearTemp;
    }

    public void setSelectedYearTemp(AppData selectedYearTemp) {
        this.selectedYearTemp = selectedYearTemp;
    }

    public AppData getSelectedMonthTemp() {
        return selectedMonthTemp;
    }

    public void setSelectedMonthTemp(AppData selectedMonthTemp) {
        this.selectedMonthTemp = selectedMonthTemp;
    }

    public List<PayHeads> getPayHeadsList() {
        return payHeadsList;
    }

    public void setPayHeadsList(List<PayHeads> payHeadsList) {
        this.payHeadsList = payHeadsList;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public List<PayheadDerivedCondition> getConditionsList() {
        return conditionsList;
    }

    public void setConditionsList(List<PayheadDerivedCondition> conditionsList) {
        this.conditionsList = conditionsList;
    }

    public List<PayHeads> getPayHeadsListTemp() {
        return payHeadsListTemp;
    }

    public void setPayHeadsListTemp(List<PayHeads> payHeadsListTemp) {
        this.payHeadsListTemp = payHeadsListTemp;
    }

    boolean showXLS;

    public void simplePostProcessXLSEmployeeReport(Object document) {
        String startDateString = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
                .get("nepaliDate4");
        String endDateString = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
                .get("nepaliDate5");
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFCellStyle headerCellStyle = wb.createCellStyle();
        HSSFCellStyle headerCellStyle1 = wb.createCellStyle();
        HSSFCellStyle headerCellStyle2 = wb.createCellStyle();

        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontName(HSSFFont.FONT_ARIAL);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        Font headerFont1 = wb.createFont();
        headerFont1.setBoldweight(Font.U_SINGLE_ACCOUNTING);
        headerFont1.setFontName(HSSFFont.FONT_ARIAL);
        headerCellStyle1.setFont(headerFont);
        headerCellStyle1.setAlignment(CellStyle.ALIGN_RIGHT);

        Font headerFont3 = wb.createFont();
        headerFont3.setBoldweight(Font.U_SINGLE);
        headerFont3.setFontName(HSSFFont.FONT_ARIAL);
        headerCellStyle2.setFont(headerFont1);
        headerCellStyle2.setAlignment(CellStyle.ALIGN_RIGHT);

        HSSFSheet sheet = wb.getSheetAt(0);
        int noOfColumns = sheet.getRow(0).getLastCellNum();
        for (int i = 0; i < noOfColumns; i++) {
            sheet.autoSizeColumn(i);
        }
        sheet.shiftRows(0, sheet.getLastRowNum(), 3);

        HSSFRow firstRow = sheet.createRow(1);
        firstRow.createCell(0).setCellValue("Salary Posting Report");
        firstRow.getCell(0).setCellStyle(headerCellStyle);

        HSSFRow secondRow = sheet.createRow(0);
        secondRow.createCell(0).setCellValue(getLoggedInOffice().getName());
        secondRow.getCell(0).setCellStyle(headerCellStyle);

        HSSFRow thirdRow = sheet.createRow(2);
        String date = ndc.convertToNepaliDate(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
        String time = sdf.format(new Date());
        thirdRow.createCell(0)
                .setCellValue("Generated on:" + date + " " + time + " by:" + getLoggedInUser().getName());
        thirdRow.getCell(0).setCellStyle(headerCellStyle2);

        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 5));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 5));
        for (Row row : sheet) {
            if (row.getRowNum() > 3) {
                for (int i = 2; i < 6; i++) {
                    String cost = row.getCell(i).getStringCellValue();
                    if (cost != null && !cost.isEmpty()) {
                        row.getCell(i).setCellType(HSSFCell.CELL_TYPE_BLANK);
                        row.getCell(i).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                        row.getCell(i).setCellValue(Double.parseDouble(cost.replace(",", "")));
                    }
                }
            }
        }
    }

    public boolean isShowXLS() {
        return showXLS;
    }

    public void setShowXLS(boolean showXLS) {
        this.showXLS = showXLS;
    }

    public int getPositiveIndexT() {
        return positiveIndexT;
    }

    public void setPositiveIndexT(int positiveIndexT) {
        this.positiveIndexT = positiveIndexT;
    }

    public int getNegativeIndexT() {
        return negativeIndexT;
    }

    public void setNegativeIndexT(int negativeIndexT) {
        this.negativeIndexT = negativeIndexT;
    }

    public List<SalaryPostingDTO> getSalaryDTO() {
        return salaryDTO;
    }

    public void setSalaryDTO(List<SalaryPostingDTO> salaryDTO) {
        this.salaryDTO = salaryDTO;
    }

    public List<AccMaster> getAccMasterList2() {
        return accMasterList2;
    }

    public void setAccMasterList2(List<AccMaster> accMasterList2) {
        this.accMasterList2 = accMasterList2;
    }

    public String getTranDate() {
        String date = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
                .get("nepaliDate4");
        if (date != null && !date.isEmpty()) {
            tranDate = date;
        }
        return tranDate;
    }

    public void setTranDate(String tranDate) {
        this.tranDate = tranDate;
    }

    public JasperReportBean getJasperReportBean() {
        return jasperReportBean;
    }

    public void setJasperReportBean(JasperReportBean jasperReportBean) {
        this.jasperReportBean = jasperReportBean;
    }

}