Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:com.nkapps.billing.dao.PaymentDaoImpl.java

@Override
public void saveKeyPaymentAndTransaction(BigDecimal keyTransactionId, BigDecimal keyCost) throws Exception {
    Session session = getSession();/* ww w .j  a v a 2  s  .  c  o m*/
    Transaction transaction = session.beginTransaction();

    LocalDateTime dateTime = LocalDateTime.now();

    KeyTransaction ktr = (KeyTransaction) session.get(KeyTransaction.class, keyTransactionId);
    String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
            + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
            + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
            + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
            + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
            + " FROM Payment p " + " WHERE p.tin = :tin AND p.state IN (1,2) AND p.claim = 0"
            + " ORDER BY p.paymentDate, p.paymentNum ";
    Query query = session.createQuery(q);
    query.setParameter("tin", ktr.getTin());

    query.setResultTransformer(Transformers.aliasToBean(Payment.class));
    List<Payment> paymentList = query.list();

    for (Payment payment : paymentList) {

        if (payment.getOverSum().compareTo(keyCost) <= 0) {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(payment.getOverSum());
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 3);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = keyCost.subtract(payment.getOverSum());
        } else {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(keyCost);
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 2);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = BigDecimal.ZERO;
        }
        if (keyCost.compareTo(BigDecimal.ZERO) <= 0) {
            break;
        }
    }
    ktr.setCommitted((short) 1);
    ktr.setDateUpdated(dateTime);
    session.update(ktr);

    transaction.commit();
    session.close();
}

From source file:com.rcv.ResultsWriter.java

private void generateSummarySpreadsheet(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct,
        String outputPath) throws IOException {
    String csvPath = outputPath + ".csv";
    Logger.log(Level.INFO, "Generating summary spreadsheets: %s...", csvPath);

    // Get all candidates sorted by their first round tally. This determines the display order.
    // container for firstRoundTally
    Map<String, BigDecimal> firstRoundTally = roundTallies.get(1);
    // candidates sorted by first round tally
    List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally);

    // totalActiveVotesPerRound is a map of round to total votes cast in each round
    Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>();
    // round indexes over all rounds plus final results round
    for (int round = 1; round <= numRounds; round++) {
        // tally is map of candidate to tally for the current round
        Map<String, BigDecimal> tallies = roundTallies.get(round);
        // total will contain total votes for all candidates in this round
        // this is used for calculating other derived data
        BigDecimal total = BigDecimal.ZERO;
        // tally indexes over all tallies for the current round
        for (BigDecimal tally : tallies.values()) {
            total = total.add(tally);//from w  ww  . ja v  a2s .c  om
        }
        totalActiveVotesPerRound.put(round, total);
    }

    // csvPrinter will be used to write output to csv file
    CSVPrinter csvPrinter;
    try {
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath));
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s", csvPath, exception.toString());
        throw exception;
    }

    // print contest info
    addHeaderRows(csvPrinter, precinct);

    // add a row header for the round column labels
    csvPrinter.print("Rounds");
    // round indexes over all rounds
    for (int round = 1; round <= numRounds; round++) {
        // label string will have the actual text which goes in the cell
        String label = String.format("Round %d", round);
        // cell for round label
        csvPrinter.print(label);
    }
    csvPrinter.println();

    // actions don't make sense in individual precinct results
    if (precinct == null || precinct.isEmpty()) {
        addActionRows(csvPrinter);
    }

    final BigDecimal totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1);

    // For each candidate: for each round: output total votes
    // candidate indexes over all candidates
    for (String candidate : sortedCandidates) {
        // show each candidate row with their totals for each round
        // text for the candidate name
        String candidateDisplayName = this.config.getNameForCandidateID(candidate);
        csvPrinter.print(candidateDisplayName);

        // round indexes over all rounds
        for (int round = 1; round <= numRounds; round++) {
            // vote tally this round
            BigDecimal thisRoundTally = roundTallies.get(round).get(candidate);
            // not all candidates may have a tally in every round
            if (thisRoundTally == null) {
                thisRoundTally = BigDecimal.ZERO;
            }
            // total votes cell
            csvPrinter.print(thisRoundTally.toString());
        }
        // advance to next line
        csvPrinter.println();
    }

    // row for the inactive CVR counts
    // inactive CVR header cell
    csvPrinter.print("Inactive ballots");

    // round indexes through all rounds
    for (int round = 1; round <= numRounds; round++) {
        // count of votes inactive this round
        BigDecimal thisRoundInactive = BigDecimal.ZERO;

        if (round > 1) {
            // Exhausted count is the difference between the total votes in round 1 and the total votes
            // in the current round.
            thisRoundInactive = totalActiveVotesFirstRound.subtract(totalActiveVotesPerRound.get(round))
                    .subtract(roundToResidualSurplus.get(round));
        }
        // total votes cell
        csvPrinter.print(thisRoundInactive.toString());
    }
    csvPrinter.println();

    // row for residual surplus (if needed)
    // We check if we accumulated any residual surplus over the course of the tabulation by testing
    // whether the value in the final round is positive.
    if (roundToResidualSurplus.get(numRounds).signum() == 1) {
        csvPrinter.print("Residual surplus");
        for (int round = 1; round <= numRounds; round++) {
            csvPrinter.print(roundToResidualSurplus.get(round).toString());
        }
        csvPrinter.println();
    }

    // write xls to disk
    try {
        // output stream is used to write data to disk
        csvPrinter.flush();
        csvPrinter.close();
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString());
        throw exception;
    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.OlePurchaseOrderAction.java

