Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:org.apache.cloudstack.quota.QuotaAlertManagerImpl.java

@Override
public void checkAndSendQuotaAlertEmails() {
    List<DeferredQuotaEmail> deferredQuotaEmailList = new ArrayList<DeferredQuotaEmail>();
    final BigDecimal zeroBalance = new BigDecimal(0);
    for (final QuotaAccountVO quotaAccount : _quotaAcc.listAllQuotaAccount()) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("checkAndSendQuotaAlertEmails accId=" + quotaAccount.getId());
        }/*from  www.ja  v a  2  s.c  o  m*/
        BigDecimal accountBalance = quotaAccount.getQuotaBalance();
        Date balanceDate = quotaAccount.getQuotaBalanceDate();
        Date alertDate = quotaAccount.getQuotaAlertDate();
        int lockable = quotaAccount.getQuotaEnforce();
        BigDecimal thresholdBalance = quotaAccount.getQuotaMinBalance();
        if (accountBalance != null) {
            AccountVO account = _accountDao.findById(quotaAccount.getId());
            if (account == null)
                continue; // the account is removed
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("checkAndSendQuotaAlertEmails: Check id=" + account.getId() + " bal="
                        + accountBalance + ", alertDate=" + alertDate + ", lockable=" + lockable);
            }
            if (accountBalance.compareTo(zeroBalance) < 0) {
                if (_lockAccountEnforcement && (lockable == 1)) {
                    if (_quotaManager.isLockable(account)) {
                        s_logger.info("Locking account " + account.getAccountName() + " due to quota < 0.");
                        lockAccount(account.getId());
                    }
                }
                if (alertDate == null
                        || (balanceDate.after(alertDate) && getDifferenceDays(alertDate, new Date()) > 1)) {
                    s_logger.info("Sending alert " + account.getAccountName() + " due to quota < 0.");
                    deferredQuotaEmailList.add(new DeferredQuotaEmail(account, quotaAccount,
                            QuotaConfig.QuotaEmailTemplateTypes.QUOTA_EMPTY));
                }
            } else if (accountBalance.compareTo(thresholdBalance) < 0) {
                if (alertDate == null
                        || (balanceDate.after(alertDate) && getDifferenceDays(alertDate, new Date()) > 1)) {
                    s_logger.info(
                            "Sending alert " + account.getAccountName() + " due to quota below threshold.");
                    deferredQuotaEmailList.add(new DeferredQuotaEmail(account, quotaAccount,
                            QuotaConfig.QuotaEmailTemplateTypes.QUOTA_LOW));
                }
            }
        }
    }

    for (DeferredQuotaEmail emailToBeSent : deferredQuotaEmailList) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(
                    "checkAndSendQuotaAlertEmails: Attempting to send quota alert email to users of account: "
                            + emailToBeSent.getAccount().getAccountName());
        }
        sendQuotaAlert(emailToBeSent);
    }
}

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

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

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

From source file:org.efaps.esjp.accounting.util.data.ConSis.java

/**
 * Needs a txt file from Concar. Reads it, analyses it and checks if an account with the same name exists.
 * @param _parameter//w  w w.  ja  v  a 2  s .  c o m
 * @return
 */
