Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

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

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRFedNonFedBudget10V1_1Generator.java

/**
 * This method gets BudgetYearDataType details like BudgetPeriodStartDate,BudgetPeriodEndDate,BudgetPeriod
 * KeyPersons,OtherPersonnel,TotalCompensation,Equipment,ParticipantTraineeSupportCosts,Travel,OtherDirectCosts
 * DirectCosts,IndirectCosts,CognizantFederalAgency,TotalCosts based on BudgetPeriodInfo for the RRFedNonFedBudget.
 * //from ww w .java2  s.co  m
 * @param periodInfo (BudgetPeriodInfo) budget period entry.
 */
private void setBudgetYearDataType(RRFedNonFedBudget10 rrFedNonFedBudget, BudgetPeriodDto periodInfo) {

    ScaleTwoDecimal totalDirectCostSharing = ScaleTwoDecimal.ZERO;
    ScaleTwoDecimal totalIndirectCostSharing = ScaleTwoDecimal.ZERO;
    BudgetYearDataType budgetYear = rrFedNonFedBudget.addNewBudgetYear();
    if (periodInfo != null) {
        budgetYear
                .setBudgetPeriodStartDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getStartDate()));
        budgetYear.setBudgetPeriodEndDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getEndDate()));
        gov.grants.apply.forms.rrFedNonFedBudget10V11.BudgetYearDataType.BudgetPeriod.Enum budgetPeriodEnum = gov.grants.apply.forms.rrFedNonFedBudget10V11.BudgetYearDataType.BudgetPeriod.Enum
                .forInt(periodInfo.getBudgetPeriod());
        budgetYear.setBudgetPeriod(budgetPeriodEnum);
        budgetYear.setKeyPersons(getKeyPersons(periodInfo));
        budgetYear.setOtherPersonnel(getOtherPersonnel(periodInfo));
        SummaryDataType summary = SummaryDataType.Factory.newInstance();
        if (periodInfo.getTotalCompensation() != null) {
            summary.setFederalSummary(periodInfo.getTotalCompensation().bigDecimalValue());
        }
        if (periodInfo.getTotalCompensationCostSharing() != null) {
            if (budget.getSubmitCostSharingFlag()) {
                summary.setNonFederalSummary(periodInfo.getTotalCompensationCostSharing().bigDecimalValue());
                if (periodInfo.getTotalCompensation() != null) {
                    summary.setTotalFedNonFedSummary(periodInfo.getTotalCompensation()
                            .add(periodInfo.getTotalCompensationCostSharing()).bigDecimalValue());
                } else {
                    summary.setTotalFedNonFedSummary(
                            periodInfo.getTotalCompensationCostSharing().bigDecimalValue());
                }
            } else {
                summary.setNonFederalSummary(BigDecimal.ZERO);
                if (periodInfo.getTotalCompensation() != null) {
                    summary.setTotalFedNonFedSummary(periodInfo.getTotalCompensation().bigDecimalValue());
                } else {
                    summary.setTotalFedNonFedSummary(BigDecimal.ZERO);
                }
            }
        }
        budgetYear.setTotalCompensation(summary);
        budgetYear.setEquipment(getEquipment(periodInfo));
        budgetYear.setTravel(getTravel(periodInfo));
        budgetYear.setParticipantTraineeSupportCosts(getParticipantTraineeSupportCosts(periodInfo));
        budgetYear.setOtherDirectCosts(getOtherDirectCosts(periodInfo));
        SummaryDataType summaryDirect = SummaryDataType.Factory.newInstance();
        if (periodInfo.getDirectCostsTotal() != null) {
            summaryDirect.setFederalSummary(periodInfo.getDirectCostsTotal().bigDecimalValue());
        }
        if (periodInfo.getTotalDirectCostSharing() != null) {
            totalDirectCostSharing = periodInfo.getTotalDirectCostSharing();
            summaryDirect.setNonFederalSummary(totalDirectCostSharing.bigDecimalValue());
            if (periodInfo.getDirectCostsTotal() != null) {
                summaryDirect.setTotalFedNonFedSummary(
                        periodInfo.getDirectCostsTotal().add(totalDirectCostSharing).bigDecimalValue());
            } else {
                summaryDirect.setTotalFedNonFedSummary(totalDirectCostSharing.bigDecimalValue());
            }
        }
        budgetYear.setDirectCosts(summaryDirect);
        IndirectCosts indirectCosts = getIndirectCosts(periodInfo);
        if (indirectCosts != null) {
            budgetYear.setIndirectCosts(indirectCosts);
        }
        budgetYear.setCognizantFederalAgency(periodInfo.getCognizantFedAgency());
        if (periodInfo.getIndirectCosts().getTotalIndirectCostSharing() != null) {
            totalIndirectCostSharing = periodInfo.getIndirectCosts().getTotalIndirectCostSharing();
        }
        SummaryDataType summaryTotal = SummaryDataType.Factory.newInstance();
        if (periodInfo.getTotalCosts() != null) {
            summaryTotal.setFederalSummary(periodInfo.getTotalCosts().bigDecimalValue());
        }
        summaryTotal.setNonFederalSummary(
                totalDirectCostSharing.bigDecimalValue().add(totalIndirectCostSharing.bigDecimalValue()));
        if (periodInfo.getCostSharingAmount() != null) {
            if (periodInfo.getTotalCosts() != null) {
                summaryTotal.setTotalFedNonFedSummary(periodInfo.getTotalCosts().add(totalDirectCostSharing)
                        .bigDecimalValue().add(totalIndirectCostSharing.bigDecimalValue()));
            } else {
                summaryTotal.setTotalFedNonFedSummary(totalDirectCostSharing.bigDecimalValue()
                        .add(totalIndirectCostSharing.bigDecimalValue()));
            }
        }

        budgetYear.setTotalCosts(summaryTotal);
    }
}

