Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

In this page you can find the example usage for java.math BigDecimal setScale.

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private String generateERPFile(FinantialInstitution institution, DateTime fromDate, DateTime toDate,
        List<? extends FinantialDocument> allDocuments, Boolean generateAllCustomers,
        Boolean generateAllProducts,
        java.util.function.UnaryOperator<AuditFile> preProcessFunctionBeforeSerialize) {

    // Build SAFT-AuditFile
    AuditFile auditFile = new AuditFile();
    // ThreadInformation information = 
    // SaftThreadRegister.retrieveCurrentThreadInformation();

    // Build SAFT-HEADER (Chapter 1 in AuditFile)
    Header header = this.createSAFTHeader(fromDate, toDate, institution, ERP_HEADER_VERSION_1_00_00);
    // SetHeader//from  www  .  ja va2s.  co  m
    auditFile.setHeader(header);

    // Build Master-Files
    oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles masterFiles = new oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles();

    // SetMasterFiles
    auditFile.setMasterFiles(masterFiles);

    // Build SAFT-MovementOfGoods (Customer and Products are built inside)
    // ProductsTable (Chapter 2.4 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Product> productList = masterFiles.getProduct();
    Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Product>();
    Set<String> productCodes = new HashSet<String>();

    // ClientsTable (Chapter 2.2 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Customer> customerList = masterFiles.getCustomer();
    Map<String, oecd.standardauditfile_tax.pt_1.Customer> customerMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Customer>();

    // Readd All  Clients if needed
    if (generateAllCustomers) {
        logger.info("Reading all Customers in Institution " + institution.getCode());

        Set<Customer> allCustomers = new HashSet<Customer>();
        for (DebtAccount debt : institution.getDebtAccountsSet()) {
            allCustomers.add(debt.getCustomer());
        }

        // Update the Total Objects Count
        // information.setTotalCounter(allCustomers.size() +
        // allProducts.size() + allDocuments.size() * 10);

        int i = 0;
        for (Customer customer : allCustomers) {
            oecd.standardauditfile_tax.pt_1.Customer saftCustomer = this
                    .convertCustomerToSAFTCustomer(customer);
            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
            customerMap.put(saftCustomer.getCustomerID(), saftCustomer);
            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allCustomers.size() + " Customers in Institution "
                        + institution.getCode());
            }
        }
    }
    // Readd All Products if needed
    if (generateAllProducts) {

        logger.info("Reading all Customers in Institution " + institution.getCode());
        Set<Product> allProducts = institution.getAvailableProductsSet();
        int i = 0;
        for (Product product : allProducts) {
            if (!productCodes.contains(product.getCode())) {
                oecd.standardauditfile_tax.pt_1.Product saftProduct = this.convertProductToSAFTProduct(product);
                productCodes.add(product.getCode());
                productMap.put(saftProduct.getProductCode(), saftProduct);
            }

            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allProducts.size() + " Products in Institution "
                        + institution.getCode());
            }

            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
        }
    } else {
        // information.setTotalCounter(allDocuments.size() * 10);
        // Update the Total Objects Count
        // information.setCurrentCounter(0);
    }

    // TaxTable (Chapter 2.5 in AuditFile)
    oecd.standardauditfile_tax.pt_1.TaxTable taxTable = new oecd.standardauditfile_tax.pt_1.TaxTable();
    masterFiles.setTaxTable(taxTable);

    for (Vat vat : institution.getVatsSet()) {
        taxTable.getTaxTableEntry().add(this.convertVATtoTaxTableEntry(vat, institution));
    }

    // Set MovementOfGoods in SourceDocuments(AuditFile)
    oecd.standardauditfile_tax.pt_1.SourceDocuments sourceDocuments = new oecd.standardauditfile_tax.pt_1.SourceDocuments();
    auditFile.setSourceDocuments(sourceDocuments);

    SourceDocuments.SalesInvoices invoices = new SourceDocuments.SalesInvoices();
    SourceDocuments.WorkingDocuments workingDocuments = new SourceDocuments.WorkingDocuments();
    Payments paymentsDocuments = new Payments();

    BigInteger numberOfPaymentsDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfPaymentsDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfPaymentsDocuments = BigDecimal.ZERO;

    BigInteger numberOfWorkingDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfWorkingDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfWorkingDocuments = BigDecimal.ZERO;

    invoices.setNumberOfEntries(BigInteger.ZERO);
    invoices.setTotalCredit(BigDecimal.ZERO);
    invoices.setTotalDebit(BigDecimal.ZERO);

    //        int i = 0;
    for (FinantialDocument document : allDocuments) {
        if ((document.isCreditNote() || document.isDebitNote())
                && (document.isClosed() || document.isAnnulled())) {
            try {
                WorkDocument workDocument = convertToSAFTWorkDocument((Invoice) document, customerMap,
                        productMap);
                workingDocuments.getWorkDocument().add(workDocument);

                // AcumulateValues
                numberOfWorkingDocuments = numberOfWorkingDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    if (document.isDebitNote()) {
                        totalDebitOfWorkingDocuments = totalDebitOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    } else if (document.isCreditNote()) {
                        totalCreditOfWorkingDocuments = totalCreditOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    }
                }

                //                    i++;

            } catch (Exception ex) {
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }
    // Update Totals of Workingdocuments
    workingDocuments.setNumberOfEntries(numberOfWorkingDocuments);
    workingDocuments.setTotalCredit(totalCreditOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));
    workingDocuments.setTotalDebit(totalDebitOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));

    sourceDocuments.setWorkingDocuments(workingDocuments);

    //PROCESSING PAYMENTS TABLE

    paymentsDocuments.setNumberOfEntries(BigInteger.ZERO);
    paymentsDocuments.setTotalCredit(BigDecimal.ZERO);
    paymentsDocuments.setTotalDebit(BigDecimal.ZERO);
    for (FinantialDocument document : allDocuments) {
        if (document.isSettlementNote() && (document.isClosed() || document.isAnnulled())) {
            try {
                Payment paymentDocument = convertToSAFTPaymentDocument((SettlementNote) document, customerMap,
                        productMap);
                paymentsDocuments.getPayment().add(paymentDocument);

                // AcumulateValues
                numberOfPaymentsDocuments = numberOfPaymentsDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    totalCreditOfPaymentsDocuments = totalCreditOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalCreditAmount());
                    totalDebitOfPaymentsDocuments = totalDebitOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalDebitAmount());
                }
                //                    i++;
            } catch (Exception ex) {
                // persistenceSupport.flush();
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }

    // Update Totals of Payment Documents
    paymentsDocuments.setNumberOfEntries(numberOfPaymentsDocuments);
    paymentsDocuments.setTotalCredit(totalCreditOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    paymentsDocuments.setTotalDebit(totalDebitOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    sourceDocuments.setPayments(paymentsDocuments);

    // Update the Customer Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Customer customer : customerMap.values()) {
        customerList.add(customer);
    }

    // Update the Product Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Product product : productMap.values()) {
        productList.add(product);
    }

    if (preProcessFunctionBeforeSerialize != null) {
        auditFile = preProcessFunctionBeforeSerialize.apply(auditFile);
    }
    String xml = exportAuditFileToXML(auditFile);

    logger.info("SAFT File export concluded with success.");
    return xml;
}