public Return initialTransaction(final Parameter _parameter) {
    final String filename = _parameter.getParameterValue("valueField");
    final File file = new File(filename);
    try {
        final List<Account> accs = readAccounts4SaldoConcar(file);
        BigDecimal amountMN = BigDecimal.ZERO;
        BigDecimal amountME = BigDecimal.ZERO;
        boolean found = true;
        for (final Account acc : accs) {
            final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
            queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, acc.getName());
            final InstanceQuery query = queryBldr.getQuery();
            query.executeWithoutAccessCheck();
            if (query.next()) {
                acc.setInstance(query.getCurrentValue());
            } else {
                ConSis.LOG.info("Not found: {}", acc);
                found = false;
            }
            amountMN = amountMN.add(acc.getAmountMN());
            amountME = amountME.add(acc.getAmountME());
        }
        ConSis.LOG.info("amountMN: {}", amountMN);
        ConSis.LOG.info("amountME: {}", amountME);
        if (found && amountMN.compareTo(BigDecimal.ZERO) == 0 && amountME.compareTo(BigDecimal.ZERO) == 0) {
            final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
            insert.add(CIAccounting.TransactionOpeningBalance.Date, new DateTime());
            insert.add(CIAccounting.TransactionOpeningBalance.Description, "Asiento de Apertura");
            insert.add(CIAccounting.TransactionOpeningBalance.Status,
                    Status.find(CIAccounting.TransactionStatus.Open));
            insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, _parameter.getInstance());
            insert.executeWithoutAccessCheck();

            final Instance basCur = Currency.getBaseCurrency();
            for (final Account acc : accs) {
                final Insert insertpos = new Insert(acc.getAmountME().compareTo(BigDecimal.ZERO) > 0
                        ? CIAccounting.TransactionPositionCredit
                        : CIAccounting.TransactionPositionDebit);
                insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
                insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
                insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
                insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
                insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
                insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
                insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
                insertpos.executeWithoutAccessCheck();
            }
        }
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final EFapsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return new Return();
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private RollUpMPSResult rollUpMPS(Mps mpsDst, MpsLine srcMpsLine, BigDecimal quan, Date countDay,
        int mpsSequence) {
    BigDecimal roundedQty = quan;
    if (srcMpsLine.getPlanningItem().getCatalog() != null) {
        Bom bom = bomService.findCurrentBOM(srcMpsLine.getPlanningItem().getCatalog().getId());
        if (bom != null) {
            BigDecimal maxQty = bom.getMaxLotQty();
            BigDecimal minQty = bom.getMinLotQty();
            BigDecimal increment = bom.getLotIncrementQty();

            if (!(MathUtils.compareToZeroOrNull(maxQty) == 0 || MathUtils.compareToZeroOrNull(minQty) == 0
                    || MathUtils.compareToZeroOrNull(increment) == 0)) {
                if (bom.getCatalog().getMeasure1().getId() != srcMpsLine.getPlanningItem().getMeasure()
                        .getId()) {/*w ww .  j a  va2 s.  c o m*/
                    maxQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), maxQty);
                    minQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), minQty);
                    increment = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), increment);
                }

                long numOfMax = roundedQty.divide(maxQty).longValue();
                roundedQty = maxQty.multiply(new BigDecimal(numOfMax));
                BigDecimal remainder = roundedQty.add(roundedQty);

                if (MathUtils.compareToZero(remainder) != 0) {
                    if (remainder.compareTo(minQty) < 0) {
                        roundedQty = roundedQty.add(minQty);
                    } else {
                        long numOfInc = remainder.subtract(minQty).divide(increment).longValue();
                        BigDecimal remInc = remainder.subtract(minQty)
                                .subtract(increment.multiply(new BigDecimal(numOfInc)));
                        if (MathUtils.compareToZero(remInc) != 0)
                            roundedQty = roundedQty.add(minQty)
                                    .add(increment.multiply(new BigDecimal(numOfInc))).add(increment);
                        else
                            roundedQty = roundedQty.add(remainder);

                    }
                }
            }
        }
    }

    short bucket = MfUtils.determineBucketOffset(mpsDst.getPlanningLevel().getId(), countDay);
    MpsLine mpsLine = null;
    for (MpsLine line : generatedMPSLines) {
        if (MathUtils.compareToZero(line.getProductionDemandQty()) <= 0
                && line.getPlanningItem().getId() == srcMpsLine.getPlanningItem().getId()
                && line.getBucketOffset() == bucket) {
            mpsLine = line;
            break;
        }
    }
    if (mpsLine == null) {
        mpsLine = mpsLineService.initialize();
        mpsLine.setPlanningItem(srcMpsLine.getPlanningItem());
        mpsLine.setLevelCode(srcMpsLine.getPlanningItem().getLowLevelCode());
        mpsLine.setMps(mpsDst);
        mpsLine.setBucketOffset(bucket);
        BucketRange bucketRange = MfUtils.determineBucketRange(mpsDst.getPlanningLevel().getId(), bucket);
        mpsLine.setBucketOffsetDate(bucketRange.getBucketStart());
        mpsLine.setDemandFenceDate(srcMpsLine.getDemandFenceDate());
        mpsLine.setMpsSequence(mpsSequence);
        mpsLine.setOutputMpsSequence(null);
        mpsLine.setMeasure(srcMpsLine.getMeasure());
        mpsLine.setPlannedQty(roundedQty);

        generatedMPSLines.add(mpsLine);
        //    ? MPS
        return new RollUpMPSResult(roundedQty, mpsSequence + 1);
    } else {
        mpsLine.setPlannedQty(mpsLine.getPlannedQty().add(roundedQty));
        return new RollUpMPSResult(roundedQty, mpsSequence);
    }
}

