Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:com.farouk.projectapp.FirstGUI.java

private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed

    if (StringThirdParty.equals("")) {
        JOptionPane.showMessageDialog(rootPane, "Please select a company first.", "Oo-Ohh", WIDTH);
    } else if (SQLConnect.ifAutomated(userID, StringThirdParty) == 2) {
        SQLConnect.removeAutomation(userID, StringThirdParty);
    } else {//from   ww  w.  ja v  a 2 s  .co  m
        String aux = jTextField4.getText();
        try {
            BigDecimal price = new BigDecimal(jTextField4.getText());
            if (price.compareTo(BigDecimal.ZERO) == 1) {
                if (jTextField4.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(rootPane, "Please enter a valid input.", "Error", WIDTH);
                } else {
                    String symb = SQLConnect.getSymbolOfCompanyFromDB(StringThirdParty);

                    SQLConnect.saveAutomateSettings(userID, symb, new BigDecimal(BigInteger.ONE), price, 0, 0,
                            0);

                }
            } else {
                JOptionPane.showMessageDialog(rootPane, "Enter a positive number.", "No !", WIDTH);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(rootPane, "Please provide a valid number", "Bad input", WIDTH);
        }

    }

}

From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java

@Override
public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) {
    final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO();
    Calendar date = dto.getDate();
    if (date == null) {
        date = Calendar.getInstance();
    }//from w  w w .  j a v  a2  s .c  om
    final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER,
            Loan.Relationships.PAYMENTS);
    LoanPayment payment = fetchService.fetch(dto.getLoanPayment());
    if (payment == null) {
        payment = loan.getFirstOpenPayment();
    }
    ret.setLoanPayment(payment);

    // Update the dto with fetched values
    dto.setLoan(loan);
    dto.setLoanPayment(payment);

    if (payment != null) {
        payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS);
        final BigDecimal paymentAmount = payment.getAmount();
        BigDecimal remainingAmount = paymentAmount;
        Calendar expirationDate = payment.getExpirationDate();
        Calendar lastPaymentDate = (Calendar) expirationDate.clone();
        expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE);
        final LoanParameters parameters = loan.getParameters();
        Collection<Transfer> transfers = payment.getTransfers();
        if (transfers == null) {
            transfers = Collections.emptyList();
        }
        final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class,
                parameters.getExpirationDailyInterest());
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final MathContext mathContext = localSettings.getMathContext();
        for (final Transfer transfer : transfers) {
            Calendar trfDate = transfer.getDate();
            trfDate = DateUtils.truncate(trfDate, Calendar.DATE);
            final BigDecimal trfAmount = transfer.getAmount();
            BigDecimal actualAmount = trfAmount;
            final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis())
                    / DateUtils.MILLIS_PER_DAY);
            if (diffDays > 0 && expirationDailyInterest != null) {
                // Apply interest
                actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays))
                        .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext)));
            }
            remainingAmount = remainingAmount.subtract(actualAmount);
            lastPaymentDate = (Calendar) trfDate.clone();
        }
        date = DateHelper.truncate(date);
        BigDecimal remainingAmountAtDate = remainingAmount;
        final int diffDays = (int) ((date.getTimeInMillis()
                - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis()
                        : expirationDate.getTimeInMillis()))
                / DateUtils.MILLIS_PER_DAY);
        if (diffDays > 0 && expirationDailyInterest != null) {
            // Apply interest
            remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays))
                    .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext)));
        }
        final Amount expirationFee = parameters.getExpirationFee();
        if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1)
                && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) {
            // Apply expiration fee
            remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount));
        }
        // Round the result
        ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount));
        ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate));
    }
    return ret;
}

From source file:com.konakart.bl.modules.ordertotal.productdiscount.ProductDiscount.java

/**
 * Create and return an OrderTotal object for the discount amount. *
 * <p>//from   w w  w  .  j  ava2s .c om
 * Custom field usage:
 * <p>
 * <ul>
 * <li>custom1 = Minimum Order Value</li>
 * <li>custom2 = Minimum quantity of a single product</li>
 * <li>custom3 = Discount Applied</li>
 * <li>custom4 = Percentage discount if set to true</li>
 * <li>custom5 = Discount applied to pre-tax value if set to true</li>
 * </ul>
 * If the promotion applies to multiple products, we create an array of order total objects and
 * attach the array to the order total that we return (ot.setOrderTotals(otArray)). The reason
 * for doing this is to get a line item of the order for each discounted product. We still need
 * to populate the order total that we return with the total discount amount because this will
 * be used to compare this promotion with other promotions in order to decide which one to use.
 * 
 * @param order
 * @param dispPriceWithTax
 * @param locale
 * @return Returns an OrderTotal object for this module
 * @throws Exception
 */