From source file:com.exilant.eGov.src.common.EGovernCommon.java

public BigDecimal getAccountBalance(final String recDate, final String bankAccountId)
        throws TaskFailedException {

    BigDecimal opeAvailable = BigDecimal.ZERO;
    BigDecimal totalAvailable = BigDecimal.ZERO;
    Query pst = null;//from www  .  j  a v a2s.  com
    List<Object[]> resultset = null;
    List<Object[]> resultset1 = null;
    try {
        final String str = "SELECT case when sum(openingDebitBalance) is null then 0 else sum(openingDebitBalance) end - case when sum(openingCreditBalance) is null then 0 else sum(openingCreditBalance) end AS \"openingBalance\" "
                + " FROM transactionSummary WHERE financialYearId=( SELECT id FROM financialYear WHERE startingDate <=? "
                + " AND endingDate >=? )  AND glCodeId =(select glcodeid from bankaccount where id=? )";
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("getAccountBalance(EGovernCommon.java): " + str);
        pst = persistenceService.getSession().createSQLQuery(str);
        SimpleDateFormat dtSlashFormat = new SimpleDateFormat("dd/MMM/yyyy");
        Date reconDate = dtSlashFormat.parse(recDate);
        java.sql.Date sDate = new java.sql.Date(reconDate.getTime());
        pst.setDate(0, sDate);
        pst.setDate(1, sDate);
        pst.setInteger(2, Integer.valueOf(bankAccountId));
        List list = pst.list();
        if (list == null || list.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getAccountBalance...");

        if (list != null || list.size() > 0) {
            opeAvailable = new BigDecimal(list.get(0).toString());
        }

        /* for (final Object[] element : resultset)
         {
            if(element[0]!=null)
        opeAvailable = new BigDecimal(element[0].toString());
         }*/

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("opening balance  " + opeAvailable);

        final String str1 = "SELECT (case when sum(gl.debitAmount) is null then 0 else sum(gl.debitAmount) end - case when sum(gl.creditAmount)  is null then 0 else sum(gl.creditAmount) end ) + "
                + opeAvailable
                + " as \"totalAmount\" FROM   generalLedger gl, voucherHeader vh WHERE vh.id = gl.voucherHeaderId and gl.glCodeid = (select glcodeid from bankaccount where id=?) AND  "
                + " vh.voucherDate >=( SELECT startingDate FROM financialYear WHERE startingDate <= ? AND endingDate >= ?) AND vh.voucherDate <= ? and vh.status!=4";

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Curr Yr Bal: " + str1);
        pst = persistenceService.getSession().createSQLQuery(str1);
        pst.setInteger(0, Integer.valueOf(bankAccountId));
        pst.setDate(1, reconDate);
        pst.setDate(2, reconDate);
        pst.setDate(3, reconDate);
        List list2 = pst.list();
        if (list2 != null)
            totalAvailable = new BigDecimal(list2.get(0).toString());
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total balance  " + totalAvailable);

        if (resultset1 == null || resultset1.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getAccountBalance...");

        totalAvailable = totalAvailable.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total balance before return " + totalAvailable);
        return totalAvailable;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw taskExc;
    }
}

From source file:org.egov.adtax.service.notice.AdvertisementNoticeService.java

private Map<String, Object> buildParametersForDemandDetails(
        final AdvertisementPermitDetail advertisementPermitDetail) {
    final Map<String, Object> reportParams = new HashMap<>();

    BigDecimal curntInsAdvertisement = BigDecimal.ZERO;
    BigDecimal curntInsEncrocFee = BigDecimal.ZERO;
    BigDecimal curntInsPenaltyFee = BigDecimal.ZERO;
    BigDecimal curntInsServiceTax = BigDecimal.ZERO;
    BigDecimal curntInsSwachBharatCess = BigDecimal.ZERO;
    BigDecimal curntInsKrishiKalyanCess = BigDecimal.ZERO;
    BigDecimal curntInsTotalTaxableAmt = BigDecimal.ZERO;

    BigDecimal curntInsNetTotal;/* ww  w .  j a  va2 s .  c  om*/
    BigDecimal arrInsNetTotal;
    BigDecimal arrInsGrossTotal;
    BigDecimal curntInsGrossTotal;

    BigDecimal arrInsAdvertisement = BigDecimal.ZERO;
    BigDecimal arrInsEncrocFee = BigDecimal.ZERO;
    BigDecimal arrInsPenaltyFee = BigDecimal.ZERO;
    BigDecimal arrInsServiceTax = BigDecimal.ZERO;
    BigDecimal arrInsSwachBharatCess = BigDecimal.ZERO;
    BigDecimal arrInsKrishiKalyanCess = BigDecimal.ZERO;
    BigDecimal arrInsTotalTaxableAmt = BigDecimal.ZERO;
    String previousInstallmentDesc = null;
    Installment currentInstallemnt = advertisementPermitDetail.getAdvertisement().getDemandId()
            .getEgInstallmentMaster();
    List<Installment> previousInstallemnt = advertisementDemandService
            .getPreviousInstallment(currentInstallemnt.getFromDate());
    Map<Installment, BigDecimal> penaltyAmountMap = advertisementPenaltyCalculator
            .getPenaltyByInstallment(advertisementPermitDetail);
    final Map<String, BigDecimal> additionalTaxes = new HashMap<>();
    final List<AdvertisementAdditionalTaxRate> additionalTaxRates = advertisementAdditinalTaxRateService
            .getAllActiveAdditinalTaxRates();
    if (previousInstallemnt.isEmpty()) {
        String currentFinYear = currentInstallemnt.getFinYearRange();
        String[] currentFinYearValues = currentFinYear.split("-");
        Integer from = Integer.parseInt(currentFinYearValues[0]) - 1;
        Integer to = Integer.parseInt(currentFinYearValues[1]) - 1;
        previousInstallmentDesc = from.toString() + "-" + to.toString();
    }
    for (final AdvertisementAdditionalTaxRate taxRates : additionalTaxRates)
        additionalTaxes.put(taxRates.getReasonCode(), taxRates.getPercentage());

    for (final EgDemandDetails demandDtl : advertisementPermitDetail.getAdvertisement().getDemandId()
            .getEgDemandDetails()) {

        if (demandDtl.getBalance().compareTo(BigDecimal.ZERO) > 0) {
            if (currentInstallemnt != null && currentInstallemnt.getDescription()
                    .equals(demandDtl.getEgDemandReason().getEgInstallmentMaster().getDescription())) {
                if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_ARREAR_ADVERTISEMENTTAX)) {
                    arrInsAdvertisement = arrInsAdvertisement.add(demandDtl.getBalance());
                    arrInsTotalTaxableAmt = arrInsTotalTaxableAmt.add(demandDtl.getBalance());
                } else if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_ADVERTISEMENTTAX)) {
                    curntInsAdvertisement = curntInsAdvertisement.add(demandDtl.getBalance());
                    reportParams.put("curntInsAdvertisement",
                            curntInsAdvertisement.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    curntInsTotalTaxableAmt = curntInsTotalTaxableAmt.add(demandDtl.getBalance());
                } else if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_ENCROCHMENTFEE)) {
                    curntInsEncrocFee = demandDtl.getBalance();
                    reportParams.put("curntInsEncrocFee",
                            curntInsEncrocFee.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    curntInsTotalTaxableAmt = curntInsTotalTaxableAmt.add(curntInsEncrocFee);
                } else if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_PENALTY)) {
                    curntInsPenaltyFee = demandDtl.getBalance();
                    reportParams.put("curntInsPenaltyFee",
                            curntInsPenaltyFee.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                }
            } else {
                if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_ARREAR_ADVERTISEMENTTAX)
                        || demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                                .equalsIgnoreCase(DEMANDREASON_ADVERTISEMENTTAX)) {
                    arrInsAdvertisement = arrInsAdvertisement.add(demandDtl.getBalance());
                    reportParams.put("arrInsAdvertisement",
                            arrInsAdvertisement.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    arrInsTotalTaxableAmt = arrInsTotalTaxableAmt.add(demandDtl.getBalance());
                } else if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_ENCROCHMENTFEE)) {
                    arrInsEncrocFee = arrInsEncrocFee.add(demandDtl.getBalance());
                    reportParams.put("arrInsEncrocFee",
                            arrInsEncrocFee.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    arrInsTotalTaxableAmt = arrInsTotalTaxableAmt.add(demandDtl.getBalance());
                } else if (demandDtl.getEgDemandReason().getEgDemandReasonMaster().getCode()
                        .equalsIgnoreCase(DEMANDREASON_PENALTY)) {
                    arrInsPenaltyFee = arrInsPenaltyFee.add(demandDtl.getBalance());
                    reportParams.put("arrInsPenaltyFee",
                            arrInsPenaltyFee.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                }
            }
        }
    }

    // Add penalty into reports
    for (final Map.Entry<Installment, BigDecimal> penaltyMap : penaltyAmountMap.entrySet())
        if (currentInstallemnt != null
                && currentInstallemnt.getDescription().equalsIgnoreCase(penaltyMap.getKey().getDescription())) {
            curntInsPenaltyFee = curntInsPenaltyFee.add(penaltyMap.getValue());
            reportParams.put("curntInsPenaltyFee", curntInsPenaltyFee);
        } else {
            arrInsPenaltyFee = arrInsPenaltyFee.add(penaltyMap.getValue());
            reportParams.put("arrInsPenaltyFee", arrInsPenaltyFee);
        }

    for (final Map.Entry<String, BigDecimal> entry : additionalTaxes.entrySet()) {
        if ("Service_Tax".equalsIgnoreCase(entry.getKey())) {
            curntInsServiceTax = calculateAdditionalTaxes(curntInsTotalTaxableAmt, entry.getValue());
            arrInsServiceTax = calculateAdditionalTaxes(arrInsTotalTaxableAmt, entry.getValue());
        } else if ("ADTAX_SB_CESS".equalsIgnoreCase(entry.getKey())) {
            curntInsSwachBharatCess = calculateAdditionalTaxes(curntInsTotalTaxableAmt, entry.getValue());
            arrInsSwachBharatCess = calculateAdditionalTaxes(arrInsTotalTaxableAmt, entry.getValue());
        } else if ("ADTAX_KRISHI_CES".equalsIgnoreCase(entry.getKey())) {
            curntInsKrishiKalyanCess = calculateAdditionalTaxes(curntInsTotalTaxableAmt, entry.getValue());
            arrInsKrishiKalyanCess = calculateAdditionalTaxes(arrInsTotalTaxableAmt, entry.getValue());
        }
    }
    // set additional taxes details and installment
    reportParams.put("currentInstallmentDesc", currentInstallemnt.getDescription());
    reportParams.put("previousInstallmentDesc", previousInstallemnt.isEmpty() ? previousInstallmentDesc
            : previousInstallemnt.get(0).getDescription());
    reportParams.put("curntInsServiceTax", curntInsServiceTax.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("curntInsKrishiKalyanCess",
            curntInsKrishiKalyanCess.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("curntInsSwachBharatCess",
            curntInsSwachBharatCess.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("arrInsServiceTax", arrInsServiceTax.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("arrInsSwachBharatCess", arrInsSwachBharatCess.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("arrInsKrishiKalyanCess", arrInsKrishiKalyanCess.setScale(2, BigDecimal.ROUND_HALF_EVEN));

    // sum demand details
    reportParams.put("curntInsTotalTaxableAmt",
            curntInsTotalTaxableAmt.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("arrInsTotalTaxableAmt", arrInsTotalTaxableAmt.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    curntInsGrossTotal = curntInsTotalTaxableAmt.add(curntInsServiceTax).add(curntInsSwachBharatCess)
            .add(curntInsKrishiKalyanCess);
    reportParams.put("curntInsGrossTotal", curntInsGrossTotal.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    curntInsNetTotal = curntInsGrossTotal.add(curntInsPenaltyFee);
    reportParams.put("curntInsNetTotal", curntInsNetTotal.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    arrInsGrossTotal = arrInsTotalTaxableAmt.add(arrInsServiceTax).add(arrInsSwachBharatCess)
            .add(arrInsKrishiKalyanCess);
    reportParams.put("arrInsGrossTotal", arrInsGrossTotal.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    arrInsNetTotal = arrInsGrossTotal.add(arrInsPenaltyFee);
    reportParams.put("arrInsNetTotal", arrInsNetTotal.setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("advertisementTaxSum",
            curntInsAdvertisement.add(arrInsAdvertisement).setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("encrochmentFeeSum",
            curntInsEncrocFee.add(arrInsEncrocFee).setScale(2, BigDecimal.ROUND_HALF_EVEN));
    reportParams.put("serviceTaxSum",
            curntInsServiceTax.add(arrInsServiceTax).setScale(0, BigDecimal.ROUND_HALF_UP));
    reportParams.put("swachBharatCessSum",
            curntInsSwachBharatCess.add(arrInsSwachBharatCess).setScale(0, BigDecimal.ROUND_HALF_UP));
    reportParams.put("krishiKalyanCessSum",
            curntInsKrishiKalyanCess.add(arrInsKrishiKalyanCess).setScale(0, BigDecimal.ROUND_HALF_UP));
    reportParams.put("penalitySum",
            curntInsPenaltyFee.add(arrInsPenaltyFee).setScale(2, BigDecimal.ROUND_HALF_EVEN));

    reportParams.put("adParticular", advertisementPermitDetail.getAdvertisementParticular());
    reportParams.put("durationOfAdvt", advertisementPermitDetail.getAdvertisementDuration());
    reportParams.put("class", advertisementPermitDetail.getAdvertisement().getRateClass().getDescription());
    reportParams.put("revenueWard", advertisementPermitDetail.getAdvertisement().getWard().getName());
    reportParams.put("electionWard",
            advertisementPermitDetail.getAdvertisement().getElectionWard() != null
                    ? advertisementPermitDetail.getAdvertisement().getElectionWard().getName()
                    : "");
    return reportParams;
}

From source file:org.egov.works.web.actions.contractorBill.ContractorBillAction.java

private void validateExpenditureForDepositCode(final String actionName) {
    if (workOrderEstimate.getEstimate() != null && workOrderEstimate.getEstimate().getDepositCode() != null)
        if (StringUtils.isNotBlank(actionName)
                && (actionName.equalsIgnoreCase(WorksConstants.ACTION_SUBMIT_FOR_APPROVAL)
                        || actionName.equalsIgnoreCase(WorksConstants.ACTION_APPROVAL)
                        || actionName.equalsIgnoreCase(WorksConstants.ACTION_APPROVE))) {
            final FinancialDetail financialDetails = workOrderEstimate.getEstimate().getFinancialDetails()
                    .get(0);//from  w w w. jav  a  2  s  . c  o m
            if (financialDetails != null) {
                BigDecimal expenditureAmount = BigDecimal.ZERO;
                BigDecimal totalExpAmount = BigDecimal.ZERO;
                final Fund fund = financialDetails.getFund();
                final CChartOfAccounts coa = financialDetails.getCoa();
                final Accountdetailtype accountdetailtype = (Accountdetailtype) persistenceService
                        .find("from Accountdetailtype where name=?", "DEPOSITCODE");
                if (fund != null && fund.getId() != null && coa != null && coa.getId() != null
                        && workOrderEstimate.getEstimate().getDepositCode().getId() != null) {
                    final BigDecimal totalAmountDeposited = egovCommon.getDepositAmountForDepositCode(
                            new Date(), coa.getGlcode(), fund.getCode(), accountdetailtype.getId(),
                            workOrderEstimate.getEstimate().getDepositCode().getId().intValue());
                    final List<Integer> projectCodeIdsList = contractorBillService
                            .getProjCodeIdsListForDepositCode(fund.getId(), coa.getId(),
                                    workOrderEstimate.getEstimate().getDepositCode().getId());
                    if (!projectCodeIdsList.isEmpty())
                        expenditureAmount = contractorBillService.getTotalExpenditure(projectCodeIdsList,
                                WorksConstants.PROJECTCODE);
                    // In case id is null, include the current bill amount
                    if (id == null)
                        totalExpAmount = expenditureAmount.add(contractorBillRegister.getBillamount());
                    else
                        totalExpAmount = expenditureAmount;
                    final BigDecimal finalExpenditureAmount = totalExpAmount.setScale(2, RoundingMode.HALF_UP);
                    final BigDecimal totalDepositedAmount = totalAmountDeposited.setScale(2,
                            RoundingMode.HALF_UP);

                    if (totalDepositedAmount.compareTo(finalExpenditureAmount) == -1) {
                        populateBudgetHeadForDepositWorksEstimate();
                        throw new ValidationException(Arrays.asList(new ValidationError(
                                "contractoBill.dwEstimate.expenditure.amount.insufficient",
                                getText("contractoBill.dwEstimate.expenditure.amount.insufficient",
                                        new String[] {
                                                workOrderEstimate.getEstimate().getDepositCode().getCode(),
                                                NumberUtil.formatNumber(finalExpenditureAmount),
                                                NumberUtil.formatNumber(totalDepositedAmount) }))));
                    }
                }
            }
        }
}

From source file:org.egov.services.recoveries.RecoveryService.java

public BigDecimal getDeductionAmount(final String recoveryCode, final String partyType,
        final String subPartyType, final String docType, final BigDecimal grossAmount, final Date asOnDate)
        throws Exception {

    final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy", Constants.LOCALE);
    BigDecimal incomeTax = new BigDecimal(0);
    BigDecimal surcharge = new BigDecimal(0);
    BigDecimal education = new BigDecimal(0);
    BigDecimal total = new BigDecimal(0);
    BigDecimal deductionAmt = new BigDecimal(0);
    EgDeductionDetails egDeductionDetails = null;

    if (null == recoveryCode || recoveryCode.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Recovery Code is missing");
        throw new ValidationException(EMPTY, "Recovery Code is missing");
    }/*from  w  ww  .j  a v a 2s. co m*/

    if (null == partyType || partyType.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Party Type is missing");
        throw new ValidationException(EMPTY, "Party Type is missing");
    }

    if (null == grossAmount) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Gross Amount is missing");
        throw new ValidationException(EMPTY, "Gross Amount is missing");
    }

    if (null == asOnDate) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("AsOnDate is missing");
        throw new ValidationException(EMPTY, "AsOnDate is missing");
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("getDeductionAmount() -> recoveryCode :" + recoveryCode + " | partyType :" + partyType
                + " | grossAmount :" + grossAmount + " | asOnDate :" + dateFormatter.format(asOnDate)
                + " | docType :" + docType);

    EgwTypeOfWork egwTypeOfWork = null;
    EgPartytype egSubPartytype = null;

    final EgPartytype egPartytype = getPartytypeByCode(partyType);
    final Recovery recovery = getTdsByTypeAndPartyType(recoveryCode, egPartytype);

    if (recovery == null)
        throw new ValidationException(EMPTY,
                "Recovery with " + recoveryCode + " code  and " + egPartytype + " party type is invalid.");
    if (recovery.getRecoveryMode() == 'M')
        return BigDecimal.valueOf(-1);

    if (null != docType)
        egwTypeOfWork = getTypeOfWorkByCode(docType);

    if (null != subPartyType)
        egSubPartytype = getSubPartytypeByCode(subPartyType);

    try {
        egDeductionDetails = egDeductionDetHibernateDao.findEgDeductionDetailsForDeduAmt(recovery, egPartytype,
                egSubPartytype, egwTypeOfWork, asOnDate);
    } catch (final Exception e) {
        LOGGER.error("Exception in egDeductionDetails fetching :" + e);
        throw new ValidationException(EMPTY, "Error while fetching the date for this " + recoveryCode
                + " code for this " + dateFormatter.format(asOnDate) + " date. " + e.getMessage());
    }

    if (null == egDeductionDetails)
        throw new ValidationException(EMPTY, "There is no data for this " + recoveryCode + " code for this "
                + dateFormatter.format(asOnDate) + " date.");

    if (null != recovery.getCalculationType() && recovery.getCalculationType().equalsIgnoreCase("flat")) {
        if (null != egDeductionDetails.getFlatAmount())
            deductionAmt = egDeductionDetails.getFlatAmount();
    } else {
        if (null != egDeductionDetails.getIncometax())
            incomeTax = egDeductionDetails.getIncometax();
        if (null != egDeductionDetails.getSurcharge())
            surcharge = egDeductionDetails.getSurcharge();
        if (null != egDeductionDetails.getEducation())
            education = egDeductionDetails.getEducation();
        total = incomeTax.add(surcharge).add(education);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total IT/SC/EC " + total);
        deductionAmt = grossAmount.multiply(total.divide(new BigDecimal(100)));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("deductionAmt :" + deductionAmt);
    return deductionAmt = deductionAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
}

From source file:de.appsolve.padelcampus.utils.BookingUtil.java

public OfferDurationPrice getOfferDurationPrice(List<CalendarConfig> configs, List<Booking> confirmedBookings,
        LocalDate selectedDate, LocalTime selectedTime, Offer selectedOffer) throws CalendarConfigException {
    List<TimeSlot> timeSlotsForDate = getTimeSlotsForDate(selectedDate, configs, confirmedBookings,
            Boolean.TRUE, Boolean.TRUE);
    boolean validStartTime = false;
    for (TimeSlot timeSlot : timeSlotsForDate) {
        if (timeSlot.getStartTime().equals(selectedTime)) {
            validStartTime = true;//from   w  w  w .  ja v a2  s . c om
            break;
        }
    }

    OfferDurationPrice offerDurationPrices = null;
    if (validStartTime) {
        //convert to required data structure
        Map<Offer, List<CalendarConfig>> offerConfigMap = new HashMap<>();
        for (CalendarConfig config : configs) {
            for (Offer offer : config.getOffers()) {
                if (offer.equals(selectedOffer)) {
                    List<CalendarConfig> list = offerConfigMap.get(offer);
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(config);

                    //sort by start time
                    Collections.sort(list);
                    offerConfigMap.put(offer, list);
                }
            }
        }

        Iterator<Map.Entry<Offer, List<CalendarConfig>>> iterator = offerConfigMap.entrySet().iterator();
        //for every offer
        while (iterator.hasNext()) {
            Map.Entry<Offer, List<CalendarConfig>> entry = iterator.next();
            Offer offer = entry.getKey();
            List<CalendarConfig> configsForOffer = entry.getValue();

            //make sure the first configuration starts before the requested booking time
            if (selectedTime.compareTo(configsForOffer.get(0).getStartTime()) < 0) {
                continue;
            }

            LocalDateTime endTime = null;
            Integer duration = configsForOffer.get(0).getMinDuration();
            BigDecimal pricePerMinute;
            BigDecimal price = null;
            CalendarConfig previousConfig = null;
            Map<Integer, BigDecimal> durationPriceMap = new TreeMap<>();
            Boolean isContiguous = true;
            for (CalendarConfig config : configsForOffer) {

                //make sure there is no gap between calendar configurations
                if (endTime == null) {
                    //first run
                    endTime = getLocalDateTime(selectedDate, selectedTime).plusMinutes(config.getMinDuration());
                } else {
                    //break if there are durations available and calendar configs are not contiguous
                    if (!durationPriceMap.isEmpty()) {
                        //we substract min interval before the comparison as it has been added during the last iteration
                        LocalDateTime configStartDateTime = getLocalDateTime(selectedDate,
                                config.getStartTime());
                        if (!endTime.minusMinutes(config.getMinInterval()).equals(configStartDateTime)) {
                            break;
                        }
                    }
                }

                Integer interval = config.getMinInterval();

                pricePerMinute = getPricePerMinute(config);

                //as long as the endTime is before the end time configured in the calendar
                LocalDateTime configEndDateTime = getLocalDateTime(selectedDate, config.getEndTime());
                while (endTime.compareTo(configEndDateTime) <= 0) {
                    TimeSlot timeSlot = new TimeSlot();
                    timeSlot.setDate(selectedDate);
                    timeSlot.setStartTime(selectedTime);
                    timeSlot.setEndTime(endTime.toLocalTime());
                    timeSlot.setConfig(config);
                    Long bookingSlotsLeft = getBookingSlotsLeft(timeSlot, offer, confirmedBookings);

                    //we only allow contiguous bookings for any given offer
                    if (bookingSlotsLeft < 1) {
                        isContiguous = false;
                        break;
                    }

                    if (price == null) {
                        //see if previousConfig endTime - minInterval matches the selected time. if so, take half of the previous config price as a basis
                        if (previousConfig != null && previousConfig.getEndTime()
                                .minusMinutes(previousConfig.getMinInterval()).equals(selectedTime)) {
                            BigDecimal previousConfigPricePerMinute = getPricePerMinute(previousConfig);
                            price = previousConfigPricePerMinute.multiply(
                                    new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128);
                            price = price.add(pricePerMinute.multiply(
                                    new BigDecimal(duration - previousConfig.getMinInterval()),
                                    MathContext.DECIMAL128));
                        } else {
                            price = pricePerMinute.multiply(new BigDecimal(duration.toString()),
                                    MathContext.DECIMAL128);
                        }
                    } else {
                        //add price for additional interval
                        price = price.add(pricePerMinute.multiply(new BigDecimal(interval.toString()),
                                MathContext.DECIMAL128));
                    }
                    price = price.setScale(2, RoundingMode.HALF_EVEN);
                    durationPriceMap.put(duration, price);

                    //increase the duration by the configured minimum interval and determine the new end time for the next iteration
                    duration += interval;
                    endTime = endTime.plusMinutes(interval);
                }

                if (!durationPriceMap.isEmpty()) {
                    OfferDurationPrice odp = new OfferDurationPrice();
                    odp.setOffer(offer);
                    odp.setDurationPriceMap(durationPriceMap);
                    odp.setConfig(config);
                    offerDurationPrices = odp;
                }

                if (!isContiguous) {
                    //we only allow coniguous bookings for one offer. process next offer
                    break;
                }
                previousConfig = config;

            }
        }
    }
    return offerDurationPrices;
}

From source file:com.inkubator.hrm.service.impl.PayTempKalkulasiServiceImpl.java

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public List<PayTempKalkulasi> getAllDataCalculatedPayment(Date startPeriodDate, Date endPeriodDate,
        Date createdOn, String createdBy) throws Exception {

    //initial//from  w w  w . ja v a 2  s  . co  m
    PaySalaryComponent totalIncomeComponent = paySalaryComponentDao
            .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAKE_HOME_PAY);
    PaySalaryComponent taxComponent = paySalaryComponentDao
            .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAX);
    PaySalaryComponent ceilComponent = paySalaryComponentDao
            .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_CEIL);
    List<PayTempKalkulasi> datas = new ArrayList<PayTempKalkulasi>();
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
    Double basicSalary = null;
    Double workingDay = null;
    Double lessTime = null;
    Double moreTime = null;
    Double overTIme = null;
    Double totalDay = this.getDefaultWorkingDay(startPeriodDate, endPeriodDate); //total working day dari kelompok kerja DEFAULT(reguler)
    Double outPut = null;

    //Start calculation
    List<EmpData> totalEmployee = empDataDao.getAllDataNotTerminateAndJoinDateLowerThan(endPeriodDate);
    /*List<EmpData> totalEmployee = new ArrayList<EmpData>();
     EmpData emp = empDataDao.getEntiyByPK((long)130);
     totalEmployee.add(emp);*/

    for (EmpData empData : totalEmployee) {
        LOGGER.info(
                " ============= EMPLOYEE : " + empData.getBioData().getFirstName() + " =====================");

        /**
         * Set initial variabel untuk masing2 karyawan, 
         * yang akan dibutuhkan untuk perhitungan model komponen FORMULA (if any) 
         * */
        basicSalary = Double.parseDouble(empData.getBasicSalaryDecrypted());
        PayTempOvertime payTempOvertime = payTempOvertimeDao.getEntityByEmpDataId(empData.getId());
        overTIme = payTempOvertime != null ? payTempOvertime.getOvertime() : 0.0;
        PayTempAttendanceStatus payTempAttendanceStatus = payTempAttendanceStatusDao
                .getEntityByEmpDataId(empData.getId());
        workingDay = payTempAttendanceStatus != null ? (double) payTempAttendanceStatus.getTotalAttendance()
                : 0.0;
        lessTime = ((workingDay > 0) && (workingDay < totalDay)) ? totalDay - workingDay : 0.0;
        moreTime = (workingDay > totalDay) ? workingDay - totalDay : 0.0;

        /**
         * Saat ini totalIncome masih temporary, karena belum dikurangi
         * pajak dan pembulatan CSR Sedangkan untuk final totalIncome (take
         * home pay) ada di proses(step) selanjutnya di batch proses,
         * silahkan lihat batch-config.xml
         */
        BigDecimal totalIncome = new BigDecimal(0);

        List<PayComponentDataException> payComponentExceptions = payComponentDataExceptionDao
                .getAllByEmpId(empData.getId());
        for (PayComponentDataException dataException : payComponentExceptions) {
            PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
            kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
            kalkulasi.setEmpData(empData);
            kalkulasi.setPaySalaryComponent(dataException.getPaySalaryComponent());
            kalkulasi.setFactor(
                    this.getFactorBasedCategory(dataException.getPaySalaryComponent().getComponentCategory()));
            kalkulasi.setNominal(dataException.getNominal());

            kalkulasi.setCreatedBy(createdBy);
            kalkulasi.setCreatedOn(createdOn);
            datas.add(kalkulasi);

            totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
            LOGGER.info("Save By ComponentDataException - " + dataException.getPaySalaryComponent().getName()
                    + ", nominal : " + dataException.getNominal());
        }

        int timeTmb = DateTimeUtil.getTotalDay(empData.getJoinDate(), createdOn);
        List<Long> componentIds = Lambda.extract(payComponentExceptions,
                Lambda.on(PayComponentDataException.class).getPaySalaryComponent().getId());
        List<PaySalaryComponent> listPayComponetNotExcp = paySalaryComponentDao
                .getAllDataByEmpTypeIdAndActiveFromTmAndIdNotIn(empData.getEmployeeType().getId(), timeTmb,
                        componentIds);
        if (null == Lambda.selectFirst(listPayComponetNotExcp,
                Lambda.having(Lambda.on(PaySalaryComponent.class).getModelComponent().getSpesific(),
                        Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY)))
                && null == Lambda.selectFirst(payComponentExceptions,
                        Lambda.having(
                                Lambda.on(PayComponentDataException.class).getPaySalaryComponent()
                                        .getModelComponent().getSpesific(),
                                Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY)))) {
            throw new BussinessException("global.error_user_does_not_have_basic_salary",
                    empData.getNikWithFullName());
        }
        for (PaySalaryComponent paySalaryComponent : listPayComponetNotExcp) {
            if (paySalaryComponent.getModelComponent().getSpesific().equals(HRMConstant.MODEL_COMP_UPLOAD)) {
                PayTempUploadData payUpload = this.payTempUploadDataDao
                        .getEntityByEmpIdAndComponentId(empData.getId(), paySalaryComponent.getId());
                if (payUpload != null) {
                    PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                    kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                    kalkulasi.setEmpData(empData);
                    kalkulasi.setPaySalaryComponent(payUpload.getPaySalaryComponent());
                    kalkulasi.setFactor(this
                            .getFactorBasedCategory(payUpload.getPaySalaryComponent().getComponentCategory()));
                    BigDecimal nominal = new BigDecimal(payUpload.getNominalValue());
                    kalkulasi.setNominal(nominal);

                    kalkulasi.setCreatedBy(createdBy);
                    kalkulasi.setCreatedOn(createdOn);
                    datas.add(kalkulasi);

                    totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                    LOGGER.info("Save By Upload - " + payUpload.getPaySalaryComponent().getName()
                            + ", nominal : " + nominal);
                }

            } else if (paySalaryComponent.getModelComponent().getSpesific()
                    .equals(HRMConstant.MODEL_COMP_BASIC_SALARY)) {
                PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                kalkulasi.setEmpData(empData);
                kalkulasi.setPaySalaryComponent(paySalaryComponent);
                kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory()));
                BigDecimal nominal = new BigDecimal(empData.getBasicSalaryDecrypted());
                if ((timeTmb / 30) < 1) {
                    //jika TMB belum memenuhi satu bulan, jadi basic salary dibagi pro-rate
                    nominal = nominal.divide(new BigDecimal(timeTmb), RoundingMode.UP);
                }
                kalkulasi.setNominal(nominal);

                kalkulasi.setCreatedBy(createdBy);
                kalkulasi.setCreatedOn(createdOn);
                datas.add(kalkulasi);

                totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                LOGGER.info("Save By Basic Salary " + (((timeTmb / 30) < 1) ? "Not Full" : "Full")
                        + ", nominal : " + nominal);

            } else if (paySalaryComponent.getModelComponent().getSpesific()
                    .equals(HRMConstant.MODEL_COMP_LOAN)) {
                //cek apakah modelReferensi di paySalaryComponent valid atau tidak
                LoanNewType loanType = loanNewTypeDao
                        .getEntiyByPK((long) paySalaryComponent.getModelReffernsil());
                if (loanType == null) {
                    throw new BussinessException("salaryCalculation.error_salary_component_reference",
                            paySalaryComponent.getName());
                }

                List<LoanNewApplicationInstallment> installments = loanNewApplicationInstallmentDao
                        .getAllDataDisbursedByEmpDataIdAndLoanTypeIdAndPeriodDate(empData.getId(),
                                loanType.getId(), startPeriodDate, endPeriodDate);
                for (LoanNewApplicationInstallment installment : installments) {
                    PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                    kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                    kalkulasi.setEmpData(empData);
                    kalkulasi.setPaySalaryComponent(paySalaryComponent);
                    kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory()));
                    BigDecimal nominal = new BigDecimal(installment.getTotalPayment());
                    nominal = nominal.setScale(0, RoundingMode.UP);
                    kalkulasi.setNominal(nominal);

                    //set detail loan
                    int termin = installment.getLoanNewApplication().getTermin();
                    long cicilanKe = termin - installment.getNumOfInstallment();
                    kalkulasi.setDetail(cicilanKe + "/" + termin);

                    kalkulasi.setCreatedBy(createdBy);
                    kalkulasi.setCreatedOn(createdOn);
                    datas.add(kalkulasi);

                    totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                    LOGGER.info("Save By Loan - " + paySalaryComponent.getName() + ", nominal : " + nominal);
                }

            } else if (paySalaryComponent.getModelComponent().getSpesific()
                    .equals(HRMConstant.MODEL_COMP_REIMBURSEMENT)) {
                //cek apakah modelReferensi di paySalaryComponent valid atau tidak
                RmbsType rmbsType = rmbsTypeDao.getEntiyByPK((long) paySalaryComponent.getModelReffernsil());
                if (rmbsType == null) {
                    throw new BussinessException("salaryCalculation.error_salary_component_reference",
                            paySalaryComponent.getName());
                }

                List<RmbsApplication> reimbursments = rmbsApplicationDao
                        .getAllDataDisbursedByEmpDataIdAndRmbsTypeIdAndPeriodDate(empData.getId(),
                                rmbsType.getId(), startPeriodDate, endPeriodDate);
                for (RmbsApplication reimbursment : reimbursments) {
                    PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                    kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                    kalkulasi.setEmpData(empData);
                    kalkulasi.setPaySalaryComponent(paySalaryComponent);
                    kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory()));
                    kalkulasi.setNominal(reimbursment.getNominal());

                    //set detail reimbursement
                    kalkulasi.setDetail(reimbursment.getCode());

                    kalkulasi.setCreatedBy(createdBy);
                    kalkulasi.setCreatedOn(createdOn);
                    datas.add(kalkulasi);

                    totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                    LOGGER.info("Save By Reimbursment, nominal : " + reimbursment.getNominal());
                }

            } else if (paySalaryComponent.getModelComponent().getSpesific()
                    .equals(HRMConstant.MODEL_COMP_FORMULA)) {
                String formulaOne = paySalaryComponent.getFormula();
                if (formulaOne != null) {
                    jsEngine.put("bS", basicSalary);
                    jsEngine.put("wD", workingDay);
                    jsEngine.put("lT", lessTime);
                    jsEngine.put("mT", moreTime);
                    jsEngine.put("oT", overTIme);
                    jsEngine.put("tD", totalDay);
                    outPut = (Double) jsEngine.eval(formulaOne);

                    PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                    kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                    kalkulasi.setEmpData(empData);
                    kalkulasi.setPaySalaryComponent(paySalaryComponent);
                    kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory()));
                    BigDecimal nominal = new BigDecimal(outPut);
                    kalkulasi.setNominal(nominal);

                    kalkulasi.setCreatedBy(createdBy);
                    kalkulasi.setCreatedOn(createdOn);
                    datas.add(kalkulasi);

                    totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                    LOGGER.info("Save By Formula, nominal : " + nominal);
                }

            } else if (paySalaryComponent.getModelComponent().getSpesific()
                    .equals(HRMConstant.MODEL_COMP_BENEFIT_TABLE)) {
                //cek apakah modelReferensi di paySalaryComponent valid atau tidak
                BenefitGroup benefitGroup = benefitGroupDao
                        .getEntiyByPK((long) paySalaryComponent.getModelReffernsil());
                if (benefitGroup == null) {
                    throw new BussinessException("salaryCalculation.error_salary_component_reference",
                            paySalaryComponent.getName());
                }

                //cek apakah tunjangan yg didapatkan sesuai dengan hak dari golonganJabatan karyawan
                BenefitGroupRate benefitGroupRate = benefitGroupRateDao
                        .getEntityByBenefitGroupIdAndGolJabatanId(benefitGroup.getId(),
                                empData.getGolonganJabatan().getId());
                if (benefitGroupRate != null) {
                    PayTempKalkulasi kalkulasi = new PayTempKalkulasi();
                    kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
                    kalkulasi.setEmpData(empData);
                    kalkulasi.setPaySalaryComponent(paySalaryComponent);
                    kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory()));
                    //nominal untuk benefit dikali nilai dari measurement                        
                    BigDecimal nominal = new BigDecimal(benefitGroupRate.getNominal()).multiply(this
                            .getMultiplierFromMeasurement(benefitGroupRate.getBenefitGroup().getMeasurement()));
                    kalkulasi.setNominal(nominal);

                    //set detail benefit
                    kalkulasi.setDetail(benefitGroupRate.getGolonganJabatan().getCode());

                    kalkulasi.setCreatedBy(createdBy);
                    kalkulasi.setCreatedOn(createdOn);
                    datas.add(kalkulasi);

                    totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary
                    LOGGER.info("Save By Benefit - " + paySalaryComponent.getName() + ", nominal : " + nominal);
                }
            }
        }

        //create totalIncome Kalkulasi, hasil penjumlahan nominal dari semua component di atas
        PayTempKalkulasi totalIncomeKalkulasi = new PayTempKalkulasi();
        totalIncomeKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
        totalIncomeKalkulasi.setEmpData(empData);
        totalIncomeKalkulasi.setPaySalaryComponent(totalIncomeComponent);
        totalIncomeKalkulasi
                .setFactor(this.getFactorBasedCategory(totalIncomeComponent.getComponentCategory()));
        totalIncomeKalkulasi.setNominal(totalIncome);
        totalIncomeKalkulasi.setCreatedBy(createdBy);
        totalIncomeKalkulasi.setCreatedOn(createdOn);
        datas.add(totalIncomeKalkulasi);

        //create initial tax Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya
        PayTempKalkulasi taxKalkulasi = new PayTempKalkulasi();
        taxKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
        taxKalkulasi.setEmpData(empData);
        taxKalkulasi.setPaySalaryComponent(taxComponent);
        taxKalkulasi.setFactor(this.getFactorBasedCategory(taxComponent.getComponentCategory()));
        taxKalkulasi.setNominal(new BigDecimal(0));
        taxKalkulasi.setCreatedBy(createdBy);
        taxKalkulasi.setCreatedOn(createdOn);
        datas.add(taxKalkulasi);

        //create initial ceil Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya 
        PayTempKalkulasi ceilKalkulasi = new PayTempKalkulasi();
        ceilKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12)));
        ceilKalkulasi.setEmpData(empData);
        ceilKalkulasi.setPaySalaryComponent(ceilComponent);
        ceilKalkulasi.setFactor(this.getFactorBasedCategory(ceilComponent.getComponentCategory()));
        ceilKalkulasi.setNominal(new BigDecimal(0));
        ceilKalkulasi.setCreatedBy(createdBy);
        ceilKalkulasi.setCreatedOn(createdOn);
        datas.add(ceilKalkulasi);
    }

    return datas;
}