From source file:org.efaps.esjp.accounting.transaction.TransInfo_Base.java

/**
 * Checks if is valid./*  www  .  j ava 2 s . c om*/
 *
 * @return true, if is valid
 */
private boolean isValid() {
    BigDecimal amount = BigDecimal.ZERO;
    for (final PositionInfo pos : this.positions) {
        amount = amount.add(pos.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
    }
    return amount.compareTo(BigDecimal.ZERO) == 0;
}

From source file:com.gst.portfolio.savings.data.DepositProductDataValidator.java

private void validateDepositAmountForCreate(JsonElement element, DataValidatorBuilder baseDataValidator) {
    final BigDecimal depositAmount = this.fromApiJsonHelper
            .extractBigDecimalWithLocaleNamed(depositAmountParamName, element);
    baseDataValidator.reset().parameter(depositAmountParamName).value(depositAmount).notNull().positiveAmount();

    BigDecimal depositMinAmount = null;
    if (this.fromApiJsonHelper.parameterExists(depositMinAmountParamName, element)) {
        depositMinAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(depositMinAmountParamName,
                element);//from ww w. j  ava 2s .c o  m
        baseDataValidator.reset().parameter(depositMinAmountParamName).value(depositMinAmount).notNull()
                .positiveAmount();
    }

    BigDecimal depositMaxAmount = null;
    if (this.fromApiJsonHelper.parameterExists(depositMaxAmountParamName, element)) {
        depositMaxAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(depositMaxAmountParamName,
                element);
        baseDataValidator.reset().parameter(depositMaxAmountParamName).value(depositMaxAmount).notNull()
                .positiveAmount();
    }

    if (depositMaxAmount != null && depositMaxAmount.compareTo(BigDecimal.ZERO) != -1) {
        if (depositMinAmount != null && depositMinAmount.compareTo(BigDecimal.ZERO) != -1) {
            baseDataValidator.reset().parameter(depositMaxAmountParamName).value(depositMaxAmount)
                    .notLessThanMin(depositMinAmount);
            if (depositMinAmount.compareTo(depositMaxAmount) <= 0) {
                baseDataValidator.reset().parameter(depositAmountParamName).value(depositAmount)
                        .inMinAndMaxAmountRange(depositMinAmount, depositMaxAmount);
            }
        } else {
            baseDataValidator.reset().parameter(depositAmountParamName).value(depositAmount)
                    .notGreaterThanMax(depositMaxAmount);
        }
    } else if (depositMinAmount != null && depositMinAmount.compareTo(BigDecimal.ZERO) != -1) {
        baseDataValidator.reset().parameter(depositAmountParamName).value(depositAmount)
                .notLessThanMin(depositMinAmount);
    }
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testDecimal() throws SQLException {
    trace("test DECIMAL");
    ResultSet rs;/*from w ww  .  jav  a 2 s.c o  m*/
    Object o;

    stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(21,-1,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(22,.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(23,1.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(24,12345678.89,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(25,99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(26,-99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(27,-99999998.99,9,'testDecimal')");
    rs = stat.executeQuery("SELECT column1,column5 FROM test where column3='testDecimal' ORDER BY column1");
    BigDecimal bd;
    rs.next();
    assertTrue(rs.getInt(1) == 21);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == -1);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("-1.00")) == 0);
    assertTrue(!rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Double);
    assertTrue(new BigDecimal((Double) o).compareTo(new BigDecimal("-1.00")) == 0);
    rs.next();
    assertTrue(rs.getInt(1) == 22);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == 0);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("0.00")) == 0);
    assertTrue(!rs.wasNull());
    rs.next();
    checkColumnBigDecimal(rs, 2, 1, "1.00");
    rs.next();
    checkColumnBigDecimal(rs, 2, 12345679, "12345678.89");
    rs.next();
    checkColumnBigDecimal(rs, 2, 99999999, "99999998.99");
    rs.next();
    checkColumnBigDecimal(rs, 2, -99999999, "-99999998.99");
    // assertTrue(!rs.next());
}

From source file:com.foglyn.fogbugz.FogBugzClient.java

/**
 * Computes remaining time from current estimate and elapsed time.
 * @param current current estimate in hours, can be null
 * @param elapsed elapsed time in hours, can be null
 *//*from  www.j  a  v  a  2  s. c  o  m*/
private BigDecimal computeRemainingTime(BigDecimal current, BigDecimal elapsed) {
    BigDecimal remaining = current; // possibly null

    if (current != null && elapsed != null) {
        remaining = current.subtract(elapsed);
        if (remaining.compareTo(BigDecimal.ZERO) < 0) {
            remaining = BigDecimal.ZERO;
        }
    }
    return remaining;
}

From source file:org.apache.pig.data.SchemaTuple.java

protected int compare(BigDecimal val, BigDecimal themVal) {
    return val.compareTo(themVal);
}

From source file:org.efaps.esjp.accounting.report.PurchaseRecordReport_Base.java

@SuppressWarnings("unchecked")
@Override/*from  ww w.  java2s .c o  m*/
public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource,
        final Map<String, Object> _jrParameters) throws EFapsException {
    QueryCache.cleanByKey(PurchaseRecordReport_Base.CACHEDQUERYKEY);

    final List<Map<String, Object>> values = new ArrayList<>();
    final List<Instance> instances = getInstances(_parameter);

    if (instances.size() > 0) {
        final Map<Instance, PosSum4Doc> posSums = getPosSums(_parameter);

        final SelectBuilder selRel = new SelectBuilder().linkto(CIAccounting.PurchaseRecord2Document.ToLink);
        final SelectBuilder selRelDocType = new SelectBuilder(selRel).type();
        final SelectBuilder selRelDocInst = new SelectBuilder(selRel).instance();
        final SelectBuilder selRelDocName = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Name);
        final SelectBuilder selRelDocRevision = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Revision);
        final SelectBuilder selRelDocDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Date);
        final SelectBuilder selRelDocDueDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.DueDate);
        final SelectBuilder selRelDocNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.NetTotal);
        final SelectBuilder selRelDocCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CrossTotal);
        final SelectBuilder selRelDocRNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateNetTotal);
        final SelectBuilder selRelDocRCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCrossTotal);
        final SelectBuilder selRelDocRateLabel = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Rate).label();

        final SelectBuilder selRelDocCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CurrencyId).instance();
        final SelectBuilder selRelDocRCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCurrencyId).instance();

        final SelectBuilder selRelDocContact = new SelectBuilder(selRel)
                .linkto(CISales.DocumentSumAbstract.Contact);
        final SelectBuilder selRelDocContactName = new SelectBuilder(selRelDocContact)
                .attribute(CIContacts.Contact.Name);
        final SelectBuilder selRelDocContactTax = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassOrganisation).attribute(CIContacts.ClassOrganisation.TaxNumber);
        final SelectBuilder selRelDocContactIdenityCard = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).attribute(CIContacts.ClassPerson.IdentityCard);
        final SelectBuilder selRelDocContactDOIType = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).linkto(CIContacts.ClassPerson.DOITypeLink)
                .attribute(CIContacts.AttributeDefinitionDOIType.MappingKey);

        final SelectBuilder selRelTypeLink = new SelectBuilder()
                .linkto(CIAccounting.PurchaseRecord2Document.TypeLink);
        final SelectBuilder selRelTypeLinkName = new SelectBuilder(selRelTypeLink)
                .attribute(CIERP.DocumentType.Name);

        final MultiPrintQuery multi = new MultiPrintQuery(instances);
        multi.addSelect(selRelDocType, selRelDocInst, selRelDocName, selRelDocRevision, selRelDocDate,
                selRelDocDueDate, selRelDocNTotal, selRelDocCTotal, selRelDocRNTotal, selRelDocRCTotal,
                selRelDocRateLabel, selRelDocCurInst, selRelDocRCurInst, selRelDocContactName,
                selRelDocContactTax, selRelTypeLinkName, selRelDocContactIdenityCard, selRelDocContactDOIType);
        multi.addAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate,
                CIAccounting.PurchaseRecord2Document.DetractionName,
                CIAccounting.PurchaseRecord2Document.DetractionAmount,
                CIAccounting.PurchaseRecord2Document.Taxed);
        multi.execute();

        while (multi.next()) {
            final Map<String, Object> map = new HashMap<>();
            final Type docType = multi.<Type>getSelect(selRelDocType);
            final Instance instDoc = multi.<Instance>getSelect(selRelDocInst);
            final String docName = multi.<String>getSelect(selRelDocName);
            final DateTime docDate = multi.<DateTime>getSelect(selRelDocDate);
            final DateTime docDueDate = multi.<DateTime>getSelect(selRelDocDueDate);
            final String contactName = multi.<String>getSelect(selRelDocContactName);
            final String contactTaxNum = multi.<String>getSelect(selRelDocContactTax);
            final BigDecimal rateTmp = multi.<BigDecimal>getSelect(selRelDocRateLabel);
            final String typeLinkName = multi.<String>getSelect(selRelTypeLinkName);
            final String docRevision = multi.<String>getSelect(selRelDocRevision);
            final String docContactIdenityCard = multi.<String>getSelect(selRelDocContactIdenityCard);
            final String docContactDOIType = multi.<String>getSelect(selRelDocContactDOIType);
            final Taxed4PurchaseRecord taxed = multi.getAttribute(CIAccounting.PurchaseRecord2Document.Taxed);

            final String detractionName = multi
                    .<String>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionName);
            final BigDecimal detractionAmount = multi
                    .<BigDecimal>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionAmount);
            final DateTime detractionDate = multi
                    .<DateTime>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate);
            final Instance docDerivatedRel = getDocumentDerivated(instDoc, true) == null
                    ? getDocumentDerivated(instDoc, false)
                    : getDocumentDerivated(instDoc, true);

            BigDecimal netTotal = multi.<BigDecimal>getSelect(selRelDocNTotal);
            BigDecimal crossTotal = multi.<BigDecimal>getSelect(selRelDocCTotal);

            final PosSum4Doc posSum = posSums.get(instDoc);
            BigDecimal taxfree;
            if (posSum != null) {
                taxfree = posSum.getTaxFree(_parameter);
            } else {
                taxfree = BigDecimal.ZERO;
            }
            BigDecimal igv = crossTotal.subtract(netTotal);
            netTotal = netTotal.subtract(taxfree);

            if (crossTotal.compareTo(netTotal) == 0) {
                taxfree = netTotal;
                netTotal = BigDecimal.ZERO;
            }

            if (CISales.IncomingCreditNote.getType().equals(docType)) {
                netTotal = netTotal.negate();
                crossTotal = crossTotal.negate();
                igv = igv.negate();
                taxfree = taxfree.negate();
            }

            PurchaseRecordReport_Base.LOG.debug("Document OID '{}'", instDoc.getOid());
            PurchaseRecordReport_Base.LOG.debug("Document name '{}'", docName);

            map.put(PurchaseRecordReport_Base.Field.DOC_RATE.getKey(), rateTmp);
            map.put(PurchaseRecordReport_Base.Field.DOC_DATE.getKey(), docDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_DUEDATE.getKey(), docDueDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_NAME.getKey(), docName);
            map.put(PurchaseRecordReport_Base.Field.DOC_CONTACT.getKey(), contactName);
            Boolean isDOI = false;
            String taxNum = contactTaxNum;
            if (taxNum == null || taxNum != null && taxNum.isEmpty()) {
                if (docContactIdenityCard != null && !docContactIdenityCard.isEmpty()) {
                    taxNum = docContactIdenityCard;
                    isDOI = true;
                }
            }
            map.put(PurchaseRecordReport_Base.Field.DOC_TAXNUM.getKey(), taxNum);

            switch (taxed) {
            case TAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVTAXED.getKey(), igv);
                break;
            case EXPORT:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALEXPORT.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVEXPORT.getKey(), igv);
                break;
            case UNTAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALUNTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVUNTAXED.getKey(), igv);
                break;
            default:
                break;
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_CROSSTOTAL.getKey(), crossTotal);
            map.put(PurchaseRecordReport_Base.Field.DOC_VALUENOTAX.getKey(), taxfree);

            final String[] nameAr = docName.split("\\W");

            if (nameAr.length == 2 && nameAr[0].length() < nameAr[1].length()) {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), nameAr[0]);
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), nameAr[1]);
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), "");
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), docName);
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey(), typeLinkName);
            map.put(PurchaseRecordReport_Base.Field.DOC_REVISION.getKey(), docRevision);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_NAME.getKey(), detractionName);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_AMOUNT.getKey(), detractionAmount);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_DATE.getKey(),
                    detractionAmount == null ? null : detractionDate);

            if (docDerivatedRel != null && docDerivatedRel.isValid()) {
                final SelectBuilder selLinkName = new SelectBuilder()
                        .linkfrom(CISales.Document2DocumentType, CISales.Document2DocumentType.DocumentLink)
                        .linkto(CISales.Document2DocumentType.DocumentTypeLink)
                        .attribute(CIERP.DocumentType.Name);

                final PrintQuery printDocRel = new PrintQuery(docDerivatedRel);
                printDocRel.addAttribute(CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
                printDocRel.addSelect(selLinkName);
                printDocRel.execute();

                final DateTime docRelDate = printDocRel
                        .<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
                final String docRelName = printDocRel.<String>getAttribute(CISales.DocumentSumAbstract.Name);

                map.put(PurchaseRecordReport_Base.Field.DOCREL_DATE.getKey(), docRelDate);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_PREFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[0] : "");
                map.put(PurchaseRecordReport_Base.Field.DOCREL_SUFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[1] : docRelName);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_TYPE.getKey(),
                        printDocRel.<String>getSelect(selLinkName));
            }

            // TODO falta implementar
            map.put(PurchaseRecordReport_Base.Field.DUA_YEAR.getKey(), "0");
            map.put(PurchaseRecordReport_Base.Field.RETENCION_APPLIES.getKey(), false);

            if (isDOI) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), docContactDOIType);
            } else if (contactTaxNum.length() == 11) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "6");
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "0");
            }

            final DateTime purchaseDate = getDate4Purchase(_parameter);
            final Integer diff = purchaseDate.getMonthOfYear() - docDate.getMonthOfYear();

            if (Math.abs(diff) > 12) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.OUSIDE.getKey());
            } else if (Math.abs(diff) > 0) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.INSIDE.getKey());
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.NORMAL.getKey());
            }

            values.add(map);
        }
    }
    final ComparatorChain chain = new ComparatorChain();
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            return val1.compareTo(val2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final DateTime date1 = (DateTime) _o1.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            final DateTime date2 = (DateTime) _o2.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            return date1.compareTo(date2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            return val1.compareTo(val2);
        }
    });

    Collections.sort(values, chain);
    getValues().addAll(values);
}