public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale) throws Exception {
    OrderTotal ot;
    StaticData sd = staticDataHM.get(getStoreId());

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale);
    if (rb == null) {
        throw new KKException("A resource file cannot be found for the country " + locale.getCountry());
    }

    // Get the promotions
    Promotion[] promArray = getPromMgr().getPromotions(code, order);

    // List to contain an order total for each promotion
    List<OrderTotal> orderTotalList = new ArrayList<OrderTotal>();

    if (promArray != null) {

        for (int i = 0; i < promArray.length; i++) {
            Promotion promotion = promArray[i];

            /*
             * Get the configuration parameters from the promotion
             */

            // Minimum value for order
            BigDecimal minTotalOrderVal = getCustomBigDecimal(promotion.getCustom1(), 1);

            // Need to order at least this quantity of a single product for promotion to apply
            int minProdQuantity = getCustomInt(promotion.getCustom2(), 2);

            // Actual discount. Could be a percentage or an amount.
            BigDecimal discountApplied = getCustomBigDecimal(promotion.getCustom3(), 3);

            // If set to true it is a percentage. Otherwise it is an amount.
            boolean percentageDiscount = getCustomBoolean(promotion.getCustom4(), 4);

            // If set to true, discount is applied to pre-tax value. Only relevant for
            // percentage discount.
            boolean applyBeforeTax = getCustomBoolean(promotion.getCustom5(), 5);

            // Don't bother going any further if there is no discount
            if (discountApplied == null || discountApplied.equals(new BigDecimal(0))) {
                continue;
            }

            // Get the order value
            BigDecimal orderValue = null;
            if (applyBeforeTax) {
                orderValue = order.getSubTotalExTax();
                log.debug("Order value before tax: " + orderValue);
            } else {
                orderValue = order.getSubTotalIncTax();
                log.debug("Order value after tax: " + orderValue);
            }

            // If promotion doesn't cover any of the products in the order then go on to the
            // next promotion
            if (promotion.getApplicableProducts() == null || promotion.getApplicableProducts().length == 0) {
                continue;
            }

            ot = new OrderTotal();
            ot.setSortOrder(sd.getSortOrder());
            ot.setClassName(code);
            ot.setPromotions(new Promotion[] { promotion });

            // Does promotion only apply to a min order value ?
            if (minTotalOrderVal != null) {
                if (orderValue.compareTo(minTotalOrderVal) < 0) {
                    // If we haven't reached the minimum amount then continue to the next
                    // promotion
                    continue;
                }
            }

            // Continue if promotion has no applicable products (should never happen)
            if (promotion.getApplicableProducts() == null) {
                continue;
            }

            /*
             * Create a new Order Total module for each discounted product and store in this
             * list
             */
            ArrayList<OrderTotal> otList = new ArrayList<OrderTotal>();

            // Loop through promotion products to determine whether to apply a discount
            boolean firstLoop = true;
            for (int j = 0; j < promotion.getApplicableProducts().length; j++) {
                OrderProductIf op = promotion.getApplicableProducts()[j];
                if (op != null && op.getQuantity() >= minProdQuantity) {
                    // Get the current total price of the product(s)
                    BigDecimal currentPrice = null;
                    if (applyBeforeTax) {
                        currentPrice = op.getFinalPriceExTax();
                    } else {
                        currentPrice = op.getFinalPriceIncTax();
                    }

                    // Apply the discount
                    BigDecimal discount = null;
                    if (percentageDiscount) {
                        // Apply a percentage discount
                        discount = (currentPrice.multiply(discountApplied)).divide(new BigDecimal(100));
                    } else {
                        // Apply an amount based discount
                        discount = discountApplied.multiply(new BigDecimal(op.getQuantity()));
                    }

                    // Determine whether it is the first discounted product or not
                    String formattedDiscount = getCurrMgr().formatPrice(discount, order.getCurrencyCode());
                    if (firstLoop) {
                        // Set the order total attributes
                        ot.setValue(discount);
                        if (percentageDiscount) {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", discountApplied, "%", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10% Philips TV"
                                ot.setTitle("-" + discountApplied + "% " + op.getName());
                            }

                        } else {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", formattedDiscount, "", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10EUR Philips TV"
                                ot.setTitle("-" + formattedDiscount + " " + op.getName());
                            }
                        }
                    } else {
                        // Set the order total attributes
                        ot.setValue(ot.getValue().add(discount));
                        ot.setText("-" + getCurrMgr().formatPrice(ot.getValue(), order.getCurrencyCode()));
                        ot.setTitle(ot.getTitle() + "," + op.getName());
                    }
                    firstLoop = false;

                    /*
                     * Create a new Order Total module for each product
                     */
                    OrderTotal singleOt = new OrderTotal();
                    singleOt.setSortOrder(sd.getSortOrder());
                    singleOt.setClassName(code);
                    singleOt.setValue(discount);
                    singleOt.setText("-" + formattedDiscount);
                    if (percentageDiscount) {
                        singleOt.setTitle("-" + discountApplied + "% " + op.getName() + ":");
                    } else {
                        singleOt.setTitle("-" + formattedDiscount + " " + op.getName() + ":");
                    }
                    otList.add(singleOt);
                }
            }

            /*
             * If we have more than one discounted product we create an array of order totals
             * (one for each product) and add the array to the order total to be returned.
             */
            if (otList.size() > 1) {
                OrderTotal[] otArray = new OrderTotal[otList.size()];
                int k = 0;
                for (Iterator<OrderTotal> iterator = otList.iterator(); iterator.hasNext();) {
                    OrderTotal lot = iterator.next();
                    otArray[k++] = lot;
                }
                ot.setOrderTotals(otArray);
            }

            if (ot.getValue() != null) {
                int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue();
                ot.setValue(ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP));
                log.debug("Order total is :" + ot.toString());
                orderTotalList.add(ot);
            }
        }
    } else {
        // Return null if there are no promotions
        return null;
    }

    // Call a helper method to decide which OrderTotal we should return
    OrderTotal retOT = getDiscountOrderTotalFromList(order, orderTotalList);
    log.debug("Selected order total is: " + retOT);

    return retOT;

}