From source file:org.kuali.coeus.propdev.impl.print.NIHResearchAndRelatedXmlStream.java

private ProposalPersonType getProposalPersonTypeWithValues(DevelopmentProposal developmentProposal,
        ProposalPerson proposalPerson, Budget budget) {
    ProposalPersonType proposalPersonType = ProposalPersonType.Factory.newInstance();
    String degree = getDegree(proposalPerson);
    proposalPersonType.setDegree(degree);
    proposalPersonType.setGraduationYear(getGraduationYear(proposalPerson));
    proposalPersonType.setEmail(proposalPerson.getEmailAddress());
    proposalPersonType.setName(getProposalPersonFullNameType(proposalPerson));
    proposalPersonType.setPhone(proposalPerson.getPhoneNumber());
    if (PROJECT_ROLE_PI.equals(proposalPerson.getProposalPersonRoleId())) {
        proposalPersonType.setProjectRole(ProjectRoleType.PI_PD);
    } else if (PROJECT_ROLE_COI.equals(proposalPerson.getProposalPersonRoleId())) {
        proposalPersonType.setProjectRole(ProjectRoleType.CO_PI_PD);
    } else {/*  w  ww  .  ja  v  a 2  s  .  c  o  m*/
        proposalPersonType.setProjectRole(ProjectRoleType.KEY_PERSON);
    }

    proposalPersonType.setSSN(proposalPerson.getSocialSecurityNumber());
    if (proposalPerson.getDateOfBirth() != null) {
        proposalPersonType.setDOB(getDateTimeService().toDateString(proposalPerson.getDateOfBirth()));
    }

    BigDecimal calendarMonths = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal academicMonths = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal summerMonths = ScaleTwoDecimal.ZERO.bigDecimalValue();
    if (budget != null)
        for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) {
            if (budgetPeriod.getBudgetPeriod().intValue() == 1) {
                for (BudgetLineItem lineItem : budgetPeriod.getBudgetLineItems()) {
                    for (BudgetPersonnelDetails budgetPersonnelDetails : lineItem
                            .getBudgetPersonnelDetailsList()) {
                        if ((proposalPerson.getPersonId() != null
                                && proposalPerson.getPersonId().equals(budgetPersonnelDetails.getPersonId()))
                                || (proposalPerson.getRolodexId() != null && proposalPerson.getRolodexId()
                                        .toString().equals(budgetPersonnelDetails.getPersonId()))) {
                            proposalPersonType.setPercentEffort(
                                    budgetPersonnelDetails.getPercentEffort().bigDecimalValue());
                            proposalPersonType.setRequestedCost(
                                    budgetPersonnelDetails.getSalaryRequested().bigDecimalValue());
                            if (ACADEMIC_PERIOD.equals(budgetPersonnelDetails.getPeriodTypeCode())) {
                                academicMonths = academicMonths.add(budgetPersonnelDetails.getPercentEffort()
                                        .bigDecimalValue().multiply(POINT_ZERO_ONE)
                                        .multiply(getNumberOfMonths(budgetPersonnelDetails.getStartDate(),
                                                budgetPersonnelDetails.getEndDate()).bigDecimalValue()));
                            } else if (CALENDAR_PERIOD.equals(budgetPersonnelDetails.getPeriodTypeCode())) {
                                calendarMonths = calendarMonths.add(budgetPersonnelDetails.getPercentEffort()
                                        .bigDecimalValue().multiply(POINT_ZERO_ONE)
                                        .multiply(getNumberOfMonths(budgetPersonnelDetails.getStartDate(),
                                                budgetPersonnelDetails.getEndDate()).bigDecimalValue()));
                            } else
                                summerMonths = summerMonths.add(budgetPersonnelDetails.getPercentEffort()
                                        .bigDecimalValue().multiply(POINT_ZERO_ONE)
                                        .multiply(getNumberOfMonths(budgetPersonnelDetails.getStartDate(),
                                                budgetPersonnelDetails.getEndDate()).bigDecimalValue()));
                        }
                    }
                }
            }
        }
    proposalPersonType.setAcademicFundingMonths(academicMonths.setScale(2, RoundingMode.HALF_UP));
    proposalPersonType.setSummerFundingMonths(summerMonths.setScale(2, RoundingMode.HALF_UP));
    proposalPersonType.setFundingMonths(calendarMonths.setScale(2, RoundingMode.HALF_UP));
    return proposalPersonType;
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