From source file:net.sourceforge.fenixedu.domain.credits.util.DepartmentCreditsPoolBean.java

@Atomic
public void editUnitCredits() {
    BigDecimal newAssignedCredits = BigDecimal.ZERO;
    for (DepartmentExecutionCourse departmentExecutionCourse : otherDepartmentSharedExecutionCourses) {
        BigDecimal newExecutionCourseCLE = departmentExecutionCourse.getDepartmentEffectiveLoad()
                .multiply(departmentExecutionCourse.getUnitCreditValue());
        newAssignedCredits = newAssignedCredits.add(newExecutionCourseCLE);
    }// w ww.  ja  v  a 2  s  . c o m

    for (DepartmentExecutionCourse departmentExecutionCourse : departmentSharedExecutionCourses) {
        newAssignedCredits = setExecutionCourseUnitCredit(departmentExecutionCourse,
                getCanEditSharedUnitCredits(), newAssignedCredits, true);
    }
    for (DepartmentExecutionCourse departmentExecutionCourse : departmentExecutionCourses) {
        newAssignedCredits = setExecutionCourseUnitCredit(departmentExecutionCourse, getCanEditUnitCredits(),
                newAssignedCredits, false);
    }
    if (newAssignedCredits.compareTo(getDepartmentCreditsPool().getCreditsPool()) > 0) {
        throw new DomainException("label.excededDepartmentCreditsPool",
                getDepartmentCreditsPool().getCreditsPool().toString(), newAssignedCredits.toString());
    }
    setValues();
}

From source file:net.sourceforge.fenixedu.domain.teacher.TeacherService.java

