List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.egov.works.services.AbstractEstimateService.java
public boolean checkForBudgetaryAppropriationForDepositWorks(final FinancialDetail financialDetail, final String appropriationNumber) throws ValidationException { boolean flag = false; final Date appDate = new Date(); double depApprAmnt = 0.0; final Accountdetailtype accountdetailtype = worksService.getAccountdetailtypeByName("DEPOSITCODE"); // In case of deposit work whole amount will be appropriated at once. if (appDate.compareTo(financialDetail.getAbstractEstimate().getEstimateDate()) >= 0) depApprAmnt = financialDetail.getAbstractEstimate().getTotalAmount().getValue(); final BigDecimal creditBalance = egovCommon.getDepositAmountForDepositCode(new Date(), financialDetail.getCoa().getGlcode(), financialDetail.getFund().getCode(), accountdetailtype.getId(),/* w w w . j a va 2 s .com*/ financialDetail.getAbstractEstimate().getDepositCode().getId().intValue()); BigDecimal utilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks(financialDetail, appDate); BigDecimal balance = BigDecimal.ZERO; if (utilizedAmt == null) { balance = creditBalance; utilizedAmt = BigDecimal.ZERO; } else balance = creditBalance.subtract(utilizedAmt); if (balance.doubleValue() >= depApprAmnt) { DepositWorksUsage depositWorksUsage = new DepositWorksUsage(); final CFinancialYear budgetApprDate_finYear = financialYearHibernateDAO.getFinYearByDate(appDate); depositWorksUsage.setTotalDepositAmount(creditBalance); depositWorksUsage.setConsumedAmount(new BigDecimal(depApprAmnt)); depositWorksUsage.setReleasedAmount(BigDecimal.ZERO); depositWorksUsage.setAppropriationNumber(appropriationNumber); depositWorksUsage.setAbstractEstimate(financialDetail.getAbstractEstimate()); depositWorksUsage.setAppropriationDate(appDate); depositWorksUsage.setFinancialYear(budgetApprDate_finYear); depositWorksUsage.setDepositCode(financialDetail.getAbstractEstimate().getDepositCode()); depositWorksUsage.setCoa(financialDetail.getCoa()); depositWorksUsage = depositWorksUsageService.persist(depositWorksUsage); persistDepositCodeAppDetails(depositWorksUsage); flag = true; } return flag; }
From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java
/** * Get Source Currency Balance - subtracts line and tax amounts from total - no rounding * /* w ww . j a v a2s . c o m*/ * @return positive amount, if total invoice is bigger than lines */ public BigDecimal getBalance() { // BigDecimal ZERO = new BigDecimal("0"); BigDecimal retValue = ZERO; StringBuffer sb = new StringBuffer(" ["); // Total retValue = retValue.add(new BigDecimal(getAmount(AcctServer.AMTTYPE_Gross))); sb.append(getAmount(AcctServer.AMTTYPE_Gross)); // - Charge retValue = retValue.subtract(new BigDecimal(getAmount(AcctServer.AMTTYPE_Charge))); sb.append("-").append(getAmount(AcctServer.AMTTYPE_Charge)); // - Tax for (int i = 0; i < m_taxes.length; i++) { retValue = retValue.subtract(new BigDecimal(m_taxes[i].getAmount())); sb.append("-").append(m_taxes[i].getAmount()); } // - Lines for (int i = 0; p_lines != null && i < p_lines.length; i++) { retValue = retValue.subtract(new BigDecimal(p_lines[i].getAmount())); sb.append("-").append(p_lines[i].getAmount()); } sb.append("]"); // log4jDocInvoice.debug("Balance=" + retValue + sb.toString()); return retValue; }
From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java
protected void prepareVkPreis(HashMap hmRabattsatzFixpreis, HashMap hmPreisbasis, Object[] source, Object[] target) {//from ww w .j a v a2s .c om // VK-Preis Berechnen BigDecimal vkPreis = null; BigDecimal vkPreisbasis = new BigDecimal(0); BigDecimal vkRabattsatz = new BigDecimal(0); BigDecimal vkFixpreis = new BigDecimal(0); if (hmRabattsatzFixpreis.containsKey(source[0])) { Object[] oTemp = (Object[]) hmRabattsatzFixpreis.get(source[0]); vkRabattsatz = (BigDecimal) oTemp[1]; vkFixpreis = (BigDecimal) oTemp[2]; } if (hmPreisbasis.containsKey(source[0])) { vkPreisbasis = (BigDecimal) hmPreisbasis.get(source[0]); } if (vkFixpreis != null) { vkPreis = vkFixpreis; } else { if (vkRabattsatz != null && vkPreisbasis != null) { BigDecimal bdRabattsumme = vkPreisbasis.multiply(vkRabattsatz.movePointLeft(2)); vkPreis = vkPreisbasis.subtract(bdRabattsumme); } else { vkPreis = vkPreisbasis; } } target[getTableColumnInformation().getViewIndex("lp.preis")] = vkPreis; }
From source file:org.efaps.esjp.accounting.transaction.FieldValue_Base.java
/** * Get the script to get the Prices for the Products. * * @param _parameter Parameter as passed from the eFaps API * @param _doc Instance of the Document the form was opened for * @throws EFapsException on error// ww w . jav a 2s . com */ protected void getPriceInformation(final Parameter _parameter, final DocumentInfo _doc) throws EFapsException { final QueryBuilder queryBldr = new QueryBuilder(CISales.PositionAbstract); queryBldr.addWhereAttrEqValue(CISales.PositionAbstract.DocumentAbstractLink, _doc.getInstance().getId()); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selTaxInst = new SelectBuilder().linkto(CISales.PositionSumAbstract.Tax).instance(); final SelectBuilder selProdInst = new SelectBuilder().linkto(CISales.PositionAbstract.Product).instance(); multi.addSelect(selTaxInst, selProdInst); multi.addAttribute(CISales.PositionSumAbstract.NetPrice, CISales.PositionSumAbstract.CrossPrice, CISales.PositionSumAbstract.Rate); multi.execute(); final Instance period = new Period().evaluateCurrentPeriod(_parameter); while (multi.next()) { final BigDecimal net = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.NetPrice); final BigDecimal cross = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.CrossPrice); final Object[] ratePos = multi.<Object[]>getAttribute(CISales.PositionSumAbstract.Rate); final BigDecimal newRatepos = ((BigDecimal) ratePos[0]).divide((BigDecimal) ratePos[1], 12, BigDecimal.ROUND_HALF_UP); final BigDecimal taxAmount = cross.subtract(net).multiply(newRatepos); final BigDecimal prodAmount = net.multiply(newRatepos); analyzeTax(_doc, false, multi.<Instance>getSelect(selTaxInst), taxAmount); final RateInfo rate = evaluateRate(_parameter, period, _doc.getDate(), _doc.getRateCurrInst()); analyzeProduct(_doc, false, multi.<Instance>getSelect(selProdInst), prodAmount, rate, CIAccounting.AccountIncomeStatementRevenue2ProductClass, CIAccounting.AccountIncomeStatementRevenue); } }
From source file:org.egov.egf.web.actions.deduction.RemitRecoveryAction.java
private void getRemittanceFromVoucher() { listRemitBean = new ArrayList<RemittanceBean>(); final List<EgRemittance> remitList = persistenceService.findAllBy("from EgRemittance where voucherheader=?", voucherHeader);/*from www.ja va2 s . com*/ for (final EgRemittance remit : remitList) { RemittanceBean rbean = null; final Set<EgRemittanceDetail> egRemittanceDetail = remit.getEgRemittanceDetail(); for (final EgRemittanceDetail remitDtl : egRemittanceDetail) { rbean = new RemittanceBean(); rbean.setPartialAmount(remitDtl.getRemittedamt()); rbean.setAmount(remitDtl.getRemittedamt()); if (remitDtl.getEgRemittanceGldtl() != null) { rbean.setDetailTypeId( remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail().getDetailTypeId().getId()); rbean.setDetailKeyid( remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail().getDetailKeyId().intValue()); rbean.setRemittance_gl_dtlId(remitDtl.getEgRemittanceGldtl().getId()); rbean.setDeductionAmount(remitDtl.getEgRemittanceGldtl().getGldtlamt()); } else rbean.setDeductionAmount(remitDtl.getRemittedamt()); rbean.setRemittanceId(remitDtl.getId()); BigDecimal calculatedEarlierPayment = BigDecimal.ZERO; if (remitDtl.getEgRemittanceGldtl() != null) calculatedEarlierPayment = calculateEarlierPayment(remitDtl); if (calculatedEarlierPayment.compareTo(BigDecimal.ZERO) == 0) rbean.setEarlierPayment(BigDecimal.ZERO); else if (remit.getVoucherheader().getStatus() .intValue() == FinancialConstants.CANCELLEDVOUCHERSTATUS.intValue() || remit.getVoucherheader().getStatus() .intValue() == FinancialConstants.REVERSALVOUCHERSTATUS.intValue()) rbean.setEarlierPayment(calculatedEarlierPayment); else rbean.setEarlierPayment(calculatedEarlierPayment.subtract(remitDtl.getRemittedamt())); final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); if (remitDtl.getEgRemittanceGldtl() != null) { final EntityType entity = voucherHibDAO.getEntityInfo( remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail().getDetailKeyId().intValue(), remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail().getDetailTypeId().getId()); rbean.setPartyCode(entity.getCode()); rbean.setPartyName(entity.getName()); rbean.setPanNo(entity.getPanno()); rbean.setVoucherDate(sdf.format(remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail() .getGeneralLedgerId().getVoucherHeaderId().getVoucherDate())); rbean.setVoucherNumber(remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail() .getGeneralLedgerId().getVoucherHeaderId().getVoucherNumber()); rbean.setVoucherName(remitDtl.getEgRemittanceGldtl().getGeneralledgerdetail() .getGeneralLedgerId().getVoucherHeaderId().getName()); } else if (remitDtl.getGeneralLedger().getVoucherHeaderId() != null) { rbean.setVoucherDate( sdf.format(remitDtl.getGeneralLedger().getVoucherHeaderId().getVoucherDate())); rbean.setVoucherNumber(remitDtl.getGeneralLedger().getVoucherHeaderId().getVoucherNumber()); rbean.setVoucherName(remitDtl.getGeneralLedger().getVoucherHeaderId().getName()); } listRemitBean.add(rbean); } if (remittanceBean.getRecoveryId() == null) remittanceBean.setRecoveryId(remit.getRecovery().getId()); } }
From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java
private void insertFizClaimPaymentByDebtor(Session sessionQuery, Session sessionTransaction, Validator validator, BankStatement bs, LocalDateTime dateTime, String tin) throws Exception { Query query = sessionQuery/* ww w. j a v a2 s . c o m*/ .createQuery("SELECT COALESCE(SUM(da.summa),0) FROM DsApplication da WHERE da.tin = :tin") .setParameter("tin", tin); BigDecimal allClaimSum = (BigDecimal) query.uniqueResult(); query = sessionQuery .createQuery("SELECT COALESCE(SUM(paymentSum),0) FROM Payment p WHERE p.tin = :tin AND p.claim = 1") .setParameter("tin", tin); BigDecimal paidClaimSum = (BigDecimal) query.uniqueResult(); BigDecimal realClaimSum, realPaymentSum; BigDecimal needClaimSum = allClaimSum.subtract(paidClaimSum); if (needClaimSum.compareTo(BigDecimal.ZERO) == 0) { realClaimSum = BigDecimal.ZERO; realPaymentSum = bs.getPaymentSum(); } else if (bs.getPaymentSum().compareTo(needClaimSum) <= 0) { realClaimSum = bs.getPaymentSum(); realPaymentSum = BigDecimal.ZERO; } else { realClaimSum = needClaimSum; realPaymentSum = bs.getPaymentSum().subtract(needClaimSum); } String tinDebtor = tin.equals(bs.getTin()) ? null : bs.getTin(); if (realClaimSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realClaimSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 1); // payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } if (realPaymentSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realPaymentSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 0); // payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } bs.setTransfered((short) 1); sessionTransaction.update(bs); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The natural logarithm.// ww w .j a v a 2s .c o m * * @param x the argument. * @return ln(x). * The precision of the result is implicitly defined by the precision in the argument. */ static public BigDecimal log(BigDecimal x) { /* the value is undefined if x is negative. */ if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("Cannot take log of negative " + x.toString()); } else if (x.compareTo(BigDecimal.ONE) == 0) { /* log 1. = 0. */ return scalePrec(BigDecimal.ZERO, x.precision() - 1); } else if (Math.abs(x.doubleValue() - 1.0) <= 0.3) { /* The standard Taylor series around x=1, z=0, z=x-1. Abramowitz-Stegun 4.124. * The absolute error is err(z)/(1+z) = err(x)/x. */ BigDecimal z = scalePrec(x.subtract(BigDecimal.ONE), 2); BigDecimal zpown = z; double eps = 0.5 * x.ulp().doubleValue() / Math.abs(x.doubleValue()); BigDecimal resul = z; for (int k = 2;; k++) { zpown = multiplyRound(zpown, z); BigDecimal c = divideRound(zpown, k); if (k % 2 == 0) { resul = resul.subtract(c); } else { resul = resul.add(c); } if (Math.abs(c.doubleValue()) < eps) { break; } } MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } else { final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); /* Map log(x) = log root[r](x)^r = r*log( root[r](x)) with the aim * to move roor[r](x) near to 1.2 (that is, below the 0.3 appearing above), where log(1.2) is roughly 0.2. */ int r = (int) (Math.log(xDbl) / 0.2); /* Since the actual requirement is a function of the value 0.3 appearing above, * we avoid the hypothetical case of endless recurrence by ensuring that r >= 2. */ r = Math.max(2, r); /* Compute r-th root with 2 additional digits of precision */ BigDecimal xhighpr = scalePrec(x, 2); BigDecimal resul = root(r, xhighpr); resul = log(resul).multiply(new BigDecimal(r)); /* error propagation: log(x+errx) = log(x)+errx/x, so the absolute error * in the result equals the relative error in the input, xUlpDbl/xDbl . */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl / xDbl)); return resul.round(mc); } }
From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java
private void insertClaimPaymentManually(Session sessionQuery, Session sessionTransaction, Validator validator, BankStatement bs, String tin, String tinDebtor, Long issuerSerialNumber, String issuerIp, LocalDateTime dateTime) throws Exception { Query query = sessionQuery//from ww w .j a va 2 s . c o m .createQuery("SELECT COALESCE(SUM(da.summa),0) FROM DsApplication da WHERE da.tin = :tin") .setParameter("tin", tin); BigDecimal allClaimSum = (BigDecimal) query.uniqueResult(); query = sessionQuery .createQuery("SELECT COALESCE(SUM(paymentSum),0) FROM Payment p WHERE p.tin = :tin AND p.claim = 1") .setParameter("tin", tin); BigDecimal paidClaimSum = (BigDecimal) query.uniqueResult(); BigDecimal realClaimSum, realPaymentSum; BigDecimal needClaimSum = allClaimSum.subtract(paidClaimSum); if (needClaimSum.compareTo(BigDecimal.ZERO) == 0) { realClaimSum = BigDecimal.ZERO; realPaymentSum = bs.getPaymentSum(); } else if (bs.getPaymentSum().compareTo(needClaimSum) <= 0) { realClaimSum = bs.getPaymentSum(); realPaymentSum = BigDecimal.ZERO; } else { realClaimSum = needClaimSum; realPaymentSum = bs.getPaymentSum().subtract(needClaimSum); } if (realClaimSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); // payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realClaimSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 1); // payment.setIssuerSerialNumber(issuerSerialNumber); payment.setIssuerIp(issuerIp); payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } if (realPaymentSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); // payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realPaymentSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 0); // payment.setIssuerSerialNumber(issuerSerialNumber); payment.setIssuerIp(issuerIp); payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } bs.setTransfered((short) 1); sessionTransaction.update(bs); }
From source file:com.heliumv.api.production.ProductionApi.java
@POST @Path("/materialwithdrawal/") @Consumes({ "application/json", "application/xml" }) public void bucheMaterialNachtraeglichVomLagerAb(@HeaderParam(ParamInHeader.TOKEN) String headerUserId, MaterialWithdrawalEntry materialEntry, @QueryParam("userId") String userId) { ArtikelDto itemDto = null;//from w ww .j a v a 2 s . c om LagerDto lagerDto = null; try { if (materialEntry == null) { respondBadRequestValueMissing("materialwithdrawal"); return; } if (StringHelper.isEmpty(materialEntry.getLotCnr())) { respondBadRequestValueMissing("lotCnr"); return; } if (StringHelper.isEmpty(materialEntry.getItemCnr())) { respondBadRequestValueMissing("itemCnr"); return; } if (materialEntry.getAmount() == null || materialEntry.getAmount().signum() == 0) { respondBadRequest("amount", "null/0"); return; } if (connectClient(headerUserId, userId) == null) return; // if(!judgeCall.hasFertLosCUD()) { if (!mandantCall.hasModulLos()) { respondNotFound(); return; } if (!fertigungCall.darfGebeMaterialNachtraeglichAus()) { respondUnauthorized(); return; } LosDto losDto = findLosByCnr(materialEntry.getLotCnr()); if (losDto == null) { respondNotFound("lotCnr", materialEntry.getLotCnr()); return; } if (!isValidLosState(losDto)) return; itemDto = findItemByCnr(materialEntry.getItemCnr()); if (itemDto == null) { respondNotFound("itemCnr", materialEntry.getItemCnr()); return; } MontageartDto montageartDto = getMontageart(); if (montageartDto == null) { respondBadRequest("montageart", "no value defined"); return; } lagerDto = getLager(materialEntry.getStockCnr(), materialEntry.getStockId()); if (lagerDto == null) { return; } if (materialEntry.getAmount().signum() > 0) { MaterialRuecknahme ausgabe = new MaterialRuecknahme(losDto.getIId(), lagerDto.getIId(), itemDto); if (!ausgabe.verifyAmounts(materialEntry.getAmount(), materialEntry.getIdentities())) { return; } gebeMaterialNachtraeglichAus(lagerDto.getIId(), losDto, itemDto, montageartDto, materialEntry.getAmount(), materialEntry.getIdentities()); } else { BigDecimal amountToReturn = materialEntry.getAmount().abs(); MaterialRuecknahme ruecknahme = new MaterialRuecknahme(losDto.getIId(), lagerDto.getIId(), itemDto); ruecknahme.setReturn(materialEntry.getReturn()); if (!ruecknahme.verifyAmounts(amountToReturn, materialEntry.getIdentities())) { return; } BigDecimal amountNotReturned = ruecknahme.returnItem(amountToReturn, materialEntry.getIdentities(), false); if (amountNotReturned.signum() == 0) { amountNotReturned = ruecknahme.returnItem(amountToReturn, materialEntry.getIdentities(), true); } if (amountNotReturned.signum() != 0) { respondBadRequest(EJBExceptionLP.FEHLER_ZUWENIG_AUF_LAGER); appendBadRequestData("stock-available", amountToReturn.subtract(amountNotReturned).toPlainString()); } } } catch (NamingException e) { respondUnavailable(e); } catch (RemoteException e) { respondUnavailable(e); } catch (EJBExceptionLP e) { respondBadRequest(e); if (e.getCode() == EJBExceptionLP.FEHLER_ZUWENIG_AUF_LAGER) { try { BigDecimal lagerStand = getLagerCall().getLagerstandOhneExc(itemDto.getIId(), lagerDto.getIId()); appendBadRequestData("stock-available", lagerStand.toPlainString()); } catch (NamingException n) { respondUnavailable(n); } catch (RemoteException r) { respondUnavailable(r); } } } }
From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java
private void insertClaimPayment(Session sessionQuery, Session sessionTransaction, Validator validator, BankStatement bs, String yurTin, LocalDateTime dateTime) throws Exception { Query query = sessionQuery//from www . j a v a 2s . c o m .createQuery("SELECT COALESCE(SUM(da.summa),0) FROM DsApplication da WHERE da.tin = :tin") .setParameter("tin", bs.getTin()); BigDecimal allClaimSum = (BigDecimal) query.uniqueResult(); query = sessionQuery .createQuery("SELECT COALESCE(SUM(paymentSum),0) FROM Payment p WHERE p.tin = :tin AND p.claim = 1") .setParameter("tin", bs.getTin()); BigDecimal paidClaimSum = (BigDecimal) query.uniqueResult(); BigDecimal realClaimSum, realPaymentSum; BigDecimal needClaimSum = allClaimSum.subtract(paidClaimSum); if (needClaimSum.compareTo(BigDecimal.ZERO) == 0) { realClaimSum = BigDecimal.ZERO; realPaymentSum = bs.getPaymentSum(); } else if (bs.getPaymentSum().compareTo(needClaimSum) <= 0) { realClaimSum = bs.getPaymentSum(); realPaymentSum = BigDecimal.ZERO; } else { realClaimSum = needClaimSum; realPaymentSum = bs.getPaymentSum().subtract(needClaimSum); } String tin, tinDebtor; if ("201122919".equals(bs.getTin())) { tin = yurTin; tinDebtor = bs.getTin(); } else { tin = bs.getTin(); tinDebtor = null; } if (realClaimSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realClaimSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 1); // payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } if (realPaymentSum.compareTo(BigDecimal.ZERO) > 0) { Payment payment = new Payment(); payment.setTin(tin); payment.setPaymentNum(bs.getPaymentNum()); payment.setPaymentDate(bs.getPaymentDate()); payment.setPaymentSum(realPaymentSum); // payment.setSourceCode((short) 1); payment.setState((short) 1); payment.setTinDebtor(tinDebtor); payment.setClaim((short) 0); // payment.setDateCreated(dateTime); payment.setDateUpdated(dateTime); Set<ConstraintViolation<Payment>> constraints = validator.validate(payment); if (constraints.isEmpty()) { sessionTransaction.save(payment); BankStatementPayment bsp = new BankStatementPayment(); BankStatementPaymentId bspId = new BankStatementPaymentId(); bspId.setBankStatement(bs); bspId.setPayment(payment); bsp.setId(bspId); sessionTransaction.save(bsp); } else { throw new Exception("payment isnot valid, tin = " + payment.getTin()); } } bs.setTransfered((short) 1); sessionTransaction.update(bs); }