Example usage for java.math BigDecimal negate

List of usage examples for java.math BigDecimal negate

Introduction

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

Prototype

public BigDecimal negate() 

Source Link

Document

Returns a BigDecimal whose value is (-this) , and whose scale is this.scale() .

Usage

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

private static boolean calculateTransactionPriceDifferenceLogic(MaterialTransaction materialTransaction)
        throws OBException {
    boolean costAdjCreated = false;

    // With Standard Algorithm, no cost adjustment is needed
    if (StringUtils.equals(materialTransaction.getCostingAlgorithm().getJavaClassName(),
            "org.openbravo.costing.StandardAlgorithm")) {
        return false;
    }// w w w .j  a  v a 2 s. c  o  m

    if (materialTransaction.isCostPermanent()) {
        // Permanently adjusted transaction costs are not checked for price differences.
        return false;
    }
    Currency trxCurrency = materialTransaction.getCurrency();
    Organization trxOrg = materialTransaction.getOrganization();
    Date trxDate = materialTransaction.getMovementDate();
    int costCurPrecission = trxCurrency.getCostingPrecision().intValue();
    ShipmentInOutLine receiptLine = materialTransaction.getGoodsShipmentLine();
    if (receiptLine == null
            || !isValidPriceAdjTrx(receiptLine.getMaterialMgmtMaterialTransactionList().get(0))) {
        // We can only adjust cost of receipt lines.
        return false;
    }

    BigDecimal receiptQty = receiptLine.getMovementQuantity();
    boolean isNegativeReceipt = receiptQty.signum() == -1;
    if (isNegativeReceipt) {
        // If the receipt is negative convert the quantity to positive.
        receiptQty = receiptQty.negate();
    }

    Date costAdjDateAcct = null;
    BigDecimal invoiceAmt = BigDecimal.ZERO;

    // Calculate current transaction unit cost including existing adjustments.
    BigDecimal currentTrxUnitCost = CostAdjustmentUtils.getTrxCost(materialTransaction, true, trxCurrency);

    // Calculate expected transaction unit cost based on current invoice amounts and purchase price.
    BigDecimal expectedCost = BigDecimal.ZERO;
    BigDecimal invoiceQty = BigDecimal.ZERO;
    for (ReceiptInvoiceMatch matchInv : receiptLine.getProcurementReceiptInvoiceMatchList()) {
        Invoice invoice = matchInv.getInvoiceLine().getInvoice();
        if (invoice.getDocumentStatus().equals("VO")) {
            // Skip voided invoices.
            continue;
        }
        if (!invoice.isProcessed()) {
            // Skip not processed invoices.
            continue;
        }
        if (isNegativeReceipt) {
            // If the receipt is negative negate the invoiced quantities.
            invoiceQty = invoiceQty.add(matchInv.getQuantity().negate());
        } else {
            invoiceQty = invoiceQty.add(matchInv.getQuantity());
        }
        invoiceAmt = matchInv.getQuantity().multiply(matchInv.getInvoiceLine().getUnitPrice());

        invoiceAmt = FinancialUtils.getConvertedAmount(invoiceAmt, invoice.getCurrency(), trxCurrency, trxDate,
                trxOrg, FinancialUtils.PRECISION_STANDARD, invoice.getCurrencyConversionRateDocList());
        expectedCost = expectedCost.add(invoiceAmt);

        Date invoiceDate = invoice.getInvoiceDate();
        if (costAdjDateAcct == null || costAdjDateAcct.before(invoiceDate)) {
            costAdjDateAcct = invoiceDate;
        }
    }

    BigDecimal notInvoicedQty = receiptQty.subtract(invoiceQty);
    if (notInvoicedQty.signum() > 0) {
        // Not all the receipt line is invoiced, add pending invoice quantity valued with current
        // order price if exists or original unit cost.
        BigDecimal basePrice = BigDecimal.ZERO;
        Currency baseCurrency = trxCurrency;
        if (receiptLine.getSalesOrderLine() != null) {
            basePrice = receiptLine.getSalesOrderLine().getUnitPrice();
            baseCurrency = receiptLine.getSalesOrderLine().getSalesOrder().getCurrency();
        } else {
            basePrice = materialTransaction.getTransactionCost().divide(receiptQty, costCurPrecission,
                    RoundingMode.HALF_UP);
        }
        BigDecimal baseAmt = notInvoicedQty.multiply(basePrice).setScale(costCurPrecission,
                RoundingMode.HALF_UP);
        if (!baseCurrency.getId().equals(trxCurrency.getId())) {
            baseAmt = FinancialUtils.getConvertedAmount(baseAmt, baseCurrency, trxCurrency, trxDate, trxOrg,
                    FinancialUtils.PRECISION_STANDARD);
        }
        expectedCost = expectedCost.add(baseAmt);
    }
    // if the sum of trx costs with flag "isInvoiceCorrection" is distinct that the amount cost
    // generated by Match Invoice then New Cost Adjustment line is created by the difference
    if (expectedCost.compareTo(currentTrxUnitCost) != 0) {
        if (costAdjDateAcct == null) {
            costAdjDateAcct = trxDate;
        }
        createCostAdjustmenHeader(trxOrg);
        CostAdjustmentLine costAdjLine = CostAdjustmentUtils.insertCostAdjustmentLine(materialTransaction,
                costAdjHeader, expectedCost.subtract(currentTrxUnitCost), Boolean.TRUE, costAdjDateAcct);
        costAdjLine.setNeedsPosting(Boolean.TRUE);
        OBDal.getInstance().save(costAdjLine);
        costAdjCreated = true;
    }

    return costAdjCreated;
}