/**
 * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  ww w.  j a va  2s  . c o m
@Override
public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
    PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;

    // index of item selected
    int itemIndex = getSelectedLine(request);
    PurApItem item = null;

    // if custom processing of an accounting line is not done then insert a line generically.
    if (processCustomInsertAccountingLine(purapForm, request) == false) {
        String errorPrefix = null;
        PurApAccountingLine line = null;

        boolean rulePassed = false;
        if (itemIndex >= 0) {
            item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
            //Calculating the dollar amount for the accounting Line.
            PurApAccountingLine lineItem = item.getNewSourceLine();
            if (lineItem.getAccountLinePercent() != null) {
                BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
            } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) {
                KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                BigDecimal dollarToPercent = dollar.bigDecimalValue()
                        .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                lineItem.setAccountLinePercent(dollarToPercent);
            }
            line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
            //end
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "["
                    + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        } else if (itemIndex == -2) {
            //corrected: itemIndex == -2 is the only case for distribute account
            //This is the case when we're inserting an accounting line for distribute account.
            line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        }
        AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
        if (accountingLineBase != null) {
            String accountNumber = accountingLineBase.getAccountNumber();
            String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
            Map<String, String> criteria = new HashMap<String, String>();
            criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
            criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
            Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
                    criteria);
            rulePassed = checkForValidAccount(account);
        }
        if (rulePassed) {
            // add accountingLine
            SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);

            PurApAccountingLine newSourceLine = item.getNewSourceLine();
            List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();

            BigDecimal initialValue = new BigDecimal(0);

            for (PurApAccountingLine accountLine : existingSourceLine) {
                initialValue = initialValue.add(accountLine.getAccountLinePercent());
            }
            if (itemIndex >= 0) {

                if ((newSourceLine.getAccountLinePercent()
                        .intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED
                        && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT
                                .subtract(initialValue).intValue())
                        && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
                    if (OleSelectConstant.MAX_PERCENT.subtract(initialValue)
                            .intValue() != OleSelectConstant.ZERO) {
                        insertAccountingLine(purapForm, item, line);
                    }
                } else {
                    checkAccountingLinePercent(newSourceLine);

                }
                for (PurApAccountingLine oldSourceAccountingLine : item.getSourceAccountingLines()) {
                    if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) {
                        ((OlePurchaseOrderAccount) oldSourceAccountingLine)
                                .setExistingAmount(oldSourceAccountingLine.getAmount());
                    }
                }
                List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
                BigDecimal totalPercent = new BigDecimal(100);
                BigDecimal initialPercent = new BigDecimal(0);
                for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
                    initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());

                }
                initialPercent = totalPercent.subtract(initialPercent);
                BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
                if (maxPercent.intValue() == OleSelectConstant.ZERO) {
                    item.resetAccount(OleSelectConstant.ZERO_PERCENT);

                } else {
                    item.resetAccount(initialPercent);

                }
            } else if (itemIndex == -2) {
                //this is the case for distribute account
                ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
            }
        }
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:org.kuali.kpme.tklm.time.rules.overtime.weekly.service.WeeklyOvertimeRuleServiceImpl.java

protected BigDecimal applyPositiveOvertimeOnTimeBlockNew(TimeBlockBo timeBlock, String overtimeEarnCode,
        Set<String> convertFromEarnCodes, BigDecimal overtimeHours) {
    BigDecimal applied = BigDecimal.ZERO;
    List<TimeHourDetailBo> timeHourDetails = timeBlock.getTimeHourDetails();
    List<TimeHourDetailBo> newTimeHourDetails = new ArrayList<TimeHourDetailBo>();

    LOG.info("INITIAL block; " + timeBlock.getTkTimeBlockId() + "overtimeHours = " + overtimeHours
            + " overall timeblock hours = " + timeBlock.getHours() + " earnCode = " + timeBlock.getEarnCode()
            + " OT = " + overtimeEarnCode + " convertFrom = " + convertFromEarnCodes + " startDate = "
            + timeBlock.getBeginDateTime());
    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        LOG.info("EC = " + timeHourDetail.getEarnCode() + " hours = " + timeHourDetail.getHours());
    }/*from ww  w  .j  a  va 2 s .co m*/

    Boolean timeBlockHasOt = false;
    for (TimeHourDetailBo tmpDetail : timeBlock.getTimeHourDetails()) {
        if (tmpDetail.getEarnCode().equals(overtimeEarnCode)) {
            timeBlockHasOt = true;
        }
    }

    Boolean changeMade = false;

    BigDecimal toApply = BigDecimal.ZERO;
    toApply = toApply.add(timeBlock.getHours());

    BigDecimal otApplied = BigDecimal.ZERO;

    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        if (convertFromEarnCodes.contains(timeHourDetail.getEarnCode())) {

            changeMade = true;
            if (overtimeHours.compareTo(timeHourDetail.getHours()) >= 0) {
                applied = timeHourDetail.getHours();
            } else {
                applied = overtimeHours;
            }

            EarnCodeContract earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(overtimeEarnCode,
                    timeBlock.getEndDateTime().toLocalDate());
            BigDecimal hours = earnCodeObj.getInflateFactor().multiply(applied, HrConstants.MATH_CONTEXT)
                    .setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP);

            TimeHourDetailBo overtimeTimeHourDetail = getTimeHourDetailByEarnCode(timeHourDetails,
                    Collections.singletonList(overtimeEarnCode));
            if (overtimeTimeHourDetail != null) {
                overtimeTimeHourDetail.setHours(hours);
                toApply = toApply.subtract(hours);
                otApplied = otApplied.add(hours);
            } else {
                TimeHourDetailBo newTimeHourDetail = new TimeHourDetailBo();
                newTimeHourDetail.setTkTimeBlockId(timeBlock.getTkTimeBlockId());
                newTimeHourDetail.setEarnCode(overtimeEarnCode);
                newTimeHourDetail.setHours(hours);

                newTimeHourDetails.add(newTimeHourDetail);
                toApply = toApply.subtract(hours);

                otApplied = otApplied.add(hours);
            }

            //                timeHourDetail.setHours(timeBlock.getHours().subtract(hours));
            /*
                            BigDecimal newHours = null;
                            if (toApply.compareTo(timeHourDetail.getHours()) >= 0 )
                            {
                            }
                            else {
            newHours = toApply.setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP);
                            }
            */
            BigDecimal newHours = toApply;
            if (newHours.compareTo(timeHourDetail.getHours()) >= 0) {
                newHours = timeHourDetail.getHours();
            }
            timeHourDetail.setHours(newHours);
            toApply = toApply.subtract(newHours);

            //timeHourDetail.setHours(timeHourDetail.getHours().subtract(applied, HrConstants.MATH_CONTEXT).setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP)   );

            /*
            if (timeBlockHasOt)
            {
            timeHourDetail.setHours(applied.setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP));
            }
            else
            {
            timeHourDetail.setHours(timeHourDetail.getHours().subtract(applied, HrConstants.MATH_CONTEXT).setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP));
            }
            */
        } else if (!timeHourDetail.getEarnCode().equals(overtimeEarnCode)) {
            toApply = toApply.subtract(timeHourDetail.getHours());
        }
    }

    for (TimeHourDetailBo newTimeHourDetail : newTimeHourDetails) {
        timeBlock.addTimeHourDetail(newTimeHourDetail);
    }
    LOG.info("COMPLETE block; " + timeBlock.getTkTimeBlockId() + " overall timeblock hours = "
            + timeBlock.getHours() + " earnCode = " + timeBlock.getEarnCode() + " OT = " + overtimeEarnCode
            + " convertFrom = " + convertFromEarnCodes);
    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        LOG.info("EC = " + timeHourDetail.getEarnCode() + " hours = " + timeHourDetail.getHours());
    }

    LOG.info("OT applied = " + otApplied);
    return overtimeHours.subtract(otApplied);
    /*
            if (changeMade)
            {
            }
            else
            {
    return overtimeHours;
            }
            */
}

