List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.ofbiz.order.order.OrderServices.java
/** Service to invoice service items from order*/ public static Map<String, Object> invoiceServiceItems(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); Locale locale = (Locale) context.get("locale"); OrderReadHelper orh = null;//from ww w .ja va2s.com try { orh = new OrderReadHelper(delegator, orderId); } catch (IllegalArgumentException e) { Debug.logError(e, "ERROR: Unable to get OrderHeader for orderId : " + orderId, module); return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorUnableToGetOrderHeaderForOrderId", UtilMisc.toMap("orderId", orderId), locale)); } // get all the approved items for the order List<GenericValue> orderItems = null; orderItems = orh.getOrderItemsByCondition(EntityCondition.makeCondition("statusId", "ITEM_APPROVED")); // find any service items List<GenericValue> serviceItems = FastList.newInstance(); if (UtilValidate.isNotEmpty(orderItems)) { for (GenericValue item : orderItems) { GenericValue product = null; try { product = item.getRelatedOne("Product"); } catch (GenericEntityException e) { Debug.logError(e, "ERROR: Unable to get Product from OrderItem", module); } if (product != null) { // check for service goods if ("SERVICE".equals(product.get("productTypeId"))) { serviceItems.add(item); } } } } // now process the service items if (UtilValidate.isNotEmpty(serviceItems)) { // Make sure there is actually something needing invoicing because createInvoiceForOrder doesn't check List<GenericValue> billItems = FastList.newInstance(); for (GenericValue item : serviceItems) { BigDecimal orderQuantity = OrderReadHelper.getOrderItemQuantity(item); BigDecimal invoiceQuantity = OrderReadHelper.getOrderItemInvoicedQuantity(item); BigDecimal outstandingQuantity = orderQuantity.subtract(invoiceQuantity); if (outstandingQuantity.compareTo(ZERO) > 0) { billItems.add(item); } } // do something tricky here: run as a different user that can actually create an invoice, post transaction, etc Map<String, Object> invoiceResult = null; try { GenericValue permUserLogin = ServiceUtil.getUserLogin(dctx, context, "system"); Map<String, Object> invoiceContext = UtilMisc.toMap("orderId", orderId, "billItems", billItems, "userLogin", permUserLogin); invoiceResult = dispatcher.runSync("createInvoiceForOrder", invoiceContext); } catch (GenericServiceException e) { Debug.logError(e, "ERROR: Unable to invoice service items", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemWithInvoiceCreationServiceItems", locale)); } if (ModelService.RESPOND_ERROR.equals(invoiceResult.get(ModelService.RESPONSE_MESSAGE))) { return ServiceUtil.returnError((String) invoiceResult.get(ModelService.ERROR_MESSAGE)); } // update the status of service goods to COMPLETED; for (GenericValue item : serviceItems) { Map<String, Object> statusCtx = FastMap.newInstance(); statusCtx.put("orderId", item.getString("orderId")); statusCtx.put("orderItemSeqId", item.getString("orderItemSeqId")); statusCtx.put("statusId", "ITEM_COMPLETED"); statusCtx.put("userLogin", userLogin); try { dispatcher.runSyncIgnore("changeOrderItemStatus", statusCtx); } catch (GenericServiceException e) { Debug.logError(e, "ERROR: Problem setting the status to COMPLETED : " + item, module); } } } return ServiceUtil.returnSuccess(); }
From source file:org.egov.egf.commons.EgovCommon.java
protected BigDecimal getGlcodeBalTillDate(final Date asondate, final String glcode, final String fundcode, final Integer accountdetailType, final Integer accountdetailkey, final Integer deptId) throws ValidationException { final StringBuffer glCodeBalQry = new StringBuffer(400); final StringBuffer glCodeDbtBalQry = new StringBuffer(400); final StringBuffer glCodeCrdBalQry = new StringBuffer(400); BigDecimal glCodeBalance = BigDecimal.ZERO; BigDecimal glCodeDbtBalance = BigDecimal.ZERO; BigDecimal glCodeCrdBalance = BigDecimal.ZERO; String deptCond = ""; String misTab = ""; String fundCond = ""; if (fundcode != null) fundCond = " and vh.fundId.code='" + fundcode + "'"; if (deptId != null) { misTab = ",Vouchermis mis"; deptCond = " and mis.voucherheaderid.id=vh.id and mis.departmentid.id=" + deptId; }//from w w w.jav a 2 s . co m final List<AppConfigValues> appList = appConfigValuesService .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "statusexcludeReport"); final String statusExclude = appList.get(0).getValue(); if (null == accountdetailType && null == accountdetailkey) { glCodeBalQry.append( "SELECT (case when sum(gl.debitAmount)=null then 0 else sum(gl.debitAmount) end - case when sum(gl.creditAmount) = null then 0 else sum(gl.creditAmount) end)") .append(" as amount FROM CGeneralLedger gl , CVoucherHeader vh ").append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.glcodeId.glcode=?") .append(fundCond + deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")"); final List<Object> list = getPersistenceService().findAllBy(glCodeBalQry.toString(), glcode); glCodeBalance = BigDecimal.valueOf((Double) list.get(0)); } else { // Getting the debit balance. glCodeDbtBalQry.append( "SELECT sum(gld.amount) as debitamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld ") .append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=? ") .append(fundCond).append(deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")").append(" and gld.detailTypeId.id =") .append(accountdetailType); if (null != accountdetailkey) glCodeDbtBalQry.append(" and gld.detailKeyId =").append(accountdetailkey); glCodeDbtBalQry.append(" and gl.debitAmount >0"); final List<Object> listDbt = getPersistenceService().findAllBy(glCodeDbtBalQry.toString(), glcode); glCodeDbtBalance = (BigDecimal) listDbt.get(0) == null ? BigDecimal.ZERO : (BigDecimal) listDbt.get(0); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total debit amount : " + glCodeDbtBalance); // get the credit balance glCodeCrdBalQry.append( "SELECT sum(gld.amount) as creditamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld") .append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=? ") .append(fundCond).append(deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")").append(" and gld.detailTypeId.id =") .append(accountdetailType); if (null != accountdetailkey) glCodeCrdBalQry.append(" and gld.detailKeyId =").append(accountdetailkey); glCodeCrdBalQry.append(" and gl.creditAmount >0"); final List<Object> listCrd = getPersistenceService().findAllBy(glCodeCrdBalQry.toString(), glcode); glCodeCrdBalance = (BigDecimal) listCrd.get(0) == null ? BigDecimal.ZERO : (BigDecimal) listCrd.get(0); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total credit amount : " + glCodeCrdBalance); glCodeBalance = glCodeDbtBalance.subtract(glCodeCrdBalance); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total balance amount : " + glCodeBalance); } return glCodeBalance; }
From source file:org.egov.egf.commons.EgovCommon.java
protected BigDecimal getGlcodeBalBeforeDate(final Date asondate, final String glcode, final String fundcode, final Integer accountdetailType, final Integer accountdetailkey, final Integer deptId) throws ValidationException { final StringBuffer glCodeBalQry = new StringBuffer(400); final StringBuffer glCodeDbtBalQry = new StringBuffer(400); final StringBuffer glCodeCrdBalQry = new StringBuffer(400); BigDecimal glCodeBalance = BigDecimal.ZERO; BigDecimal glCodeDbtBalance = BigDecimal.ZERO; BigDecimal glCodeCrdBalance = BigDecimal.ZERO; String deptCond = ""; String misTab = ""; String fundCond = ""; if (fundcode != null) fundCond = " and vh.fundId.code='" + fundcode + "'"; if (deptId != null) { misTab = ",Vouchermis mis"; deptCond = " and mis.voucherheaderid.id=vh.id and mis.departmentid.id=" + deptId; }//from ww w.ja va 2 s . co m final List<AppConfigValues> appList = appConfigValuesService .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "statusexcludeReport"); final String statusExclude = appList.get(0).getValue(); if (null == accountdetailType && null == accountdetailkey) { glCodeBalQry.append( "SELECT (case when sum(gl.debitAmount) is null then 0 else sum(gl.debitAmount) end - case when sum(gl.creditAmount) is null then 0 else sum(gl.creditAmount) end)") .append(" as amount FROM CGeneralLedger gl , CVoucherHeader vh ").append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.glcodeId.glcode=?") .append(fundCond + deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <'") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")"); final List<Object> list = getPersistenceService().findAllBy(glCodeBalQry.toString(), glcode); glCodeBalance = BigDecimal.valueOf((Integer) list.get(0)); } else { // Getting the debit balance. glCodeDbtBalQry.append( "SELECT sum(gld.amount) as debitamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld ") .append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=? ") .append(fundCond).append(deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <'") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")").append(" and gld.detailTypeId.id =") .append(accountdetailType); if (null != accountdetailkey) glCodeDbtBalQry.append(" and gld.detailKeyId =").append(accountdetailkey); glCodeDbtBalQry.append(" and gl.debitAmount >0"); final List<Object> listDbt = getPersistenceService().findAllBy(glCodeDbtBalQry.toString(), glcode); glCodeDbtBalance = (BigDecimal) listDbt.get(0) == null ? BigDecimal.ZERO : (BigDecimal) listDbt.get(0); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total debit amount : " + glCodeDbtBalance); // get the credit balance glCodeCrdBalQry.append( "SELECT sum(gld.amount) as creditamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld") .append(misTab) .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=? ") .append(fundCond).append(deptCond) .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <'") .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (") .append(statusExclude).append(")").append(" and gld.detailTypeId.id =") .append(accountdetailType); if (null != accountdetailkey) glCodeCrdBalQry.append(" and gld.detailKeyId =").append(accountdetailkey); glCodeCrdBalQry.append(" and gl.creditAmount >0"); final List<Object> listCrd = getPersistenceService().findAllBy(glCodeCrdBalQry.toString(), glcode); glCodeCrdBalance = (BigDecimal) listCrd.get(0) == null ? BigDecimal.ZERO : (BigDecimal) listCrd.get(0); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total credit amount : " + glCodeCrdBalance); glCodeBalance = glCodeDbtBalance.subtract(glCodeCrdBalance); if (LOGGER.isDebugEnabled()) LOGGER.debug(" total balance amount : " + glCodeBalance); } return glCodeBalance; }
From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentProcess.java
private void processPayment(FIN_Payment payment, String strAction, Boolean isPosOrder, String paymentDate, String comingFrom, String selectedCreditLineIds) throws OBException { dao = new AdvPaymentMngtDao(); String msg = ""; try {/*w w w. j a v a2s.c o m*/ final boolean isReceipt = payment.isReceipt(); if (strAction.equals("P") || strAction.equals("D")) { if (payment.getBusinessPartner() != null) { if (FIN_Utility.isBlockedBusinessPartner(payment.getBusinessPartner().getId(), isReceipt, 4)) { // If the Business Partner is blocked for Payments, the Payment will not be completed. msg = OBMessageUtils.messageBD("ThebusinessPartner") + " " + payment.getBusinessPartner().getIdentifier() + " " + OBMessageUtils.messageBD("BusinessPartnerBlocked"); throw new OBException(msg); } } else { OBContext.setAdminMode(true); try { for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) { for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) { BusinessPartner bPartner = null; if (psd.getInvoicePaymentSchedule() != null) { bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner(); } else if (psd.getOrderPaymentSchedule() != null) { bPartner = psd.getOrderPaymentSchedule().getOrder().getBusinessPartner(); } if (bPartner != null && FIN_Utility.isBlockedBusinessPartner(bPartner.getId(), payment.isReceipt(), 4)) { // If the Business Partner is blocked for Payments, the Payment will not be // completed. msg = OBMessageUtils.messageBD("ThebusinessPartner") + " " + bPartner.getIdentifier() + " " + OBMessageUtils.messageBD("BusinessPartnerBlocked"); throw new OBException(msg); } } } } finally { OBContext.restorePreviousMode(); } } } if (strAction.equals("P") || strAction.equals("D")) { // Guess if this is a refund payment boolean isRefund = false; OBContext.setAdminMode(false); try { List<FIN_PaymentDetail> paymentDetailList = payment.getFINPaymentDetailList(); if (paymentDetailList.size() > 0) { for (FIN_PaymentDetail det : paymentDetailList) { if (det.isRefund()) { isRefund = true; break; } } } } finally { OBContext.restorePreviousMode(); } if (!isRefund) { // Undo Used credit as it will be calculated again payment.setUsedCredit(BigDecimal.ZERO); OBDal.getInstance().save(payment); } boolean documentEnabled = getDocumentConfirmation(null, payment.getId()); boolean periodNotAvailable = documentEnabled && !FIN_Utility.isPeriodOpen(payment.getClient().getId(), payment.getDocumentType().getDocumentCategory(), payment.getOrganization().getId(), OBDateUtils.formatDate(payment.getPaymentDate())) && FIN_Utility.periodControlOpened(FIN_Payment.TABLE_NAME, payment.getId(), FIN_Payment.TABLE_NAME + "_ID", "LE"); if (periodNotAvailable) { msg = OBMessageUtils.messageBD("PeriodNotAvailable"); throw new OBException(msg); } Set<String> documentOrganizations = OBContext.getOBContext() .getOrganizationStructureProvider(payment.getClient().getId()) .getNaturalTree(payment.getOrganization().getId()); if (!documentOrganizations.contains(payment.getAccount().getOrganization().getId())) { msg = OBMessageUtils.messageBD("APRM_FinancialAccountNotInNaturalTree"); throw new OBException(msg); } Set<String> invoiceDocNos = new TreeSet<String>(); Set<String> orderDocNos = new TreeSet<String>(); Set<String> glitems = new TreeSet<String>(); BigDecimal paymentAmount = BigDecimal.ZERO; BigDecimal paymentWriteOfAmount = BigDecimal.ZERO; // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be // removed when new security implementation is done OBContext.setAdminMode(); boolean flushDone = false; try { String strRefundCredit = ""; // update payment schedule amount List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList(); // Show error message when payment has no lines if (paymentDetails.size() == 0) { msg = OBMessageUtils.messageBD("APRM_PaymentNoLines"); log4j.debug(msg); throw new OBException(msg, false); } for (FIN_PaymentDetail paymentDetail : paymentDetails) { for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail .getFINPaymentScheduleDetailList()) { paymentAmount = paymentAmount.add(paymentScheduleDetail.getAmount()); BigDecimal writeoff = paymentScheduleDetail.getWriteoffAmount(); if (writeoff == null) writeoff = BigDecimal.ZERO; paymentWriteOfAmount = paymentWriteOfAmount.add(writeoff); if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) { final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice(); invoiceDocNos .add(FIN_Utility.getDesiredDocumentNo(payment.getOrganization(), invoice)); } if (paymentScheduleDetail.getOrderPaymentSchedule() != null) { orderDocNos.add( paymentScheduleDetail.getOrderPaymentSchedule().getOrder().getDocumentNo()); } if (paymentScheduleDetail.getInvoicePaymentSchedule() == null && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getPaymentDetails().getGLItem() == null) { if (paymentDetail.isRefund()) strRefundCredit = OBMessageUtils.messageBD("APRM_RefundAmount"); else { strRefundCredit = OBMessageUtils.messageBD("APRM_CreditAmount"); payment.setGeneratedCredit(paymentDetail.getAmount()); } strRefundCredit += ": " + paymentDetail.getAmount().toString(); } } if (paymentDetail.getGLItem() != null) glitems.add(paymentDetail.getGLItem().getName()); } // Set description if (!isPosOrder) { StringBuffer description = new StringBuffer(); if (payment.getDescription() != null && !payment.getDescription().equals("")) description.append(payment.getDescription()).append("\n"); if (!invoiceDocNos.isEmpty()) { description.append(OBMessageUtils.messageBD("InvoiceDocumentno")); description.append(": ").append( invoiceDocNos.toString().substring(1, invoiceDocNos.toString().length() - 1)); description.append("\n"); } if (!orderDocNos.isEmpty()) { description.append(OBMessageUtils.messageBD("OrderDocumentno")); description.append(": ").append( orderDocNos.toString().substring(1, orderDocNos.toString().length() - 1)); description.append("\n"); } if (!glitems.isEmpty()) { description.append(OBMessageUtils.messageBD("APRM_GLItem")); description.append(": ") .append(glitems.toString().substring(1, glitems.toString().length() - 1)); description.append("\n"); } if (!"".equals(strRefundCredit)) description.append(strRefundCredit).append("\n"); String truncateDescription = (description.length() > 255) ? description.substring(0, 251).concat("...").toString() : description.toString(); payment.setDescription(truncateDescription); } if (paymentAmount.compareTo(payment.getAmount()) != 0) { payment.setUsedCredit(paymentAmount.subtract(payment.getAmount())); } if (payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) { updateUsedCredit(payment, selectedCreditLineIds); } payment.setWriteoffAmount(paymentWriteOfAmount); payment.setProcessed(true); payment.setAPRMProcessPayment("RE"); if (payment.getGeneratedCredit() == null) { payment.setGeneratedCredit(BigDecimal.ZERO); } if (BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0 || BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0) { BusinessPartner businessPartner = payment.getBusinessPartner(); if (businessPartner == null) { msg = OBMessageUtils.messageBD("APRM_CreditWithoutBPartner"); throw new OBException(msg); } String currency = null; if (businessPartner.getCurrency() == null) { currency = payment.getCurrency().getId(); businessPartner.setCurrency(payment.getCurrency()); } else { currency = businessPartner.getCurrency().getId(); } if (!payment.getCurrency().getId().equals(currency)) { msg = String.format(OBMessageUtils.messageBD("APRM_CreditCurrency"), businessPartner.getCurrency().getISOCode()); throw new OBException(msg); } } // Execution Process if (!isPosOrder && dao.isAutomatedExecutionPayment(payment.getAccount(), payment.getPaymentMethod(), payment.isReceipt())) { try { payment.setStatus("RPAE"); if (dao.hasNotDeferredExecutionProcess(payment.getAccount(), payment.getPaymentMethod(), payment.isReceipt())) { PaymentExecutionProcess executionProcess = dao.getExecutionProcess(payment); if (dao.isAutomaticExecutionProcess(executionProcess)) { final List<FIN_Payment> payments = new ArrayList<FIN_Payment>(1); payments.add(payment); FIN_ExecutePayment executePayment = new FIN_ExecutePayment(); executePayment.init("APP", executionProcess, payments, null, payment.getOrganization()); executePayment.addInternalParameter("comingFrom", comingFrom); OBError result = executePayment.execute(); if ("Error".equals(result.getType())) { msg = OBMessageUtils.messageBD(result.getMessage()); } else if (!"".equals(result.getMessage())) { String execProcessMsg = OBMessageUtils.messageBD(result.getMessage()); if (!"".equals(msg)) { msg += "<br>"; } msg += execProcessMsg; } } } } catch (final NoExecutionProcessFoundException e) { msg = OBMessageUtils.messageBD("NoExecutionProcessFound"); throw new OBException(msg); } catch (final Exception e) { msg = OBMessageUtils.messageBD("IssueOnExecutionProcess"); throw new OBException(msg); } } else { BusinessPartner businessPartner = payment.getBusinessPartner(); // When credit is used (consumed) we compensate so_creditused as this amount is already // included in the payment details. Credit consumed should not affect to so_creditused if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) { if (isReceipt) { increaseCustomerCredit(businessPartner, payment.getUsedCredit()); } else { decreaseCustomerCredit(businessPartner, payment.getUsedCredit()); } } for (FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) { List<FIN_PaymentScheduleDetail> orderPaymentScheduleDetails = new ArrayList<FIN_PaymentScheduleDetail>( paymentDetail.getFINPaymentScheduleDetailList()); // Get payment schedule detail list ordered by amount asc. // First negative if they exist and then positives if (orderPaymentScheduleDetails.size() > 1) { Collections.sort(orderPaymentScheduleDetails, new Comparator<FIN_PaymentScheduleDetail>() { @Override public int compare(FIN_PaymentScheduleDetail o1, FIN_PaymentScheduleDetail o2) { // TODO Auto-generated method stub return o1.getAmount().compareTo(o2.getAmount()); } }); } for (FIN_PaymentScheduleDetail paymentScheduleDetail : orderPaymentScheduleDetails) { BigDecimal amount = paymentScheduleDetail.getAmount() .add(paymentScheduleDetail.getWriteoffAmount()); // Do not restore paid amounts if the payment is awaiting execution. boolean invoicePaidAmounts = (FIN_Utility .seqnumberpaymentstatus(isReceipt ? "RPR" : "PPM")) >= (FIN_Utility .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment))); paymentScheduleDetail.setInvoicePaid(false); // Payment = 0 when the payment is generated by a invoice that consume credit if (invoicePaidAmounts || (payment.getAmount().compareTo(new BigDecimal("0.00")) == 0)) { if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) { // BP SO_CreditUsed businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice().getBusinessPartner(); // Payments update credit opposite to invoices BigDecimal paidAmount = BigDecimal.ZERO; Invoice invoiceForConversion = paymentScheduleDetail .getInvoicePaymentSchedule() != null ? paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice() : null; paidAmount = BigDecimal.ZERO; String fromCurrency = payment.getCurrency().getId(); if (businessPartner.getCurrency() == null) { String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk", false); msg = String.format(errorMSG, businessPartner.getId(), businessPartner.getName()); throw new OBException(msg); } String toCurrency = businessPartner.getCurrency().getId(); if (!fromCurrency.equals(toCurrency)) { BigDecimal exchangeRate = BigDecimal.ZERO; // check at invoice document level List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice( invoiceForConversion); if (conversionRateDocumentForInvoice.size() > 0) { exchangeRate = conversionRateDocumentForInvoice.get(0).getRate(); } else { // global exchangeRate = getConversionRate(payment.getOrganization().getId(), fromCurrency, toCurrency, invoiceForConversion != null ? invoiceForConversion.getInvoiceDate() : payment.getPaymentDate()); } if (exchangeRate == BigDecimal.ZERO) { msg = OBMessageUtils.messageBD("NoCurrencyConversion"); throw new OBException(msg); } paidAmount = amount.multiply(exchangeRate); } else { paidAmount = amount; } if (isReceipt) { decreaseCustomerCredit(businessPartner, paidAmount); } else { increaseCustomerCredit(businessPartner, paidAmount); } FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail, paymentScheduleDetail.getInvoicePaymentSchedule(), paymentScheduleDetail.getAmount(), paymentScheduleDetail.getWriteoffAmount()); paymentScheduleDetail.setInvoicePaid(true); } if (paymentScheduleDetail.getOrderPaymentSchedule() != null) { FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail, paymentScheduleDetail.getOrderPaymentSchedule(), paymentScheduleDetail.getAmount(), paymentScheduleDetail.getWriteoffAmount()); paymentScheduleDetail.setInvoicePaid(true); } // when generating credit for a BP SO_CreditUsed is also updated if (paymentScheduleDetail.getInvoicePaymentSchedule() == null && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getPaymentDetails().getGLItem() == null && !paymentDetail.isRefund()) { // BP SO_CreditUsed if (isReceipt) { decreaseCustomerCredit(businessPartner, amount); } else { increaseCustomerCredit(businessPartner, amount); } } } } } payment.setStatus(isReceipt ? "RPR" : "PPM"); if ((strAction.equals("D") || FIN_Utility.isAutomaticDepositWithdrawn(payment)) && payment.getAmount().compareTo(BigDecimal.ZERO) != 0 && !"TRANSACTION".equals(comingFrom)) { triggerAutomaticFinancialAccountTransaction(payment); flushDone = true; } } if (!payment.getAccount().getCurrency().equals(payment.getCurrency()) && getConversionRateDocument(payment).size() == 0) { insertConversionRateDocument(payment); flushDone = true; } } finally { if (!flushDone) { OBDal.getInstance().flush(); } OBContext.restorePreviousMode(); } // *********************** // Reverse Payment // *********************** } else if (strAction.equals("RV")) { FIN_Payment reversedPayment = (FIN_Payment) DalUtil.copy(payment, false); OBContext.setAdminMode(); try { if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0 && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0) { throw new OBException("@APRM_CreditConsumed@"); } else if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0 && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) == 0) { reversedPayment.setUsedCredit(payment.getGeneratedCredit()); reversedPayment.setGeneratedCredit(BigDecimal.ZERO); } else { reversedPayment.setUsedCredit(BigDecimal.ZERO); reversedPayment.setGeneratedCredit(BigDecimal.ZERO); } reversedPayment.setDocumentNo( "*R*" + FIN_Utility.getDocumentNo(payment.getDocumentType(), "FIN_Payment")); reversedPayment.setPaymentDate(FIN_Utility.getDate(paymentDate)); reversedPayment.setDescription(""); reversedPayment.setProcessed(false); reversedPayment.setPosted("N"); reversedPayment.setProcessNow(false); reversedPayment.setAPRMProcessPayment("P"); reversedPayment.setStatus("RPAP"); // Amounts reversedPayment.setAmount(payment.getAmount().negate()); reversedPayment.setWriteoffAmount(payment.getWriteoffAmount().negate()); reversedPayment.setFinancialTransactionAmount(payment.getFinancialTransactionAmount().negate()); OBDal.getInstance().save(reversedPayment); List<FIN_PaymentDetail> reversedDetails = new ArrayList<FIN_PaymentDetail>(); OBDal.getInstance().save(reversedPayment); List<FIN_Payment_Credit> credits = payment.getFINPaymentCreditList(); for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) { FIN_PaymentDetail reversedPaymentDetail = (FIN_PaymentDetail) DalUtil.copy(pd, false); reversedPaymentDetail.setFinPayment(reversedPayment); reversedPaymentDetail.setAmount(pd.getAmount().negate()); reversedPaymentDetail.setWriteoffAmount(pd.getWriteoffAmount().negate()); if (pd.isRefund()) { reversedPaymentDetail.setPrepayment(true); reversedPaymentDetail.setRefund(false); reversedPayment .setGeneratedCredit(reversedPayment.getGeneratedCredit().add(pd.getAmount())); credits = new ArrayList<FIN_Payment_Credit>(); OBDal.getInstance().save(reversedPayment); } else if (pd.isPrepayment() && pd.getFINPaymentScheduleDetailList().get(0).getOrderPaymentSchedule() == null) { reversedPaymentDetail.setPrepayment(true); reversedPaymentDetail.setRefund(true); } List<FIN_PaymentScheduleDetail> reversedSchedDetails = new ArrayList<FIN_PaymentScheduleDetail>(); OBDal.getInstance().save(reversedPaymentDetail); // Create or update PSD of orders and invoices to set the new outstanding amount for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) { if (psd.getInvoicePaymentSchedule() != null || psd.getOrderPaymentSchedule() != null) { OBCriteria<FIN_PaymentScheduleDetail> unpaidSchedDet = OBDal.getInstance() .createCriteria(FIN_PaymentScheduleDetail.class); if (psd.getInvoicePaymentSchedule() != null) unpaidSchedDet.add(Restrictions.eq( FIN_PaymentScheduleDetail.PROPERTY_INVOICEPAYMENTSCHEDULE, psd.getInvoicePaymentSchedule())); if (psd.getOrderPaymentSchedule() != null) unpaidSchedDet.add( Restrictions.eq(FIN_PaymentScheduleDetail.PROPERTY_ORDERPAYMENTSCHEDULE, psd.getOrderPaymentSchedule())); unpaidSchedDet.add( Restrictions.isNull(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS)); List<FIN_PaymentScheduleDetail> openPSDs = unpaidSchedDet.list(); // If invoice/order not fully paid, update outstanding amount if (openPSDs.size() > 0) { FIN_PaymentScheduleDetail openPSD = openPSDs.get(0); BigDecimal openAmount = openPSD.getAmount() .add(psd.getAmount().add(psd.getWriteoffAmount())); if (openAmount.compareTo(BigDecimal.ZERO) == 0) { OBDal.getInstance().remove(openPSD); } else { openPSD.setAmount(openAmount); } } else { // If invoice is fully paid create a new schedule detail. FIN_PaymentScheduleDetail openPSD = (FIN_PaymentScheduleDetail) DalUtil .copy(psd, false); openPSD.setPaymentDetails(null); // Amounts openPSD.setWriteoffAmount(BigDecimal.ZERO); openPSD.setAmount(psd.getAmount().add(psd.getWriteoffAmount())); openPSD.setCanceled(false); OBDal.getInstance().save(openPSD); } } FIN_PaymentScheduleDetail reversedPaymentSchedDetail = (FIN_PaymentScheduleDetail) DalUtil .copy(psd, false); reversedPaymentSchedDetail.setPaymentDetails(reversedPaymentDetail); // Amounts reversedPaymentSchedDetail.setWriteoffAmount(psd.getWriteoffAmount().negate()); reversedPaymentSchedDetail.setAmount(psd.getAmount().negate()); OBDal.getInstance().save(reversedPaymentSchedDetail); reversedSchedDetails.add(reversedPaymentSchedDetail); if ((FIN_Utility.invoicePaymentStatus(reversedPayment) .equals(reversedPayment.getStatus()))) { reversedPaymentSchedDetail.setInvoicePaid(true); } else { reversedPaymentSchedDetail.setInvoicePaid(false); } OBDal.getInstance().save(reversedPaymentSchedDetail); } reversedPaymentDetail.setFINPaymentScheduleDetailList(reversedSchedDetails); OBDal.getInstance().save(reversedPaymentDetail); reversedDetails.add(reversedPaymentDetail); } reversedPayment.setFINPaymentDetailList(reversedDetails); OBDal.getInstance().save(reversedPayment); List<FIN_Payment_Credit> reversedCredits = new ArrayList<FIN_Payment_Credit>(); for (FIN_Payment_Credit pc : credits) { FIN_Payment_Credit reversedPaymentCredit = (FIN_Payment_Credit) DalUtil.copy(pc, false); reversedPaymentCredit.setAmount(pc.getAmount().negate()); reversedPaymentCredit.setCreditPaymentUsed(pc.getCreditPaymentUsed()); pc.getCreditPaymentUsed().setUsedCredit( pc.getCreditPaymentUsed().getUsedCredit().add(pc.getAmount().negate())); reversedPaymentCredit.setPayment(reversedPayment); OBDal.getInstance().save(pc.getCreditPaymentUsed()); OBDal.getInstance().save(reversedPaymentCredit); reversedCredits.add(reversedPaymentCredit); } reversedPayment.setFINPaymentCreditList(reversedCredits); OBDal.getInstance().save(reversedPayment); List<ConversionRateDoc> conversions = new ArrayList<ConversionRateDoc>(); for (ConversionRateDoc cr : payment.getCurrencyConversionRateDocList()) { ConversionRateDoc reversedCR = (ConversionRateDoc) DalUtil.copy(cr, false); reversedCR.setForeignAmount(cr.getForeignAmount().negate()); reversedCR.setPayment(reversedPayment); OBDal.getInstance().save(reversedCR); conversions.add(reversedCR); } reversedPayment.setCurrencyConversionRateDocList(conversions); OBDal.getInstance().save(reversedPayment); OBDal.getInstance().flush(); } finally { OBContext.restorePreviousMode(); } payment.setReversedPayment(reversedPayment); OBDal.getInstance().save(payment); OBDal.getInstance().flush(); String newStrAction = "P"; FIN_PaymentProcess fpp = WeldUtils.getInstanceFromStaticBeanManager(FIN_PaymentProcess.class); fpp.processPayment(reversedPayment, newStrAction, isPosOrder, paymentDate, comingFrom, selectedCreditLineIds); return; // *********************** // Reactivate Payment // *********************** } else if (strAction.equals("R") || strAction.equals("RE")) { // Already Posted Document if ("Y".equals(payment.getPosted())) { msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo()); throw new OBException(msg); } // Reversed Payment if (payment.getReversedPayment() != null) { msg = OBMessageUtils.messageBD("APRM_PaymentReversed"); throw new OBException(msg); } // Reverse Payment if (strAction.equals("RE") && FIN_Utility.isReversePayment(payment)) { msg = OBMessageUtils.messageBD("APRM_ReversePayment"); throw new OBException(msg); } // Do not reactive the payment if it is tax payment if (payment.getFinancialMgmtTaxPaymentList().size() != 0) { msg = OBMessageUtils.messageBD("APRM_TaxPaymentReactivation"); throw new OBException(msg); } // Transaction exists if (hasTransaction(payment)) { msg = OBMessageUtils.messageBD("APRM_TransactionExists"); throw new OBException(msg); } // Payment with generated credit already used on other payments. if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) { msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed"); throw new OBException(msg); } if (FIN_Utility.invoicePaymentStatus(payment) == null) { msg = String.format(OBMessageUtils.messageBD("APRM_NoPaymentMethod"), payment.getPaymentMethod().getIdentifier(), payment.getDocumentNo(), payment.getAccount().getName()); throw new OBException(msg); } // Do not restore paid amounts if the payment is awaiting execution. boolean restorePaidAmounts = (FIN_Utility .seqnumberpaymentstatus(payment.getStatus())) == (FIN_Utility .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment))); // Initialize amounts payment.setProcessed(false); OBDal.getInstance().save(payment); OBDal.getInstance().flush(); payment.setWriteoffAmount(BigDecimal.ZERO); payment.setDescription(""); // if all line are deleted then update amount to zero if (strAction.equals("R")) { payment.setAmount(BigDecimal.ZERO); } payment.setStatus("RPAP"); payment.setAPRMProcessPayment("P"); OBDal.getInstance().save(payment); OBDal.getInstance().flush(); final List<FIN_PaymentDetail> removedPD = new ArrayList<FIN_PaymentDetail>(); List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>(); final List<String> removedPDIds = new ArrayList<String>(); // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be // removed when new security implementation is done OBContext.setAdminMode(); try { BusinessPartner businessPartner = payment.getBusinessPartner(); BigDecimal paidAmount = BigDecimal.ZERO; if (!(businessPartner == null)) { // When credit is used (consumed) we compensate so_creditused as this amount is already // included in the payment details. Credit consumed should not affect to so_creditused if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) { if (isReceipt) { decreaseCustomerCredit(businessPartner, payment.getUsedCredit()); } else { increaseCustomerCredit(businessPartner, payment.getUsedCredit()); } } } List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList(); List<ConversionRateDoc> conversionRates = payment.getCurrencyConversionRateDocList(); Set<String> invoiceDocNos = new HashSet<String>(); // Undo Reversed payment relationship List<FIN_Payment> revPayments = new ArrayList<FIN_Payment>(); for (FIN_Payment reversedPayment : payment.getFINPaymentReversedPaymentList()) { reversedPayment.setReversedPayment(null); OBDal.getInstance().save(reversedPayment); } payment.setFINPaymentReversedPaymentList(revPayments); OBDal.getInstance().save(payment); for (FIN_PaymentDetail paymentDetail : paymentDetails) { removedPDS = new ArrayList<FIN_PaymentScheduleDetail>(); for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail .getFINPaymentScheduleDetailList()) { Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid(); if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) { BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount(); BigDecimal psdAmount = paymentScheduleDetail.getAmount(); BigDecimal amount = psdAmount.add(psdWriteoffAmount); if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) { // Remove invoice description related to the credit payments final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice(); invoiceDocNos.add(invoice.getDocumentNo()); final String invDesc = invoice.getDescription(); if (invDesc != null) { final String creditMsg = OBMessageUtils .messageBD("APRM_InvoiceDescUsedCredit"); if (creditMsg != null) { StringBuffer newDesc = new StringBuffer(); for (final String line : invDesc.split("\n")) { if (!line.startsWith( creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) { newDesc.append(line); if (!"".equals(line)) newDesc.append("\n"); } } if (newDesc.length() > 255) { newDesc = newDesc.delete(251, newDesc.length()); newDesc = newDesc.append("...\n"); } invoice.setDescription(newDesc.toString()); } } if (restorePaidAmounts) { FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail, paymentScheduleDetail.getInvoicePaymentSchedule(), psdAmount.negate(), psdWriteoffAmount.negate()); paymentScheduleDetail.setInvoicePaid(false); OBDal.getInstance().save(paymentScheduleDetail); // BP SO_CreditUsed businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice().getBusinessPartner(); Invoice invoiceForConversion = paymentScheduleDetail .getInvoicePaymentSchedule() != null ? paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice() : null; paidAmount = BigDecimal.ZERO; if (!(businessPartner == null)) { final Currency fromCurrency = payment.getCurrency(); if (businessPartner.getCurrency() == null) { String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk", false); msg = String.format(errorMSG, businessPartner.getId(), businessPartner.getName()); throw new OBException(msg); } final Currency toCurrency = businessPartner.getCurrency(); if (fromCurrency != null && toCurrency != null && !fromCurrency.getId().equals(toCurrency.getId())) { BigDecimal exchangeRate = BigDecimal.ZERO; // check at invoice document level List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice( invoiceForConversion); if (conversionRateDocumentForInvoice.size() > 0) { exchangeRate = conversionRateDocumentForInvoice.get(0) .getRate(); } else { // global exchangeRate = getConversionRate( payment.getOrganization().getId(), fromCurrency.getId(), toCurrency.getId(), invoiceForConversion != null ? invoiceForConversion.getInvoiceDate() : payment.getPaymentDate()); } if (exchangeRate == BigDecimal.ZERO) { msg = OBMessageUtils.messageBD("NoCurrencyConversion"); throw new OBException(msg); } paidAmount = amount.multiply(exchangeRate); } else { paidAmount = amount; } if (isReceipt) { increaseCustomerCredit(businessPartner, paidAmount); } else { decreaseCustomerCredit(businessPartner, paidAmount); } } } } if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) { FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail, paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(), psdWriteoffAmount.negate()); } if (restorePaidAmounts) { // when generating credit for a BP SO_CreditUsed is also updated if (paymentScheduleDetail.getInvoicePaymentSchedule() == null && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getPaymentDetails().getGLItem() == null && restorePaidAmounts && !paymentDetail.isRefund()) { // BP SO_CreditUsed if (isReceipt) { increaseCustomerCredit(businessPartner, amount); } else { decreaseCustomerCredit(businessPartner, amount); } } } } if (strAction.equals("R") || (strAction.equals("RE") && paymentScheduleDetail.getInvoicePaymentSchedule() == null && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getPaymentDetails().getGLItem() == null)) { FIN_AddPayment.mergePaymentScheduleDetails(paymentScheduleDetail); removedPDS.add(paymentScheduleDetail); } } paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS); if (strAction.equals("R")) { OBDal.getInstance().getSession().refresh(paymentDetail); } // If there is any schedule detail with amount zero, those are deleted // Besides it removes the payment proposal lines linked to the PSD when // a) we are removing the PSD and // b) if we are reactivating a payment (deleting lines only) and we don't come from // payment proposal reactivation process for (FIN_PaymentScheduleDetail psd : removedPDS) { int proposalLinesRemoved = 0; if (BigDecimal.ZERO.compareTo(psd.getAmount()) == 0 && BigDecimal.ZERO.compareTo(psd.getWriteoffAmount()) == 0) { paymentDetail.getFINPaymentScheduleDetailList().remove(psd); OBDal.getInstance().getSession().refresh(paymentDetail); if (psd.getInvoicePaymentSchedule() != null) { psd.getInvoicePaymentSchedule() .getFINPaymentScheduleDetailInvoicePaymentScheduleList().remove(psd); } if (psd.getOrderPaymentSchedule() != null) { psd.getOrderPaymentSchedule() .getFINPaymentScheduleDetailOrderPaymentScheduleList().remove(psd); } // Before deleting the PSD, we must delete any payment proposal line linked to it proposalLinesRemoved = removePaymentProposalLines(psd); OBDal.getInstance().remove(psd); } // Delete any payment proposal line linked to the PSD if we are reactivating a payment // (deleting lines only), we haven't removed it in a previous step and we don't come // from payment proposal reactivation process if (strAction.equals("R") && proposalLinesRemoved == 0 && !StringUtils.equals(comingFrom, FIN_PaymentProposalProcess.COMINGFROM_PAYMENTPROPOSALPROCESS)) { removePaymentProposalLines(psd); } } if (paymentDetail.getFINPaymentScheduleDetailList().size() == 0) { removedPD.add(paymentDetail); removedPDIds.add(paymentDetail.getId()); } OBDal.getInstance().save(paymentDetail); } for (String pdToRm : removedPDIds) { OBDal.getInstance().remove(OBDal.getInstance().get(FIN_PaymentDetail.class, pdToRm)); } payment.getFINPaymentDetailList().removeAll(removedPD); if (strAction.equals("R")) { payment.getCurrencyConversionRateDocList().removeAll(conversionRates); payment.setFinancialTransactionConvertRate(BigDecimal.ZERO); } OBDal.getInstance().save(payment); if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) { undoUsedCredit(payment, invoiceDocNos); } List<FIN_Payment> creditPayments = new ArrayList<FIN_Payment>(); for (final FIN_Payment_Credit pc : payment.getFINPaymentCreditList()) { creditPayments.add(pc.getCreditPaymentUsed()); } for (final FIN_Payment creditPayment : creditPayments) { // Update Description final String payDesc = creditPayment.getDescription(); if (payDesc != null) { final String invoiceDocNoMsg = OBMessageUtils.messageBD("APRM_CreditUsedinInvoice"); if (invoiceDocNoMsg != null) { final StringBuffer newDesc = new StringBuffer(); for (final String line : payDesc.split("\n")) { boolean include = true; if (line.startsWith( invoiceDocNoMsg.substring(0, invoiceDocNoMsg.lastIndexOf("%s")))) { for (final String docNo : invoiceDocNos) { if (line.indexOf(docNo) > 0) { include = false; break; } } } if (include) { newDesc.append(line); if (!"".equals(line)) newDesc.append("\n"); } } // Truncate Description to keep length as 255 creditPayment.setDescription( newDesc.toString().length() > 255 ? newDesc.toString().substring(0, 255) : newDesc.toString()); } } } payment.getFINPaymentCreditList().clear(); if (payment.isReceipt() || strAction.equals("R")) { payment.setGeneratedCredit(BigDecimal.ZERO); } if (strAction.equals("R")) { payment.setUsedCredit(BigDecimal.ZERO); } } finally { OBDal.getInstance().flush(); OBContext.restorePreviousMode(); } } else if (strAction.equals("V")) { // Void OBContext.setAdminMode(); try { if (payment.isProcessed()) { // Already Posted Document if ("Y".equals(payment.getPosted())) { msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo()); throw new OBException(msg); } // Transaction exists if (hasTransaction(payment)) { msg = OBMessageUtils.messageBD("APRM_TransactionExists"); throw new OBException(msg); } // Payment with generated credit already used on other payments. if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) { msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed"); throw new OBException(msg); } // Payment not in Awaiting Execution boolean restorePaidAmounts = (FIN_Utility .seqnumberpaymentstatus(payment.getStatus())) < (FIN_Utility .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment))); if (!restorePaidAmounts) { msg = OBMessageUtils.messageBD("APRM_PaymentNotRPAE_NotVoid"); throw new OBException(msg); } /* * Void the payment */ payment.setStatus("RPVOID"); /* * Cancel all payment schedule details related to the payment */ final List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>(); Set<String> invoiceDocNos = new HashSet<String>(); for (final FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) { for (final FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail .getFINPaymentScheduleDetailList()) { Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid(); if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) { paymentScheduleDetail.setInvoicePaid(false); } BigDecimal outStandingAmt = BigDecimal.ZERO; if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) { // Related to invoices for (final FIN_PaymentScheduleDetail invScheDetail : paymentScheduleDetail .getInvoicePaymentSchedule() .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) { if (invScheDetail.isCanceled()) { continue; } if (invScheDetail.getPaymentDetails() == null) { outStandingAmt = outStandingAmt.add(invScheDetail.getAmount()) .add(invScheDetail.getWriteoffAmount()); removedPDS.add(invScheDetail); } else if (invScheDetail.equals(paymentScheduleDetail)) { outStandingAmt = outStandingAmt.add(invScheDetail.getAmount()) .add(invScheDetail.getWriteoffAmount()); paymentScheduleDetail.setCanceled(true); } invoiceDocNos.add(paymentScheduleDetail.getInvoicePaymentSchedule() .getInvoice().getDocumentNo()); } // Create merged Payment Schedule Detail with the pending to be paid amount if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) { final FIN_PaymentScheduleDetail mergedScheduleDetail = dao .getNewPaymentScheduleDetail(payment.getOrganization(), outStandingAmt); mergedScheduleDetail.setInvoicePaymentSchedule( paymentScheduleDetail.getInvoicePaymentSchedule()); mergedScheduleDetail.setOrderPaymentSchedule( paymentScheduleDetail.getOrderPaymentSchedule()); OBDal.getInstance().save(mergedScheduleDetail); } } else if (paymentScheduleDetail.getOrderPaymentSchedule() != null) { // Related to orders for (final FIN_PaymentScheduleDetail ordScheDetail : paymentScheduleDetail .getOrderPaymentSchedule() .getFINPaymentScheduleDetailOrderPaymentScheduleList()) { if (ordScheDetail.isCanceled()) { continue; } if (ordScheDetail.getPaymentDetails() == null) { outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount()) .add(ordScheDetail.getWriteoffAmount()); removedPDS.add(ordScheDetail); } else if (ordScheDetail.equals(paymentScheduleDetail)) { outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount()) .add(ordScheDetail.getWriteoffAmount()); paymentScheduleDetail.setCanceled(true); } } // Create merged Payment Schedule Detail with the pending to be paid amount if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) { final FIN_PaymentScheduleDetail mergedScheduleDetail = dao .getNewPaymentScheduleDetail(payment.getOrganization(), outStandingAmt); mergedScheduleDetail.setOrderPaymentSchedule( paymentScheduleDetail.getOrderPaymentSchedule()); OBDal.getInstance().save(mergedScheduleDetail); } } else if (paymentDetail.getGLItem() != null) { paymentScheduleDetail.setCanceled(true); } else if (paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getInvoicePaymentSchedule() == null) { // Credit payment payment.setGeneratedCredit(payment.getGeneratedCredit() .subtract(paymentScheduleDetail.getAmount())); removedPDS.add(paymentScheduleDetail); } OBDal.getInstance().save(payment); OBDal.getInstance().flush(); } paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS); for (FIN_PaymentScheduleDetail removedPD : removedPDS) { if (removedPD.getOrderPaymentSchedule() != null) { removedPD.getOrderPaymentSchedule() .getFINPaymentScheduleDetailOrderPaymentScheduleList() .remove(removedPD); OBDal.getInstance().save(removedPD.getOrderPaymentSchedule()); } if (removedPD.getInvoicePaymentSchedule() != null) { removedPD.getInvoicePaymentSchedule() .getFINPaymentScheduleDetailInvoicePaymentScheduleList() .remove(removedPD); OBDal.getInstance().save(removedPD.getInvoicePaymentSchedule()); } OBDal.getInstance().remove(removedPD); } OBDal.getInstance().flush(); removedPDS.clear(); } if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) { undoUsedCredit(payment, invoiceDocNos); } payment.getFINPaymentCreditList().clear(); payment.setUsedCredit(BigDecimal.ZERO); } OBDal.getInstance().flush(); } finally { OBContext.restorePreviousMode(); } } } catch (final Exception e) { log4j.error(e.getMessage()); msg = OBMessageUtils.translateError(FIN_Utility.getExceptionMessage(e)).getMessage(); throw new OBException(msg); } }
From source file:org.openconcerto.erp.generationDoc.gestcomm.EtatVentesXmlSheet.java
protected void createListeValues() { final SQLElementDirectory directory = Configuration.getInstance().getDirectory(); final SQLElement eltVenteFacutreElement = directory.getElement("SAISIE_VENTE_FACTURE_ELEMENT"); final SQLElement eltVenteFacture = directory.getElement("SAISIE_VENTE_FACTURE"); final SQLElement eltEncaissement = directory.getElement("ENCAISSER_MONTANT"); final SQLElement eltTicketCaisse = directory.getElement("TICKET_CAISSE"); final SQLElement eltModeReglement = directory.getElement("MODE_REGLEMENT"); final SQLTable tableModeReglement = eltModeReglement.getTable(); final SQLTable tableFactureElement = eltVenteFacutreElement.getTable(); final SQLTable tableFacture = eltVenteFacture.getTable(); final AliasedTable tableModeReglement1 = new AliasedTable(tableModeReglement, MODE1); final AliasedTable tableModeReglement2 = new AliasedTable(tableModeReglement, MODE2); final AliasedTable tableTicket = new AliasedTable(eltTicketCaisse.getTable(), "ticket"); // Requete Pour obtenir les quantits pour chaque type de rglement SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase()); sel.addSelect(tableFactureElement.getField("CODE")); sel.addSelect(tableFactureElement.getField("NOM")); // Elements assoscis une facture Where w = new Where(tableFactureElement.getField("ID_TICKET_CAISSE"), "=", tableTicket.getTable().getUndefinedID()); sel.addJoin("LEFT", tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE")).setWhere(w); // Elements associs un ticket de caisse Where w2 = new Where(tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE"), "=", 1); sel.addJoin("LEFT", tableFacture.getField("ID_MODE_REGLEMENT"), MODE1); sel.addJoin("LEFT", tableFactureElement.getField("ID_TICKET_CAISSE"), "ticket").setWhere(w2); sel.addBackwardJoin("LEFT", "enc", eltEncaissement.getTable().getField("ID_TICKET_CAISSE"), "ticket"); sel.addJoin("LEFT", new AliasedField(eltEncaissement.getTable().getField("ID_MODE_REGLEMENT"), "enc"), MODE2);/*from ww w. ja v a2s . co m*/ final String idTypeReglement1 = tableModeReglement1.getField("ID_TYPE_REGLEMENT").getFieldRef(); final String idTypeReglement2 = tableModeReglement2.getField("ID_TYPE_REGLEMENT").getFieldRef(); final String qte = sel.getAlias(tableFactureElement.getField("QTE")).getFieldRef(); sel.addRawSelect("SUM(CASE WHEN " + idTypeReglement1 + "=2 OR " + idTypeReglement2 + "=2 THEN " + qte + " ELSE 0 END)", "Cheque"); sel.addRawSelect("SUM(CASE WHEN " + idTypeReglement1 + "=3 OR " + idTypeReglement2 + "=3 THEN " + qte + " ELSE 0 END)", "CB"); sel.addRawSelect("SUM(CASE WHEN " + idTypeReglement1 + "=4 OR " + idTypeReglement2 + "=4 THEN " + qte + " ELSE 0 END)", "Especes"); Where w3 = new Where(tableTicket.getField("DATE"), this.du, this.au); Where w4 = new Where(tableFacture.getField("DATE"), this.du, this.au); if (this.du != null && this.au != null) { sel.setWhere(w3.or(w4)); } // FIXME traiter le cas du!=null et au==null et vice versa sel.addGroupBy(tableFactureElement.getField("NOM")); sel.addGroupBy(tableFactureElement.getField("CODE")); System.err.println(sel.asString()); // Requete pour obtenir les quantits vendus SQLSelect selQte = new SQLSelect(Configuration.getInstance().getBase()); selQte.addSelect(tableFactureElement.getField("CODE")); selQte.addSelect(tableFactureElement.getField("NOM")); selQte.addSelect(tableFactureElement.getField("QTE"), "SUM"); selQte.addSelect(tableFactureElement.getField("T_PA_HT"), "SUM"); selQte.addSelect(tableFactureElement.getField("T_PV_HT"), "SUM"); selQte.addSelect(tableFactureElement.getField("T_PV_TTC"), "SUM"); selQte.addJoin("LEFT", tableFactureElement.getField("ID_SAISIE_VENTE_FACTURE")).setWhere(w); selQte.addJoin("LEFT", tableFactureElement.getField("ID_TICKET_CAISSE"), "ticket").setWhere(w2); if (this.du != null && this.au != null) { selQte.setWhere(w3.or(w4)); // FIXME traiter le cas du!=null et au==null et vice versa } selQte.addGroupBy(tableFactureElement.getField("NOM")); selQte.addGroupBy(tableFactureElement.getField("CODE")); List<Object[]> listeQte = (List<Object[]>) Configuration.getInstance().getBase().getDataSource() .execute(selQte.asString(), new ArrayListHandler()); // Rcupration des quantits et des montant totaux pour chaque article Map<String, ArticleVendu> map = new HashMap<String, ArticleVendu>(); for (Object[] sqlRow : listeQte) { String code = (String) sqlRow[0]; String nom = (String) sqlRow[1]; Number qteVendu = (Number) sqlRow[2]; Number ha = (Number) sqlRow[3]; Number ht = (Number) sqlRow[4]; Number ttc = (Number) sqlRow[5]; ArticleVendu a = new ArticleVendu(code, nom, qteVendu.intValue(), (BigDecimal) ht, (BigDecimal) ha, (BigDecimal) ttc); map.put(code + "##" + nom, a); } List<Object[]> listeIds = (List<Object[]>) Configuration.getInstance().getBase().getDataSource() .execute(sel.asString(), new ArrayListHandler()); if (listeIds == null) { return; } // Liste des valeurs de la feuille OO ArrayList<Map<String, Object>> listValues = new ArrayList<Map<String, Object>>(listeIds.size()); BigDecimal totalTPA = BigDecimal.ZERO; BigDecimal totalTPVTTC = BigDecimal.ZERO; for (Object[] obj : listeIds) { Map<String, Object> mValues = new HashMap<String, Object>(); String code = (String) obj[0]; String nom = (String) obj[1]; ArticleVendu a = map.get(code + "##" + nom); mValues.put("CODE", code); mValues.put("NOM", nom); mValues.put("QTE", a.qte); mValues.put("T_PA", a.ha); mValues.put("T_PV_HT", a.ht); mValues.put("T_PV_TTC", a.ttc); mValues.put("NB_CHEQUE", obj[2]); mValues.put("NB_CB", obj[3]); mValues.put("NB_ESPECES", obj[4]); totalTPA = totalTPA.add(a.ha); totalTPVTTC = totalTPVTTC.add(a.ttc); listValues.add(mValues); System.out.println("EtatVentesXmlSheet.createListeValues():" + listValues); } // Liste des ventes comptoirs final SQLTable venteComptoirT = directory.getElement("SAISIE_VENTE_COMPTOIR").getTable(); SQLSelect selVC = new SQLSelect(venteComptoirT.getBase()); selVC.addSelect(venteComptoirT.getField("NOM")); selVC.addSelect(venteComptoirT.getField("MONTANT_HT"), "SUM"); selVC.addSelect(venteComptoirT.getField("MONTANT_TTC"), "SUM"); selVC.addSelect(venteComptoirT.getField("NOM"), "COUNT"); if (this.du != null && this.au != null) { Where wVC = new Where(venteComptoirT.getField("DATE"), this.du, this.au); wVC = wVC.and(new Where(venteComptoirT.getField("ID_ARTICLE"), "=", venteComptoirT.getForeignTable("ID_ARTICLE").getKey())); selVC.setWhere(wVC); } else { selVC.setWhere(new Where(venteComptoirT.getField("ID_ARTICLE"), "=", venteComptoirT.getForeignTable("ID_ARTICLE").getKey())); } // FIXME traiter le cas du!=null et au==null et vice versa selVC.addGroupBy(venteComptoirT.getField("NOM")); List<Object[]> listVC = (List<Object[]>) venteComptoirT.getDBSystemRoot().getDataSource() .execute(selVC.asString(), new ArrayListHandler()); long totalVCInCents = 0; if (listVC.size() > 0) { Map<String, Object> mValues = new HashMap<String, Object>(); mValues.put("NOM", " "); listValues.add(mValues); Map<String, Object> mValues2 = new HashMap<String, Object>(); if (listVC.size() > 1) { mValues2.put("NOM", "VENTES COMPTOIR"); } else { mValues2.put("NOM", "VENTE COMPTOIR"); } Map<Integer, String> style = styleAllSheetValues.get(0); if (style == null) { style = new HashMap<Integer, String>(); } style.put(listValues.size(), "Titre 1"); styleAllSheetValues.put(0, style); listValues.add(mValues2); } for (Object[] rowVenteComptoir : listVC) { final Map<String, Object> mValues = new HashMap<String, Object>(); // Nom mValues.put("NOM", rowVenteComptoir[0]); // HT mValues.put("T_PV_HT", ((Number) rowVenteComptoir[1]).longValue() / 100.0D); // TTC final long ttcInCents = ((Number) rowVenteComptoir[2]).longValue(); mValues.put("T_PV_TTC", ttcInCents / 100.0D); totalVCInCents += ttcInCents; // Quantit mValues.put("QTE", rowVenteComptoir[3]); listValues.add(mValues); } // Liste des Achats final ArrayList<Map<String, Object>> listValuesAchat = new ArrayList<Map<String, Object>>(listeIds.size()); Map<String, Object> valuesAchat = this.mapAllSheetValues.get(1); if (valuesAchat == null) { valuesAchat = new HashMap<String, Object>(); } final SQLElement eltAchat = directory.getElement("SAISIE_ACHAT"); final SQLTable tableAchat = eltAchat.getTable(); final SQLSelect selAchat = new SQLSelect(Configuration.getInstance().getBase()); selAchat.addSelect(tableAchat.getField("NOM")); selAchat.addSelect(tableAchat.getField("MONTANT_HT"), "SUM"); selAchat.addSelect(tableAchat.getField("MONTANT_TTC"), "SUM"); final Where wHA = new Where(tableAchat.getField("DATE"), this.du, this.au); selAchat.setWhere(wHA); selAchat.addGroupBy(tableAchat.getField("NOM")); List<Object[]> listAchat = (List<Object[]>) Configuration.getInstance().getBase().getDataSource() .execute(selAchat.asString(), new ArrayListHandler()); long totalAchatInCents = 0; for (Object[] row : listAchat) { Map<String, Object> mValues = new HashMap<String, Object>(); mValues.put("NOM", row[0]); long ht = ((Number) row[1]).longValue(); long pA = ((Number) row[2]).longValue(); mValues.put("T_PV_HT", -ht / 100.0D); mValues.put("T_PV_TTC", -pA / 100.0D); totalAchatInCents -= pA; listValuesAchat.add(mValues); } totalTPVTTC = totalTPVTTC.add(new BigDecimal(totalVCInCents).movePointLeft(2)); // Rcapitulatif Map<String, Object> valuesE = this.mapAllSheetValues.get(2); if (valuesE == null) { valuesE = new HashMap<String, Object>(); } SQLElement eltE = directory.getElement("ENCAISSER_MONTANT"); SQLElement eltM = directory.getElement("MODE_REGLEMENT"); SQLElement eltT = directory.getElement("TYPE_REGLEMENT"); SQLSelect selE = new SQLSelect(Configuration.getInstance().getBase()); selE.addSelect(eltT.getTable().getField("NOM")); selE.addSelect(eltT.getTable().getField("NOM"), "COUNT"); selE.addSelect(eltE.getTable().getField("MONTANT"), "SUM"); Where wE = new Where(eltE.getTable().getField("DATE"), this.du, this.au); wE = wE.and(new Where(eltE.getTable().getField("ID_MODE_REGLEMENT"), "=", eltM.getTable().getKey())); wE = wE.and(new Where(eltM.getTable().getField("ID_TYPE_REGLEMENT"), "=", eltT.getTable().getKey())); selE.setWhere(wE); selE.addGroupBy(eltT.getTable().getField("NOM")); selE.addFieldOrder(eltT.getTable().getField("NOM")); List<Object[]> listE = (List<Object[]>) Configuration.getInstance().getBase().getDataSource() .execute(selE.asString(), new ArrayListHandler()); ArrayList<Map<String, Object>> listValuesE = new ArrayList<Map<String, Object>>(listeIds.size()); long totalEInCents = 0; for (Object[] o : listE) { Map<String, Object> mValues = new HashMap<String, Object>(); mValues.put("NOM", o[0]); final long pA = ((Number) o[2]).longValue(); mValues.put("QTE", o[1]); mValues.put("TOTAL", pA / 100.0D); totalEInCents += pA; listValuesE.add(mValues); } Map<String, Object> values = this.mapAllSheetValues.get(0); if (values == null) { values = new HashMap<String, Object>(); } valuesAchat.put("TOTAL", totalAchatInCents / 100f); valuesE.put("TOTAL_HA", totalAchatInCents / 100f); valuesE.put("TOTAL", totalEInCents / 100f); valuesE.put("TOTAL_VT", totalTPVTTC); values.put("TOTAL", totalVCInCents / 100f); values.put("TOTAL_MARGE", totalTPVTTC.subtract(totalTPA)); valuesE.put("TOTAL_GLOBAL", totalTPVTTC.add(new BigDecimal(totalAchatInCents).movePointLeft(2))); values.put("TOTAL_PA", totalTPA); values.put("TOTAL_PV_TTC", totalTPVTTC); String periode = ""; if (this.du != null && this.au != null) { periode = "Priode du " + DATE_FORMAT.format(this.du) + " au " + DATE_FORMAT.format(this.au); } else if (du == null && au != null) { periode = "Priode jusqu'au " + DATE_FORMAT.format(this.au); } else if (du != null && du != null) { periode = "Priode depuis le " + DATE_FORMAT.format(this.du); } values.put("DATE", periode); valuesAchat.put("DATE", periode); valuesE.put("DATE", periode); System.err.println(this.du); System.err.println(this.au); this.listAllSheetValues.put(0, listValues); this.mapAllSheetValues.put(0, values); this.listAllSheetValues.put(1, listValuesAchat); this.mapAllSheetValues.put(1, valuesAchat); this.listAllSheetValues.put(2, listValuesE); this.mapAllSheetValues.put(2, valuesE); }
From source file:org.egov.egf.commons.EgovCommon.java
@SuppressWarnings("unchecked") public BigDecimal getAccountBalanceFromLedger(final Date VoucherDate, final Integer bankId, final BigDecimal amount, final Long paymentId) { if (LOGGER.isDebugEnabled()) LOGGER.debug("EgovCommon | getCashBalance"); BigDecimal opeAvailable = BigDecimal.ZERO; BigDecimal bankBalance = BigDecimal.ZERO; try {//www .j a va 2s . co m final StringBuffer opBalncQuery1 = new StringBuffer(300); opBalncQuery1.append( "SELECT CASE WHEN sum(openingdebitbalance) is null THEN 0 ELSE sum(openingdebitbalance) END -") .append(" CASE WHEN sum(openingcreditbalance) is null THEN 0 ELSE sum(openingcreditbalance) END as openingBalance from TransactionSummary") .append(" where financialyear.id = ( select id from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)) .append("') and glcodeid.id=(select chartofaccounts.id from Bankaccount where id=? )"); final List<Object> tsummarylist = getPersistenceService().findAllBy(opBalncQuery1.toString(), bankId.longValue()); opeAvailable = BigDecimal.valueOf(Double.parseDouble(tsummarylist.get(0).toString())); if (LOGGER.isDebugEnabled()) LOGGER.debug("opeAvailable :" + opeAvailable); final StringBuffer opBalncQuery2 = new StringBuffer(300); List<Object> list = getPersistenceService() .findAllBy("select chartofaccounts.id from Bankaccount where id=?", bankId.longValue()); final Integer glcodeid = Integer.valueOf(list.get(0).toString()); final List<AppConfigValues> appList = appConfigValuesService .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "statusexcludeReport"); final String statusExclude = appList.get(0).getValue(); opBalncQuery2.append( "SELECT (CASE WHEN sum(gl.debitAmount) is null THEN 0 ELSE sum(gl.debitAmount) END - CASE WHEN sum(gl.creditAmount) is null THEN 0 ELSE sum(gl.creditAmount) END)") .append(" as amount FROM CGeneralLedger gl , CVoucherHeader vh WHERE gl.voucherHeaderId.id=vh.id and gl.glcodeId=? ") .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("') and vh.voucherDate <='") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("'and vh.status not in (") .append(statusExclude).append(")"); final CChartOfAccounts coa = (CChartOfAccounts) persistenceService .find("from CChartOfAccounts where id=?", Long.valueOf(glcodeid)); list = getPersistenceService().findAllBy(opBalncQuery2.toString(), coa); bankBalance = BigDecimal.valueOf(Double.parseDouble(list.get(0).toString())); bankBalance = opeAvailable.add(bankBalance); // get the preapproved voucher amount also, if payment workflow // status in FMU level.... and subtract the amount from the balance // . boolean amountTobeInclude = false; if (paymentId != null) { // get the payment wf status final State s = (State) persistenceService.find( " from org.egov.infra.workflow.entity.State where id in (select state.id from Paymentheader where id=?) ", paymentId); String paymentWFStatus = ""; final List<AppConfigValues> paymentStatusList = appConfigValuesService .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "PAYMENT_WF_STATUS_FOR_BANK_BALANCE_CHECK"); for (final AppConfigValues values : paymentStatusList) { if (s.getValue().equals(values.getValue())) amountTobeInclude = true; paymentWFStatus = paymentWFStatus + "'" + values.getValue() + "',"; } if (!paymentWFStatus.equals("")) paymentWFStatus = paymentWFStatus.substring(0, paymentWFStatus.length() - 1); final List<AppConfigValues> preAppList = appConfigValuesService.getConfigValuesByModuleAndKey( FinancialConstants.MODULE_NAME_APPCONFIG, "PREAPPROVEDVOUCHERSTATUS"); final String preApprovedStatus = preAppList.get(0).getValue(); final StringBuffer paymentQuery = new StringBuffer(400); paymentQuery.append( "SELECT (CASE WHEN sum(gl.debitAmount) is null THEN 0 ELSE sum(gl.debitAmount) END - CASE WHEN sum(gl.creditAmount) is null THEN 0 ELSE sum(gl.creditAmount) END )") .append(" as amount FROM CGeneralLedger gl , CVoucherHeader vh,Paymentheader ph WHERE gl.voucherHeaderId.id=vh.id and ph.voucherheader.id=vh.id and gl.glcodeId=? ") .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where startingDate <= '") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("' AND endingDate >='") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("') and vh.voucherDate <='") .append(Constants.DDMMYYYYFORMAT1.format(VoucherDate)).append("'and vh.status in (") .append(preApprovedStatus).append(")") .append(" and ph.state in (from org.egov.infra.workflow.entity.State where type='Paymentheader' and value in (") .append(paymentWFStatus).append(") )"); list = getPersistenceService().findAllBy(paymentQuery.toString(), coa); bankBalance = bankBalance.subtract(BigDecimal.valueOf(Math.abs((Double) list.get(0)))); final Integer voucherStatus = (Integer) persistenceService.find( "select status from CVoucherHeader where id in (select voucherheader.id from Paymentheader where id=?)", paymentId); // if voucher is not preapproved and status is 0 then it is // modify so add the amount if (voucherStatus == 0) amountTobeInclude = true; // if payment workflow status in FMU level.... and add the // transaction amount to it. if (amountTobeInclude) bankBalance = bankBalance.add(amount); } if (LOGGER.isDebugEnabled()) LOGGER.debug("bankBalance :" + bankBalance); } catch (final Exception e) { if (LOGGER.isDebugEnabled()) LOGGER.debug("exception occuered while geeting cash balance" + e.getMessage(), e); throw new HibernateException(e); } return bankBalance; }
From source file:org.ofbiz.order.order.OrderServices.java
/** * Cancels remaining (unreceived) quantities for items of an order. Does not consider received-but-rejected quantities. * @param dctx the dispatch context/* w w w. ja v a 2s .c o m*/ * @param context the context * @return cancels remaining (unreceived) quantities for items of an order */ public static Map<String, Object> cancelRemainingPurchaseOrderItems(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String orderId = (String) context.get("orderId"); try { GenericValue orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId)); if (UtilValidate.isEmpty(orderHeader)) { String errorMessage = UtilProperties.getMessage(resource_error, "OrderErrorOrderIdNotFound", UtilMisc.toMap("orderId", orderId), locale); Debug.logError(errorMessage, module); return ServiceUtil.returnError(errorMessage); } if (!"PURCHASE_ORDER".equals(orderHeader.getString("orderTypeId"))) { String errorMessage = UtilProperties.getMessage(resource_error, "OrderErrorOrderNotPurchaseOrder", UtilMisc.toMap("orderId", orderId), locale); Debug.logError(errorMessage, module); return ServiceUtil.returnError(errorMessage); } List<GenericValue> orderItems = orderHeader.getRelated("OrderItem"); Iterator<GenericValue> oiit = orderItems.iterator(); while (oiit.hasNext()) { GenericValue orderItem = oiit.next(); if (!"PRODUCT_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) continue; // Get the ordered quantity for the item BigDecimal orderItemQuantity = BigDecimal.ZERO; if (!UtilValidate.isEmpty(orderItem.get("quantity"))) { orderItemQuantity = orderItem.getBigDecimal("quantity"); } BigDecimal orderItemCancelQuantity = BigDecimal.ZERO; if (!UtilValidate.isEmpty(orderItem.get("cancelQuantity"))) { orderItemCancelQuantity = orderItem.getBigDecimal("cancelQuantity"); } // Get the received quantity for the order item - ignore the quantityRejected, since rejected items should be reordered List<GenericValue> shipmentReceipts = orderItem.getRelated("ShipmentReceipt"); BigDecimal receivedQuantity = BigDecimal.ZERO; Iterator<GenericValue> srit = shipmentReceipts.iterator(); while (srit.hasNext()) { GenericValue shipmentReceipt = srit.next(); if (!UtilValidate.isEmpty(shipmentReceipt.get("quantityAccepted"))) { receivedQuantity = receivedQuantity.add(shipmentReceipt.getBigDecimal("quantityAccepted")); } } BigDecimal quantityToCancel = orderItemQuantity.subtract(orderItemCancelQuantity) .subtract(receivedQuantity); if (quantityToCancel.compareTo(BigDecimal.ZERO) > 0) { Map<String, Object> cancelOrderItemResult = dispatcher.runSync("cancelOrderItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "cancelQuantity", quantityToCancel, "userLogin", userLogin)); if (ServiceUtil.isError(cancelOrderItemResult)) return cancelOrderItemResult; } // If there's nothing to cancel, the item should be set to completed, if it isn't already orderItem.refresh(); if ("ITEM_APPROVED".equals(orderItem.getString("statusId"))) { Map<String, Object> changeOrderItemStatusResult = dispatcher.runSync("changeOrderItemStatus", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "statusId", "ITEM_COMPLETED", "userLogin", userLogin)); if (ServiceUtil.isError(changeOrderItemStatusResult)) return changeOrderItemStatusResult; } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (GenericServiceException se) { Debug.logError(se, module); return ServiceUtil.returnError(se.getMessage()); } return ServiceUtil.returnSuccess(); }
From source file:org.ofbiz.order.order.OrderServices.java
/** Service for resetting the OrderHeader grandTotal */ public static Map<String, Object> resetGrandTotal(DispatchContext ctx, Map<String, ? extends Object> context) { Delegator delegator = ctx.getDelegator(); //appears to not be used: GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); GenericValue orderHeader = null;/*from w ww. ja va2 s. c o m*/ try { orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId)); } catch (GenericEntityException e) { String errMsg = "ERROR: Could not set grantTotal on OrderHeader entity: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } if (orderHeader != null) { OrderReadHelper orh = new OrderReadHelper(orderHeader); BigDecimal currentTotal = orderHeader.getBigDecimal("grandTotal"); BigDecimal currentSubTotal = orderHeader.getBigDecimal("remainingSubTotal"); // get the new grand total BigDecimal updatedTotal = orh.getOrderGrandTotal(); String productStoreId = orderHeader.getString("productStoreId"); String showPricesWithVatTax = null; if (UtilValidate.isNotEmpty(productStoreId)) { GenericValue productStore = null; try { productStore = delegator.findByPrimaryKeyCache("ProductStore", UtilMisc.toMap("productStoreId", productStoreId)); } catch (GenericEntityException e) { String errorMessage = UtilProperties.getMessage(resource_error, "OrderErrorCouldNotFindProductStoreWithID", UtilMisc.toMap("productStoreId", productStoreId), (Locale) context.get("locale")) + e.toString(); Debug.logError(e, errorMessage, module); return ServiceUtil.returnError(errorMessage + e.getMessage() + ")."); } showPricesWithVatTax = productStore.getString("showPricesWithVatTax"); } BigDecimal remainingSubTotal = ZERO; if (UtilValidate.isNotEmpty(productStoreId) && "Y".equalsIgnoreCase(showPricesWithVatTax)) { // calculate subTotal as grandTotal + taxes - (returnsTotal + shipping of all items) remainingSubTotal = updatedTotal.subtract(orh.getOrderReturnedTotal()) .subtract(orh.getShippingTotal()); } else { // calculate subTotal as grandTotal - returnsTotal - (tax + shipping of items not returned) remainingSubTotal = updatedTotal.subtract(orh.getOrderReturnedTotal()) .subtract(orh.getOrderNonReturnedTaxAndShipping()); } if (currentTotal == null || currentSubTotal == null || updatedTotal.compareTo(currentTotal) != 0 || remainingSubTotal.compareTo(currentSubTotal) != 0) { orderHeader.set("grandTotal", updatedTotal); orderHeader.set("remainingSubTotal", remainingSubTotal); try { orderHeader.store(); } catch (GenericEntityException e) { String errMsg = "ERROR: Could not set grandTotal on OrderHeader entity: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } } } return ServiceUtil.returnSuccess(); }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public Integer createtransactionBanknewCheck(MoAccount moAccount, Motransaction M1, String DepositType, Integer yearID, Integer periodID, String userName, BigDecimal balance, boolean accountStatus, int motransiid, String oper, String gridData, boolean futureornot, BigDecimal currentbalance, BigDecimal oldamount, String NewMoTypeId, BigDecimal amt, String aMemo, String aRxMasterID) throws BankingException, CompanyException { Transaction aTransaction;/* www.j a v a 2s . c o m*/ Session aSession = null; aSession = itsSessionFactory.openSession(); aTransaction = aSession.beginTransaction(); try { aTransaction.begin(); if (oper.equals("new")) { updateDepositAndWithDraw(moAccount, aSession); M1.setBalance(balance); motransiid = addTransactionDetails(M1, aSession, "new"); M1.setMoTransactionId(motransiid); if (accountStatus) gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); } else if (oper.equals("add")) { Momultipleaccount momulaccount = null; BigDecimal TotalAmt = new BigDecimal(0); updateDepositAndWithDraw(moAccount, aSession); M1.setBalance(balance); motransiid = addTransactionDetails(M1, aSession, "new"); M1.setMoTransactionId(motransiid); if (accountStatus) { gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); } else { JsonParser parser = new JsonParser(); if (null != gridData && gridData.length() > 6) { JsonElement ele = parser.parse(gridData); JsonArray array = ele.getAsJsonArray(); System.out.println("array length==>" + array.size()); for (JsonElement ele1 : array) { momulaccount = new Momultipleaccount(); JsonObject obj = ele1.getAsJsonObject(); momulaccount.setCoAccountId(obj.get("coAccountId").getAsInt()); M1.setCoAccountId(obj.get("coAccountId").getAsInt()); momulaccount.setAmount(obj.get("amount").getAsBigDecimal()); M1.setAmount(obj.get("amount").getAsBigDecimal()); momulaccount.setMoTransactionId(motransiid); momulaccount.setMoMultipleAccountsId(obj.get("moMultipleAccountsId").getAsInt()); System.out.println("checkupdates" + momulaccount.getCoAccountId() + "==" + momulaccount.getAmount() + "==" + obj.get("moMultipleAccountsId").getAsInt()); if (obj.get("moMultipleAccountsId").getAsInt() == 0) { saveGlmultipleAccount1(momulaccount, aSession); } else { updateGlmultipleAccount1(momulaccount, aSession); } DepositType = "Multiple with subaccounts"; gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); TotalAmt = TotalAmt.add(obj.get("amount").getAsBigDecimal()); } DepositType = "Multiple with mainaccounts"; M1.setAmount(TotalAmt); gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); } } } else if (oper.equals("edit")) { Momultipleaccount momulaccount = null; BigDecimal TotalAmt = new BigDecimal(0); updateTransactionDetails1(M1, aSession); Coledgersource aColedgersource = gltransactionService.getColedgersourceDetail("BT"); GlRollback glRollback = new GlRollback(); glRollback.setVeBillID(M1.getMoTransactionId()); glRollback.setCoLedgerSourceID(aColedgersource.getCoLedgerSourceId()); glRollback.setPeriodID(periodID); glRollback.setYearID(yearID); glRollback.setTransactionDate(M1.getTransactionDate()); gltransactionService.rollBackGlTransaction1(glRollback, aSession); String aDescription = M1.getDescription(); String aReference = M1.getReference(); if (M1.getMoTransactionTypeId() == 0) { /*if(futureornot){ balance=currentbalance.subtract(oldamount); }else{ balance=currentbalance; }*/ balance = currentbalance.subtract(oldamount); oldamount = oldamount.multiply(new BigDecimal(-1)); short change = 1; M1.setMoTransactionTypeId(change); moAccount.setSubtractions(oldamount); // 220 } else { /*if(futureornot){ balance=currentbalance.add(oldamount); }else{ balance=currentbalance; }*/ balance = currentbalance.add(oldamount); short change = 0; M1.setMoTransactionTypeId(change); moAccount.setAdditions(oldamount); } moAccount.setMoTransactionTypeId(M1.getMoTransactionTypeId()); updateDepositAndWithDraw(moAccount, aSession); M1.setAmount(oldamount); M1.setBalance(balance); addTransactionDetails(M1, aSession, "rollback"); BigDecimal newbalance = new BigDecimal("0.00"); short editmotypeid = Short.parseShort(NewMoTypeId); M1.setMoTransactionTypeId(editmotypeid); M1.setAmount(amt); M1.setStatus(false); if (M1.getMoTransactionTypeId() == 0) { if (M1.getAmount().doubleValue() < 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } /*if(futureornot){ newbalance=balance.add(M1.getAmount()); }else{ newbalance=currentbalance; }*/ newbalance = balance.add(M1.getAmount()); moAccount.setAdditions(M1.getAmount()); } else { if (M1.getAmount().doubleValue() > 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } /*if(futureornot){ newbalance=balance.add(M1.getAmount()); }else{ newbalance=currentbalance; }*/ newbalance = balance.add(M1.getAmount()); moAccount.setSubtractions(M1.getAmount()); } M1.setBalance(newbalance); moAccount.setMoTransactionTypeId(M1.getMoTransactionTypeId()); updateDepositAndWithDraw(moAccount, aSession); if (editmotypeid == 2) { M1.setMemo(aMemo); M1.setRxMasterId(Integer.parseInt(aRxMasterID)); } M1.setDescription(aDescription); M1.setReference(aReference); motransiid = addTransactionDetails(M1, aSession, "new"); M1.setMoTransactionId(motransiid); if (accountStatus == true) { gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); } else { JsonParser parser = new JsonParser(); if (null != gridData && gridData.length() > 6) { if ((oper.equals("edit") || oper.equals("delete"))) { glRollback.setVeBillID(M1.getMoTransactionId()); glRollback.setCoLedgerSourceID(aColedgersource.getCoLedgerSourceId()); glRollback.setPeriodID(periodID); glRollback.setYearID(yearID); glRollback.setTransactionDate(M1.getTransactionDate()); gltransactionService.rollBackGlTransaction1(glRollback, aSession); } JsonElement ele = parser.parse(gridData); JsonArray array = ele.getAsJsonArray(); System.out.println("array length==>" + array.size()); for (JsonElement ele1 : array) { momulaccount = new Momultipleaccount(); JsonObject obj = ele1.getAsJsonObject(); momulaccount.setCoAccountId(obj.get("coAccountId").getAsInt()); M1.setCoAccountId(obj.get("coAccountId").getAsInt()); momulaccount.setAmount(obj.get("amount").getAsBigDecimal()); M1.setAmount(obj.get("amount").getAsBigDecimal()); momulaccount.setMoTransactionId(motransiid); momulaccount.setMoMultipleAccountsId(obj.get("moMultipleAccountsId").getAsInt()); System.out.println("checkupdates" + momulaccount.getCoAccountId() + "==" + momulaccount.getAmount() + "==" + obj.get("moMultipleAccountsId").getAsInt()); if (obj.get("moMultipleAccountsId").getAsInt() == 0) { saveGlmultipleAccount1(momulaccount, aSession); } else { updateGlmultipleAccount1(momulaccount, aSession); } DepositType = "Multiple with subaccounts"; gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); TotalAmt = TotalAmt.add(obj.get("amount").getAsBigDecimal()); } DepositType = "Multiple with mainaccounts"; M1.setAmount(TotalAmt); gltransactionService.bankingDeposits(M1, DepositType, yearID, periodID, userName, aSession); } } } else if (oper.equals("delete")) { updateTransactionDetails1(M1, aSession); Coledgersource aColedgersource = gltransactionService.getColedgersourceDetail("BT"); GlRollback glRollback = new GlRollback(); glRollback.setVeBillID(M1.getMoTransactionId()); glRollback.setCoLedgerSourceID(aColedgersource.getCoLedgerSourceId()); glRollback.setPeriodID(periodID); glRollback.setYearID(yearID); glRollback.setTransactionDate(new Date()); gltransactionService.rollBackGlTransaction1(glRollback, aSession); balance = new BigDecimal("0.00"); if (M1.getMoTransactionTypeId() == 0) { if (M1.getAmount().doubleValue() < 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } moAccount.setSubtractions(M1.getAmount()); /*if(futureornot){ balance=currentbalance.add(M1.getAmount()); }else{ balance=currentbalance; }*/ balance = currentbalance.add(M1.getAmount()); } else { if (M1.getAmount().doubleValue() > 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } moAccount.setAdditions(M1.getAmount()); /*if(futureornot){ balance=currentbalance.add(M1.getAmount()); }else{ balance=currentbalance; }*/ balance = currentbalance.add(M1.getAmount()); } moAccount.setOper(oper); updateDepositAndWithDraw(moAccount, aSession); M1.setStatus(true); M1.setBalance(balance); addTransactionDetails(M1, aSession, "rollback"); } else if (oper.equals("void")) { boolean statusChk = true; statusChk = voidTransactionDetails1(M1, aSession); GlRollback glRollback = new GlRollback(); if (statusChk) { Coledgersource aColedgersource = gltransactionService.getColedgersourceDetail("WC"); glRollback.setVeBillID(Integer.parseInt(M1.getMoAccountId() + "" + M1.getReference())); glRollback.setCoLedgerSourceID(aColedgersource.getCoLedgerSourceId()); glRollback.setPeriodID(periodID); glRollback.setYearID(yearID); glRollback.setTransactionDate(new Date()); gltransactionService.rollBackGlTransaction1(glRollback, aSession); } else { Coledgersource aColedgersource = gltransactionService.getColedgersourceDetail("BT"); glRollback.setVeBillID(M1.getMoTransactionId()); glRollback.setCoLedgerSourceID(aColedgersource.getCoLedgerSourceId()); glRollback.setPeriodID(periodID); glRollback.setYearID(yearID); glRollback.setTransactionDate(new Date()); gltransactionService.rollBackGlTransaction1(glRollback, aSession); } balance = new BigDecimal("0.00"); if (M1.getMoTransactionTypeId() == 0) { if (M1.getAmount().doubleValue() < 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } moAccount.setSubtractions(M1.getAmount()); /*if(futureornot){ balance=currentbalance.add(M1.getAmount()); }else{ balance=currentbalance; }*/ balance = currentbalance.add(M1.getAmount()); } else { if (M1.getAmount().doubleValue() < 0) { M1.setAmount(M1.getAmount().multiply(new BigDecimal(-1))); } moAccount.setAdditions(M1.getAmount()); /*if(futureornot){ balance=currentbalance.add(M1.getAmount()); }else{ balance=currentbalance; }*/ balance = currentbalance.add(M1.getAmount()); } moAccount.setOper(oper); updateDepositAndWithDraw(moAccount, aSession); M1.setStatus(false); M1.setBalance(balance); M1.setDescription("[VOID]" + M1.getDescription()); M1.setUniquechkRef(M1.getReference()); addTransactionDetails(M1, aSession, "rollbackfromvoid"); } aTransaction.commit(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); aTransaction.rollback(); CompanyException aCompanyException = new CompanyException(e.getCause().getMessage(), e); throw aCompanyException; } finally { aSession.flush(); aSession.close(); } return motransiid; }
From source file:org.ofbiz.order.order.OrderServices.java
/** Service for checking and re-calc the shipping amount */ public static Map<String, Object> recalcOrderShipping(DispatchContext ctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = ctx.getDispatcher(); Delegator delegator = ctx.getDelegator(); String orderId = (String) context.get("orderId"); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); // check and make sure we have permission to change the order Security security = ctx.getSecurity(); boolean hasPermission = OrderServices.hasPermission(orderId, userLogin, "UPDATE", security, delegator); if (!hasPermission) { return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToChangeThisOrdersStatus", locale)); }/*from ww w.j ava 2s .c o m*/ // get the order header GenericValue orderHeader = null; try { orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId)); } catch (GenericEntityException e) { return ServiceUtil.returnError( UtilProperties.getMessage(resource_error, "OrderErrorCannotGetOrderHeaderEntity", locale) + e.getMessage()); } if (orderHeader == null) { return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorNoValidOrderHeaderFoundForOrderId", UtilMisc.toMap("orderId", orderId), locale)); } OrderReadHelper orh = new OrderReadHelper(orderHeader); List<GenericValue> shipGroups = orh.getOrderItemShipGroups(); if (shipGroups != null) { Iterator<GenericValue> i = shipGroups.iterator(); while (i.hasNext()) { GenericValue shipGroup = i.next(); String shipGroupSeqId = shipGroup.getString("shipGroupSeqId"); if (shipGroup.get("contactMechId") == null || shipGroup.get("shipmentMethodTypeId") == null) { // not shipped (face-to-face order) continue; } Map<String, Object> shippingEstMap = ShippingEvents.getShipEstimate(dispatcher, delegator, orh, shipGroupSeqId); BigDecimal shippingTotal = null; if (UtilValidate.isEmpty(orh.getValidOrderItems(shipGroupSeqId))) { shippingTotal = ZERO; Debug.log("No valid order items found - " + shippingTotal, module); } else { shippingTotal = UtilValidate.isEmpty(shippingEstMap.get("shippingTotal")) ? ZERO : (BigDecimal) shippingEstMap.get("shippingTotal"); shippingTotal = shippingTotal.setScale(orderDecimals, orderRounding); Debug.log("Got new shipping estimate - " + shippingTotal, module); } if (Debug.infoOn()) { Debug.log("New Shipping Total [" + orderId + " / " + shipGroupSeqId + "] : " + shippingTotal, module); } BigDecimal currentShipping = OrderReadHelper.getAllOrderItemsAdjustmentsTotal( orh.getOrderItemAndShipGroupAssoc(shipGroupSeqId), orh.getAdjustments(), false, false, true); currentShipping = currentShipping .add(OrderReadHelper.calcOrderAdjustments(orh.getOrderHeaderAdjustments(shipGroupSeqId), orh.getOrderItemsSubTotal(), false, false, true)); if (Debug.infoOn()) { Debug.log("Old Shipping Total [" + orderId + " / " + shipGroupSeqId + "] : " + currentShipping, module); } List<String> errorMessageList = UtilGenerics .checkList(shippingEstMap.get(ModelService.ERROR_MESSAGE_LIST)); if (errorMessageList != null) { Debug.logWarning("Problem finding shipping estimates for [" + orderId + "/ " + shipGroupSeqId + "] = " + errorMessageList, module); continue; } if ((shippingTotal != null) && (shippingTotal.compareTo(currentShipping) != 0)) { // place the difference as a new shipping adjustment BigDecimal adjustmentAmount = shippingTotal.subtract(currentShipping); String adjSeqId = delegator.getNextSeqId("OrderAdjustment"); GenericValue orderAdjustment = delegator.makeValue("OrderAdjustment", UtilMisc.toMap("orderAdjustmentId", adjSeqId)); orderAdjustment.set("orderAdjustmentTypeId", "SHIPPING_CHARGES"); orderAdjustment.set("amount", adjustmentAmount); orderAdjustment.set("orderId", orh.getOrderId()); orderAdjustment.set("shipGroupSeqId", shipGroupSeqId); orderAdjustment.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA); orderAdjustment.set("createdDate", UtilDateTime.nowTimestamp()); orderAdjustment.set("createdByUserLogin", userLogin.getString("userLoginId")); //orderAdjustment.set("comments", "Shipping Re-Calc Adjustment"); try { orderAdjustment.create(); } catch (GenericEntityException e) { Debug.logError(e, "Problem creating shipping re-calc adjustment : " + orderAdjustment, module); return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotCreateAdjustment", locale)); } } // TODO: re-balance free shipping adjustment } } return ServiceUtil.returnSuccess(); }