Example usage for org.apache.commons.lang.time DateUtils truncate

List of usage examples for org.apache.commons.lang.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils truncate.

Prototype

public static Date truncate(Object date, int field) 

Source Link

Document

Truncate this date, leaving the field specified as the most significant field.

For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.Reconciliation.java

private void processReconciliation(HttpServletResponse response, VariablesSecureApp vars, String strTabId,
        String strFinancialAccountId, String strDifference, String strStatementDate, String strBeginBalance,
        String strEndBalance, boolean process) throws IOException, ServletException {

    log4j.debug(/*from  w ww.  ja v a 2 s . c o m*/
            "Output: Process or Save button pressed on Financial Account || Transaction || Reconciliation manual window");

    dao = new AdvPaymentMngtDao();
    OBError msg = new OBError();
    OBContext.setAdminMode();
    try {

        FIN_FinancialAccount account = OBDal.getInstance().get(FIN_FinancialAccount.class,
                strFinancialAccountId);

        FIN_Reconciliation reconciliation = TransactionsDao.getLastReconciliation(account, "N");

        FIN_Reconciliation lastProcessedReconciliation = TransactionsDao.getLastReconciliation(account, "Y");

        reconciliation.setEndingBalance(new BigDecimal(strEndBalance));
        reconciliation.setTransactionDate(FIN_Utility.getDateTime(strStatementDate));
        reconciliation.setEndingDate(FIN_Utility.getDateTime(strStatementDate));
        reconciliation.setDocumentStatus("DR");
        reconciliation.setProcessed(false);
        reconciliation.setAPRMProcessReconciliation("P");
        reconciliation.setAprmProcessRec("P");
        OBDal.getInstance().save(reconciliation);
        OBDal.getInstance().flush();

        if (process) { // Validations
            String strMessage = "";
            boolean raiseException = false;

            if (new BigDecimal(strDifference).compareTo(BigDecimal.ZERO) != 0) {
                strMessage = "@APRM_ReconciliationDiscrepancy@" + " " + strDifference;
                raiseException = true;
            }

            Calendar calCurrent = Calendar.getInstance();
            calCurrent.setTime(FIN_Utility.getDateTime(strStatementDate));

            if (lastProcessedReconciliation != null) {
                Calendar calLast = Calendar.getInstance();
                calLast.setTime(lastProcessedReconciliation.getEndingDate());
                if (calCurrent.before(calLast)) {
                    strMessage = "@APRM_ReconcileInFutureOrPast@";
                    raiseException = true;
                }
            }

            Calendar tomorrow = Calendar.getInstance();
            tomorrow.add(Calendar.DATE, 1);
            tomorrow.setTime(DateUtils.truncate(tomorrow.getTime(), Calendar.DATE));
            if (calCurrent.after(tomorrow)) {
                strMessage = "@APRM_ReconcileInFutureOrPast@";
                raiseException = true;
            }
            if (raiseException) {
                msg.setType("Error");
                msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
                msg.setMessage(Utility.parseTranslation(this, vars, vars.getLanguage(), strMessage));
                vars.setMessage(strTabId, msg);
                msg = null;
                printPageClosePopUpAndRefreshParent(response, vars);
                return;
            }

            boolean orgLegalWithAccounting = FIN_Utility.periodControlOpened(reconciliation.TABLE_NAME,
                    reconciliation.getId(), reconciliation.TABLE_NAME + "_ID", "LE");
            boolean documentEnabled = getDocumentConfirmation(this, reconciliation.getId());
            if (documentEnabled && !FIN_Utility.isPeriodOpen(reconciliation.getClient().getId(),
                    AcctServer.DOCTYPE_Reconciliation, reconciliation.getOrganization().getId(),
                    strStatementDate) && orgLegalWithAccounting) {
                msg.setType("Error");
                msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
                msg.setMessage(
                        Utility.parseTranslation(this, vars, vars.getLanguage(), "@PeriodNotAvailable@"));
                vars.setMessage(strTabId, msg);
                msg = null;
                printPageClosePopUpAndRefreshParent(response, vars);
                return;
            }

            if (documentEnabled && orgLegalWithAccounting) {
                String identifier = linesInNotAvailablePeriod(reconciliation.getId());
                if (!identifier.equalsIgnoreCase("")) {
                    msg.setType("Error");
                    msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
                    msg.setMessage(String.format(
                            Utility.messageBD(this, "APRM_PeriodNotAvailableClearedItem", vars.getLanguage()),
                            identifier));
                    vars.setMessage(strTabId, msg);
                    msg = null;
                    printPageClosePopUpAndRefreshParent(response, vars);
                    return;
                }
            }

            for (APRM_FinaccTransactionV finacctrxv : reconciliation.getAPRMFinaccTransactionVList()) {
                if (reconciliation.getEndingDate()
                        .compareTo(finacctrxv.getFinancialAccountTransaction().getTransactionDate()) < 0) {
                    FIN_FinaccTransaction trans = finacctrxv.getFinancialAccountTransaction();
                    // We set processed to false before changing dates to avoid trigger exception
                    boolean posted = "Y".equals(trans.getPosted());
                    if (posted) {
                        trans.setPosted("N");
                        OBDal.getInstance().save(trans);
                        OBDal.getInstance().flush();
                    }
                    trans.setProcessed(false);
                    OBDal.getInstance().save(trans);
                    OBDal.getInstance().flush();
                    trans.setTransactionDate(reconciliation.getEndingDate());
                    trans.setDateAcct(reconciliation.getEndingDate());
                    OBDal.getInstance().save(trans);
                    OBDal.getInstance().flush();
                    // We set processed to true afterwards
                    trans.setProcessed(true);
                    OBDal.getInstance().save(trans);
                    OBDal.getInstance().flush();
                    if (posted) {
                        trans.setPosted("Y");
                        OBDal.getInstance().save(trans);
                        OBDal.getInstance().flush();
                    }
                    // Changing dates for accounting entries as well
                    TransactionsDao.updateAccountingDate(trans);
                }
                Boolean invoicePaidold = false;
                if (finacctrxv.getPayment() != null) {
                    for (FIN_PaymentDetail pd : finacctrxv.getPayment().getFINPaymentDetailList()) {
                        for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                            invoicePaidold = psd.isInvoicePaid();
                            if (!invoicePaidold) {
                                if ((FIN_Utility
                                        .invoicePaymentStatus(finacctrxv.getPayment().getPaymentMethod(),
                                                reconciliation.getAccount(),
                                                finacctrxv.getPayment().isReceipt())
                                        .equals(finacctrxv.getPayment().getStatus()))) {
                                    psd.setInvoicePaid(true);
                                }
                                if (psd.isInvoicePaid()) {
                                    FIN_Utility.updatePaymentAmounts(psd);
                                }
                            }
                        }
                        FIN_Utility.updateBusinessPartnerCredit(finacctrxv.getPayment());
                    }
                }
            }

            reconciliation.setDocumentStatus("CO");
            reconciliation.setProcessed(true);
            reconciliation.setAPRMProcessReconciliation("R");
            reconciliation.setAprmProcessRec("R");
            OBDal.getInstance().save(reconciliation);
            OBDal.getInstance().flush();

        }

        String strMessage = "@APRM_ReconciliationNo@" + ": " + reconciliation.getDocumentNo();
        msg.setType("Success");
        msg.setTitle(Utility.messageBD(this, "Success", vars.getLanguage()));
        msg.setMessage(Utility.parseTranslation(this, vars, vars.getLanguage(), strMessage));
        vars.setMessage(strTabId, msg);
        msg = null;
        printPageClosePopUpAndRefreshParent(response, vars);

    } catch (Exception e) {
        throw new OBException(e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.SelectExpectedPayments.java

private void printGrid(HttpServletResponse response, VariablesSecureApp vars, String strPaymentProposalId,
        String strSelectedPaymentDetails, boolean showAlternativePM) throws IOException, ServletException {
    log4j.debug("Output: Grid with pending payments");

    dao = new AdvPaymentMngtDao();

    XmlDocument xmlDocument = xmlEngine/*from  w  w  w .  j a va 2  s  .co  m*/
            .readXmlTemplate("org/openbravo/advpaymentmngt/ad_actionbutton/AddPaymentProposalGrid")
            .createXmlDocument();

    FIN_PaymentProposal paymentProposal = dao.getObject(FIN_PaymentProposal.class, strPaymentProposalId);
    List<FIN_PaymentScheduleDetail> selectedScheduledPaymentDetails = new ArrayList<FIN_PaymentScheduleDetail>();
    boolean firstLoad = false;
    if (strSelectedPaymentDetails == null || "".equals(strSelectedPaymentDetails))
        firstLoad = true;
    if (firstLoad)
        selectedScheduledPaymentDetails = FIN_AddPayment
                .getSelectedPendingPaymentsFromProposal(paymentProposal);
    else
        selectedScheduledPaymentDetails = FIN_AddPayment.getSelectedPaymentDetails(null,
                strSelectedPaymentDetails);

    Date dueDate = paymentProposal.getDuedate();
    if (dueDate != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtils.truncate(paymentProposal.getDuedate(), Calendar.DATE));
        cal.add(Calendar.DATE, 1);
        dueDate = cal.getTime();
    }
    // filtered scheduled payments list
    final List<FIN_PaymentScheduleDetail> filteredScheduledPaymentDetails = dao
            .getFilteredScheduledPaymentDetails(paymentProposal.getOrganization(),
                    paymentProposal.getBusinessPartner(), paymentProposal.getCurrency(), null, null, null,
                    dueDate, null, null, "B", "", showAlternativePM ? null : paymentProposal.getPaymentMethod(),
                    selectedScheduledPaymentDetails, paymentProposal.isReceipt());

    final FieldProvider[] data = FIN_AddPayment.getShownScheduledPaymentDetails(vars,
            selectedScheduledPaymentDetails, filteredScheduledPaymentDetails, firstLoad, paymentProposal);
    xmlDocument.setData("structure", (data == null) ? set() : data);

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
}

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

/**
 * Method used to calculate the Day still due for the payment.
 * /*from   www . j  a  v  a2  s.  co  m*/
 * @param date
 *          . Due date of the payment.
 * @return dayStillDue. Calculated Day Still due.
 */
public static Long getDaysToDue(Date date) {
    final Date now = DateUtils.truncate(new Date(), Calendar.DATE);
    return getDaysBetween(now, date);
}

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

@Override
public void execute(ProcessBundle bundle) throws Exception {
    logger = bundle.getLogger();//www.  j a v a2  s  .  co  m
    OBError msg = new OBError();
    msg.setType("Success");
    msg.setTitle(OBMessageUtils.messageBD("Success"));
    try {
        OBContext.setAdminMode(false);
        final String ruleId = (String) bundle.getParams().get("M_Costing_Rule_ID");
        CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId);
        if (rule.getOrganization().getCurrency() == null) {
            throw new OBException("@NoCurrencyInCostingRuleOrg@");
        }
        OrganizationStructureProvider osp = OBContext.getOBContext()
                .getOrganizationStructureProvider(rule.getClient().getId());
        final Set<String> childOrgs = osp.getChildTree(rule.getOrganization().getId(), true);
        final Set<String> naturalOrgs = osp.getNaturalTree(rule.getOrganization().getId());

        // Checks
        migrationCheck();
        CostingRule prevCostingRule = getPreviousRule(rule);
        boolean existsPreviousRule = prevCostingRule != null;
        boolean existsTransactions = existsTransactions(naturalOrgs, childOrgs);
        if (existsPreviousRule) {
            // Product with costing rule. All trx must be calculated.
            checkAllTrxCalculated(naturalOrgs, childOrgs);
        } else if (existsTransactions) {
            // Product configured to have cost not calculated cannot have transactions with cost
            // calculated.
            checkNoTrxWithCostCalculated(naturalOrgs, childOrgs);
            if (rule.getStartingDate() != null) {
                // First rule of an instance that does not need migration. Old transactions costs are not
                // calculated. They are initialized with ZERO cost.
                initializeOldTrx(childOrgs, rule.getStartingDate());
            }
        }
        // Inventories are only needed:
        // - if the costing rule is updating a previous rule
        // - or legacy cost was never used and the first validated rule has a starting date different
        // than null. If the date is old enough that there are not prior transactions no inventories
        // are created.
        if (existsPreviousRule || rule.getStartingDate() != null) {
            Date startingDate = rule.getStartingDate();
            if (existsPreviousRule) {
                // Set valid from date
                startingDate = DateUtils.truncate(new Date(), Calendar.SECOND);
                rule.setStartingDate(startingDate);
                log4j.debug("setting starting date " + startingDate);
                prevCostingRule.setEndingDate(startingDate);
                OBDal.getInstance().save(prevCostingRule);
                OBDal.getInstance().flush();
            }
            if (rule.getFixbackdatedfrom() == null && rule.isBackdatedTransactionsFixed()) {
                rule.setFixbackdatedfrom(startingDate);
            }
            createCostingRuleInits(ruleId, childOrgs, startingDate);

            // Update cost of inventories and process starting physical inventories.
            updateInventoriesCostAndProcessInitInventories(ruleId, startingDate, existsPreviousRule);
        }

        if (rule.getStartingDate() != null && rule.getFixbackdatedfrom() != null
                && rule.isBackdatedTransactionsFixed()
                && rule.getFixbackdatedfrom().before(rule.getStartingDate())) {
            throw new OBException("@FixBackdateFromBeforeStartingDate@");
        }

        // Reload rule after possible session clear.
        rule = OBDal.getInstance().get(CostingRule.class, ruleId);
        rule.setValidated(true);
        CostingStatus.getInstance().setMigrated();
        OBDal.getInstance().save(rule);
    } catch (final OBException e) {
        OBDal.getInstance().rollbackAndClose();
        String resultMsg = OBMessageUtils.parseTranslation(e.getMessage());
        logger.log(resultMsg);
        log4j.error(e);
        msg.setType("Error");
        msg.setTitle(OBMessageUtils.messageBD("Error"));
        msg.setMessage(resultMsg);
        bundle.setResult(msg);

    } catch (final Exception e) {
        OBDal.getInstance().rollbackAndClose();
        String message = DbUtility.getUnderlyingSQLException(e).getMessage();
        logger.log(message);
        log4j.error(message, e);
        msg.setType("Error");
        msg.setTitle(OBMessageUtils.messageBD("Error"));
        msg.setMessage(message);
        bundle.setResult(msg);
    } finally {
        OBContext.restorePreviousMode();
    }
    bundle.setResult(msg);
}