From source file:org.openvpms.component.system.common.jxpath.BigDecimalOperationNegate.java

@Override
public Object computeValue(EvalContext context) {
    BigDecimal a = TypeConversionUtil.bigDecimalValue(args[0].computeValue(context));
    return a.negate();
}

From source file:jp.furplag.util.commons.NumberUtils.java

public static BigDecimal cos(final BigDecimal angle, MathContext mc, boolean isRadians) {
    if (angle == null)
        return null;
    BigDecimal cos = BigDecimal.ONE;
    BigDecimal radians = isRadians ? angle : valueOf(toRadians(angle), BigDecimal.class);
    BigDecimal nSquare = radians.pow(2);
    int index = 0;
    for (BigDecimal factor : COSINE_FACTOR_DECIMAL128) {
        BigDecimal temporary = factor.multiply(nSquare);
        if (index % 2 == 0)
            temporary = temporary.negate();
        cos = cos.add(temporary);//from  w  w  w . j a  va2s  .co  m
        nSquare = nSquare.multiply(radians.pow(2)).setScale(
                ((mc == null ? MathContext.DECIMAL128 : mc).getPrecision() + 2), RoundingMode.HALF_UP);
        index++;
    }

    return cos.setScale((mc == null ? MathContext.DECIMAL128 : mc).getPrecision(), RoundingMode.HALF_UP);
}

From source file:org.openvpms.archetype.rules.stock.StockRules.java

/**
 * Transfers a quantity of a product from one stock location to another.
 *
 * @param product  the product to transfer
 * @param from     the from location//  w w w. j  a v  a 2s  .c  o m
 * @param to       the to location
 * @param quantity the quantity to transfer
 * @return the list updated objects. These must be saved to complete the transfer
 */
protected List<IMObject> transfer(Product product, Party from, Party to, BigDecimal quantity) {
    List<IMObject> result = new ArrayList<IMObject>();
    result.addAll(calcStock(product, from, quantity.negate()));
    result.addAll(calcStock(product, to, quantity));
    return result;
}

From source file:org.libreplan.business.planner.entities.SigmoidFunction.java

private BigDecimal calculateNumberOfAccumulatedHoursAtDay(BigDecimal valueAtOneDay, int totalHours) {
    BigDecimal epow = BigDecimal.valueOf(Math.pow(Math.E, valueAtOneDay.negate().doubleValue()));
    BigDecimal denominator = BigDecimal.valueOf(1).add(epow);
    return BigDecimal.valueOf(totalHours).divide(denominator, PRECISSION, ROUND_MODE);
}