From source file:com.xumpy.timesheets.services.implementations.JobsGraphics.java

public OverviewWorkDetails getOverviewWorkDetails(List<Jobs> jobs) throws ParseException {
    MathContext mc = new MathContext(3, RoundingMode.HALF_UP);

    OverviewWorkDetailsSrvPojo overviewWorkDetails = new OverviewWorkDetailsSrvPojo();

    List<WorkingDay> workingDays = calculateWorkingDates(jobs);

    overviewWorkDetails.setHoursToWorkPerDay(new BigDecimal(8)); // Hardcoded

    BigDecimal hoursPayedPerDay = new BigDecimal(0, mc);
    BigDecimal workedWeekHours = new BigDecimal(0, mc);
    BigDecimal workedWeekendHours = new BigDecimal(0, mc);
    BigDecimal weekDays = new BigDecimal(0, mc);
    BigDecimal weekendDays = new BigDecimal(0, mc);
    BigDecimal workedWeekDays = new BigDecimal(0, mc);
    BigDecimal workedWeekendDays = new BigDecimal(0, mc);
    BigDecimal overtimeHours = new BigDecimal(0, mc);
    BigDecimal overtimeDays = new BigDecimal(0, mc);

    for (WorkingDay workingDay : workingDays) {
        if (CustomDateUtils.isWeekDay(workingDay.getDate())) {
            weekDays = weekDays.add(new BigDecimal(1));
            workedWeekHours = workedWeekHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekDays = workedWeekDays.add(new BigDecimal(1));
        } else {/*  w ww  .  j  av a2s.co  m*/
            weekendDays = weekendDays.add(new BigDecimal(1));
            workedWeekendHours = workedWeekendHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekendDays = workedWeekendDays.add(new BigDecimal(1));
        }

        overtimeHours = overtimeHours.add(workingDay.getOvertimeHours(), mc);

        for (Jobs jobPerDay : workingDay.getJobs()) {
            if (jobPerDay.getJobsGroup().getCompany() != null) {
                if (hoursPayedPerDay
                        .compareTo(jobPerDay.getJobsGroup().getCompany().getDailyPayedHours()) < 0) {
                    hoursPayedPerDay = jobPerDay.getJobsGroup().getCompany().getDailyPayedHours();
                }
            }
        }

        if (!hoursPayedPerDay.equals(new BigDecimal(0))) {
            overtimeDays = overtimeHours.divide(hoursPayedPerDay, mc);
        } else {
            overtimeDays = workedWeekDays.add(workedWeekendDays);
        }
    }

    overviewWorkDetails.setHoursPayedPerDay(hoursPayedPerDay);

    overviewWorkDetails.setWorkedWeekHours(workedWeekHours);
    overviewWorkDetails.setWorkedWeekendHours(workedWeekendHours);
    overviewWorkDetails.setWeekDays(weekDays);
    overviewWorkDetails.setWeekendDays(weekendDays);

    overviewWorkDetails.setWorkedWeekDays(workedWeekDays);
    overviewWorkDetails.setWorkedWeekendDays(workedWeekendDays);

    overviewWorkDetails.setOvertimeHours(overtimeHours);
    overviewWorkDetails.setOvertimeDays(overtimeDays);

    return overviewWorkDetails;
}

From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java