/**
 * Update demand details of current or latest year data on renewal. Assumption: There is no partial payment collected for
 * selected year./* w ww .  ja v a  2 s  . c o m*/
 *
 * @param advertisementPermitDetail
 * @param demand
 * @return
 */
public EgDemand updateDemandOnRenewal(final AdvertisementPermitDetail advertisementPermitDetail,
        final EgDemand demand) {

    if (demand != null) {

        final List<EgDemandDetails> removableDemandDetailList = new ArrayList<>();
        final Installment installment = demand.getEgInstallmentMaster();

        BigDecimal totalDemandAmount = BigDecimal.ZERO;

        Boolean enchroachmentFeeAlreadyExistInDemand = false;

        /*
         * EgDemandReason pendingTaxReason = getDemandReasonByCodeAndInstallment(
         * AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment);
         */
        final EgDemandReason encroachmentFeeReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment);
        final EgDemandReason taxReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX, installment);

        for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails()) {
            // Assumption: tax amount is mandatory.
            if (dmdDtl.getEgDemandReason().getId() == taxReason.getId()
                    && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) >= 0) {
                totalDemandAmount = totalDemandAmount
                        .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount()));
                dmdDtl.setAmount(
                        advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP));
            }
            /*
             * if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId() &&
             * advertisementPermitDetail.getAdvertisement().getPendingTax()!=null &&
             * advertisementPermitDetail.getAdvertisement().getPendingTax().compareTo(BigDecimal.ZERO) > 0) { // TODO: Also
             * check whether fully collected ? totalDemandAmount =
             * totalDemandAmount.add(advertisementPermitDetail.getAdvertisement().getPendingTax().subtract(dmdDtl.getAmount())
             * ); dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0,
             * BigDecimal.ROUND_HALF_UP)); }
             */
            // Encroachment fee may not mandatory. If already part of demand
            if (dmdDtl.getEgDemandReason().getId() == encroachmentFeeReason.getId()) {
                enchroachmentFeeAlreadyExistInDemand = true;
                if (advertisementPermitDetail.getEncroachmentFee() != null
                        && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
                    totalDemandAmount = totalDemandAmount
                            .add(advertisementPermitDetail.getEncroachmentFee().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(advertisementPermitDetail.getEncroachmentFee().setScale(0,
                            BigDecimal.ROUND_HALF_UP));

                    // update encroachment fee..
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    // demand.removeEgDemandDetails(dmdDtl);
                    removableDemandDetailList.add(dmdDtl);
                    // delete demand detail
                }

            }
        }

        if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null
                && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(
                    createDemandDetails(advertisementPermitDetail.getEncroachmentFee(),
                            getDemandReasonByCodeAndInstallment(
                                    AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment),
                            BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee());
        }
        for (final EgDemandDetails removableDmdDtl : removableDemandDetailList)
            demand.removeEgDemandDetails(removableDmdDtl);
        demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    }
    return demand;

}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

