Example usage for org.hibernate ScrollableResults close

List of usage examples for org.hibernate ScrollableResults close

Introduction

In this page you can find the example usage for org.hibernate ScrollableResults close.

Prototype

void close();

Source Link

Document

Release resources immediately.

Usage

From source file:org.ng200.openolympus.services.TaskService.java

License:Open Source License

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
@Transactional// w  ww  .j  a  va  2 s  .  c o  m
public void rejudgeTask(final Task task) throws ExecutionException, IOException {

    final Lock lock = task.writeLock();
    lock.lock();

    try {

        this.verdictRepository.flush();
        this.solutionRepository.flush();

        this.verdictRepository.deleteBySolutionTask(task);
        this.verdictRepository.flush();

        final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory()
                .openStatelessSession();
        try {
            final Query query = session.createQuery("from Solution where task_id=:taskID");
            query.setParameter("taskID", task.getId());
            query.setFetchSize(Integer.valueOf(1000));
            query.setReadOnly(false);
            final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
            try {
                while (results.next()) {
                    final Solution solution = (Solution) results.get(0);
                    this.testingService.testSolutionOnAllTests(solution);
                }
            } finally {
                results.close();
            }
        } finally {
            session.close();
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openbravo.advpaymentmngt.actionHandler.MatchStatementOnLoadActionHandler.java

License:Open Source License

private int runAutoMatchingAlgorithm(String strReconciliationId, final String strFinancialAccountId,
        final FIN_FinancialAccount financialAccount, FIN_Reconciliation reconciliation)
        throws InterruptedException, SQLException {
    final MatchingAlgorithm ma = financialAccount.getMatchingAlgorithm();
    final FIN_MatchingTransaction matchingTransaction = new FIN_MatchingTransaction(ma.getJavaClassName());
    final ScrollableResults bankLinesSR = APRM_MatchingUtility
            .getPendingToBeMatchedBankStatementLines(strFinancialAccountId, strReconciliationId);
    final List<FIN_FinaccTransaction> excluded = new ArrayList<FIN_FinaccTransaction>();
    int matchedLines = 0, i = 0;
    try {//from  w ww .ja  v a2  s  . c om
        List<String> bankLines = new ArrayList<String>();
        while (bankLinesSR.next()) {
            final FIN_BankStatementLine bankStatementLine = (FIN_BankStatementLine) bankLinesSR.get(0);
            bankLines.add(bankStatementLine.getId());
            if ((i % 100) == 0) {
                OBDal.getInstance().getSession().clear();
            }
            i++;
        }
        bankLinesSR.close();
        i = 0;
        for (i = 0; i < bankLines.size(); i++) {
            final FIN_BankStatementLine bankStatementLine = OBDal.getInstance().get(FIN_BankStatementLine.class,
                    bankLines.get(i));
            FIN_MatchedTransaction matched;
            // try to match if exception is thrown continue
            try {
                matched = matchingTransaction.match(bankStatementLine, excluded);
            } catch (Exception e) {
                matched = new FIN_MatchedTransaction(null, FIN_MatchedTransaction.NOMATCH);
            }

            FIN_FinaccTransaction transaction = matched.getTransaction();
            if (transaction != null && APRM_MatchingUtility.matchBankStatementLine(bankStatementLine,
                    transaction, reconciliation, matched.getMatchLevel(), false)) {
                excluded.add(transaction);
                matchedLines++;
                // Required to persist current matching so that it is not rollbacked afterwards because
                // of
                // a
                // future error
                OBDal.getInstance().getConnection().commit();
            }

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
        }
    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
    }

    return matchedLines;
}

From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentMonitorProcess.java

License:Open Source License

public void doExecute(ProcessBundle bundle) throws Exception {
    logger = bundle.getLogger();//from  w  ww . j a  v a2  s  .  c o m
    // Check to know if PaymentMonitor property is set in the system.
    try {
        Preferences.getPreferenceValue("PaymentMonitor", true, null, null, OBContext.getOBContext().getUser(),
                null, null);
    } catch (PropertyNotFoundException e) {
        logger.log("Property not found \n");
        return;
    } catch (PropertyException e) {
        logger.log("PropertyException, there is a conflict for PaymentMonitor property\n");
        return;
    }
    // Check to know that this APR is the module implementing the PaymentMonitor property
    if (isPreferenceOfModule("PaymentMonitor", "A918E3331C404B889D69AA9BFAFB23AC")) {
        logger.log("Starting Update Paid Amount for Invoices Background Process.\n");
    } else {
        logger.log("Payment Monitor active for other module.\n");
        logger.log("Core's background process is executed.\n");
        return;
    }

    ScrollableResults invoiceScroller = null;
    try {
        int counter = 0;
        final Module migration = OBDal.getInstance().get(Module.class, "4BD3D4B262B048518FE62496EF09D549");

        StringBuilder whereClause = new StringBuilder();
        whereClause.append(" as i");
        whereClause.append("   left join i.fINPaymentScheduleList fps ");
        whereClause.append(" where i.processed=true");
        whereClause.append(" and (i.paymentComplete=false ");
        whereClause.append("      or fps.updated >= i.lastCalculatedOnDate ");
        whereClause.append("      or i.outstandingAmount <> 0");
        if (migration != null) {
            whereClause.append("  or (i.finalSettlementDate is null");
            whereClause.append(" and fps.id is not null");
            whereClause.append(" and i.aprmtIsmigrated = 'N'))");
        } else {
            whereClause.append(" or i.finalSettlementDate is null)");
        }

        final OBQuery<Invoice> obc = OBDal.getInstance().createQuery(Invoice.class, whereClause.toString());

        // For Background process execution at system level
        if (OBContext.getOBContext().isInAdministratorMode()) {
            obc.setFilterOnReadableClients(false);
            obc.setFilterOnReadableOrganization(false);
        }

        invoiceScroller = obc.scroll(ScrollMode.FORWARD_ONLY);
        while (invoiceScroller.next()) {
            final Invoice invoice = (Invoice) invoiceScroller.get()[0];
            updateInvoice(invoice);
            counter++;
            if (counter % 100 == 0) {
                OBDal.getInstance().getSession().flush();
                OBDal.getInstance().getSession().clear();
                logger.log("Invoices updated: " + counter + "\n");
            }
        }
        if (counter % 100 != 0)
            logger.log("Invoices updated: " + counter + "\n");
    } catch (Exception e) {
        // catch any possible exception and throw it as a Quartz
        // JobExecutionException
        throw new JobExecutionException(e.getMessage(), e);
    } finally {
        if (invoiceScroller != null) {
            invoiceScroller.close();
        }
    }
}

From source file:org.openbravo.advpaymentmngt.utility.FIN_BankStatementImport.java

License:Open Source License

private BusinessPartner matchBusinessPartnerByNameTokens(String partnername, Organization organization) {
    if (partnername == null || "".equals(partnername.trim())) {
        return null;
    }/* w ww.  jav a2s.  c om*/
    String parsedPartnername = partnername.toLowerCase();
    // Remove exceptions
    for (String eliminate : stringExceptions) {
        parsedPartnername = parsedPartnername.replaceAll(eliminate.toLowerCase(), "");
    }
    StringTokenizer st = new StringTokenizer(parsedPartnername);
    List<String> list = new ArrayList<String>();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (token.length() > 3) {
            list.add(token);
        }
    }
    if (list.isEmpty()) {
        return null;
    }
    final StringBuilder whereClause = new StringBuilder();
    OBContext.setAdminMode();
    ScrollableResults businessPartnersScroll = null;
    try {
        whereClause.append("select b.id as id, b.name as name from ");
        whereClause.append(" BusinessPartner b ");
        whereClause.append(" where (");
        for (String token : list) {
            whereClause.append(
                    " lower(b." + BusinessPartner.PROPERTY_NAME + ") like lower('%" + token + "%') or ");
        }
        whereClause.delete(whereClause.length() - 3, whereClause.length()).append(")");
        whereClause.append(" and b." + BusinessPartner.PROPERTY_ORGANIZATION + ".id in (");
        whereClause.append(
                Utility.getInStrSet(new OrganizationStructureProvider().getNaturalTree(organization.getId()))
                        + ") ");
        final Query bl = OBDal.getInstance().getSession().createQuery(whereClause.toString());
        businessPartnersScroll = bl.scroll(ScrollMode.SCROLL_SENSITIVE);

        if (!businessPartnersScroll.next()) {
            return null;
        }

        else {
            final Object[] resultObject = (Object[]) businessPartnersScroll.get(0);
            if (!businessPartnersScroll.next()) {
                String strParnterId = "";
                if (resultObject.getClass().isArray()) {
                    final Object[] values = resultObject;
                    strParnterId = (String) values[0];
                }
                BusinessPartner bp = OBDal.getInstance().get(BusinessPartner.class, strParnterId);
                return bp;
            }

            else {
                String closestId = closest(businessPartnersScroll, partnername);
                BusinessPartner closest = OBDal.getInstance().get(BusinessPartner.class, closestId);
                return closest;
            }
        }

    } finally {
        businessPartnersScroll.close();
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.client.application.event.AcctSchemaEventHandler.java

License:Open Source License

private void updateElementValues(Element _element, AcctSchema acctSchema, boolean assetPositive,
        boolean liabilityPositive, boolean ownersEquityPositive, boolean expensePositive,
        boolean revenuePositive) {
    StringBuffer where = new StringBuffer();
    final String ACCOUNTSIGN_CREDIT = "C";
    final String ACCOUNTSIGN_DEBIT = "D";
    final String ACCOUNTTYPE_MEMO = "M";
    Element element = OBDal.getInstance().get(Element.class, _element.getId());
    where.append(ElementValue.PROPERTY_ACCOUNTINGELEMENT + ".id = :element");
    OBQuery<ElementValue> elementValueQry = OBDal.getInstance().createQuery(ElementValue.class,
            where.toString());/*from w  ww  .jav  a2s  .  c om*/
    elementValueQry.setFilterOnActive(false);
    elementValueQry.setFilterOnReadableClients(false);
    elementValueQry.setFilterOnReadableOrganization(false);
    elementValueQry.setNamedParameter("element", element.getId());
    elementValueQry.setFetchSize(1000);

    ScrollableResults elementvalues = elementValueQry.scroll(ScrollMode.FORWARD_ONLY);
    try {
        // TODO: Review with Martin to see if flush is permitted in handlers
        // int i = 0;
        while (elementvalues.next()) {
            ElementValue elementValue = (ElementValue) elementvalues.get(0);
            boolean isCredit = getAccountSign(elementValue.getAccountType(), assetPositive, liabilityPositive,
                    ownersEquityPositive, expensePositive, revenuePositive);
            if (!ACCOUNTTYPE_MEMO.equals(elementValue.getAccountType())) {
                elementValue.setAccountSign(isCredit ? ACCOUNTSIGN_CREDIT : ACCOUNTSIGN_DEBIT);
            }
            // if ((i % 100) == 0) {
            // OBDal.getInstance().flush();
            // OBDal.getInstance().getSession().clear();
            // element = OBDal.getInstance().get(Element.class, element.getId());
            // }
            // i++;
        }
    } finally {
        elementvalues.close();
    }
}

From source file:org.openbravo.common.actionhandler.CheckAvailableCreditActionHandler.java

License:Open Source License

@Override
protected JSONObject execute(Map<String, Object> parameters, String data) {
    try {// ww  w .j ava  2s .c  o  m
        final JSONObject jsonData = new JSONObject(data);
        final String businessPartnerId = jsonData.getString("businessPartnerId");
        final String currencyId = jsonData.getString("currencyId");
        JSONObject result = new JSONObject();

        if (currencyId != null && !StringUtils.isEmpty(currencyId)) {
            ScrollableResults scroll = FinancialUtils.getPaymentsWithCredit(businessPartnerId, currencyId);
            try {
                result.put("availableCredit", scroll.next());
            } catch (Exception e) {
                result.put("availableCredit", false);
            } finally {
                scroll.close();
            }
        } else {
            result.put("availableCredit", false);
        }
        return result;
    } catch (Exception e) {
        throw new OBException(e);
    }
}

From source file:org.openbravo.common.actionhandler.SetNewBPCurrency.java

License:Open Source License

@Override
protected JSONObject doExecute(Map<String, Object> parameters, String content) {

    JSONObject jsonRequest = null;//  w  w  w  .  jav  a  2  s.  c  om
    OBContext.setAdminMode(true);
    try {
        jsonRequest = new JSONObject(content);
        JSONObject params = jsonRequest.getJSONObject("_params");
        final String strOrgId = jsonRequest.getString("inpadOrgId");
        final String strFromCurrencyId = jsonRequest.getString("inpbpCurrencyId");
        final String strToCurrencyId = params.getString("C_Currency_ID");
        final String strRate = params.getString("Rate");
        final String strAmount = params.getString("Foreign_Amount");
        final boolean strSetAmount = params.getBoolean("Amount");
        final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
        final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
        final String glItemId = params.getString("c_glitem_id");
        BigDecimal creditUsed = BigDecimal.ZERO;
        BigDecimal rate = BigDecimal.ZERO;
        Double amount = new Double(0);
        if (strSetAmount && !"null".equals(strAmount)) {
            amount = Double.parseDouble(strAmount);
        }

        if (strUseDefaultConversion && !strSetAmount) {
            rate = getConversionRate(strOrgId, strFromCurrencyId, strToCurrencyId);
            if (rate == BigDecimal.ZERO && !strFromCurrencyId.equals(strToCurrencyId)) {
                try {
                    jsonRequest = new JSONObject();
                    String message = OBMessageUtils.messageBD("NoCurrencyConversion");
                    JSONObject errorMessage = new JSONObject();
                    errorMessage.put("severity", "error");
                    errorMessage.put("text", message);
                    jsonRequest.put("message", errorMessage);
                } catch (Exception e) {
                    OBDal.getInstance().rollbackAndClose();
                    log.error(e.getMessage(), e);
                }
                return jsonRequest;
            }
        } else {
            rate = "null".equals(strRate) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(strRate));
        }
        BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class, strBpartnerId);
        creditUsed = businessPartner.getCreditUsed();

        ScrollableResults scroll = null;
        GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
        Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
        BigDecimal creditAmount = BigDecimal.ZERO;
        BigDecimal creditRate = BigDecimal.ONE;

        // Convert available credit automatically
        if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
                && !StringUtils.equals(glItemId, "null")) {

            // Get the rate
            if (!strSetAmount) {
                creditRate = rate;
            } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
                creditRate = BigDecimal.valueOf(amount).divide(creditUsed,
                        FIN_Utility.getConversionRatePrecision(RequestContext.get().getVariablesSecureApp()),
                        RoundingMode.HALF_UP);
            }

            // Loop through all payment documents which generate credit
            scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
            int i = 0;
            try {
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);
                    creditAmount = paymentCredit.getGeneratedCredit().subtract(paymentCredit.getUsedCredit());

                    // Create a payment to consume the credit with a glitem
                    FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment1.setPaymentDate(new Date());
                    payment1.setAmount(creditAmount);
                    payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(),
                            payment1.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment1.setProcessed(false);
                    payment1.setPosted("N");
                    payment1.setDescription(null);
                    payment1.setGeneratedCredit(BigDecimal.ZERO);
                    payment1.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to consume the credit with a glitem
                    FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail1.setClient(paymentCredit.getClient());
                    paymentDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentDetail1.setFinPayment(payment1);
                    paymentDetail1.setAmount(creditAmount);
                    paymentDetail1.setRefund(false);
                    paymentDetail1.setGLItem(glItem);
                    paymentDetail1.setPrepayment(false);

                    // Create a payment schedule detail to consume the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail1.setClient(paymentCredit.getClient());
                    paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
                    paymentScheduleDetail1.setAmount(creditAmount);

                    // Process the payment
                    paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
                    payment1.getFINPaymentDetailList().add(paymentDetail1);
                    OBDal.getInstance().save(payment1);
                    OBDal.getInstance().save(paymentDetail1);
                    OBDal.getInstance().save(paymentScheduleDetail1);
                    FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);

                    // Modify description of original credit payment
                    String paymentCreditDesc = paymentCredit.getDescription() + "\n" + String.format(
                            OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment1.getDocumentNo());
                    paymentCredit.setDescription((paymentCreditDesc.length() > 255)
                            ? paymentCreditDesc.substring(0, 251).concat("...").toString()
                            : paymentCreditDesc.toString());

                    // Create a payment to refund the credit
                    FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment2.setPaymentDate(new Date());
                    payment2.setAmount(creditAmount.negate());
                    payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(),
                            payment2.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment2.setProcessed(false);
                    payment2.setPosted("N");
                    payment2.setDescription(
                            OBMessageUtils.messageBD("APRM_RefundPayment") + ": " + payment1.getDocumentNo());
                    payment2.setGeneratedCredit(BigDecimal.ZERO);
                    payment2.setUsedCredit(creditAmount);

                    // Create a payment credit to refund the credit
                    FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(FIN_Payment_Credit.class);
                    paymentCredit2.setClient(paymentCredit.getClient());
                    paymentCredit2.setOrganization(paymentCredit.getOrganization());
                    paymentCredit2.setPayment(payment2);
                    paymentCredit2.setCreditPaymentUsed(paymentCredit);
                    paymentCredit2.setAmount(creditAmount);
                    paymentCredit2.setCurrency(paymentCredit.getCurrency());

                    // Create a payment detail to refund the credit
                    FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail2.setClient(paymentCredit.getClient());
                    paymentDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentDetail2.setFinPayment(payment2);
                    paymentDetail2.setAmount(creditAmount.negate());
                    paymentDetail2.setRefund(true);
                    paymentDetail2.setPrepayment(true);

                    // Create a payment schedule detail to refund the credit
                    FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail2.setClient(paymentCredit.getClient());
                    paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
                    paymentScheduleDetail2.setAmount(creditAmount.negate());

                    // Process the payment
                    paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
                    payment2.getFINPaymentDetailList().add(paymentDetail2);
                    payment2.getFINPaymentCreditList().add(paymentCredit2);
                    paymentCredit.setUsedCredit(creditAmount);
                    OBDal.getInstance().save(paymentCredit);
                    OBDal.getInstance().save(payment2);
                    OBDal.getInstance().save(paymentCredit2);
                    OBDal.getInstance().save(paymentDetail2);
                    OBDal.getInstance().save(paymentScheduleDetail2);
                    FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }

                // Set the new currency
                businessPartner.setCurrency(currency);

                // Loop through all payment documents which generate credit
                scroll.beforeFirst();
                i = 0;
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);

                    // Create a payment to create the credit with a glitem
                    FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment3.setPaymentDate(new Date());
                    payment3.setCurrency(currency);
                    payment3.setAmount(BigDecimal.ZERO);
                    payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(),
                            payment3.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment3.setProcessed(false);
                    payment3.setPosted("N");
                    payment3.setDescription(null);
                    final BigDecimal generatedCredit = creditAmount.multiply(creditRate)
                            .setScale(currency.getStandardPrecision().intValue(), RoundingMode.HALF_UP);
                    payment3.setGeneratedCredit(generatedCredit);
                    payment3.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail3.setClient(paymentCredit.getClient());
                    paymentDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentDetail3.setFinPayment(payment3);
                    paymentDetail3.setAmount(generatedCredit);
                    paymentDetail3.setRefund(false);
                    paymentDetail3.setPrepayment(true);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail4.setClient(paymentCredit.getClient());
                    paymentDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentDetail4.setFinPayment(payment3);
                    paymentDetail4.setAmount(generatedCredit.negate());
                    paymentDetail4.setGLItem(glItem);
                    paymentDetail4.setRefund(false);
                    paymentDetail4.setPrepayment(false);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail3.setClient(paymentCredit.getClient());
                    paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
                    paymentScheduleDetail3.setAmount(generatedCredit);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail4.setClient(paymentCredit.getClient());
                    paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
                    paymentScheduleDetail4.setAmount(generatedCredit.negate());

                    // Process the payment
                    paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
                    paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
                    payment3.getFINPaymentDetailList().add(paymentDetail3);
                    payment3.getFINPaymentDetailList().add(paymentDetail4);
                    OBDal.getInstance().save(payment3);
                    OBDal.getInstance().save(paymentDetail3);
                    OBDal.getInstance().save(paymentDetail4);
                    OBDal.getInstance().save(paymentScheduleDetail3);
                    OBDal.getInstance().save(paymentScheduleDetail4);
                    OBDal.getInstance().save(paymentCredit);
                    FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }
            } finally {
                scroll.close();
            }
        }

        if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
            businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
        }
        if (!strToCurrencyId.equals(strFromCurrencyId) && strToCurrencyId != null
                && !"null".equals(strToCurrencyId)) {
            businessPartner.setCurrency(OBDal.getInstance().get(Currency.class, strToCurrencyId));
            if (rate.compareTo(BigDecimal.ZERO) != 0 && creditUsed.compareTo(BigDecimal.ZERO) != 0
                    && !strSetAmount) {
                businessPartner.setCreditUsed(creditUsed.multiply(rate));
            }
        }

        String messageText = OBMessageUtils.messageBD("CurrencyUpdated");
        JSONObject msg = new JSONObject();
        msg.put("severity", "success");
        msg.put("text", OBMessageUtils.parseTranslation(messageText));
        jsonRequest.put("message", msg);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error in set new currency Action Handler", e);

        try {
            jsonRequest = new JSONObject();
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            JSONObject errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("text", message);
            jsonRequest.put("message", errorMessage);
        } catch (Exception e2) {
            log.error(e.getMessage(), e2);
            // do nothing, give up
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return jsonRequest;
}