From source file:org.openbravo.erpCommon.info.PriceListVersionFilterExpressionName.java

private Date getDate() {
    Date date = parseDate(requestMap.get("inpDate"));
    if (date != null) {
        log.debug("Return date ordered from request." + date.toString());
        return date;
    }/*  w  w  w. j  a v a  2s  . c  om*/
    date = parseDate((String) httpSession.getAttribute(windowId + "|" + "DATEORDERED"));
    if (date != null) {
        log.debug("Return date ordered from window's session: " + date.toString());
        return date;
    }
    date = parseDate((String) httpSession.getAttribute(windowId + "|" + "DATEINVOICED"));
    if (date != null) {
        log.debug("Return date invoiced from window's session: " + date.toString());
        return date;
    }
    return DateUtils.truncate(new Date(), Calendar.DATE);
}

From source file:org.openbravo.financial.paymentreport.erpCommon.ad_reports.PaymentReportDao.java

FieldProvider[] getPaymentReport(VariablesSecureApp vars, String strOrg, String strInclSubOrg,
        String strDueDateFrom, String strDueDateTo, String strAmountFrom, String strAmountTo,
        String strDocumentDateFrom, String strDocumentDateTo, String strcBPartnerIdIN, String strcBPGroupIdIN,
        String strcNoBusinessPartner, String strcProjectIdIN, String strfinPaymSt, String strPaymentMethodId,
        String strFinancialAccountId, String strcCurrency, String strConvertCurrency, String strConversionDate,
        String strPaymType, String strOverdue, String strGroupCrit, String strOrdCrit,
        String strInclPaymentUsingCredit, String strPaymentDateFrom, String strPaymentDateTo,
        String strExpectedDateFrom, String strExpectedDateTo, String strOutput) throws OBException {

    StringBuilder hsqlScript = new StringBuilder();
    final java.util.List<Object> parameters = new ArrayList<Object>();

    String dateFormatString = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
    Currency transCurrency;//from   w w  w  .j  a v  a 2 s .co m
    BigDecimal transAmount = null;
    ConversionRate convRate = null;
    ArrayList<FieldProvider> totalData = new ArrayList<FieldProvider>();
    int numberOfElements = 0;
    int lastElement = 0;
    boolean existsConvRate = false;
    ScrollableResults scroller = null;

    OBContext.setAdminMode(true);
    try {

        hsqlScript.append(" from FIN_Payment_ScheduleDetail as fpsd ");
        hsqlScript.append(" left outer join fpsd.paymentDetails.finPayment pay");
        hsqlScript.append(" left outer join pay.businessPartner paybp");
        hsqlScript.append(" left outer join paybp.businessPartnerCategory paybpc");
        hsqlScript.append(" left outer join fpsd.invoicePaymentSchedule invps");
        hsqlScript.append(" left outer join invps.invoice inv");
        hsqlScript.append(" left outer join inv.businessPartner invbp");
        hsqlScript.append(" left outer join invbp.businessPartnerCategory invbpc");
        hsqlScript.append(" left outer join fpsd.paymentDetails.finPayment.currency paycur");
        hsqlScript.append(" left outer join fpsd.invoicePaymentSchedule.invoice.currency invcur");
        hsqlScript.append(" left outer join pay.project paypro");
        hsqlScript.append(" left outer join inv.project invpro");
        hsqlScript.append(" where (fpsd.");
        hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS);
        hsqlScript.append(" is not null or invps is not null ");
        hsqlScript.append(") ");

        hsqlScript.append(" and fpsd.");
        hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_ORGANIZATION);
        hsqlScript.append(".id in ");
        hsqlScript.append(concatOrganizations(OBContext.getOBContext().getReadableOrganizations()));

        // organization + include sub-organization
        if (!strOrg.isEmpty()) {
            if (!strInclSubOrg.equalsIgnoreCase("include")) {
                hsqlScript.append(" and fpsd.");
                hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_ORGANIZATION);
                hsqlScript.append(".id = '");
                hsqlScript.append(strOrg);
                hsqlScript.append("'");
            } else {
                hsqlScript.append(" and fpsd.");
                hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_ORGANIZATION);
                hsqlScript.append(".id in ('");
                Set<String> orgChildTree = OBContext.getOBContext().getOrganizationStructureProvider()
                        .getChildTree(strOrg, true);
                Iterator<String> orgChildTreeIter = orgChildTree.iterator();
                while (orgChildTreeIter.hasNext()) {
                    hsqlScript.append(orgChildTreeIter.next());
                    orgChildTreeIter.remove();
                    hsqlScript.append("'");
                    if (orgChildTreeIter.hasNext())
                        hsqlScript.append(", '");
                }
                hsqlScript.append(")");
            }
        }

        // Exclude payments that use credit payment
        if (!strInclPaymentUsingCredit.equalsIgnoreCase("Y")) {
            hsqlScript.append(" and (not (pay.amount = 0 ");
            hsqlScript.append(" and pay.usedCredit > pay.generatedCredit) or pay is null)");
        }

        // due date from - due date to
        if (!strDueDateFrom.isEmpty()) {
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_DUEDATE);
            hsqlScript.append(" >= ?");
            parameters.add(FIN_Utility.getDate(strDueDateFrom));
        }
        if (!strDueDateTo.isEmpty()) {
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_DUEDATE);
            hsqlScript.append(" <= ?");
            parameters.add(FIN_Utility.getDate(strDueDateTo));
        }

        // expected date from - expected date to
        if (!strExpectedDateFrom.isEmpty()) {
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
            hsqlScript.append(" >= ?");
            parameters.add(FIN_Utility.getDate(strExpectedDateFrom));
        }
        if (!strExpectedDateTo.isEmpty()) {
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
            hsqlScript.append(" <= ?");
            parameters.add(FIN_Utility.getDate(strExpectedDateTo));
        }

        // document date from - document date to
        if (!strDocumentDateFrom.isEmpty()) {
            hsqlScript.append(" and coalesce(inv.");
            hsqlScript.append(Invoice.PROPERTY_INVOICEDATE);
            hsqlScript.append(", pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTDATE);
            hsqlScript.append(") >= ?");
            parameters.add(FIN_Utility.getDate(strDocumentDateFrom));
        }
        if (!strDocumentDateTo.isEmpty()) {
            hsqlScript.append(" and coalesce(inv.");
            hsqlScript.append(Invoice.PROPERTY_INVOICEDATE);
            hsqlScript.append(", pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTDATE);
            hsqlScript.append(") <= ?");
            parameters.add(FIN_Utility.getDate(strDocumentDateTo));
        }

        // payment date from - payment date to
        if (!strPaymentDateFrom.isEmpty()) {
            hsqlScript.append(" and ((pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTDATE);
            hsqlScript.append(" >= ?)  or (pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTDATE);
            hsqlScript.append(" is null and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
            hsqlScript.append(" >= ?))");
            parameters.add(FIN_Utility.getDate(strPaymentDateFrom));
            parameters.add(FIN_Utility.getDate(strPaymentDateFrom));
        }
        if (!strPaymentDateTo.isEmpty()) {
            hsqlScript.append(" and coalesce(pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTDATE);
            hsqlScript.append(", invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
            hsqlScript.append(") <= ?");
            parameters.add(FIN_Utility.getDate(strPaymentDateTo));
        }

        // Empty Business Partner included
        if (strcNoBusinessPartner.equals("include")) {

            // business partner
            if (!strcBPartnerIdIN.isEmpty()) {
                hsqlScript.append(" and ((coalesce(pay.");
                hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(", inv.");
                hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(") in ");
                hsqlScript.append(strcBPartnerIdIN);
                hsqlScript.append(") or (pay.");
                hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is null and inv.");
                hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is null))");
            }
            // business partner category
            if (!strcBPGroupIdIN.isEmpty()) {
                hsqlScript.append(" and (coalesce(paybpc, invbpc) = '");
                hsqlScript.append(strcBPGroupIdIN);
                hsqlScript.append("' or (pay.");
                hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is null and inv.");
                hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is null))");
            }

            // Empty Businesss Partner excluded
        } else if (strcNoBusinessPartner.equals("exclude")) {

            // business partner
            if (!strcBPartnerIdIN.isEmpty()) {
                hsqlScript.append(" and coalesce(pay.");
                hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(", inv.");
                hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(") in ");
                hsqlScript.append(strcBPartnerIdIN);
            }

            // business partner category
            if (!strcBPGroupIdIN.isEmpty()) {
                hsqlScript.append(" and coalesce(paybpc, invbpc) = '");
                hsqlScript.append(strcBPGroupIdIN);
                hsqlScript.append("'");
            }
            // exclude empty business partner
            if (strcBPartnerIdIN.isEmpty() && strcBPGroupIdIN.isEmpty()) {
                hsqlScript.append(" and (pay.");
                hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is not null or inv.");
                hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
                hsqlScript.append(" is not null) ");
            }

            // Only Empty Business Partner
        } else {// if ((strcNoBusinessPartner.equals("only")))
            hsqlScript.append(" and pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_BUSINESSPARTNER);
            hsqlScript.append(" is null and inv.");
            hsqlScript.append(Invoice.PROPERTY_BUSINESSPARTNER);
            hsqlScript.append(" is null ");
        }

        // project
        if (!strcProjectIdIN.isEmpty()) {
            hsqlScript.append(" and coalesce(pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PROJECT);
            hsqlScript.append(", inv.");
            hsqlScript.append(Invoice.PROPERTY_PROJECT);
            hsqlScript.append(") in ");
            hsqlScript.append(strcProjectIdIN);
        }

        // status
        if (!strfinPaymSt.isEmpty() && !strfinPaymSt.equalsIgnoreCase("('')")) {
            hsqlScript.append(" and (pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_STATUS);
            hsqlScript.append(" in ");
            hsqlScript.append(strfinPaymSt);
            if (strfinPaymSt.contains("RPAP")) {
                hsqlScript.append(" or fpsd.");
                hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS);
                hsqlScript.append(" is null)");
            } else {
                hsqlScript.append(" )");
            }
        }

        // payment method
        if (!strPaymentMethodId.isEmpty()) {
            hsqlScript.append(" and coalesce(pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_PAYMENTMETHOD);
            hsqlScript.append(", invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_FINPAYMENTMETHOD);
            hsqlScript.append(") = '");
            hsqlScript.append(strPaymentMethodId);
            hsqlScript.append("'");
        }

        // financial account
        if (!strFinancialAccountId.isEmpty()) {
            hsqlScript.append(" and  (pay is not null and ");
            hsqlScript.append(
                    "(select case when trans is not null then trans.account.id else payment.account.id end from FIN_Finacc_Transaction trans right outer join trans.finPayment payment where payment=pay)");

            hsqlScript.append(" = '");
            hsqlScript.append(strFinancialAccountId);
            hsqlScript.append("' or ((pay is null and inv.");
            hsqlScript.append(Invoice.PROPERTY_SALESTRANSACTION);
            hsqlScript.append(" = 'Y'");
            hsqlScript.append(" and invbp.");
            hsqlScript.append(BusinessPartner.PROPERTY_ACCOUNT);
            hsqlScript.append(".id = '");
            hsqlScript.append(strFinancialAccountId);
            hsqlScript.append("')");
            hsqlScript.append(" or (pay is null and inv.");
            hsqlScript.append(Invoice.PROPERTY_SALESTRANSACTION);
            hsqlScript.append(" = 'N'");
            hsqlScript.append(" and invbp.");
            hsqlScript.append(BusinessPartner.PROPERTY_POFINANCIALACCOUNT);
            hsqlScript.append(".id = '");
            hsqlScript.append(strFinancialAccountId);
            hsqlScript.append("')))");
        }

        // currency
        if (!strcCurrency.isEmpty()) {
            hsqlScript.append(" and coalesce(pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_CURRENCY);
            hsqlScript.append(", inv.");
            hsqlScript.append(Invoice.PROPERTY_CURRENCY);
            hsqlScript.append(") = '");
            hsqlScript.append(strcCurrency);
            hsqlScript.append("'");
        }

        // payment type
        if (strPaymType.equalsIgnoreCase("FINPR_Receivables")) {
            hsqlScript.append(" and (pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_RECEIPT);
            hsqlScript.append(" = 'Y'");
            hsqlScript.append(" or inv.");
            hsqlScript.append(Invoice.PROPERTY_SALESTRANSACTION);
            hsqlScript.append(" = 'Y')");
        } else if (strPaymType.equalsIgnoreCase("FINPR_Payables")) {
            hsqlScript.append(" and (pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_RECEIPT);
            hsqlScript.append(" = 'N'");
            hsqlScript.append(" or inv.");
            hsqlScript.append(Invoice.PROPERTY_SALESTRANSACTION);
            hsqlScript.append(" = 'N')");
        }

        // overdue
        if (!strOverdue.isEmpty()) {
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_OUTSTANDINGAMOUNT);
            hsqlScript.append(" != '0'");
            hsqlScript.append(" and invps.");
            hsqlScript.append(FIN_PaymentSchedule.PROPERTY_DUEDATE);
            hsqlScript.append(" <  ?");
            parameters.add(DateUtils.truncate(new Date(), Calendar.DATE));
        }

        if ("HTML".equals(strOutput)) {
            int maxRecords = 1000;
            final Session sessionCount = OBDal.getInstance().getSession();
            final Query queryCount = sessionCount.createQuery("select count(*)" + hsqlScript.toString());
            int px = 0;
            for (final Object param : parameters) {
                if (param instanceof BaseOBObject) {
                    queryCount.setEntity(px++, param);
                } else {
                    queryCount.setParameter(px++, param);
                }
            }
            final Long hqlRecordsCount = (Long) queryCount.list().get(0);
            if ((int) (long) hqlRecordsCount > maxRecords) {
                String message = "FINPR_TooManyRecords";
                throw new OBException(message);
            }
        }

        final StringBuilder firstLineQuery = new StringBuilder();
        firstLineQuery.append(
                "select fpsd, (select a.sequenceNumber from ADList a where a.reference.id = '575BCB88A4694C27BC013DE9C73E6FE7' and a.searchKey = coalesce(pay.status, 'RPAP')) as a");
        hsqlScript = firstLineQuery.append(hsqlScript);

        hsqlScript.append(" order by ");

        if (strGroupCrit.equalsIgnoreCase("APRM_FATS_BPARTNER")) {
            hsqlScript.append(" coalesce(paybp.");
            hsqlScript.append(BusinessPartner.PROPERTY_NAME);
            hsqlScript.append(", invbp.");
            hsqlScript.append(BusinessPartner.PROPERTY_NAME);
            hsqlScript.append("), ");
        } else if (strGroupCrit.equalsIgnoreCase("Project")) {
            hsqlScript.append("  coalesce(paypro.");
            hsqlScript.append(Project.PROPERTY_NAME);
            hsqlScript.append(", invpro.");
            hsqlScript.append(Project.PROPERTY_NAME);
            hsqlScript.append("), ");
        } else if (strGroupCrit.equalsIgnoreCase("FINPR_BPartner_Category")) {
            hsqlScript.append("  coalesce(paybpc.");
            hsqlScript.append(Category.PROPERTY_NAME);
            hsqlScript.append(", invbpc.");
            hsqlScript.append(Category.PROPERTY_NAME);
            hsqlScript.append("), ");
        } else if (strGroupCrit.equalsIgnoreCase("INS_CURRENCY")) {
            hsqlScript.append("  coalesce(paycur.");
            hsqlScript.append(Currency.PROPERTY_ISOCODE);
            hsqlScript.append(", invcur.");
            hsqlScript.append(Currency.PROPERTY_ISOCODE);
            hsqlScript.append("), ");
        } else if (strGroupCrit.equalsIgnoreCase("ACCS_ACCOUNT_ID_D")) {
            hsqlScript.append(" coalesce(");
            hsqlScript.append(
                    " (select trans.account.name from FIN_Finacc_Transaction trans left outer join trans.finPayment payment where payment.id=pay.id),");
            hsqlScript.append(" pay.");
            hsqlScript.append(FIN_Payment.PROPERTY_ACCOUNT);
            hsqlScript.append(".name, 'Awaiting Payment'");
            hsqlScript.append("), ");
        }

        hsqlScript.append(" a, coalesce(pay.");
        hsqlScript.append(FIN_Payment.PROPERTY_STATUS);
        hsqlScript.append(", 'RPAP')");

        if (!strOrdCrit.isEmpty()) {
            String[] strOrdCritList = strOrdCrit.substring(2, strOrdCrit.length() - 2).split("', '");

            for (int i = 0; i < strOrdCritList.length; i++) {
                if (strOrdCritList[i].equalsIgnoreCase("Date")) {
                    hsqlScript.append(", inv.");
                    hsqlScript.append(Invoice.PROPERTY_INVOICEDATE);
                }
                if (strOrdCritList[i].contains("Project")) {
                    hsqlScript.append(",  coalesce(paypro.");
                    hsqlScript.append(Project.PROPERTY_NAME);
                    hsqlScript.append(", invpro.");
                    hsqlScript.append(Project.PROPERTY_NAME);
                    hsqlScript.append(")");
                }
                if (strOrdCritList[i].contains("FINPR_BPartner_Category")) {
                    hsqlScript.append(",  coalesce(paybpc.");
                    hsqlScript.append(Category.PROPERTY_NAME);
                    hsqlScript.append(", invbpc.");
                    hsqlScript.append(Category.PROPERTY_NAME);
                    hsqlScript.append(")");
                }
                if (strOrdCritList[i].contains("APRM_FATS_BPARTNER")) {
                    hsqlScript.append(",  coalesce(paybp.");
                    hsqlScript.append(BusinessPartner.PROPERTY_NAME);
                    hsqlScript.append(", invbp.");
                    hsqlScript.append(BusinessPartner.PROPERTY_NAME);
                    hsqlScript.append(")");
                }
                if (strOrdCritList[i].contains("INS_CURRENCY")) {
                    hsqlScript.append(",  coalesce(paycur.");
                    hsqlScript.append(Currency.PROPERTY_ISOCODE);
                    hsqlScript.append(", invcur.");
                    hsqlScript.append(Currency.PROPERTY_ISOCODE);
                    hsqlScript.append(")");
                }
                if (strOrdCritList[i].equalsIgnoreCase("ACCS_ACCOUNT_ID_D")) {
                    hsqlScript.append(", coalesce(");
                    hsqlScript.append(
                            " (select trans.account.name from FIN_Finacc_Transaction trans left outer join trans.finPayment payment where payment.id=pay.id),");
                    hsqlScript.append(" pay.");
                    hsqlScript.append(FIN_Payment.PROPERTY_ACCOUNT);
                    hsqlScript.append(".name)");
                }
                if (strOrdCritList[i].equalsIgnoreCase("DueDate")) {
                    hsqlScript.append(", invps.");
                    hsqlScript.append(FIN_PaymentSchedule.PROPERTY_DUEDATE);
                }
            }
        }

        hsqlScript.append(", fpsd.");
        hsqlScript.append(FIN_PaymentScheduleDetail.PROPERTY_INVOICEPAYMENTSCHEDULE);
        hsqlScript.append(".");
        hsqlScript.append(FIN_PaymentSchedule.PROPERTY_ID);
        final Session session = OBDal.getInstance().getSession();
        final Query query = session.createQuery(hsqlScript.toString());

        int pos = 0;
        for (final Object param : parameters) {
            if (param instanceof BaseOBObject) {
                query.setEntity(pos++, param);
            } else {
                query.setParameter(pos++, param);
            }
        }

        scroller = query.scroll(ScrollMode.FORWARD_ONLY);

        FIN_PaymentDetail finPaymDetail;
        Boolean mustGroup;
        String previousFPSDInvoiceId = null;
        String previousPaymentId = null;
        BigDecimal amountSum = BigDecimal.ZERO;
        BigDecimal balanceSum = BigDecimal.ZERO;
        FieldProvider previousRow = null;
        FieldProvider lastGroupedDatarow = null;
        ConversionRate previousConvRate = null;
        boolean isReceipt = false;
        boolean isAmtInLimit = false;

        // Before processing the data the Transactions without a Payment associated are recovered
        java.util.List<FIN_FinaccTransaction> transactionsList = getTransactionsList(strInclSubOrg, strOrg,
                strcBPartnerIdIN, strFinancialAccountId, strDocumentDateFrom, strDocumentDateTo,
                strPaymentDateFrom, strPaymentDateTo, strAmountFrom, strAmountTo, strcBPGroupIdIN,
                strcProjectIdIN, strfinPaymSt, strcCurrency, strPaymType, strGroupCrit, strOrdCrit,
                strcNoBusinessPartner, strDueDateFrom, strDueDateTo, strExpectedDateFrom, strExpectedDateTo);

        // There are three variables involved in this loop. The first one is data, wich is the
        // the one the loop processes. Then grouped data is used to group similar data lines into
        // one. Finally total data adds the remaining information that is not in data.
        int i = 0;
        while (scroller.next()) {
            i++;
            // get 1st column (idx=0)
            Object value = scroller.get(0);

            // TODO: rename variable to not have same name as class
            FIN_PaymentScheduleDetail FIN_PaymentScheduleDetail = (FIN_PaymentScheduleDetail) value;

            // make a empty FieldProvider instead of saving link to DAL-object
            FieldProvider data = FieldProviderFactory.getFieldProvider(null);

            if (i % 100 == 0) {
                OBDal.getInstance().getSession().clear();
            }
            OBDal.getInstance().getSession().buildLockRequest(LockOptions.NONE)
                    .lock(FIN_PaymentScheduleDetail.ENTITY_NAME, FIN_PaymentScheduleDetail);

            // search for fin_finacc_transaction for this payment
            FIN_FinaccTransaction trx = null;
            FIN_PaymentDetail detail = FIN_PaymentScheduleDetail.getPaymentDetails();
            if (detail != null) {
                OBCriteria<FIN_FinaccTransaction> trxQuery = OBDal.getInstance()
                        .createCriteria(FIN_FinaccTransaction.class);
                trxQuery.add(
                        Restrictions.eq(FIN_FinaccTransaction.PROPERTY_FINPAYMENT, detail.getFinPayment()));
                // uniqueness guaranteed via unique constraint in db
                trx = (FIN_FinaccTransaction) trxQuery.uniqueResult();
            }
            // If the payment schedule detail has a payment detail, then, the information is taken from
            // the payment. If not, the information is taken from the invoice (the else).
            if (FIN_PaymentScheduleDetail.getPaymentDetails() != null) {
                BusinessPartner bp = getDocumentBusinessPartner(FIN_PaymentScheduleDetail);
                if (bp == null) {
                    FieldProviderFactory.setField(data, "BP_GROUP", "");
                    FieldProviderFactory.setField(data, "BPARTNER", "");
                } else {
                    // bp_group -- bp_category
                    FieldProviderFactory.setField(data, "BP_GROUP", bp.getBusinessPartnerCategory().getName());
                    // bpartner
                    FieldProviderFactory.setField(data, "BPARTNER", bp.getName());
                }

                // transCurrency
                transCurrency = FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getCurrency();
                FieldProviderFactory.setField(data, "TRANS_CURRENCY", transCurrency.getISOCode());
                // paymentMethod
                FieldProviderFactory.setField(data, "PAYMENT_METHOD", FIN_PaymentScheduleDetail
                        .getPaymentDetails().getFinPayment().getPaymentMethod().getIdentifier());

                // payment
                FieldProviderFactory.setField(data, "PAYMENT",
                        ((FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment()
                                .getPaymentDate() != null)
                                        ? dateFormat.format(FIN_PaymentScheduleDetail.getPaymentDetails()
                                                .getFinPayment().getPaymentDate())
                                        : "Null")
                                + " - " + FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment()
                                        .getDocumentNo());
                // payment description
                FieldProviderFactory.setField(data, "PAYMENT_DESC",
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getDescription());
                // payment_id
                FieldProviderFactory.setField(data, "PAYMENT_ID",
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getId().toString());
                // payment_date
                FieldProviderFactory.setField(data, "PAYMENT_DATE",
                        (FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getPaymentDate() != null)
                                ? dateFormat.format(FIN_PaymentScheduleDetail
                                        .getPaymentDetails().getFinPayment().getPaymentDate())
                                : "Null");
                // payment_docNo
                FieldProviderFactory.setField(data, "PAYMENT_DOCNO",
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getDocumentNo());
                // payment yes / no
                FieldProviderFactory.setField(data, "PAYMENT_Y_N", "");
                // financialAccount
                FieldProviderFactory.setField(data, "FINANCIAL_ACCOUNT",
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment()
                                .getFINFinaccTransactionList().size() != 0
                                        ? FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment()
                                                .getFINFinaccTransactionList().get(0).getAccount().getName()
                                        : FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment()
                                                .getAccount().getName());
                // status
                FieldProviderFactory.setField(data, "STATUS", translateRefList(
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getStatus()));
                FieldProviderFactory.setField(data, "STATUS_CODE",
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getStatus());
                // is receipt
                if (FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().isReceipt()) {
                    FieldProviderFactory.setField(data, "ISRECEIPT", "Y");
                    isReceipt = true;
                } else {
                    FieldProviderFactory.setField(data, "ISRECEIPT", "N");
                    isReceipt = false;
                }
                // deposit/withdraw date
                if (trx != null) {
                    FieldProviderFactory.setField(data, "DEPOSIT_WITHDRAW_DATE",
                            dateFormat.format(trx.getTransactionDate()));
                } else {
                    FieldProviderFactory.setField(data, "DEPOSIT_WITHDRAW_DATE", "");
                }
            } else {

                // bp_group -- bp_category
                FieldProviderFactory.setField(data, "BP_GROUP",
                        FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getInvoice().getBusinessPartner()
                                .getBusinessPartnerCategory().getName());
                // bpartner
                FieldProviderFactory.setField(data, "BPARTNER", FIN_PaymentScheduleDetail
                        .getInvoicePaymentSchedule().getInvoice().getBusinessPartner().getName());
                // transCurrency
                transCurrency = FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getInvoice()
                        .getCurrency();
                FieldProviderFactory.setField(data, "TRANS_CURRENCY", transCurrency.getISOCode());
                // paymentMethod
                FieldProviderFactory.setField(data, "PAYMENT_METHOD", FIN_PaymentScheduleDetail
                        .getInvoicePaymentSchedule().getFinPaymentmethod().getIdentifier());
                // payment
                FieldProviderFactory.setField(data, "PAYMENT", "");
                // payment_id
                FieldProviderFactory.setField(data, "PAYMENT_ID", "");
                // payment_date
                FieldProviderFactory.setField(data, "PAYMENT_DATE", "");
                // payment_docNo
                FieldProviderFactory.setField(data, "PAYMENT_DOCNO", "");
                // payment yes / no
                FieldProviderFactory.setField(data, "PAYMENT_Y_N", "Display:None");
                // financialAccount
                FieldProviderFactory.setField(data, "FINANCIAL_ACCOUNT", "");
                // status
                FieldProviderFactory.setField(data, "STATUS", translateRefList("RPAP"));
                FieldProviderFactory.setField(data, "STATUS_CODE", "RPAP");
                // is receipt
                if (FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getInvoice().isSalesTransaction()) {
                    FieldProviderFactory.setField(data, "ISRECEIPT", "Y");
                    isReceipt = true;
                } else {
                    FieldProviderFactory.setField(data, "ISRECEIPT", "N");
                    isReceipt = false;
                }
                // deposit/withdraw date
                FieldProviderFactory.setField(data, "DEPOSIT_WITHDRAW_DATE", "");
            }

            /*
             * - If the payment schedule detail has an invoice, the line is filled normally.
             * 
             * - If it has a payment it does not have an invoice or it should have entered the first if,
             * thus, it is a credit payment. If it is a credit payment, it is checked whether it pays
             * one or multiple invoices. If it is one, the information of that invoice is provided. If
             * not, it is filled with '**'.
             * 
             * - Otherwise, it is filled empty.
             */
            if (FIN_PaymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                fillLine(dateFormat, data, FIN_PaymentScheduleDetail,
                        FIN_PaymentScheduleDetail.getInvoicePaymentSchedule(), false);
            } else if (FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment() != null) {
                java.util.List<Invoice> invoices = getInvoicesUsingCredit(
                        FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment());
                if (invoices.size() == 1) {
                    java.util.List<FIN_PaymentSchedule> ps = getInvoicePaymentSchedules(
                            FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment());
                    fillLine(dateFormat, data, FIN_PaymentScheduleDetail, ps.get(0), true);
                } else {
                    // project
                    FieldProviderFactory.setField(data, "PROJECT", "");
                    // salesPerson
                    FieldProviderFactory.setField(data, "SALES_PERSON", "");
                    // invoiceNumber.
                    FieldProviderFactory.setField(data, "INVOICE_NUMBER",
                            invoices.size() > 1 ? "**" + getInvoicesDocNos(invoices) : "");
                    // payment plan id
                    FieldProviderFactory.setField(data, "PAYMENT_PLAN_ID", "");
                    // payment plan yes / no
                    FieldProviderFactory.setField(data, "PAYMENT_PLAN_Y_N",
                            invoices.size() != 1 ? "Display:none" : "");
                    // payment plan yes / no
                    FieldProviderFactory.setField(data, "NOT_PAYMENT_PLAN_Y_N",
                            invoices.size() > 1 ? "" : "Display:none");
                    // invoiceDate
                    FieldProviderFactory.setField(data, "INVOICE_DATE", "");
                    // dueDate.
                    FieldProviderFactory.setField(data, "DUE_DATE", "");
                    // expectedDate.
                    FieldProviderFactory.setField(data, "EXPECTED_DATE", "");
                    // plannedDSO
                    FieldProviderFactory.setField(data, "PLANNED_DSO", "0");
                    // currentDSO
                    FieldProviderFactory.setField(data, "CURRENT_DSO", "0");
                    // daysOverdue
                    FieldProviderFactory.setField(data, "OVERDUE", "0");
                }
            } else {
                // project
                FieldProviderFactory.setField(data, "PROJECT", "");
                // salesPerson
                FieldProviderFactory.setField(data, "SALES_PERSON", "");
                // invoiceNumber.
                FieldProviderFactory.setField(data, "INVOICE_NUMBER", "");
                // payment plan id
                FieldProviderFactory.setField(data, "PAYMENT_PLAN_ID", "");
                // payment plan yes / no
                FieldProviderFactory.setField(data, "PAYMENT_PLAN_Y_N", "Display:none");
                // payment plan yes / no
                FieldProviderFactory.setField(data, "NOT_PAYMENT_PLAN_Y_N", "Display:none");
                // invoiceDate
                FieldProviderFactory.setField(data, "INVOICE_DATE", "");
                // dueDate.
                FieldProviderFactory.setField(data, "DUE_DATE", "");
                // expectedDate.
                FieldProviderFactory.setField(data, "EXPECTED_DATE", "");
                // plannedDSO
                FieldProviderFactory.setField(data, "PLANNED_DSO", "0");
                // currentDSO
                FieldProviderFactory.setField(data, "CURRENT_DSO", "0");
                // daysOverdue
                FieldProviderFactory.setField(data, "OVERDUE", "0");

            }

            // transactional and base amounts
            transAmount = FIN_PaymentScheduleDetail.getAmount();

            Currency baseCurrency = OBDal.getInstance().get(Currency.class, strConvertCurrency);

            boolean sameCurrency = baseCurrency.getISOCode().equalsIgnoreCase(transCurrency.getISOCode());

            if (!sameCurrency) {
                convRate = this.getConversionRate(transCurrency, baseCurrency, strConversionDate);

                if (convRate != null) {
                    final int stdPrecission = convRate.getToCurrency().getStandardPrecision().intValue();
                    if (isReceipt) {
                        FieldProviderFactory.setField(data, "TRANS_AMOUNT", transAmount.toString());
                        FieldProviderFactory.setField(data, "BASE_AMOUNT",
                                transAmount.multiply(convRate.getMultipleRateBy())
                                        .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).toString());
                    } else {
                        FieldProviderFactory.setField(data, "TRANS_AMOUNT", transAmount.negate().toString());
                        FieldProviderFactory.setField(data, "BASE_AMOUNT",
                                transAmount.multiply(convRate.getMultipleRateBy())
                                        .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).negate().toString());
                    }
                } else {
                    String message = transCurrency.getISOCode() + " -> " + baseCurrency.getISOCode() + " "
                            + strConversionDate;
                    throw new OBException(message);
                }
            } else {
                convRate = null;
                if (isReceipt) {
                    FieldProviderFactory.setField(data, "TRANS_AMOUNT", transAmount.toString());
                    FieldProviderFactory.setField(data, "BASE_AMOUNT", transAmount.toString());
                } else {
                    FieldProviderFactory.setField(data, "TRANS_AMOUNT", transAmount.negate().toString());
                    FieldProviderFactory.setField(data, "BASE_AMOUNT", transAmount.negate().toString());
                }
            }

            // currency
            FieldProviderFactory.setField(data, "BASE_CURRENCY", baseCurrency.getISOCode());
            // baseCurrency
            FieldProviderFactory.setField(data, "TRANS_CURRENCY", transCurrency.getISOCode());

            // Balance
            String status = "RPAE";
            try {
                status = FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getStatus();
            } catch (NullPointerException e) {
            }
            final boolean isCreditPayment = FIN_PaymentScheduleDetail.getInvoicePaymentSchedule() == null
                    && FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment() != null;

            BigDecimal balance = BigDecimal.ZERO;
            if (isCreditPayment && status != null && "PWNC RPR RPPC PPM RDNC".indexOf(status) >= 0) {
                balance = FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getGeneratedCredit()
                        .subtract(
                                FIN_PaymentScheduleDetail.getPaymentDetails().getFinPayment().getUsedCredit());
                if (isReceipt) {
                    balance = balance.negate();
                }
            } else if (!isCreditPayment && status != null
                    && "PWNC RPR RPPC PPM RDNC RPVOID".indexOf(status) == -1) {
                balance = isReceipt ? transAmount : transAmount.negate();
            }
            if (convRate != null) {
                final int stdPrecission = convRate.getToCurrency().getStandardPrecision().intValue();
                balance = balance.multiply(convRate.getMultipleRateBy()).setScale(stdPrecission,
                        BigDecimal.ROUND_HALF_UP);
            }
            FieldProviderFactory.setField(data, "BALANCE", balance.toString());

            finPaymDetail = FIN_PaymentScheduleDetail.getPaymentDetails();

            // Payment Schedule Detail grouping criteria
            if (finPaymDetail != null && FIN_PaymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                mustGroup = finPaymDetail.getFinPayment().getId().equalsIgnoreCase(previousPaymentId)
                        && FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getId()
                                .equalsIgnoreCase(previousFPSDInvoiceId);
                previousFPSDInvoiceId = FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getId();
                previousPaymentId = finPaymDetail.getFinPayment().getId();
            } else if (finPaymDetail != null && FIN_PaymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                mustGroup = finPaymDetail.getFinPayment().getId().equalsIgnoreCase(previousPaymentId)
                        && previousFPSDInvoiceId == null;
                previousPaymentId = finPaymDetail.getFinPayment().getId();
                previousFPSDInvoiceId = null;
            } else if (finPaymDetail == null && FIN_PaymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                mustGroup = previousPaymentId == null && FIN_PaymentScheduleDetail.getInvoicePaymentSchedule()
                        .getId().equalsIgnoreCase(previousFPSDInvoiceId);
                previousPaymentId = null;
                previousFPSDInvoiceId = FIN_PaymentScheduleDetail.getInvoicePaymentSchedule().getId();
            } else {
                mustGroup = false;
            }

            if (mustGroup) {
                amountSum = amountSum.add(transAmount);
                balanceSum = balanceSum.add(balance);
            } else {
                if (previousRow != null) {
                    // The current row has nothing to do with the previous one. Because of that, the
                    // previous row has to be added to grouped data.
                    if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                        FieldProviderFactory.setField(previousRow, "TRANS_AMOUNT", amountSum.toString());
                    else
                        FieldProviderFactory.setField(previousRow, "TRANS_AMOUNT",
                                amountSum.negate().toString());
                    FieldProviderFactory.setField(previousRow, "BALANCE", balanceSum.toString());
                    if (previousConvRate == null) {
                        if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                            FieldProviderFactory.setField(previousRow, "BASE_AMOUNT", amountSum.toString());
                        else
                            FieldProviderFactory.setField(previousRow, "BASE_AMOUNT",
                                    amountSum.negate().toString());
                    } else {
                        final int stdPrecission = previousConvRate.getToCurrency().getStandardPrecision()
                                .intValue();
                        if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                            FieldProviderFactory.setField(previousRow, "BASE_AMOUNT",
                                    amountSum.multiply(previousConvRate.getMultipleRateBy())
                                            .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).toString());
                        else
                            FieldProviderFactory.setField(previousRow, "BASE_AMOUNT",
                                    amountSum.multiply(previousConvRate.getMultipleRateBy())
                                            .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).negate()
                                            .toString());
                    }

                    if (strAmountFrom.isEmpty() && strAmountTo.isEmpty()) {
                        isAmtInLimit = true;
                    } else if (!strAmountFrom.isEmpty() && strAmountTo.isEmpty()) {
                        isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) >= Double
                                .parseDouble(strAmountFrom);
                    } else if (strAmountFrom.isEmpty() && !strAmountTo.isEmpty()) {
                        isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) <= Double
                                .parseDouble(strAmountTo);
                    } else {
                        isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) >= Double
                                .parseDouble(strAmountFrom)
                                && Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) <= Double
                                        .parseDouble(strAmountTo);
                    }
                    if (isAmtInLimit) {
                        lastGroupedDatarow = previousRow;
                        isAmtInLimit = false;
                        numberOfElements++;
                    }
                }
                previousRow = data;
                previousConvRate = convRate;
                amountSum = transAmount;
                balanceSum = balance;
            }

            // group_crit_id this is the column that has the ids of the grouping criteria selected
            if (strGroupCrit.equalsIgnoreCase("APRM_FATS_BPARTNER")) {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID", previousRow.getField("BPARTNER"));
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT", "Business Partner");
            } else if (strGroupCrit.equalsIgnoreCase("Project")) {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID", previousRow.getField("PROJECT"));
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT", "Project");
            } else if (strGroupCrit.equalsIgnoreCase("FINPR_BPartner_Category")) {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID", previousRow.getField("BP_GROUP"));
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT", "Business Partner Category");
            } else if (strGroupCrit.equalsIgnoreCase("INS_CURRENCY")) {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID",
                        previousRow.getField("TRANS_CURRENCY"));
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT", "Currency");
            } else if (strGroupCrit.equalsIgnoreCase("ACCS_ACCOUNT_ID_D")) {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID",
                        previousRow.getField("FINANCIAL_ACCOUNT"));
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT", "Financial Account");
            } else {
                FieldProviderFactory.setField(previousRow, "GROUP_CRIT_ID", "");
            }

            // Insert the transactions without payment if necessary
            if (lastElement != numberOfElements) {
                if (transactionsList.size() > 0) {
                    try {
                        existsConvRate = insertIntoTotal(lastGroupedDatarow, transactionsList, totalData,
                                strGroupCrit, strOrdCrit, strConvertCurrency, strConversionDate);
                    } catch (OBException e) {
                        // If there is no conversion rate
                        throw e;
                    }
                }
                totalData.add(lastGroupedDatarow);
                lastElement++;
            }

        }
        if (previousRow != null) {
            // The current row has nothing to do with the previous one. Because of that, the
            // previous row has to be added to grouped data.
            if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                FieldProviderFactory.setField(previousRow, "TRANS_AMOUNT", amountSum.toString());
            else
                FieldProviderFactory.setField(previousRow, "TRANS_AMOUNT", amountSum.negate().toString());
            FieldProviderFactory.setField(previousRow, "BALANCE", balanceSum.toString());
            if (previousConvRate == null) {
                if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                    FieldProviderFactory.setField(previousRow, "BASE_AMOUNT", amountSum.toString());
                else
                    FieldProviderFactory.setField(previousRow, "BASE_AMOUNT", amountSum.negate().toString());
            } else {
                final int stdPrecission = previousConvRate.getToCurrency().getStandardPrecision().intValue();
                if (previousRow.getField("ISRECEIPT").equalsIgnoreCase("Y"))
                    FieldProviderFactory.setField(previousRow, "BASE_AMOUNT",
                            amountSum.multiply(previousConvRate.getMultipleRateBy())
                                    .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).toString());
                else
                    FieldProviderFactory.setField(previousRow, "BASE_AMOUNT",
                            amountSum.multiply(previousConvRate.getMultipleRateBy())
                                    .setScale(stdPrecission, BigDecimal.ROUND_HALF_UP).negate().toString());
            }

            if (strAmountFrom.isEmpty() && strAmountTo.isEmpty()) {
                isAmtInLimit = true;
            } else if (!strAmountFrom.isEmpty() && strAmountTo.isEmpty()) {
                isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) >= Double
                        .parseDouble(strAmountFrom);
            } else if (strAmountFrom.isEmpty() && !strAmountTo.isEmpty()) {
                isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) <= Double
                        .parseDouble(strAmountTo);
            } else {
                isAmtInLimit = Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) >= Double
                        .parseDouble(strAmountFrom)
                        && Double.parseDouble(previousRow.getField("TRANS_AMOUNT")) <= Double
                                .parseDouble(strAmountTo);
            }
            if (isAmtInLimit) {
                lastGroupedDatarow = previousRow;
                isAmtInLimit = false;
                numberOfElements++;
            }
        }

        // Insert the transactions without payment if necessary
        if (lastElement != numberOfElements) {
            if (transactionsList.size() > 0) {
                try {
                    existsConvRate = insertIntoTotal(lastGroupedDatarow, transactionsList, totalData,
                            strGroupCrit, strOrdCrit, strConvertCurrency, strConversionDate);
                } catch (OBException e) {
                    // If there is no conversion rate
                    throw e;
                }
            }
            totalData.add(lastGroupedDatarow);
            lastElement++;
        }

        // Insert the remaining transactions wihtout payment if necessary
        while (transactionsList.size() > 0) {
            // throws OBException if there is no conversion rate
            FieldProvider transactionData = createFieldProviderForTransaction(transactionsList.get(0),
                    strGroupCrit, strConvertCurrency, strConversionDate);
            totalData.add(transactionData);
            transactionsList.remove(0);
        }
    } finally {
        if (scroller != null) {
            scroller.close();
        }
        OBContext.restorePreviousMode();
    }
    return totalData.toArray(new FieldProvider[totalData.size()]);
}