/**
 * This method used to get API from governance artifact specific to copyAPI
 *
 * @param artifact API artifact//from   w w w .  ja v  a2  s  . c  o  m
 * @param registry Registry
 * @return API
 * @throws APIManagementException if failed to get API from artifact
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext)
        throws APIManagementException {

    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        api = new API(new APIIdentifier(providerName, apiName, apiVersion));
        int apiId = ApiMgtDAO.getInstance().getAPIID(oldId, null);
        if (apiId == -1) {
            return null;
        }
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath));
        BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
        api.setRating(res.floatValue());
        //set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        //set last access time
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        //set uuid
        api.setUUID(artifact.getId());
        // set url
        api.setStatus(getApiStatus(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setEndpointSecured(
                Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(
                Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));

        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));

        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(
                Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));

        api.setSubscriptionAvailability(
                artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(
                artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));

        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));

        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomainName);

        boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled();

        if (isGlobalThrottlingEnabled) {
            String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
            api.setApiLevelPolicy(apiLevelTier);
        }

        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
        api.addAvailableTiers(availableTier);

        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        ArrayList<URITemplate> urlPatternsList;

        Set<Scope> scopes = ApiMgtDAO.getInstance().getAPIScopes(oldId);
        api.setScopes(scopes);

        HashMap<String, String> resourceScopes;
        resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(oldId);

        urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);

        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
            String resourceScopeKey = APIUtil.getResourceKey(oldContext, oldId.getVersion(),
                    uriTemplate.getUriTemplate(), uriTemplate.getHTTPVerb());
            uriTemplate.setScope(findScopeByKey(scopes, resourceScopes.get(resourceScopeKey)));

        }
        api.setUriTemplates(uriTemplates);

        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.addTags(tags);
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        api.setAsDefaultVersion(
                Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));

        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));

    } catch (GovernanceException e) {
        String msg = "Failed to get API fro artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    }
    return api;
}