From source file:org.openbravo.costing.AverageCostAdjustment.java

License:Open Source License

@Override
protected void getRelatedTransactionsByAlgorithm() {
    // Search all transactions after the date of the adjusted line and recalculate the costs of them
    // to adjust differences
    MaterialTransaction basetrx = getTransaction();
    // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting
    // the cost of the related opening inventory.
    if (basetrx.getPhysicalInventoryLine() != null
            && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) {
        return;//  ww w.  ja v  a  2  s.c  o m
    }
    BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
    Date trxDate = basetrx.getTransactionProcessDate();

    BigDecimal adjustmentBalance = BigDecimal.ZERO;
    BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO;
    // Initialize adjustment balance looping through all cost adjustment lines of current
    // transaction.
    log.debug("Initialize adjustment balance");
    CostAdjustmentLine baseCAL = getCostAdjLine();
    for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) {
        if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted()
                && !costAdjLine.getId().equals(strCostAdjLineId)) {
            searchRelatedTransactionCosts(costAdjLine);
        }

        costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE);
        if (!costAdjLine.getId().equals(strCostAdjLineId)) {
            costAdjLine.setParentCostAdjustmentLine(baseCAL);
        }
        OBDal.getInstance().save(costAdjLine);
        // If the cost adjustment line has Transaction Costs those adjustment amount are included
        // in the Current Value Amount and not in the Adjustment Balance
        if (!costAdjLine.getTransactionCostList().isEmpty()) {
            continue;
        }
        BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount();
        if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) {
            adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(),
                    getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(),
                    FinancialUtils.PRECISION_STANDARD);
        }
        adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier));
        if (costAdjLine.isUnitCost()) {
            unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt);
        }
    }

    // Initialize current stock qty and value amt.
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency());
    log.debug(
            "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}",
            currentStock.toPlainString(), currentValueAmt.toPlainString());

    // Initialize current unit cost including the cost adjustments.
    Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(),
            getCostOrg());
    if (costing == null) {
        throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: "
                + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate));
    }
    BigDecimal cost = null;
    // If current stock is zero the cost is not modified until a related transaction that modifies
    // the stock is found.
    if (currentStock.signum() != 0) {
        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                RoundingMode.HALF_UP);
    }
    log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString());
    if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) {
        BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency());
        BigDecimal trxPrice = null;
        if (basetrx.getMovementQuantity().signum() == 0) {
            trxPrice = BigDecimal.ZERO;
        } else {
            trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(),
                    costCurPrecission, RoundingMode.HALF_UP);
        }
        if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0
                && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection()
                && AverageAlgorithm.modifiesAverage(trxType)) {
            // stock was negative and cost different than trx price then Negative Stock Correction
            // is added
            BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
            BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                    .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                    .subtract(adjustmentBalance);
            adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
            // If there is a difference insert a cost adjustment line.
            CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null);
            newCAL.setNegativeStockCorrection(Boolean.TRUE);
            newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
            newCAL.setUnitCost(Boolean.FALSE);
            OBDal.getInstance().save(newCAL);
            cost = trxPrice;
            log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                    cost.toPlainString());
        }
        if (basetrx.getMaterialMgmtCostingList().size() == 0) {
            Date newDate = new Date();
            Date dateTo = costing.getEndingDate();
            costing.setEndingDate(newDate);
            OBDal.getInstance().save(costing);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(basetrx);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(basetrx.getMovementQuantity());
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
            OBDal.getInstance().flush();
        } else {
            Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);

            if (curCosting.getCost().compareTo(cost) != 0
                    || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                curCosting.setPermanent(Boolean.FALSE);
                OBDal.getInstance().save(curCosting);
                OBDal.getInstance().flush();
                // Update existing costing
                if (curCosting.getCost().compareTo(cost) != 0) {
                    if (curCosting.getOriginalCost() == null) {
                        curCosting.setOriginalCost(curCosting.getCost());
                    }
                    curCosting.setCost(cost);
                    curCosting.setPrice(trxPrice);
                }
                curCosting.setTotalMovementQuantity(currentStock);
                curCosting.setPermanent(Boolean.TRUE);
                OBDal.getInstance().flush();
                OBDal.getInstance().save(curCosting);
            }
        }
    }

    // Modify isManufacturingProduct flag in case it has changed at some point.
    isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0");

    ScrollableResults trxs = getRelatedTransactions();
    String strCurrentCurId = strCostCurrencyId;
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get()[0];
            log.debug("Process related transaction {}", trx.getIdentifier());
            BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum());
            BigDecimal trxAdjAmt = BigDecimal.ZERO;
            BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) {
                // If there is a backdated source adjustment pending modify the dates of its m_costing.
                updateBDCostingTimeRange(trx);
                // This update is done only on the first related transaction.
                bdCostingId = "";
            }

            if (!strCurrentCurId.equals(trx.getCurrency().getId())) {
                Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                Organization costOrg = getCostOrg();

                currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency,
                        trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD);
                if (cost != null) {
                    cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(),
                            trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING);
                }

                strCurrentCurId = trx.getCurrency().getId();
            }

            List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx);
            for (CostAdjustmentLine existingCAL : existingAdjLines) {
                if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) {
                    searchRelatedTransactionCosts(existingCAL);
                }
                if (existingCAL.getTransactionCostList().isEmpty()
                        && !existingCAL.isRelatedTransactionAdjusted()) {
                    BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount();
                    if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) {
                        Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                        adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt,
                                existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(),
                                getCostOrg(), FinancialUtils.PRECISION_STANDARD);
                    }
                    trxAdjAmt = trxAdjAmt.add(adjustmentAmt);
                    adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier));
                    if (existingCAL.isUnitCost()) {
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt);
                    }
                }

                existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance()
                        .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId));

                OBDal.getInstance().save(existingCAL);
            }
            log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString());

            BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier));
            currentStock = currentStock.add(trx.getMovementQuantity());
            log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(),
                    currentValueAmt.toPlainString());

            TrxType currentTrxType = TrxType.getTrxType(trx);

            if (AverageAlgorithm.modifiesAverage(currentTrxType)) {
                // Recalculate average, if current stock is zero the average is not modified
                if (currentStock.signum() != 0) {
                    cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                            RoundingMode.HALF_UP);
                }
                if (cost == null) {
                    continue;
                }
                log.debug("New average cost: {}", cost.toPlainString());
                Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                BigDecimal trxPrice = null;
                if (trx.getMovementQuantity().signum() == 0) {
                    trxPrice = BigDecimal.ZERO;
                } else {
                    trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                            costCurPrecission, RoundingMode.HALF_UP);
                }

                if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0
                        && cost.compareTo(trxPrice) != 0) {
                    // stock was negative and cost different than trx price then Negative Stock Correction
                    // is added
                    BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                            .subtract(adjustmentBalance);
                    adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
                    trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier));
                    // If there is a difference insert a cost adjustment line.
                    CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null);
                    newCAL.setNegativeStockCorrection(Boolean.TRUE);
                    newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                    newCAL.setUnitCost(Boolean.FALSE);
                    OBDal.getInstance().save(newCAL);
                    cost = trxPrice;
                    log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                            cost.toPlainString());
                }

                if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId)
                        && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) {
                    // new cost hasn't changed and total movement qty is equal to current stock, following
                    // transactions will have the same cost, so no more
                    // related transactions are needed to include.
                    // If bdCosting is not empty it is needed to loop through the next related transaction
                    // to set the new time ringe of the costing.
                    log.debug("New cost matches existing cost. Adjustment finished.");
                    return;
                } else {
                    // Update existing costing
                    curCosting.setPermanent(Boolean.FALSE);
                    OBDal.getInstance().save(curCosting);
                    OBDal.getInstance().flush();
                    if (curCosting.getCost().compareTo(cost) != 0) {
                        if (curCosting.getOriginalCost() == null) {
                            curCosting.setOriginalCost(curCosting.getCost());
                        }
                        curCosting.setPrice(trxPrice);
                        curCosting.setCost(cost);
                    }
                    curCosting.setTotalMovementQuantity(currentStock);
                    curCosting.setPermanent(Boolean.TRUE);
                    OBDal.getInstance().save(curCosting);
                }
            } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) {
                if (!trx.isCostPermanent()) {
                    // Check current trx unit cost matches new expected cost
                    BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs())
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP);
                    BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                            OBDal.getInstance().get(Currency.class, strCurrentCurId));
                    unitCost = unitCost.add(trxAdjAmt);
                    log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(),
                            unitCost.toPlainString());
                    if (expectedCost.compareTo(unitCost) != 0) {
                        trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost));
                        adjustmentBalance = adjustmentBalance
                                .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        // If there is a difference insert a cost adjustment line.
                        CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx,
                                expectedCost.subtract(unitCost), null);
                        newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                        OBDal.getInstance().save(newCAL);
                        log.debug("Adjustment added. Amount {}.",
                                expectedCost.subtract(unitCost).toPlainString());
                    }
                }
                if (trx.getMaterialMgmtCostingList().size() != 0) {
                    Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                    if (currentStock.signum() != 0) {
                        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                                RoundingMode.HALF_UP);
                    }
                    BigDecimal trxPrice = null;
                    if (trx.getMovementQuantity().signum() == 0) {
                        trxPrice = BigDecimal.ZERO;
                    } else {
                        trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                                costCurPrecission, RoundingMode.HALF_UP);
                    }
                    if (curCosting.getCost().compareTo(cost) != 0
                            || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                        curCosting.setPermanent(Boolean.FALSE);
                        OBDal.getInstance().save(curCosting);
                        OBDal.getInstance().flush();
                        if (curCosting.getCost().compareTo(cost) != 0) {
                            if (curCosting.getOriginalCost() == null) {
                                curCosting.setOriginalCost(curCosting.getCost());
                            }
                            curCosting.setPrice(trxPrice);
                            curCosting.setCost(cost);
                        }
                        curCosting.setTotalMovementQuantity(currentStock);
                        curCosting.setPermanent(Boolean.TRUE);
                        OBDal.getInstance().save(curCosting);
                    }
                }
            }

            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    } finally {
        trxs.close();
    }

    if (getCostingRule().getEndingDate() == null && cost != null) {
        // This is the current costing rule. Check if current average cost needs to be updated.
        Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(),
                getCostDimensions(), getCostOrg());
        if (currentCosting == null) {
            throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName()
                    + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: "
                    + OBDateUtils.formatDate(new Date()));
        }
        if (currentCosting.getCost().compareTo(cost) != 0) {
            basetrx = getTransaction();
            Date newDate = new Date();
            Date dateTo = currentCosting.getEndingDate();
            currentCosting.setEndingDate(newDate);
            OBDal.getInstance().save(currentCosting);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(null);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(null);
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
        }
    }
}