From source file:com.ccserver.digital.service.LOSService.java

private CustomerInfoType getCustomerInfoType(CreditCardApplicationDTO dto) {
    CustomerInfoType customerInfo = new CustomerInfoType();
    customerInfo.setFirstName(dto.getFirstName());
    customerInfo.setLastName(dto.getLastName());
    customerInfo.setMidName(dto.getMiddleName());

    customerInfo.setFullName(getFullName(dto));
    customerInfo.setCustomerType(getConfiguration("LOS_PCARD", "NORMAL"));

    IDInfoType idInfo = new IDInfoType();
    switch (dto.getTypeOfID()) {
    case Passport:
        idInfo.setIDType(getConfiguration("LOS_PV", "PV"));
        break;//w  w  w  .  j a va2  s .c  o m
    case NationalID:
        idInfo.setIDType(getConfiguration("LOS_IDTYPE_IC", "IC"));
        break;
    }
    idInfo.setIDNo(dto.getPassportNumber());
    idInfo.setIDIssueDate(dateToXMLGregorianCalendar(dto.getDateOfIssue()));

    if (dto.getPlaceOfIssue() != null) {
        idInfo.setIDIssueBy(dto.getPlaceOfIssue().getCode());
    }

    CountryDTO citizenship = dto.getCitizenship();
    if (citizenship != null) {
        customerInfo.setNationality(citizenship.getIsoCode());
        idInfo.setCountry(citizenship.getCode());
        if (!"+84".equalsIgnoreCase(citizenship.getCode())) {
            idInfo.setIDIssueBy(getConfiguration("LOS_ID_ISSUE_BY_FOREIGNER", "Cuc quan ly xuat nhap canh"));
        }
    }

    customerInfo.getIDInfo().add(idInfo);

    if (!StringUtils.isEmpty(dto.getLicenseNumber())) {
        IDInfoType licenseNumberInfo = new IDInfoType();
        licenseNumberInfo.setIDType(getConfiguration("LOS_IDTYPE_BSL", "BSL"));
        licenseNumberInfo.setIDNo(dto.getLicenseNumber());
        customerInfo.getIDInfo().add(licenseNumberInfo);
    }

    ContactInfoType contactInfo = new ContactInfoType();
    PhoneInfoType phoneInfoMobile = new PhoneInfoType();
    phoneInfoMobile.setPhoneNo(getPhoneNumber(dto.getMobile()));
    phoneInfoMobile.setPhoneType(getConfiguration("LOS_PHONETYPE", "mobiphone"));
    contactInfo.getPhoneInfo().add(phoneInfoMobile);

    // TODO check with UI design (aLy)
    PhoneInfoType workPhone = new PhoneInfoType();
    workPhone.setPhoneNo(getPhoneNumber(dto.getMobile()));
    workPhone.setPhoneType(getConfiguration("LOS_WORKPHONETYPE", "workphone"));
    contactInfo.getPhoneInfo().add(workPhone);

    AddressDTO currentAddressDto = dto.getCurrentAddress();
    if (dto.isCurrentIsPermanent()) {
        currentAddressDto = dto.getPermanentAddress();
    }
    String totalMonthsLiving = getDurationFormat(dto.getMonthsOfLiving(), dto.getYearsOfLiving());
    LocalDateTime startLivingTime = LocalDateTime.now().minusMonths(Integer.parseInt(totalMonthsLiving));
    AddressInfoType currentAddress = getAddressInfoType(currentAddressDto);
    currentAddress.setStartDate(dateToXMLGregorianCalendar(startLivingTime));
    currentAddress.setDuration(totalMonthsLiving);
    currentAddress.setIsPermanent(
            dto.isCurrentIsPermanent() ? getConfiguration("LOS_YES", "Y") : getConfiguration("LOS_NO", "N"));
    contactInfo.setAddressInfo(currentAddress);

    contactInfo.setMailAddress(dto.getEmail());
    AddressInfoType permanentAddress = getAddressInfoType(dto.getPermanentAddress());
    permanentAddress.setStartDate(dateToXMLGregorianCalendar(startLivingTime));
    permanentAddress.setDuration(totalMonthsLiving);
    permanentAddress.setIsPermanent(dto.isCurrentIsPermanent() ? "Y" : "N");
    contactInfo.setPermanentAddressInfo(permanentAddress);

    customerInfo.setContactInfo(contactInfo);

    switch (dto.getGender()) {
    case Male:
        customerInfo.setGender(getConfiguration("LOS_MALE", "M"));
        break;
    case Female:
        customerInfo.setGender(getConfiguration("LOS_FEMALE", "F"));
        break;
    }

    customerInfo.setBirthday(dateToXMLGregorianCalendar(dto.getDob()));

    SelectionListDTO education = dto.getEducation();
    if (education != null) {
        customerInfo.setEducation(education.getCode());
    }

    SelectionListDTO maritalStatus = dto.getMaritalStatus();
    if (maritalStatus != null) {
        customerInfo.setMaritalStatus(maritalStatus.getCode());
    }

    if (dto.getNumberOfChildren() != null) {
        customerInfo.setNumberOfChildren(dto.getNumberOfChildren().toString());
    }
    customerInfo.setSector(getConfiguration("LOS_SECTOR", "1001"));
    customerInfo.setSegments(getConfiguration("LOS_KHCN", "SEG1"));
    // pass FT because risk from los
    customerInfo.setEmploymentStatus(getConfiguration("LOS_FT", "FT"));
    // customerInfo.setEmploymentStatus(dto.getTypeOfEmployement().equals(TypeOfEmployement.Business)
    // ? "BO" : "FT");

    FrequencyInfoType incomeFrequency = new FrequencyInfoType();
    incomeFrequency.setType(getConfiguration("LOS_IC", "INC2"));
    incomeFrequency.setFrequency(getConfiguration("LOS_FREQUENCY", "M"));
    AmountType amountType = new AmountType();
    BigDecimal monthlyIncome = dto.getMonthlyIncome();
    if (monthlyIncome != null) {
        amountType.setAmount(monthlyIncome.toString());
    }
    amountType.setCurrency(getConfiguration("LOS_VND", "VND"));
    incomeFrequency.setAmount(amountType);
    incomeFrequency.setMonthlyAmount(amountType);
    incomeFrequency.setTotalMonthlyAmount(amountType);
    customerInfo.setIncomeFrequency(incomeFrequency);

    FrequencyInfoType expenseFrequency = new FrequencyInfoType();
    expenseFrequency.setType(getConfiguration("LOS_FREQUENCY_TYPE", "EXP1"));
    expenseFrequency.setFrequency(getConfiguration("LOS_FREQUENCY", "M"));
    AmountType exAmountType = new AmountType();
    exAmountType.setAmount(dto.getMonthlyExpenses() + "");
    exAmountType.setCurrency(getConfiguration("LOS_VND", "VND"));
    expenseFrequency.setAmount(exAmountType);
    expenseFrequency.setMonthlyAmount(exAmountType);
    expenseFrequency.setTotalMonthlyAmount(exAmountType);
    customerInfo.setExpenseFrequency(expenseFrequency);
    FrequencyInfoType netFrequency = new FrequencyInfoType();
    AmountType netAmountType = new AmountType();
    if (monthlyIncome != null) {
        netAmountType.setAmount(monthlyIncome.subtract(
                dto.getMonthlyExpenses() != null ? dto.getMonthlyExpenses() : BigDecimal.valueOf(0L)) + "");
    }
    netFrequency.setAmount(netAmountType);
    netFrequency.setMonthlyAmount(netAmountType);
    netFrequency.setTotalMonthlyAmount(netAmountType);
    customerInfo.setNetFrequency(netFrequency);

    customerInfo.setGreenCard(String.valueOf(convertBooleanToString(dto.isHaveGreenCard())));
    customerInfo.setTinNumber(StringUtils.isEmpty(dto.getTinNumber()) ? "0" : dto.getTinNumber());
    customerInfo.setGLPNumber(dto.getGlpNumber());
    return customerInfo;
}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.Reconciliation.java