private BigDecimal calculateVolumeCharge(final MemberAccount account, final AccountFee volumeFee,
        final Period period, final BigDecimal additionalReserved, final boolean currentPeriod) {
    Calendar fromDate = period.getBegin();

    // Get the account status right after the last charged period
    AccountStatus status = accountService.getStatus(account, fromDate);

    // When there is some additional amount to consider as reserved, add it to the status
    status.setReservedAmount(status.getReservedAmount().add(additionalReserved));

    // Calculate the total days. We want the entire charged period. For example: if the fee was enabled in the middle of a month, it would be the
    // entire month. Likewise, if no end limit was given, the current period will be used (ie, and the last day in the current month)
    TimePeriod recurrence = volumeFee.getRecurrence();
    Period totalPeriod = recurrence.currentPeriod(period.getBegin());
    int totalDays = totalPeriod.getDays() + 1;

    // Calculate each difference, with the corresponding reserved amount
    Calendar lastDay = fromDate;/*from   w w w .j a v  a2s. c o m*/
    Calendar lastChargedDay = fromDate;
    BigDecimal result = BigDecimal.ZERO;
    IteratorList<AccountDailyDifference> diffs = accountDao.iterateDailyDifferences(account, period);
    if (LOG.isDebugEnabled()) {
        LOG.debug("********************************");
        LOG.debug(FormatObject.formatObject(period.getBegin()) + "\t" + status.getBalance() + "\t"
                + status.getAvailableBalance());
    }
    try {
        if (diffs.hasNext()) {
            // There are differences - the lastChargedAvailable balance will be obtained within the loop
            for (AccountDailyDifference diff : diffs) {
                Calendar day = diff.getDay();
                int days = DateHelper.daysBetween(lastDay, day);
                // Get the available balance at that day
                BigDecimal available = status.getAvailableBalanceWithoutCreditLimit();
                if (volumeFee.getChargeMode().isNegative()) {
                    // If the charge is over negative amounts, consider the negated amount
                    available = available.negate();
                }
                // Take the free base into account
                if (volumeFee.getFreeBase() != null) {
                    available = available.subtract(volumeFee.getFreeBase());
                }
                // If the available balance was significant, calculate the charge
                if (available.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal volume = new BigDecimal(available.doubleValue() * days / totalDays);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(FormatObject.formatObject(day) + "\t" + diff.getBalance() + "\t"
                                + status.getAvailableBalanceWithoutCreditLimit().add(diff.getBalance()) + "\t"
                                + days + "\t" + totalDays + "\t" + volume);
                    }
                    BigDecimal toCharge = volume.multiply(volumeFee.getAmount())
                            .divide(BigDecimalHelper.ONE_HUNDRED);
                    // status.setReservedAmount(status.getReservedAmount().add(toCharge));
                    result = result.add(toCharge);
                    lastChargedDay = day;
                }
                lastDay = day;
                status.setBalance(status.getBalance().add(diff.getBalance()));
                status.setReservedAmount(status.getReservedAmount().add(diff.getReserved()));
            }
        }
    } finally {
        DataIteratorHelper.close(diffs);
    }

    Calendar toDate = period.getEnd();
    boolean lastPaymentInPeriodEnd = !toDate.before(lastChargedDay);
    LocalSettings settings = settingsService.getLocalSettings();

    // Only if the last payment was not today we have to take into account the results so far
    if (DateHelper.daysBetween(lastChargedDay, Calendar.getInstance()) != 0) {
        BigDecimal resultSoFar = settings.round(result);
        status.setReservedAmount(status.getReservedAmount().add(resultSoFar));
    }

    // Calculate the avaliable balance after the last diff, which will remain the same until the period end
    BigDecimal finalAvailableBalance = status.getAvailableBalanceWithoutCreditLimit();
    if (volumeFee.getChargeMode().isNegative()) {
        finalAvailableBalance = finalAvailableBalance.negate();
    }
    if (volumeFee.getFreeBase() != null) {
        finalAvailableBalance = finalAvailableBalance.subtract(volumeFee.getFreeBase());
    }

    // Consider the last time slice, between the last diff and the period end, if any
    if (lastPaymentInPeriodEnd && finalAvailableBalance.compareTo(BigDecimal.ZERO) > 0) {
        int days = DateHelper.daysBetween(lastChargedDay, toDate) + (currentPeriod ? 0 : 1);
        // Here, the lastChargedAvailableBalance is already subtracted from the free base (if any)
        BigDecimal volume = new BigDecimal(finalAvailableBalance.doubleValue() * days / totalDays);
        BigDecimal toCharge = volume.multiply(volumeFee.getAmount()).divide(BigDecimalHelper.ONE_HUNDRED);
        result = result.add(toCharge);
        if (LOG.isDebugEnabled()) {
            status.setReservedAmount(settings.round(status.getReservedAmount().add(toCharge)));
            LOG.debug(FormatObject.formatObject(lastChargedDay) + "\t0\t"
                    + status.getAvailableBalanceWithoutCreditLimit() + "\t" + days + "\t" + totalDays + "\t"
                    + volume);
        }
    }

    return settings.round(result);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des fichiers dtails
 * @param mlr//  ww w  .j  a  v a  2s  . c  om
 * @param fileName
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public void exportMoveLineAllTypeSelectFILE2(MoveLineReport moveLineReport, String fileName)
        throws AxelorException, IOException {

    log.info("In export service FILE 2 :");

    Company company = moveLineReport.getCompany();

    String companyCode = "";
    String moveLineQueryStr = "";

    int typeSelect = moveLineReport.getTypeSelect();

    if (company != null) {
        companyCode = company.getCode();
        moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    }
    if (moveLineReport.getJournal() != null) {
        moveLineQueryStr += String.format(" AND self.move.journal = %s", moveLineReport.getJournal().getId());
    } else {
        moveLineQueryStr += String.format(" AND self.move.journal.type = %s",
                moveLineReportService.getJournalType(moveLineReport).getId());
    }

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }

    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (typeSelect != 8) {
        moveLineQueryStr += String.format(" AND self.account.reconcileOk = false ");
    }
    moveLineQueryStr += String.format(
            "AND self.move.accountingOk = true AND self.move.ignoreInAccountingOk = false AND self.move.moveLineReport = %s",
            moveLineReport.getId());
    moveLineQueryStr += String.format(" AND self.move.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    Query queryDate = JPA.em().createQuery(
            "SELECT self.date from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                    + moveLineQueryStr + " group by self.date ORDER BY self.date");

    List<LocalDate> dates = new ArrayList<LocalDate>();
    dates = queryDate.getResultList();

    log.debug("dates : {}", dates);

    List<String[]> allMoveLineData = new ArrayList<String[]>();

    for (LocalDate localDate : dates) {

        Query queryExportAgressoRef = JPA.em().createQuery(
                "SELECT DISTINCT self.move.exportNumber from MoveLine self where self.account != null "
                        + "AND (self.debit > 0 OR self.credit > 0) AND self.date = '" + localDate.toString()
                        + "'" + moveLineQueryStr);
        List<String> exportAgressoRefs = new ArrayList<String>();
        exportAgressoRefs = queryExportAgressoRef.getResultList();
        for (String exportAgressoRef : exportAgressoRefs) {

            if (exportAgressoRef != null && !exportAgressoRef.isEmpty()) {

                int sequence = 1;

                Query query = JPA.em().createQuery(
                        "SELECT self.account.id from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                                + "AND self.date = '" + localDate.toString()
                                + "' AND self.move.exportNumber = '" + exportAgressoRef + "'" + moveLineQueryStr
                                + " group by self.account.id");

                List<Long> accountIds = new ArrayList<Long>();
                accountIds = query.getResultList();

                log.debug("accountIds : {}", accountIds);

                for (Long accountId : accountIds) {
                    if (accountId != null) {
                        String accountCode = accountRepo.find(accountId).getCode();
                        List<MoveLine> moveLines = moveLineRepo.all().filter(
                                "self.account.id = ?1 AND (self.debit > 0 OR self.credit > 0) AND self.date = '"
                                        + localDate.toString() + "' AND self.move.exportNumber = '"
                                        + exportAgressoRef + "'" + moveLineQueryStr,
                                accountId).fetch();

                        log.debug("movelines  : {} ", moveLines);

                        if (moveLines.size() > 0) {

                            List<MoveLine> moveLineList = moveLineService.consolidateMoveLines(moveLines);

                            List<MoveLine> sortMoveLineList = this.sortMoveLineByDebitCredit(moveLineList);

                            for (MoveLine moveLine3 : sortMoveLineList) {

                                Journal journal = moveLine3.getMove().getJournal();
                                LocalDate date = moveLine3.getDate();
                                String items[] = null;

                                if (typeSelect == 9) {
                                    items = new String[13];
                                } else {
                                    items = new String[12];
                                }

                                items[0] = companyCode;
                                items[1] = journal.getExportCode();
                                items[2] = moveLine3.getMove().getExportNumber();
                                items[3] = String.format("%s", sequence);
                                sequence++;
                                items[4] = accountCode;

                                BigDecimal totAmt = moveLine3.getCredit().subtract(moveLine3.getDebit());
                                String moveLineSign = "C";
                                if (totAmt.compareTo(BigDecimal.ZERO) == -1) {
                                    moveLineSign = "D";
                                    totAmt = totAmt.negate();
                                }
                                items[5] = moveLineSign;
                                items[6] = totAmt.toString();

                                String analyticAccounts = "";
                                for (AnalyticMoveLine analyticDistributionLine : moveLine3
                                        .getAnalyticMoveLineList()) {
                                    analyticAccounts = analyticAccounts
                                            + analyticDistributionLine.getAnalyticAccount().getCode() + "/";
                                }

                                if (typeSelect == 9) {
                                    items[7] = "";
                                    items[8] = analyticAccounts;
                                    items[9] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                } else {
                                    items[7] = analyticAccounts;
                                    items[8] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                }

                                allMoveLineData.add(items);

                            }
                        }
                    }
                }
            }
        }
    }

    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|',  this.createHeaderForDetailFile(typeSelect), allMoveLineData);
}