From source file:org.openbravo.costing.CancelCostAdjustment.java

License:Open Source License

public static JSONObject doCancelCostAdjustment(CostAdjustment costAdjustmentOrig)
        throws OBException, JSONException {
    CostAdjustment costAdjustmentCancel = (CostAdjustment) DalUtil.copy(costAdjustmentOrig, false);

    final DocumentType docType = FIN_Utility.getDocumentType(costAdjustmentOrig.getOrganization(),
            strCategoryCostAdj);/*from w  w  w .  j a v  a2s. c o  m*/
    final String docNo = FIN_Utility.getDocumentNo(docType, strTableCostAdj);
    costAdjustmentCancel.setDocumentNo(docNo);
    costAdjustmentCancel.setUpdated(new Date());
    costAdjustmentCancel.setUpdatedBy(OBContext.getOBContext().getUser());
    costAdjustmentCancel.setCreationDate(new Date());
    costAdjustmentCancel.setCreatedBy(OBContext.getOBContext().getUser());
    costAdjustmentCancel.setProcessed(false);
    costAdjustmentCancel.setPosted("N");
    OBDal.getInstance().save(costAdjustmentOrig);

    costAdjustmentOrig.setCostAdjustmentCancel(costAdjustmentCancel);
    costAdjustmentOrig.setDocumentStatus("VO");
    OBDal.getInstance().save(costAdjustmentCancel);
    OBDal.getInstance().flush();

    CostAdjustment cacProxy = (CostAdjustment) OBDal.getInstance().getProxy(CostAdjustment.ENTITY_NAME,
            costAdjustmentCancel.getId());
    // Call cost
    OBCriteria<CostAdjustmentLine> qLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    qLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, costAdjustmentOrig));
    qLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_ISSOURCE, true));
    ScrollableResults scrollLines = qLines.scroll(ScrollMode.FORWARD_ONLY);
    try {
        int cnt = 0;
        while (scrollLines.next()) {
            final CostAdjustmentLine lineOrig = (CostAdjustmentLine) scrollLines.get()[0];
            CostAdjustmentLine lineCancel = (CostAdjustmentLine) DalUtil.copy(lineOrig, false);
            lineCancel.setUpdated(new Date());
            lineCancel.setUpdatedBy(OBContext.getOBContext().getUser());
            lineCancel.setCreationDate(new Date());
            lineCancel.setCreatedBy(OBContext.getOBContext().getUser());
            lineCancel.setCostAdjustment(cacProxy);
            lineCancel.setAdjustmentAmount(lineOrig.getAdjustmentAmount().negate());
            lineCancel.setBackdatedTrx(Boolean.FALSE);
            lineCancel.setNegativeStockCorrection(Boolean.FALSE);
            if (lineOrig.getInventoryTransaction().isCostPermanent()) {
                lineOrig.getInventoryTransaction().setCostPermanent(Boolean.FALSE);
                OBDal.getInstance().save(lineOrig.getInventoryTransaction());
            }
            OBDal.getInstance().save(lineCancel);
            if ((cnt++ % 10) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
        }
    } finally {
        scrollLines.close();
    }
    OBDal.getInstance().flush();
    JSONObject message = new JSONObject();
    message.put("severity", "success");
    String strResult = OBMessageUtils.messageBD("CostAdjustmentCanceled");
    Map<String, String> map = new HashMap<String, String>();
    map.put("documentNo", docNo);
    message.put("title", OBMessageUtils.messageBD("Success"));
    message.put("text", OBMessageUtils.parseTranslation(strResult, map));

    CostAdjustmentProcess.doProcessCostAdjustment(costAdjustmentCancel);
    CostAdjustment costAdjCancel = OBDal.getInstance().get(CostAdjustment.class, costAdjustmentCancel.getId());
    costAdjCancel.setDocumentStatus("VO");
    costAdjCancel.setPosted("N");
    OBDal.getInstance().save(costAdjCancel);
    OBDal.getInstance().flush();
    return message;
}