From source file:com.liato.bankdroid.banking.banks.ResursBank.java

@Override
public void update() throws BankException, LoginException, BankChoiceException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }//w  w  w.j av a2s  . co  m

    urlopen = login();
    Matcher matcher = reAccounts.matcher(response);
    while (matcher.find()) {
        /*
         * Capture groups:
         * GROUP                    EXAMPLE DATA
         * 1: Account number        0000000000000000
         * 2: Beviljad kredit       0,00 kr
         * 3: Utnyttjad kredit      0,00 kr
         * 4: Reserverat  belopp    0,00 kr
         * 5: Kvar att utnyttja     0,00 kr
         * 
         */
        String accountId = Html.fromHtml(matcher.group(1)).toString().trim().replaceAll("[^0-9]*", "");
        accounts.add(new Account("Beviljad kredit", Helpers.parseBalance(matcher.group(2)), "b_" + accountId));

        BigDecimal utnyttjad = Helpers.parseBalance(matcher.group(3));
        utnyttjad = utnyttjad.add(Helpers.parseBalance(matcher.group(4)));
        utnyttjad = utnyttjad.negate();
        accounts.add(new Account("Utnyttjad kredit", utnyttjad, "u_" + accountId));

        balance = balance.add(Helpers.parseBalance(matcher.group(3)));
        balance = balance.add(utnyttjad);
        accounts.add(
                new Account("Reserverat belopp", Helpers.parseBalance(matcher.group(4)), "r_" + accountId));
        accounts.add(new Account("Disponibelt", Helpers.parseBalance(matcher.group(5)), "k_" + accountId));
    }

    if (accounts.isEmpty()) {
        throw new BankException(res.getText(R.string.no_accounts_found).toString());
    }
    super.updateComplete();
}

From source file:org.jpos.gl.GLTransaction.java

private BigDecimal negate(BigDecimal bd) {
    return bd != null ? bd.negate() : null;
}

From source file:org.kuali.kpme.tklm.leave.payout.web.LeavePayoutMaintainableImpl.java