private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strOrgId,
        String strWindowId, String strTabId, String strFinancialAccountId, String strStatementDate,
        String strEndBalance) throws IOException, ServletException {

    log4j.debug("Output: Reconcile button pressed on Financial Account || Transaction tab");

    dao = new AdvPaymentMngtDao();
    String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    SimpleDateFormat dateFormater = new SimpleDateFormat(dateFormat);

    FIN_Reconciliation currentReconciliation = null;
    OBContext.setAdminMode();//from  www .j a v  a  2  s .co m
    try {
        FIN_FinancialAccount account = OBDal.getInstance().get(FIN_FinancialAccount.class,
                strFinancialAccountId);

        FIN_Reconciliation lastProcessedReconciliation = TransactionsDao.getLastReconciliation(account, "Y");
        currentReconciliation = TransactionsDao.getLastReconciliation(account, "N");
        if (isAutomaticReconciliation(currentReconciliation)) {
            OBDal.getInstance().rollbackAndClose();
            OBError message = Utility.translateError(this, vars, vars.getLanguage(),
                    Utility.parseTranslation(this, vars, vars.getLanguage(), "@APRM_ReconciliationMixed@"));
            vars.setMessage(strTabId, message);
            printPageClosePopUp(response, vars, Utility.getTabURL(strTabId, "R", true));
            return;
        }

        XmlDocument xmlDocument = xmlEngine
                .readXmlTemplate("org/openbravo/advpaymentmngt/ad_actionbutton/Reconciliation")
                .createXmlDocument();

        xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
        xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
        xmlDocument.setParameter("theme", vars.getTheme());

        xmlDocument.setParameter("dateDisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
        xmlDocument.setParameter("mainDate", DateTimeData.today(this));
        xmlDocument.setParameter("windowId", strWindowId);
        xmlDocument.setParameter("tabId", strTabId);
        xmlDocument.setParameter("orgId", strOrgId);
        xmlDocument.setParameter("finFinancialAccountId", strFinancialAccountId);

        BigDecimal currentEndBalance = BigDecimal.ZERO;
        if (vars.commandIn("PROCESS")) {
            xmlDocument.setParameter("statementDate", strStatementDate);
            xmlDocument.setParameter("endBalance", strEndBalance);
            xmlDocument.setParameter("calcEndingBalance", strEndBalance);

        } else {
            String currentStatementDate = DateTimeData.today(this);
            if (currentReconciliation != null) {
                currentStatementDate = dateFormater.format(currentReconciliation.getTransactionDate());
                currentEndBalance = currentReconciliation.getEndingBalance();
            }
            xmlDocument.setParameter("statementDate", currentStatementDate);
            xmlDocument.setParameter("endBalance", currentEndBalance.toString());
            xmlDocument.setParameter("calcEndingBalance", currentEndBalance.toString());
        }

        BigDecimal beginBalance = (lastProcessedReconciliation == null) ? account.getInitialBalance()
                : lastProcessedReconciliation.getEndingBalance();

        xmlDocument.setParameter("account", account.getName());
        xmlDocument.setParameter("beginBalance", beginBalance.toString());

        // Hidden inputs
        xmlDocument.setParameter("calcBeginningBalance", beginBalance.toString());
        xmlDocument.setParameter("calcTotalPayment", BigDecimal.ZERO.toString());
        xmlDocument.setParameter("calcTotalDeposit", BigDecimal.ZERO.toString());
        xmlDocument.setParameter("calcDifferenceToClear", currentEndBalance.subtract(beginBalance).toString());
        xmlDocument.setParameter("calcCurrentlyCleared",
                TransactionsDao.getCurrentlyClearedAmt(account.getId()).toString());
        xmlDocument.setParameter("calcDifference",
                currentEndBalance
                        .subtract(beginBalance.add(TransactionsDao.getCurrentlyClearedAmt(account.getId())))
                        .toString());

        OBContext.setAdminMode();
        try {
            xmlDocument.setParameter("precision", account.getCurrency().getStandardPrecision().toString());

            if (currentReconciliation == null) {
                DocumentType docType = FIN_Utility.getDocumentType(account.getOrganization(), "REC");
                if (docType == null) {
                    OBError msg = new OBError();
                    String strMessage = "@APRM_DocumentTypeNotFound@";
                    msg.setType("Error");
                    msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
                    msg.setMessage(Utility.parseTranslation(this, vars, vars.getLanguage(), strMessage));
                    vars.setMessage(strTabId, msg);
                    msg = null;
                    printPageClosePopUpAndRefreshParent(response, vars);
                    return;
                }
                String docNumber = FIN_Utility.getDocumentNo(account.getOrganization(), "REC",
                        "DocumentNo_FIN_Reconciliation");

                dao.getNewReconciliation(account.getOrganization(), account, docNumber, docType, new Date(),
                        new Date(), beginBalance, BigDecimal.ZERO, "DR");
            }
        } finally {
            OBContext.restorePreviousMode();
        }

        OBError myMessage = vars.getMessage(strWindowId);
        vars.removeMessage(strWindowId);
        if (myMessage != null) {
            xmlDocument.setParameter("messageType", myMessage.getType());
            xmlDocument.setParameter("messageTitle", myMessage.getTitle());
            xmlDocument.setParameter("messageMessage", myMessage.getMessage());
        }

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(xmlDocument.print());
        out.close();
    } catch (Exception e) {
        throw new OBException(e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.yccheok.jstock.gui.NewSellTransactionJDialog.java

private List<Transaction> generateTransactions() {
    if (this.sellTransaction != null && this.buyTransactions.size() > 0) {
        throw new java.lang.UnsupportedOperationException(
                "You cannot sell transaction and edit transaction at the same time");
    }// ww  w .jav a  2 s.c  om

    final List<Transaction> transactions = new ArrayList<Transaction>();

    if (this.sellTransaction != null) {
        // Editing...

        final DateField dateField = (DateField) jPanel3;
        final SimpleDate date = new SimpleDate((Date) dateField.getValue());
        final double unit = ((java.lang.Double) this.jSpinner1.getValue());
        final double price = ((Double) this.jFormattedTextField1.getValue());
        Contract.ContractBuilder builder = new Contract.ContractBuilder(this.sellTransaction.getStock(), date);
        final Contract oldContract = this.sellTransaction.getContract();
        final Contract contract = builder.type(type).quantity(unit).price(price)
                .referencePrice(oldContract.getReferencePrice())
                .referenceBroker(oldContract.getReferenceBroker())
                .referenceClearingFee(oldContract.getReferenceClearingFee())
                .referenceStampDuty(oldContract.getReferenceStampDuty())
                .referenceDate(oldContract.getReferenceDate()).build();

        final double brokerFeeValue = (Double) this.jFormattedTextField4.getValue();
        final double stampDutyValue = (Double) jFormattedTextField7.getValue();
        final double clearingFeeValue = (Double) this.jFormattedTextField5.getValue();

        Transaction t = new Transaction(contract, brokerFeeValue, stampDutyValue, clearingFeeValue);
        t.setComment(this.sellTransaction.getComment());
        transactions.add(t);
    } else {
        final DateField dateField = (DateField) jPanel3;
        final SimpleDate date = new SimpleDate((Date) dateField.getValue());
        final double unit = ((java.lang.Double) this.jSpinner1.getValue());
        final double price = ((Double) this.jFormattedTextField1.getValue());
        final double brokerFee = (Double) this.jFormattedTextField4.getValue();
        final double stampDuty = (Double) jFormattedTextField7.getValue();
        final double clearingFee = (Double) this.jFormattedTextField5.getValue();

        // Use BigDecimal, for precision purpose. Please refer to Effective Java,
        // Item 48: Avoid float and double if exact answers are required            
        BigDecimal quantity = new BigDecimal(unit);
        boolean shouldBreakInNextRound = false;

        int i = 0;
        BigDecimal totalBrokerFee = new BigDecimal(0);
        BigDecimal totalStampDuty = new BigDecimal(0);
        BigDecimal totalClearingFee = new BigDecimal(0);

        for (Transaction buyTransaction : this.buyTransactions) {
            i++;

            if (shouldBreakInNextRound) {
                break;
            }

            double realTransactionQuantity = 0.0;
            if (quantity.doubleValue() >= buyTransaction.getQuantity()) {
                realTransactionQuantity = buyTransaction.getQuantity();
                quantity = quantity.subtract(new BigDecimal(buyTransaction.getQuantity()));
            } else {
                realTransactionQuantity = quantity.doubleValue();
                quantity = BigDecimal.ZERO;
                shouldBreakInNextRound = true;

                // 0 quantity. Break early.
                if (false == org.yccheok.jstock.portfolio.Utils.definitelyGreaterThan(realTransactionQuantity,
                        0)) {
                    break;
                }
            }

            Contract.ContractBuilder builder = new Contract.ContractBuilder(buyTransaction.getStock(), date);
            final double referenceBroker = buyTransaction.getBroker();
            final double referenceClearingFee = buyTransaction.getClearingFee();
            final double referenceStampDuty = buyTransaction.getStampDuty();
            final double goodReferenceBroker = getGoodCurrencyDouble(referenceBroker, realTransactionQuantity,
                    buyTransaction.getQuantity());
            final double goodReferenceClearingFee = getGoodCurrencyDouble(referenceClearingFee,
                    realTransactionQuantity, buyTransaction.getQuantity());
            final double goodReferenceStampDuty = getGoodCurrencyDouble(referenceStampDuty,
                    realTransactionQuantity, buyTransaction.getQuantity());

            final Contract contract = builder.type(type).quantity(realTransactionQuantity).price(price)
                    .referencePrice(buyTransaction.getPrice()).referenceBroker(goodReferenceBroker)
                    .referenceClearingFee(goodReferenceClearingFee).referenceStampDuty(goodReferenceStampDuty)
                    .referenceDate(buyTransaction.getDate()).build();

            // Do not use the following code, as our objective is
            // 1) Sum of individual transactions' fee must be equal to 
            // transaction summary's fee.
            // 2) Three decimal places.
            // 
            //final double brokerFeeValue = brokerFee * realTransactionQuantity / unit;
            //final double stampDutyValue = stampDuty * realTransactionQuantity / unit;
            //final double clearingFeeValue = clearingFee * realTransactionQuantity / unit;

            // Use BigDecimal, for precision purpose. Please refer to Effective Java,
            // Item 48: Avoid float and double if exact answers are required                
            BigDecimal brokerFeeBigDecimal;
            BigDecimal stampDutyBigDecimal;
            BigDecimal clearingFeeBigDecimal;
            // Is this last item?
            if (i != buyTransactions.size()) {
                brokerFeeBigDecimal = getGoodCurrencyBigDecimal(brokerFee, realTransactionQuantity, unit);
                stampDutyBigDecimal = getGoodCurrencyBigDecimal(stampDuty, realTransactionQuantity, unit);
                clearingFeeBigDecimal = getGoodCurrencyBigDecimal(clearingFee, realTransactionQuantity, unit);

                totalBrokerFee = totalBrokerFee.add(brokerFeeBigDecimal);
                totalStampDuty = totalStampDuty.add(stampDutyBigDecimal);
                totalClearingFee = totalClearingFee.add(clearingFeeBigDecimal);
            } else {
                // This is the last item.
                brokerFeeBigDecimal = new BigDecimal(brokerFee).subtract(totalBrokerFee).max(BigDecimal.ZERO);
                stampDutyBigDecimal = new BigDecimal(stampDuty).subtract(totalStampDuty).max(BigDecimal.ZERO);
                clearingFeeBigDecimal = new BigDecimal(clearingFee).subtract(totalClearingFee)
                        .max(BigDecimal.ZERO);
            }

            // Do not pass in brokerFee, stampDuty and clearingFee.
            Transaction t = new Transaction(contract, brokerFeeBigDecimal.doubleValue(),
                    stampDutyBigDecimal.doubleValue(), clearingFeeBigDecimal.doubleValue());
            t.setComment(buyTransaction.getComment());
            transactions.add(t);
        }
    }

    return transactions;
}

From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java

/**
 * Prepare list of WaterTaxPayerDetails for each bill collector by summing
 * up the values in each ward for the respective bil collector
 *
 * @param waterChargedashBoardRequest//from  w  ww.  j  a  v a 2  s. c  o  m
 * @param billCollectorWiseMap
 * @param billCollectorWiseWaterTaxPayerDetails
 */
private void prepareTaxersInfoForBillCollectors(final WaterChargeDashBoardRequest waterChargedashBoardRequest,
        final Map<String, List<WaterTaxPayerDetails>> billCollectorWiseMap,
        final List<WaterTaxPayerDetails> billCollectorWiseWaterTaxPayerDetails) {
    BigDecimal cytdColl;
    BigDecimal lytdColl;
    BigDecimal cytdDmd;
    BigDecimal totalDmd;
    WaterTaxPayerDetails waterTaxPayerDetails;
    for (final Entry<String, List<WaterTaxPayerDetails>> entry : billCollectorWiseMap.entrySet()) {
        waterTaxPayerDetails = new WaterTaxPayerDetails();
        cytdColl = BigDecimal.ZERO;
        lytdColl = BigDecimal.ZERO;
        cytdDmd = BigDecimal.ZERO;
        totalDmd = BigDecimal.ZERO;
        for (final WaterTaxPayerDetails taxPayer : entry.getValue()) {
            totalDmd = totalDmd.add(taxPayer.getTotalDmd() == null ? BigDecimal.ZERO : taxPayer.getTotalDmd());
            cytdColl = cytdColl.add(taxPayer.getCurrentYearTillDateColl() == null ? BigDecimal.ZERO
                    : taxPayer.getCurrentYearTillDateColl());
            cytdDmd = cytdDmd.add(taxPayer.getCurrentYearTillDateDmd() == null ? BigDecimal.ZERO
                    : taxPayer.getCurrentYearTillDateDmd());
            lytdColl = lytdColl.add(taxPayer.getLastYearTillDateColl() == null ? BigDecimal.ZERO
                    : taxPayer.getLastYearTillDateColl());
        }
        waterTaxPayerDetails.setBillCollector(entry.getKey());
        waterTaxPayerDetails.setRegionName(waterChargedashBoardRequest.getRegionName());
        waterTaxPayerDetails.setDistrictName(waterChargedashBoardRequest.getDistrictName());
        waterTaxPayerDetails.setUlbGrade(waterChargedashBoardRequest.getUlbGrade());
        waterTaxPayerDetails.setCurrentYearTillDateColl(cytdColl);
        waterTaxPayerDetails.setCurrentYearTillDateDmd(cytdDmd);
        waterTaxPayerDetails.setCurrentYearTillDateBalDmd(cytdDmd.subtract(cytdColl));
        waterTaxPayerDetails.setTotalDmd(totalDmd);
        waterTaxPayerDetails.setLastYearTillDateColl(lytdColl);
        waterTaxPayerDetails.setAchievement(cytdColl.multiply(WaterTaxConstants.BIGDECIMAL_100).divide(cytdDmd,
                1, BigDecimal.ROUND_HALF_UP));
        if (lytdColl.compareTo(BigDecimal.ZERO) > 0)
            cytdColl.subtract(lytdColl).multiply(WaterTaxConstants.BIGDECIMAL_100).divide(lytdColl, 1,
                    BigDecimal.ROUND_HALF_UP);
        billCollectorWiseWaterTaxPayerDetails.add(waterTaxPayerDetails);
    }
}

From source file:org.kuali.ole.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * Generates a PurAP accounting line and adds to the specified tax item.
 *
 * @param taxItem       The specified tax item the accounting line will be associated with.
 * @param taxableAmount The amount to which tax is computed against.
 * @return A fully populated PurApAccountingLine instance for the specified tax item.
 *///from   w  ww  .  ja v  a2s. c  om
protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) {
    PaymentRequestDocument preq = taxItem.getPurapDocument();
    PurApAccountingLine taxLine = null;

    try {
        taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("Unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("Unable to instantiate sourceAccountingLineClass", e);
    }

    // tax item type indicators
    boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross
    boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax

    // obtain accounting line info according to tax item type code
    String taxChart = null;
    String taxAccount = null;
    String taxObjectCode = null;

    if (isGross) {
        // for gross up tax items, use preq's first item's first accounting line, which shall exist at this point
        AccountingLine line1 = preq.getFirstAccount();
        taxChart = line1.getChartOfAccountsCode();
        taxAccount = line1.getAccountNumber();
        taxObjectCode = line1.getFinancialObjectCode();
    } else if (isFederalTax) {
        // for federal tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }
    } else if (isStateTax) {
        // for state tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }
    }

    // calculate tax amount according to gross up indicator and federal/state tax type
    /*
     * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount *
     * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax
     * = - gross
     */

    // pick federal/state tax rate
    BigDecimal taxPercentFederal = preq.getTaxFederalPercent();
    BigDecimal taxPercentState = preq.getTaxStatePercent();
    BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState;

    // divider value according to gross up or not
    BigDecimal taxDivider = new BigDecimal(100);
    if (preq.getTaxGrossUpIndicator()) {
        taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState));
    }

    // tax = amount * rate / divider
    BigDecimal taxAmount = taxableAmount.multiply(taxPercent);
    taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP);

    // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax
    if (!isGross) {
        taxAmount = taxAmount.negate();
    }

    // populate necessary accounting line fields
    taxLine.setDocumentNumber(preq.getDocumentNumber());
    taxLine.setSequenceNumber(preq.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(taxChart);
    taxLine.setAccountNumber(taxAccount);
    taxLine.setFinancialObjectCode(taxObjectCode);
    taxLine.setAmount(new KualiDecimal(taxAmount));

    // add the accounting line to the item
    taxLine.setItemIdentifier(taxItem.getItemIdentifier());
    taxLine.setPurapItem(taxItem);
    taxItem.getSourceAccountingLines().add(taxLine);

    return taxLine;
}

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

public List<HoardingAgencyWiseSearch> getAgencyWiseAdvertisementSearchResult(
        final AdvertisementPermitDetail advPermitDetail) {

    final List<AdvertisementPermitDetail> advPermitDtl = advertisementPermitDetailRepository
            .searchAdvertisementPermitDetailBySearchParams(advPermitDetail);
    final HashMap<String, HoardingAgencyWiseSearch> agencyWiseHoardingMap = new HashMap<String, HoardingAgencyWiseSearch>();
    final List<HoardingAgencyWiseSearch> agencyWiseFinalHoardingList = new ArrayList<HoardingAgencyWiseSearch>();

    advPermitDtl.forEach(result -> {//from   w  w  w .j  ava 2s .  c  om
        if (result.getAgency() != null) {
            final HoardingAgencyWiseSearch hoardingSearchResult = new HoardingAgencyWiseSearch();
            hoardingSearchResult.setAdvertisementNumber(result.getAdvertisement().getAdvertisementNumber());
            hoardingSearchResult.setAgencyName(result.getAgency() != null ? result.getAgency().getName() : "");
            hoardingSearchResult.setCategoryName(result.getAdvertisement().getCategory().getName());
            hoardingSearchResult
                    .setSubCategoryName(result.getAdvertisement().getSubCategory().getDescription());
            BigDecimal totalDemandAmount = BigDecimal.ZERO;
            BigDecimal totalCollectedAmount = BigDecimal.ZERO;
            BigDecimal totalPending = BigDecimal.ZERO;
            BigDecimal totalPenalty = BigDecimal.ZERO;
            BigDecimal totalAdditionalTax = BigDecimal.ZERO;
            final Map<String, BigDecimal> demandWiseFeeDetail = advertisementDemandService
                    .checkPendingAmountByDemand(result);
            totalDemandAmount = totalDemandAmount
                    .add(demandWiseFeeDetail.get(AdvertisementTaxConstants.TOTAL_DEMAND));
            totalCollectedAmount = totalCollectedAmount
                    .add(demandWiseFeeDetail.get(AdvertisementTaxConstants.TOTALCOLLECTION));
            totalPending = totalPending
                    .add(demandWiseFeeDetail.get(AdvertisementTaxConstants.PENDINGDEMANDAMOUNT));
            totalPenalty = totalPenalty.add(demandWiseFeeDetail.get(AdvertisementTaxConstants.PENALTYAMOUNT));
            totalAdditionalTax = totalAdditionalTax
                    .add(demandWiseFeeDetail.get(AdvertisementTaxConstants.ADDITIONALTAXAMOUNT));

            final HoardingAgencyWiseSearch hoardingSearchObj = agencyWiseHoardingMap
                    .get(result.getAgency().getName());
            if (hoardingSearchObj == null) {
                hoardingSearchResult.setAgency(result.getAgency().getId());
                hoardingSearchResult.setTotalDemand(totalDemandAmount);
                hoardingSearchResult.setCollectedAmount(totalCollectedAmount);
                hoardingSearchResult.setPendingAmount(totalDemandAmount.subtract(totalCollectedAmount));
                hoardingSearchResult.setPenaltyAmount(totalPenalty);
                hoardingSearchResult.setAdditionalTaxAmount(totalAdditionalTax);
                hoardingSearchResult.setTotalHoardingInAgency(1);
                hoardingSearchResult.setHordingIdsSearchedByAgency(result.getId().toString());
                hoardingSearchResult
                        .setOwnerDetail(result.getOwnerDetail() != null ? result.getOwnerDetail() : "");
                agencyWiseHoardingMap.put(result.getAgency().getName(), hoardingSearchResult);
            } else {

                hoardingSearchResult.setAgency(result.getAgency().getId());
                hoardingSearchResult.setTotalDemand(agencyWiseHoardingMap.get(result.getAgency().getName())
                        .getTotalDemand().add(totalDemandAmount));
                hoardingSearchResult.setCollectedAmount(agencyWiseHoardingMap.get(result.getAgency().getName())
                        .getCollectedAmount().add(totalCollectedAmount));
                hoardingSearchResult.setPendingAmount(agencyWiseHoardingMap.get(result.getAgency().getName())
                        .getPendingAmount().add(totalPending));
                hoardingSearchResult.setPenaltyAmount(agencyWiseHoardingMap.get(result.getAgency().getName())
                        .getPenaltyAmount().add(totalPenalty));
                hoardingSearchResult.setAdditionalTaxAmount(agencyWiseHoardingMap
                        .get(result.getAgency().getName()).getAdditionalTaxAmount().add(totalAdditionalTax));
                hoardingSearchResult.setTotalHoardingInAgency(hoardingSearchObj.getTotalHoardingInAgency() + 1);
                agencyWiseHoardingMap.put(result.getAgency().getName(), hoardingSearchResult);
            }

        }

    });
    if (agencyWiseHoardingMap.size() > 0)
        agencyWiseHoardingMap.forEach((key, value) -> {
            agencyWiseFinalHoardingList.add(value);
        });

    return agencyWiseFinalHoardingList;
}