From source file:org.openbravo.costing.CostAdjustmentProcess.java

License:Open Source License

private void checkPermanentelyAdjustedTrx(String strCostAdjId) throws OBException {
    OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    critLines.createAlias(CostAdjustmentLine.PROPERTY_INVENTORYTRANSACTION, "trx");
    critLines.createAlias(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, "ca");
    critLines.add(Restrictions.eq("ca.id", strCostAdjId));
    critLines.add(Restrictions.eq("trx." + MaterialTransaction.PROPERTY_ISCOSTPERMANENT, Boolean.TRUE));
    critLines.add(Restrictions.ne(CostAdjustmentLine.PROPERTY_ADJUSTMENTAMOUNT, BigDecimal.ZERO));
    critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_UNITCOST, Boolean.TRUE));
    critLines.addOrder(Order.asc(CostAdjustmentLine.PROPERTY_LINENO));

    ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY);
    long count = 1L;
    try {/*from   w  w w.  jav  a  2 s .  c  o m*/
        String strLines = "";
        while (lines.next()) {
            CostAdjustmentLine line = (CostAdjustmentLine) lines.get()[0];
            strLines += line.getLineNo() + ", ";

            if (count % 10000 == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
            count++;
        }
        if (!strLines.isEmpty()) {
            strLines = strLines.substring(0, strLines.length() - 2);
            String errorMessage = OBMessageUtils.messageBD("CostAdjustmentWithPermanentLines");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("lines", strLines);
            throw new OBException(OBMessageUtils.parseTranslation(errorMessage, map));
        }
        OBDal.getInstance().flush();
        OBDal.getInstance().getSession().clear();
    } finally {
        lines.close();
    }
}