@Override
public void doRouteStatusChange(DocumentHeader documentHeader) {
    //ProcessDocReport pdr = new ProcessDocReport(true, "");
    String documentId = documentHeader.getDocumentNumber();
    LeavePayout payout = (LeavePayout) this.getDataObject();
    DocumentService documentService = KRADServiceLocatorWeb.getDocumentService();
    payout.setDocumentHeaderId(documentId);
    DocumentStatus newDocumentStatus = documentHeader.getWorkflowDocument().getStatus();
    String routedByPrincipalId = documentHeader.getWorkflowDocument().getRoutedByPrincipalId();
    if (DocumentStatus.ENROUTE.equals(newDocumentStatus) && CollectionUtils.isEmpty(payout.getLeaveBlocks())) {
        //when payout document is routed, initiate the leave payout - creating the leave blocks
        try {//from w  ww.  java  2s .  c om
            MaintenanceDocument md = (MaintenanceDocument) KRADServiceLocatorWeb.getDocumentService()
                    .getByDocumentHeaderId(documentId);
            payout = LmServiceLocator.getLeavePayoutService().payout(payout);
            md.getDocumentHeader().setDocumentDescription(
                    TKUtils.getDocumentDescription(payout.getPrincipalId(), payout.getEffectiveLocalDate()));
            md.getNewMaintainableObject().setDataObject(payout);
            documentService.saveDocument(md);
        } catch (WorkflowException e) {
            LOG.error(
                    "caught exception while handling doRouteStatusChange -> documentService.getByDocumentHeaderId("
                            + documentHeader.getDocumentNumber() + "). ",
                    e);
            throw new RuntimeException(
                    "caught exception while handling doRouteStatusChange -> documentService.getByDocumentHeaderId("
                            + documentHeader.getDocumentNumber() + "). ",
                    e);
        }
    } else if (DocumentStatus.DISAPPROVED.equals(newDocumentStatus)) {
        //When payout document is disapproved, set all leave block's request statuses to disapproved.
        for (LeaveBlock lb : payout.getLeaveBlocks()) {
            if (ObjectUtils.isNotNull(lb)) {
                LeaveBlock.Builder builder = LeaveBlock.Builder.create(lb);
                builder.setRequestStatus(HrConstants.REQUEST_STATUS.DISAPPROVED);
                LmServiceLocator.getLeaveBlockService().deleteLeaveBlock(builder.getLmLeaveBlockId(),
                        routedByPrincipalId);
            }
        }
        //update status of document and associated leave blocks.
    } else if (DocumentStatus.FINAL.equals(newDocumentStatus)) {
        //When payout document moves to final, set all leave block's request statuses to approved.
        for (LeaveBlock lb : payout.getLeaveBlocks()) {
            if (ObjectUtils.isNotNull(lb)) {
                LeaveBlock.Builder builder = LeaveBlock.Builder.create(lb);
                builder.setRequestStatus(HrConstants.REQUEST_STATUS.APPROVED);
                LmServiceLocator.getLeaveBlockService().updateLeaveBlock(builder.build(), routedByPrincipalId);
            }
        }

        List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService()
                .getLeaveBlocksForDocumentId(payout.getLeaveCalendarDocumentId());
        for (LeaveBlock lb : leaveBlocks) {
            if (StringUtils.equals(lb.getAccrualCategory(), payout.getFromAccrualCategory()) && StringUtils
                    .equals(lb.getLeaveBlockType(), LMConstants.LEAVE_BLOCK_TYPE.CARRY_OVER_ADJUSTMENT)) {
                BigDecimal adjustment = new BigDecimal(0);
                if (payout.getPayoutAmount() != null)
                    adjustment = adjustment.add(payout.getPayoutAmount().abs());
                if (payout.getForfeitedAmount() != null)
                    adjustment = adjustment.add(payout.getForfeitedAmount().abs());
                BigDecimal adjustedLeaveAmount = lb.getLeaveAmount().abs().subtract(adjustment);
                LeaveBlock.Builder builder = LeaveBlock.Builder.create(lb);
                builder.setLeaveAmount(adjustedLeaveAmount.negate());
                LmServiceLocator.getLeaveBlockService().updateLeaveBlock(builder.build(), routedByPrincipalId);
            }
        }
    } else if (DocumentStatus.CANCELED.equals(newDocumentStatus)) {
        //When payout document is canceled, set all leave block's request statuses to deferred
        for (LeaveBlock lb : payout.getLeaveBlocks()) {
            if (ObjectUtils.isNotNull(lb)) {
                LeaveBlock.Builder builder = LeaveBlock.Builder.create(lb);
                builder.setRequestStatus(HrConstants.REQUEST_STATUS.DEFERRED);
                LmServiceLocator.getLeaveBlockService().updateLeaveBlock(builder.build(), routedByPrincipalId);
            }
        }
    }
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdater.java

/**
 * Updates stock quantities when a charge item is removed.
 *
 * @param act the charge item act//  www .  j a v  a2  s  . c  o  m
 * @throws ArchetypeServiceException for any archetype service error
 */
private void removeChargeItem(FinancialAct act) {
    if (!act.isNew()) {
        ActBean bean = new ActBean(act, service);
        StockQty stockQty = new StockQty(bean);
        if (stockQty.isValid()) {
            boolean credit = bean.isA(CustomerAccountArchetypes.CREDIT_ITEM);
            BigDecimal quantity = stockQty.getQuantity();
            updateStockQuantities(stockQty, quantity.negate(), credit);

        }
    }
}

From source file:org.broadleafcommerce.core.pricing.service.workflow.FulfillmentItemPricingActivity.java

/**
 * Returns the unit amount (e.g. .01 for US)
 * @param currency// www .j av a2  s  .co m
 * @return
 */
public Money getUnitAmount(Money difference) {
    Currency currency = difference.getCurrency();
    BigDecimal divisor = new BigDecimal(Math.pow(10, currency.getDefaultFractionDigits()));
    BigDecimal unitAmount = new BigDecimal("1").divide(divisor);

    if (difference.lessThan(BigDecimal.ZERO)) {
        unitAmount = unitAmount.negate();
    }
    return new Money(unitAmount, currency);
}