From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java

@Override
public void writeDirectiveArguments(DirectiveInOutState state) {

    _deltaWriter.setIndent(2);/* w w w  .ja va  2s .  c  o m*/
    MutableDeltaDataSet dataSet = state.getDataSet();
    Directive curDirective = state.getCurrentDirective().getDirective();
    // Dir directive;
    DirectiveArguments directiveArgs = state.getCurrentDirective().getDirectiveArguments();

    int argType = curDirective.getArgType();
    String temp = "";
    DirectiveType directiveType = state.getCurrentDirective().getType();
    List<Integer> dataList = null;

    int prevNo, curNo;

    List<DirectiveArgument<?>> args = null;

    switch (argType) {
    case DirectiveArgType.DIRARG_NONE:
    case DirectiveArgType.DIRARG_TRANSLATION:
    case DirectiveArgType.DIRARG_INTKEY_INCOMPLETE:
        break;

    case DirectiveArgType.DIRARG_TEXT: // What about multiple lines of text?
        // Should line breaks ALWAYS be
        // preserved?
    case DirectiveArgType.DIRARG_COMMENT: // Will actually be handled within
        // DirComment
        _deltaWriter.setIndent(0);
    case DirectiveArgType.DIRARG_FILE:
    case DirectiveArgType.DIRARG_OTHER:
    case DirectiveArgType.DIRARG_INTERNAL:
        writeText(directiveArgs, argType);
        break;

    case DirectiveArgType.DIRARG_INTEGER:
    case DirectiveArgType.DIRARG_REAL:
        if (directiveArgs.size() > 0) {
            _textBuffer.append(' ');
            _textBuffer.append(directiveArgs.getFirstArgumentValueAsString());
        }
        break;

    case DirectiveArgType.DIRARG_CHAR:
    case DirectiveArgType.DIRARG_ITEM:
        if (directiveArgs.size() > 0) {
            _textBuffer.append(' ');
            curNo = directiveArgs.getFirstArgumentIdAsInt();
            _textBuffer.append(curNo);
        }
        break;

    case DirectiveArgType.DIRARG_CHARLIST:
    case DirectiveArgType.DIRARG_ITEMLIST:
        if (directiveArgs.size() > 0) {
            dataList = new ArrayList<Integer>();
            for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments())
                dataList.add((Integer) vectIter.getId());
            _textBuffer.append(' ');
            appendRange(dataList, ' ', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_TEXTLIST:
        // Special handling for "legacy" data, when this was stored as a
        // simple, large
        // text block...
        if (directiveArgs.size() == 1 && directiveArgs.getFirstArgumentIdAsInt() <= 0
                && directiveArgs.getFirstArgumentText().length() > 1) {
            writeText(directiveArgs, DirectiveArgType.DIRARG_TEXT);
            break;
        }
        // Otherwise drop through...
    case DirectiveArgType.DIRARG_CHARTEXTLIST:
    case DirectiveArgType.DIRARG_ITEMTEXTLIST:
    case DirectiveArgType.DIRARG_ITEMFILELIST: {
        writeTextList(dataSet, directiveArgs, argType, temp);
        break;
    }
    case DirectiveArgType.DIRARG_CHARINTEGERLIST:
    case DirectiveArgType.DIRARG_CHARREALLIST:
    case DirectiveArgType.DIRARG_ITEMREALLIST:
        writeNumberList(directiveArgs);
        break;

    case DirectiveArgType.DIRARG_CHARGROUPS:
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            dataList = new ArrayList<Integer>(vectIter.getDataList());
            _textBuffer.append(' ');
            appendRange(dataList, ':', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_ITEMCHARLIST:
        writeItemCharacterList(dataSet, directiveArgs, directiveType);
        break;

    case DirectiveArgType.DIRARG_ALLOWED:
        args = directiveArgs.getDirectiveArguments();
        Collections.sort(args);
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            curNo = (Integer) vectIter.getId();
            _textBuffer.append(' ');
            _textBuffer.append(curNo);
            _textBuffer.append(',');

            List<Integer> tmpData = vectIter.getDataList();
            if (tmpData.size() < 3)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            temp = Integer.toString(tmpData.get(0));
            _textBuffer.append(temp + ':');
            temp = Integer.toString(tmpData.get(1));
            _textBuffer.append(temp + ':');
            temp = Integer.toString(tmpData.get(2));
            _textBuffer.append(temp);
        }
        break;

    case DirectiveArgType.DIRARG_KEYSTATE:
        writeKeyStates(dataSet, directiveArgs);
        break;

    case DirectiveArgType.DIRARG_PRESET:
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            curNo = (Integer) vectIter.getId();
            _textBuffer.append(' ');
            _textBuffer.append(curNo);
            _textBuffer.append(',');
            if (vectIter.getData().size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            _textBuffer.append(vectIter.getDataList().get(0));
            _textBuffer.append(':');
            _textBuffer.append(vectIter.getDataList().get(1));
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ONOFF:
        if (directiveArgs.size() > 0 && directiveArgs.getFirstArgumentValue() != 0.0) {
            _textBuffer.append(' ');
            if (directiveArgs.getFirstArgumentValue() < 0.0)
                _textBuffer.append("Off");
            else if (directiveArgs.getFirstArgumentValue() > 0.0)
                _textBuffer.append("On");
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ITEM:
        if (directiveArgs.size() > 0) {
            if (directiveArgs.getFirstArgumentIdAsInt() > 0) {
                _textBuffer.append(' ');
                curNo = directiveArgs.getFirstArgumentIdAsInt();
                _textBuffer.append(curNo);
            } else
                appendKeyword(_textBuffer, directiveArgs.getFirstArgumentText());
        }
        break;

    case DirectiveArgType.DIRARG_KEYWORD_CHARLIST:
    case DirectiveArgType.DIRARG_KEYWORD_ITEMLIST:
    case DirectiveArgType.DIRARG_INTKEY_CHARLIST:
    case DirectiveArgType.DIRARG_INTKEY_ITEMLIST:
        dataList = new ArrayList<Integer>();
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            if ((Integer) vectIter.getId() > 0)
                dataList.add((Integer) vectIter.getId());
            else
                appendKeyword(_textBuffer, vectIter.getText(),
                        (argType == DirectiveArgType.DIRARG_KEYWORD_CHARLIST
                                || argType == DirectiveArgType.DIRARG_KEYWORD_ITEMLIST)
                                && vectIter == directiveArgs.get(0));
        }
        if (dataList.size() > 0) {
            _textBuffer.append(' ');
            appendRange(dataList, ' ', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_CHARREALLIST:
        if (directiveArgs.size() > 0) {
            // Will sort all keywords to appear before actual character
            // numbers, and group characters appropriately
            args = directiveArgs.getDirectiveArguments();
            Collections.sort(args);
            curNo = Integer.MAX_VALUE;
            prevNo = Integer.MAX_VALUE;
            dataList = new ArrayList<Integer>();
            BigDecimal curVal = BigDecimal.ZERO;
            BigDecimal prevVal = BigDecimal.ZERO;
            boolean firstChar = true;
            for (int i = 0; i <= args.size(); i++)
            // Note that vectIter is allowed to equal .end()
            // This allows the last value to be handled correctly within the
            // loop.
            // Be careful not to de-reference vectIter when this happens.
            {
                if (i != args.size()) {
                    DirectiveArgument<?> vectIter = args.get(i);
                    curVal = vectIter.getValue();
                    if ((Integer) vectIter.getId() <= 0) {
                        appendKeyword(_textBuffer, vectIter.getText());
                        if (!(curVal.compareTo(BigDecimal.ZERO) < 0.0)) {
                            _textBuffer.append(',');
                            _textBuffer.append(curVal.toPlainString());
                        }
                        continue;
                    }
                    curNo = (Integer) vectIter.getId();
                }
                if (firstChar || (prevNo == curNo - 1 && prevVal.equals(curVal))) {
                    dataList.add(curNo);
                    firstChar = false;
                } else if (dataList.size() > 0) {
                    _textBuffer.append(' ');
                    appendRange(dataList, ' ', false, _textBuffer);
                    if (!(prevVal.compareTo(BigDecimal.ZERO) < 0.0)) {

                        _textBuffer.append(',');
                        _textBuffer.append(prevVal.toPlainString());
                    }
                    dataList = new ArrayList<Integer>();
                    dataList.add(curNo);
                }
                prevNo = curNo;
                prevVal = curVal;
            }
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ITEMCHARSET:
        writeIntItemCharSetArgs(argType, directiveArgs, _textBuffer);
        break;

    case DirectiveArgType.DIRARG_INTKEY_ATTRIBUTES:
        writeIntkeyAttributesArgs(directiveArgs, _textBuffer, dataSet);
        break;

    default:
        break;
    }
    outputTextBuffer(0, 2, false);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

@RequestMapping(value = "/recordpayment", method = RequestMethod.POST)
@ResponseBody//from   w ww.  ja v  a2  s . c om
public String recordPayment(@RequestParam BigDecimal amount, @RequestParam String memo,
        @RequestParam String tenantParam, HttpServletResponse response, ModelMap map) {
    logger.debug("###Entering in recordPaymentInvoice(tenantId,form, amount,response) method @POST");
    Tenant tenant = tenantService.get(tenantParam);
    try {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return "failed";
        }
        BigDecimal roundedAmount = billingPostProcessor.setScaleByCurrency(amount, tenant.getCurrency());
        billingService.addPaymentOrCredit(tenant, roundedAmount, Type.RECORD, memo, null);

        String message = "payment.received";
        String messageArgs = tenant.getName();
        eventService.createEvent(new Date(), tenant, message, messageArgs, Source.PORTAL, Scope.ACCOUNT,
                Category.ACCOUNT, Severity.INFORMATION, true);
        logger.debug("###Exiting recordPaymentInvoice(tenantId,amount,form ,response) method @POST");
    } catch (BillingServiceException e) {
        response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
        return "failed";
    }
    map.addAttribute("tenant", tenant);
    return "success";
}

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

@Override
public void updatePaymentManual(BigDecimal paymentId, String tin, String paymentNum, Date paymentDate,
        BigDecimal paymentSum, String tinDebtor, Long issuerSerialNumber, String issuerIp) throws Exception {
    Session session = getSession();/*from   w  w w  .j a  v a2s  . com*/
    Transaction transaction = session.beginTransaction();

    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.id = :paymentId ";
    Query query = session.createQuery(q);
    query.setParameter("paymentId", paymentId);
    query.setResultTransformer(Transformers.aliasToBean(Payment.class));

    Payment payment = (Payment) query.uniqueResult();

    // checking paymentsum >= key sum - (payment.payment_sum - payment.over_sum)
    short state;
    if (paymentSum.compareTo(payment.getPaymentSum().subtract(payment.getOverSum())) <= 0) {
        paymentSum = payment.getPaymentSum().subtract(payment.getOverSum());
        state = 3;
    } else {
        if (payment.getPaymentSum().compareTo(payment.getOverSum()) == 0) {
            state = 1;
        } else {
            state = 2;
        }
    }

    payment.setTin(tin);
    payment.setPaymentNum(paymentNum);
    payment.setPaymentDate(paymentDate);
    payment.setPaymentSum(paymentSum);
    payment.setState(state);
    payment.setTinDebtor(tinDebtor);
    payment.setIssuerSerialNumber(issuerSerialNumber);
    payment.setIssuerIp(issuerIp);
    LocalDateTime dateTime = LocalDateTime.now();
    payment.setDateUpdated(dateTime);

    session.update(payment);

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

From source file:net.sourceforge.fenixedu.domain.Lesson.java

private void checkShiftLoad(Shift shift) {

    if (shift != null) {

        Collection<CourseLoad> courseLoads = shift.getCourseLoadsSet();

        if (courseLoads.size() == 1) {

            CourseLoad courseLoad = courseLoads.iterator().next();

            if (courseLoad.getUnitQuantity() != null
                    && getUnitHours().compareTo(courseLoad.getUnitQuantity()) != 0) {
                throw new DomainException("error.Lesson.shift.load.unit.quantity.exceeded",
                        getUnitHours().toString(), courseLoad.getUnitQuantity().toString());
            }// w  ww. ja  va2s .  com

            //                if (shift.getTotalHours().compareTo(courseLoad.getTotalQuantity()) == 1) {
            //                    throw new DomainException("error.Lesson.shift.load.total.quantity.exceeded",
            //                            shift.getTotalHours().toString(), courseLoad.getTotalQuantity().toString());
            //                }

        } else if (courseLoads.size() > 1) {

            boolean unitValid = false, totalValid = false;
            BigDecimal lessonHours = getUnitHours();
            BigDecimal totalHours = shift.getTotalHours();

            for (CourseLoad courseLoad : courseLoads) {

                unitValid = false;
                totalValid = false;

                if (courseLoad.getUnitQuantity() == null
                        || lessonHours.compareTo(courseLoad.getUnitQuantity()) == 0) {
                    unitValid = true;
                }
                if (totalHours.compareTo(courseLoad.getTotalQuantity()) != 1) {
                    totalValid = true;
                    if (unitValid) {
                        break;
                    }
                }
            }

            //                if (!totalValid) {
            //                    throw new DomainException("error.Lesson.shift.load.total.quantity.exceeded.2", shift.getTotalHours()
            //                            .toString());
            //                }
            if (!unitValid) {
                throw new DomainException("error.Lesson.shift.load.unit.quantity.exceeded.2",
                        getUnitHours().toString());
            }
        }
    }
}