public BigDecimal getReductionServiceCredits() {
    return getReductionService() == null || getReductionService().getCreditsReductionAttributed() == null
            ? BigDecimal.ZERO
            : getReductionService().getCreditsReductionAttributed();
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the duty charges of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if dutyAmount < 0 or is incorrectly formatted for the currency.
 *///  w  w  w. ja va  2  s.c o  m
public void setDutyAmount(BigDecimal dutyAmount) {
    if (dutyAmount == null) {
        this.dutyAmount = null;
    } else {
        if (dutyAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.lessThanZero");
        try {
            this.dutyAmount = dutyAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.cannotNormalize");
        }
    }
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.PHS398ModularBudgetV1_2Generator.java

/**
 * //from w  w w  .j  a  v  a  2s  . co  m
 * This method is used to get 1st BudgetPeriod for Modular Budget form
 * 
 * @param budget
 *            budget
 * @return Periods object containing modular budget details for the
 *         corresponding budget period.
 */
private Periods[] getPeriods(BudgetContract budget) {
    List<Periods> periods = new ArrayList<>();
    for (BudgetPeriodContract budgetPeriod : budget.getBudgetPeriods()) {
        if (budgetPeriod.getBudgetPeriod() <= BudgetPeriodNum.P5.getNum()) {
            Periods period = Periods.Factory.newInstance();
            DirectCost directCost = DirectCost.Factory.newInstance();
            IndirectCost indirectCost = IndirectCost.Factory.newInstance();

            ScaleTwoDecimal consortiumFandA = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal directCostLessConsortiumFandA = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal totalDirectCosts = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal bdTotalIndirectCost = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal bdCost = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal bdBaseCost = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal bdRate = ScaleTwoDecimal.ZERO;
            String costType = null;

            // StartDate And EndDate
            if (budgetPeriod.getStartDate() != null) {
                period.setBudgetPeriodStartDate(
                        s2SDateTimeService.convertDateToCalendar(budgetPeriod.getStartDate()));
            }
            if (budgetPeriod.getEndDate() != null) {
                period.setBudgetPeriodEndDate(
                        s2SDateTimeService.convertDateToCalendar(budgetPeriod.getEndDate()));
            }

            // Set dfault values for mandatory fields.
            directCost.setDirectCostLessConsortiumFandA(BigDecimal.ZERO);
            directCost.setTotalFundsRequestedDirectCosts(BigDecimal.ZERO);
            period.setTotalFundsRequestedDirectIndirectCosts(BigDecimal.ZERO);

            // TotalDirectAndIndirectCost
            BudgetModularContract budgetModular = budgetPeriod.getBudgetModular();
            if (budgetModular != null) {
                ScaleTwoDecimal totalCost = getTotalCost(budgetModular);
                period.setTotalFundsRequestedDirectIndirectCosts(totalCost.bigDecimalValue());
                cumulativeTotalFundsRequestedDirectIndirectCosts = cumulativeTotalFundsRequestedDirectIndirectCosts
                        .add(totalCost);
                // DirectCosts
                if (budgetModular.getConsortiumFna() != null) {
                    consortiumFandA = budgetModular.getConsortiumFna();
                    directCost.setConsortiumFandA(consortiumFandA.bigDecimalValue());
                    cumulativeConsortiumFandA = cumulativeConsortiumFandA.add(consortiumFandA);
                }
                if (budgetModular.getDirectCostLessConsortiumFna() != null) {
                    directCostLessConsortiumFandA = budgetModular.getDirectCostLessConsortiumFna();
                    directCost
                            .setDirectCostLessConsortiumFandA(directCostLessConsortiumFandA.bigDecimalValue());
                    cumulativeDirectCostLessConsortiumFandA = cumulativeDirectCostLessConsortiumFandA
                            .add(directCostLessConsortiumFandA);
                }
                if (budgetModular.getTotalDirectCost() != null) {
                    totalDirectCosts = budgetModular.getTotalDirectCost();
                    directCost.setTotalFundsRequestedDirectCosts(totalDirectCosts.bigDecimalValue());
                    cumulativeTotalFundsRequestedDirectCosts = cumulativeTotalFundsRequestedDirectCosts
                            .add(totalDirectCosts);
                }

                List<IndirectCostItems> indirectCostItemsList = new ArrayList<>();
                for (BudgetModularIdcContract budgetModularIdc : budgetModular.getBudgetModularIdcs()) {
                    IndirectCostItems indirectCostItems = IndirectCostItems.Factory.newInstance();
                    if (budgetModularIdc.getFundsRequested() != null) {
                        bdCost = budgetModularIdc.getFundsRequested();
                        indirectCostItems.setIndirectCostFundsRequested(bdCost.bigDecimalValue());
                        bdTotalIndirectCost = bdTotalIndirectCost.add(bdCost);
                    }
                    if (budgetModularIdc.getIdcBase() != null) {
                        bdBaseCost = budgetModularIdc.getIdcBase();
                        indirectCostItems.setIndirectCostBase(bdBaseCost.bigDecimalValue());
                    }
                    if (budgetModularIdc.getIdcRate() != null) {
                        bdRate = budgetModularIdc.getIdcRate();
                        indirectCostItems.setIndirectCostRate(bdRate.bigDecimalValue());
                    }
                    if (budgetModularIdc.getDescription() != null) {
                        if (budgetModularIdc.getRateClass() != null) {

                            costType = budgetModularIdc.getRateClass().getDescription();
                        } else {
                            costType = budgetModularIdc.getDescription();
                        }
                        indirectCostItems.setIndirectCostTypeDescription(costType);
                    }
                    indirectCostItemsList.add(indirectCostItems);
                }
                IndirectCostItems[] indirectCostItemsArray = new IndirectCostItems[0];
                indirectCostItemsArray = indirectCostItemsList.toArray(indirectCostItemsArray);
                indirectCost.setIndirectCostItemsArray(indirectCostItemsArray);
            }
            period.setDirectCost(directCost);

            // CognizantFederalAgency
            OrganizationContract organization = pdDoc.getDevelopmentProposal().getApplicantOrganization()
                    .getOrganization();
            if (organization != null) {
                if (organization.getCognizantAuditor() != null) {
                    RolodexContract rolodex = rolodexService.getRolodex(organization.getCognizantAuditor());
                    if (rolodex != null) {
                        indirectCost.setCognizantFederalAgency(getCognizantFederalAgency(rolodex));
                    }
                }

                if (organization.getIndirectCostRateAgreement() != null) {
                    indirectCost.setIndirectCostAgreementDate(s2SDateTimeService
                            .convertDateStringToCalendar(organization.getIndirectCostRateAgreement()));
                }

            }
            // TotalFundsRequestedIndirectCost
            indirectCost.setTotalFundsRequestedIndirectCost(bdTotalIndirectCost.bigDecimalValue());
            cumulativeTotalFundsRequestedIndirectCost = cumulativeTotalFundsRequestedIndirectCost
                    .add(bdTotalIndirectCost);
            period.setIndirectCost(indirectCost);
            periods.add(period);
        }
    }
    return periods.toArray(new Periods[0]);
}

From source file:alfio.manager.PaypalManager.java

Optional<PaymentInformation> getInfo(String paymentId, String transactionId, Event event,
        Supplier<String> platformFeeSupplier) {
    try {//from   ww w.j a v  a 2  s  .  com
        String refund = null;

        APIContext apiContext = getApiContext(event);

        //check for backward compatibility  reason...
        if (paymentId != null) {
            //navigate in all refund objects and sum their amount
            refund = Payment.get(apiContext, paymentId).getTransactions().stream()
                    .map(Transaction::getRelatedResources).flatMap(List::stream)
                    .filter(f -> f.getRefund() != null).map(RelatedResources::getRefund).map(Refund::getAmount)
                    .map(Amount::getTotal).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add)
                    .toPlainString();
            //
        }
        Capture c = Capture.get(apiContext, transactionId);
        String gatewayFee = Optional.ofNullable(c.getTransactionFee()).map(Currency::getValue)
                .map(BigDecimal::new).map(MonetaryUtil::unitToCents).map(String::valueOf).orElse(null);
        return Optional.of(new PaymentInformation(c.getAmount().getTotal(), refund, gatewayFee,
                platformFeeSupplier.get()));
    } catch (PayPalRESTException ex) {
        log.warn("Paypal: error while fetching information for payment id " + transactionId, ex);
        return Optional.empty();
    }
}

From source file:org.openinfobutton.responder.service.impl.ResponderServiceImplMockitoTest.java

public List<ValueSetCode> getRxNormFilterValueSet() {

    List<ValueSetCode> valueSet = new ArrayList<>();
    ValueSetCode v1 = new ValueSetCode();
    v1.setValueSetId(BigDecimal.ZERO);
    v1.setCode("A");

    ValueSetCode v2 = new ValueSetCode();
    v2.setValueSetId(BigDecimal.ONE);
    v2.setCode("B");

    valueSet.add(v1);//from www.  j a va2s  .com
    valueSet.add(v2);

    return valueSet;
}

From source file:alfio.manager.WaitingQueueProcessorIntegrationTest.java

private Pair<String, Event> initSoldOutEvent(boolean withUnboundedCategory) throws InterruptedException {
    int boundedCategorySize = AVAILABLE_SEATS - (withUnboundedCategory ? 1 : 0);
    List<TicketCategoryModification> categories = new ArrayList<>();
    categories.add(new TicketCategoryModification(null, "default", boundedCategorySize,
            new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
            new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
            BigDecimal.ZERO, false, "", true, null, null, null, null, null));

    if (withUnboundedCategory) {
        categories.add(new TicketCategoryModification(null, "unbounded", 0,
                new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
                new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
                BigDecimal.ZERO, false, "", false, null, null, null, null, null));
    }//  ww  w  .  j av a 2  s. c o m

    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);
    Event event = pair.getKey();
    List<TicketCategory> ticketCategories = eventManager.loadTicketCategories(event);
    TicketCategory bounded = ticketCategories.stream().filter(t -> t.getName().equals("default")).findFirst()
            .orElseThrow(IllegalStateException::new);
    List<Integer> boundedReserved = ticketRepository.selectFreeTicketsForPreReservation(event.getId(), 20,
            bounded.getId());
    assertEquals(boundedCategorySize, boundedReserved.size());
    List<Integer> reserved = new ArrayList<>(boundedReserved);
    String reservationId = UUID.randomUUID().toString();
    ticketReservationRepository.createNewReservation(reservationId, DateUtils.addHours(new Date(), 1), null,
            Locale.ITALIAN.getLanguage(), event.getId(), event.getVat(), event.isVatIncluded());
    List<Integer> reservedForUpdate = withUnboundedCategory ? reserved.subList(0, 19) : reserved;
    ticketRepository.reserveTickets(reservationId, reservedForUpdate, bounded.getId(),
            Locale.ITALIAN.getLanguage(), 0);
    if (withUnboundedCategory) {
        TicketCategory unbounded = ticketCategories.stream().filter(t -> t.getName().equals("unbounded"))
                .findFirst().orElseThrow(IllegalStateException::new);
        List<Integer> unboundedReserved = ticketRepository
                .selectNotAllocatedFreeTicketsForPreReservation(event.getId(), 20);
        assertEquals(1, unboundedReserved.size());
        reserved.addAll(unboundedReserved);
        ticketRepository.reserveTickets(reservationId, reserved.subList(19, 20), unbounded.getId(),
                Locale.ITALIAN.getLanguage(), 0);
    }
    ticketRepository.updateTicketsStatusWithReservationId(reservationId, Ticket.TicketStatus.ACQUIRED.name());

    //sold-out
    waitingQueueManager.subscribe(event, new CustomerName("Giuseppe Garibaldi", "Giuseppe", "Garibaldi", event),
            "peppino@garibaldi.com", null, Locale.ENGLISH);
    Thread.sleep(100L);//we are testing ordering, not concurrency...
    waitingQueueManager.subscribe(event, new CustomerName("Nino Bixio", "Nino", "Bixio", event),
            "bixio@mille.org", null, Locale.ITALIAN);
    List<WaitingQueueSubscription> subscriptions = waitingQueueRepository.loadAll(event.getId());
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    assertTrue(subscriptions.stream()
            .allMatch(w -> w.getSubscriptionType().equals(WaitingQueueSubscription.Type.SOLD_OUT)));

    //the following call shouldn't have any effect
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    return Pair.of(reservationId, event);
}

From source file:alfio.manager.system.DataMigrator.java

private void migratePrices(final int eventId) {
    final Map<String, Integer> eventIdParam = Collections.singletonMap("eventId", eventId);
    final String srcPriceCtsParam = "srcPriceCts";
    Map<String, List<MapSqlParameterSource>> migrationData = jdbc.queryForList(
            "select * from event where type = :type and id = :eventId and regular_price_cts > 0",
            new MapSqlParameterSource("type", Event.EventType.INTERNAL.name()).addValue("eventId", eventId))
            .stream().flatMap(event -> {
                //fill the event prices
                boolean eventVatIncluded = (boolean) event.get("vat_included");
                BigDecimal vatPercentage = Optional.ofNullable((BigDecimal) event.get("vat"))
                        .orElse(BigDecimal.ZERO);
                int price = (int) event.get("regular_price_cts");
                String currencyCode = (String) event.get("currency");
                int eventSrcPrice = eventVatIncluded ? MonetaryUtil.addVAT(price, vatPercentage) : price;

                List<Pair<String, MapSqlParameterSource>> modifications = new ArrayList<>();

                if (((int) event.get("src_price_cts")) == 0) {
                    modifications/*from  w w  w  . java  2 s.co m*/
                            .add(Pair
                                    .of("event",
                                            new MapSqlParameterSource(srcPriceCtsParam, eventSrcPrice)
                                                    .addValue("vatStatus",
                                                            eventVatIncluded ? INCLUDED.name()
                                                                    : NOT_INCLUDED.name())
                                                    .addValue("eventId", eventId)));
                }

                //ticket categories
                modifications.addAll(collectTicketCategoryMigrationData(srcPriceCtsParam, eventVatIncluded,
                        vatPercentage, eventIdParam));

                //tickets
                modifications.addAll(collectTicketMigrationData(srcPriceCtsParam, eventVatIncluded,
                        vatPercentage, currencyCode, eventId, eventIdParam));

                //additional_service
                modifications.addAll(collectASMigrationData(srcPriceCtsParam, eventVatIncluded, vatPercentage,
                        eventIdParam));

                //additional_service_item
                modifications.addAll(collectASItemMigrationData(srcPriceCtsParam, eventVatIncluded,
                        vatPercentage, currencyCode, eventIdParam));

                log.debug("Price migration: got {} modifications for event {}", modifications.size(),
                        event.get("short_name"));
                return modifications.stream();
            }).collect(groupingBy(Pair::getKey, mapping(Pair::getValue, toList())));

    if (migrationData.size() > 0) {
        log.debug("Price migration: got modifications for: {}", migrationData.keySet());
        PRICE_UPDATE_BY_KEY.entrySet().stream().filter(e -> migrationData.containsKey(e.getKey()))
                .map(e -> Pair.of(e, migrationData.get(e.getKey()))).forEach(p -> {
                    Map.Entry<String, String> entry = p.getLeft();
                    log.debug("migrating {} prices...", entry.getKey());
                    performPriceMigration(entry.getValue(), p.getRight(), jdbc);
                });
    }
}

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

@Override
public void savePaymentManual(String bankStatementId, List<Payment> paymentList, Long issuerSerialNumber,
        String issuerIp) throws Exception {
    Session session = getSession();/*from   www.j a v a2 s.  c o  m*/
    Transaction transaction = session.beginTransaction();
    BankStatement bs = (BankStatement) session.get(BankStatement.class, bankStatementId);
    if (bs == null) {
        throw new Exception(messageSource.getMessage("bank_statement.editable.bs_not_found", null,
                LocaleContextHolder.getLocale()));
    }

    String q = "SELECT COALESCE(bs.paymentSum,0) - COALESCE(bs.returnSum,0) - (SELECT COALESCE(SUM(kp.paidSum),0) FROM bs.bankStatementPayments bsp JOIN bsp.id.payment p JOIN p.keyPayments kp WHERE p.claim = 0) AS overpaymentSum"
            + " FROM BankStatement bs" + " WHERE bs = :bs";
    Query query = session.createQuery(q);
    query.setParameter("bs", bs);
    BigDecimal overpaymentSum = (BigDecimal) query.uniqueResult();

    if (overpaymentSum.compareTo(BigDecimal.ZERO) > 0) {
        LocalDateTime dateTime = LocalDateTime.now();

        overpaymentDao.returnStateCommit(session, bs, overpaymentSum, issuerSerialNumber, issuerIp, dateTime); // if bankstatement already converted to payment, then them must revert

        for (Payment payment : paymentList) {
            BigDecimal paymentSum = payment.getPaymentSum();
            if (paymentSum.compareTo(overpaymentSum) > 0) {
                paymentSum = overpaymentSum;
                overpaymentSum = BigDecimal.ZERO;
            } else {
                overpaymentSum = overpaymentSum.subtract(paymentSum);
            }
            payment.setPaymentSum(paymentSum);
            payment.setIssuerSerialNumber(issuerSerialNumber);
            payment.setIssuerIp(issuerIp);
            payment.setDateCreated(dateTime);
            payment.setDateUpdated(dateTime);

            session.save(payment);

            BankStatementPayment bsp = new BankStatementPayment();
            BankStatementPaymentId bspId = new BankStatementPaymentId();
            bspId.setBankStatement(bs);
            bspId.setPayment(payment);
            bsp.setId(bspId);

            session.save(bsp);

            if (overpaymentSum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }

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