From source file:org.openbravo.test.accounting.RecordID2Test.java

/**
 * Verifies documents can be posted and unposted and that affects fact_acct (RecordID2 and
 * DateBalanced) Case 1: Invoice posted and just reconciliation posted. After both are posted
 * receivables entry should be balanced Invoice: I/1 Reconciliation: 1000032
 *//*from   w w w .j av  a 2 s. c om*/
@Test
public void testRecordID2_case1() {
    // Invoice I/1 from QA dataset
    String strCInvoiceId = "FF808081328278B5013282A1A35800A0";
    String strCAcctSchemaId = "9A68A0F8D72D4580B3EC3CAA00A5E1F0";

    OBContext.setAdminMode(true);
    try {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strRecordID2 = invoice.getFINPaymentScheduleList().get(0).getId();
        assertEquals("Invoice Not Posted", "Y", invoice.getPosted());
        ResetAccounting.delete(invoice.getClient().getId(), invoice.getOrganization().getId(), "318",
                invoice.getId(), "", "");
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strReceivablesAccountId = getReceivablesAccount(invoice.getBusinessPartner(), strCAcctSchemaId);
        assertEquals("Invoice Could Not Be Unposted", "N", invoice.getPosted());
        assertTrue("RecordID2 not updated after unposting invoice", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strCInvoiceId, "318", invoice.getClient().getId(), invoice.getOrganization().getId());
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        assertTrue("RecordID2 not updated after posting invoice", new BigDecimal("100").compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Invoice Could Not be Posted", "Y", invoice.getPosted());

        // Reconciliation: 1000032 - 02-07-2011 from QA Dataset. Paying previous invoice
        String strFINReconciliationId = "FF808081328278B5013282A3F67700C5";
        FIN_Reconciliation reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class,
                strFINReconciliationId);
        assertEquals("Reconciliation Not Posted", "Y", reconciliation.getPosted());
        ResetAccounting.delete(reconciliation.getClient().getId(), reconciliation.getOrganization().getId(),
                TABLE_RECONCILIATION, reconciliation.getId(), "", "");
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, strFINReconciliationId);
        assertEquals("Reconciliation Could Not Be Unposted", "N", reconciliation.getPosted());
        assertTrue("RecordID2 not updated after unposting reconciliation",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2, TABLE_RECONCILIATION, strCAcctSchemaId,
                        strReceivablesAccountId)) == 0);
        postDocument(strFINReconciliationId, TABLE_RECONCILIATION, reconciliation.getClient().getId(),
                reconciliation.getOrganization().getId());
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, strFINReconciliationId);
        assertTrue("RecordID2 not updated after posting reconciliation",
                new BigDecimal("-100").compareTo(getBalance(strRecordID2, TABLE_RECONCILIATION,
                        strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Reconciliation Could Not be Posted", "Y", reconciliation.getPosted());
        assertEquals("Entry Not Balanced",
                DateUtils.truncate(reconciliation.getAPRMFinaccTransactionVList().get(0).getTransactionDate(),
                        Calendar.DATE),
                getBalancedDate(strRecordID2, strReceivablesAccountId));
    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.test.accounting.RecordID2Test.java

/**
 * Verifies documents can be posted and unposted and that affects fact_acct (RecordID2 and
 * DateBalanced) Case 2: Invoice posted and transaction posted. After both are posted receivables
 * entry should be balanced Invoice: I/10 Transaction: line 50 - 400012 - 02-04-2011 - Customer A
 * - 146.00//from w w  w . j a  v  a  2s.  co m
 */
@Test
public void testRecordID2_case2() {
    // Invoice I/10 from QA dataset
    String strCInvoiceId = "FF8080813285D49A0132874B35C7030C";
    String strCAcctSchemaId = "9A68A0F8D72D4580B3EC3CAA00A5E1F0";

    OBContext.setAdminMode(true);
    try {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strRecordID2 = invoice.getFINPaymentScheduleList().get(0).getId();
        assertEquals("Invoice Not Posted", "Y", invoice.getPosted());
        ResetAccounting.delete(invoice.getClient().getId(), invoice.getOrganization().getId(), "318",
                invoice.getId(), "", "");
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strReceivablesAccountId = getReceivablesAccount(invoice.getBusinessPartner(), strCAcctSchemaId);
        assertEquals("Invoice Could Not Be Unposted", "N", invoice.getPosted());
        assertTrue("RecordID2 not updated after unposting invoice", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strCInvoiceId, "318", invoice.getClient().getId(), invoice.getOrganization().getId());
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        assertTrue("RecordID2 not updated after posting invoice", new BigDecimal("146").compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Invoice Could Not be Posted", "Y", invoice.getPosted());

        // Transaction: 1000032 - 02-07-2011 from QA Dataset. Paying previous invoice
        String strFINFinaccTransactionId = "FF8080813285D49A013287518E1C033E";
        FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                strFINFinaccTransactionId);
        assertEquals("Transaction Not Posted", "Y", transaction.getPosted());
        ResetAccounting.delete(transaction.getClient().getId(), transaction.getOrganization().getId(),
                TABLE_TRANSACTION, transaction.getId(), "", "");
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, strFINFinaccTransactionId);
        assertEquals("Transaction Could Not Be Unposted", "N", transaction.getPosted());
        assertTrue("RecordID2 not updated after unposting transaction", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_TRANSACTION, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strFINFinaccTransactionId, TABLE_TRANSACTION, transaction.getClient().getId(),
                transaction.getOrganization().getId());
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, strFINFinaccTransactionId);
        assertTrue("RecordID2 not updated after posting transaction", new BigDecimal("-146").compareTo(
                getBalance(strRecordID2, TABLE_TRANSACTION, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Transaction Could Not be Posted", "Y", transaction.getPosted());
        assertEquals("Entry Not Balanced", DateUtils.truncate(transaction.getTransactionDate(), Calendar.DATE),
                getBalancedDate(strRecordID2, strReceivablesAccountId));
    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.test.accounting.RecordID2Test.java

/**
 * Verifies documents can be posted and unposted and that affects fact_acct (RecordID2 and
 * DateBalanced) Case 3: Invoice posted and payment posted. After both are posted receivables
 * entry should be balanced Invoice: I/11 Payment: 400013 - 02-04-2011 - Customer A - 30.00 Then
 * transaction is posted and in transit balance is checked
 *//* w  w w.  j  av a 2  s  . c o  m*/
@Test
public void testRecordID2_case3() {
    // Invoice I/11 from QA dataset
    String strCInvoiceId = "FF8080813285D49A0132875C1EF60374";
    String strCAcctSchemaId = "9A68A0F8D72D4580B3EC3CAA00A5E1F0";

    OBContext.setAdminMode(true);
    try {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strRecordID2 = invoice.getFINPaymentScheduleList().get(0).getId();
        assertEquals("Invoice Not Posted", "Y", invoice.getPosted());
        ResetAccounting.delete(invoice.getClient().getId(), invoice.getOrganization().getId(), "318",
                invoice.getId(), "", "");
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strReceivablesAccountId = getReceivablesAccount(invoice.getBusinessPartner(), strCAcctSchemaId);
        assertEquals("Invoice Could Not Be Unposted", "N", invoice.getPosted());
        assertTrue("RecordID2 not updated after unposting invoice", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strCInvoiceId, "318", invoice.getClient().getId(), invoice.getOrganization().getId());
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);

        assertTrue("RecordID2 not updated after posting invoice", new BigDecimal("30").compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Invoice Could Not be Posted", "Y", invoice.getPosted());

        // Payment: 400013 - 02-04-2011 - Customer A - 30.00 from QA Dataset. Paying previous invoice
        String strFINPaymentId = "FF8080813285D49A0132875DB5780380";
        FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);
        String strRecordID2InTransit = payment.getId();
        String strInTransitAccountId = getInTransitAccount(payment.getAccount(), strCAcctSchemaId);
        assertEquals("Payment Not Posted", "Y", payment.getPosted());
        ResetAccounting.delete(payment.getClient().getId(), payment.getOrganization().getId(), TABLE_PAYMENT,
                payment.getId(), "", "");
        payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);

        assertEquals("Payment Could Not Be Unposted", "N", payment.getPosted());
        assertTrue("RecordID2 for receivables not updated after unposting Payment", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_PAYMENT, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for In Transit not updated after unposting Payment",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_PAYMENT, strCAcctSchemaId,
                        strInTransitAccountId)) == 0);

        postDocument(strFINPaymentId, TABLE_PAYMENT, payment.getClient().getId(),
                payment.getOrganization().getId());
        payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);

        assertTrue("RecordID2 for receivables not updated after posting Payment",
                new BigDecimal("-30").compareTo(getBalance(strRecordID2, TABLE_PAYMENT, strCAcctSchemaId,
                        strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for In Transit not updated after posting Payment",
                new BigDecimal("30").compareTo(getBalance(strRecordID2InTransit, TABLE_PAYMENT,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Payment Could Not be Posted", "Y", payment.getPosted());
        assertEquals("Entry Not Balanced for Receivables",
                DateUtils.truncate(payment.getPaymentDate(), Calendar.DATE),
                getBalancedDate(strRecordID2, strReceivablesAccountId));
        FIN_FinaccTransaction transaction = payment.getFINFinaccTransactionList().get(0);
        assertEquals("Transaction Not Posted", "Y", transaction.getPosted());
        ResetAccounting.delete(transaction.getClient().getId(), transaction.getOrganization().getId(),
                TABLE_TRANSACTION, transaction.getId(), "", "");
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, transaction.getId());
        assertEquals("Transaction Could Not Be Unposted", "N", transaction.getPosted());
        assertTrue("RecordID2 not updated after unposting transaction",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_TRANSACTION, strCAcctSchemaId,
                        strInTransitAccountId)) == 0);
        postDocument(transaction.getId(), TABLE_TRANSACTION, transaction.getClient().getId(),
                transaction.getOrganization().getId());
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, transaction.getId());
        assertTrue("RecordID2 not updated after posting transaction",
                new BigDecimal("-30").compareTo(getBalance(strRecordID2InTransit, TABLE_TRANSACTION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Transaction Could Not be Posted", "Y", transaction.getPosted());
        assertEquals("Entry Not Balanced for In Transit ",
                DateUtils.truncate(transaction.getTransactionDate(), Calendar.DATE),
                getBalancedDate(strRecordID2InTransit, strInTransitAccountId));
    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.test.accounting.RecordID2Test.java

/**
 * Verifies documents can be posted and unposted and that affects fact_acct (RecordID2 and
 * DateBalanced) Case 4: Invoice posted , transaction posted and reconciliation posted. After both
 * are posted receivables entry should be balanced Invoice: I/14 Transaction: Accounting Documents
 * EURO - EUR - 400016 - 02-04-2011 - Customer A - 40.00 - 0 Reconciliation: 1000042 . When
 * Transaction and reconciliation are posted in transit account balance should be 0
 *//*from  ww  w .  j a v a  2s. c om*/
@Test
public void testRecordID2_case4() {
    // Invoice I/14 from QA dataset
    String strCInvoiceId = "FF808081328B2FE901328B5AE4030098";
    String strCAcctSchemaId = "9A68A0F8D72D4580B3EC3CAA00A5E1F0";

    OBContext.setAdminMode(true);
    try {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strRecordID2 = invoice.getFINPaymentScheduleList().get(0).getId();
        assertEquals("Invoice Not Posted", "Y", invoice.getPosted());
        ResetAccounting.delete(invoice.getClient().getId(), invoice.getOrganization().getId(), "318",
                invoice.getId(), "", "");
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strReceivablesAccountId = getReceivablesAccount(invoice.getBusinessPartner(), strCAcctSchemaId);
        assertEquals("Invoice Could Not Be Unposted", "N", invoice.getPosted());
        assertTrue("RecordID2 not updated after unposting invoice", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strCInvoiceId, "318", invoice.getClient().getId(), invoice.getOrganization().getId());
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        assertTrue("RecordID2 not updated after posting invoice", new BigDecimal("50").compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Invoice Could Not be Posted", "Y", invoice.getPosted());

        // Payment: 400016 - 02-04-2011 - Customer A - 40.00 from QA Dataset. Paying previous invoice
        String strFINPaymentId = "FF808081328B2FE901328B5D698000B1";
        FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);
        String strInTransitAccountId = getDepositAccount(payment.getAccount(), strCAcctSchemaId);
        FIN_FinaccTransaction transaction = payment.getFINFinaccTransactionList().get(0);
        String strRecordID2InTransit = transaction.getId();
        assertEquals("Transaction Not Posted", "Y", transaction.getPosted());
        ResetAccounting.delete(transaction.getClient().getId(), transaction.getOrganization().getId(),
                TABLE_TRANSACTION, transaction.getId(), "", "");
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, transaction.getId());
        assertEquals("Transaction Could Not Be Unposted", "N", transaction.getPosted());
        assertTrue("RecordID2 for receivables not updated after unposting transaction",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2, TABLE_TRANSACTION, strCAcctSchemaId,
                        strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for in transit not updated after unposting transaction",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_TRANSACTION, strCAcctSchemaId,
                        strInTransitAccountId)) == 0);
        postDocument(transaction.getId(), TABLE_TRANSACTION, transaction.getClient().getId(),
                transaction.getOrganization().getId());
        transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, transaction.getId());
        assertTrue("RecordID2 for receivables not updated after posting transaction",
                new BigDecimal("-50").compareTo(getBalance(strRecordID2, TABLE_TRANSACTION, strCAcctSchemaId,
                        strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for in transit not updated after posting transaction",
                new BigDecimal("40").compareTo(getBalance(strRecordID2InTransit, TABLE_TRANSACTION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Transaction Could Not be Posted", "Y", transaction.getPosted());
        assertEquals("Entry Not Balanced", DateUtils.truncate(transaction.getTransactionDate(), Calendar.DATE),
                getBalancedDate(strRecordID2, strReceivablesAccountId));
        FIN_Reconciliation reconciliation = transaction.getReconciliation();
        assertEquals("Reconciliation Not Posted", "Y", reconciliation.getPosted());
        ResetAccounting.delete(reconciliation.getClient().getId(), reconciliation.getOrganization().getId(),
                TABLE_RECONCILIATION, reconciliation.getId(), "", "");
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, reconciliation.getId());
        assertEquals("Reconciliation Could Not Be Unposted", "N", reconciliation.getPosted());
        assertTrue("RecordID2 for in transit not updated after unposting reconciliation",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_RECONCILIATION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        postDocument(reconciliation.getId(), TABLE_RECONCILIATION, reconciliation.getClient().getId(),
                reconciliation.getOrganization().getId());
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, reconciliation.getId());
        assertTrue("RecordID2 for in transit not updated after posting reconciliation",
                new BigDecimal("-40").compareTo(getBalance(strRecordID2InTransit, TABLE_RECONCILIATION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Reconciliation Could Not be Posted", "Y", reconciliation.getPosted());
        assertEquals("Entry Not Balanced",
                DateUtils.truncate(reconciliation.getAPRMFinaccTransactionVList().get(0).getTransactionDate(),
                        Calendar.DATE),
                getBalancedDate(strRecordID2InTransit, strInTransitAccountId));

    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        OBContext.restorePreviousMode();
    }
}