/**
   * Adjusts the number of units and the amounts if the total is different from the transaction line
   * units. The correction will be done on the oldest tax lot. This method is specific to the Asset
   * Decrease document and is used in updateTaxLotsForSubTypeNonCashAndTransAmtNonZero().
   *
   * @param transLine
   * @param keepIntegers
   */
  private void adjustUnitsAndAmountsForNonCashAndTransactionAmtNotZero(
      EndowmentTransactionLine transLine) {
    // Adjust the number of units if the total is different from the transaction line units
    BigDecimal totalComputedTaxLotUnits = BigDecimal.ZERO;
    BigDecimal totalComputedCost = BigDecimal.ZERO;
    EndowmentTransactionTaxLotLine oldestTaxLotLine = null;

    if (transLine.getTaxLotLines() != null && transLine.getTaxLotLines().size() > 0) {
      for (EndowmentTransactionTaxLotLine taxLotLine : transLine.getTaxLotLines()) {
        BigDecimal lotUnits = taxLotLine.getLotUnits().negate();

        // calculate the total number of units to be decreased
        totalComputedTaxLotUnits = totalComputedTaxLotUnits.add(lotUnits);
        totalComputedCost = totalComputedCost.add(taxLotLine.getLotHoldingCost().negate());

        if (taxLotLine.getLotShortTermGainLoss() != null) {
          totalComputedCost = totalComputedCost.add(taxLotLine.getLotShortTermGainLoss());
        }

        if (taxLotLine.getLotLongTermGainLoss() != null) {
          totalComputedCost = totalComputedCost.add(taxLotLine.getLotLongTermGainLoss());
        }

        // keep the tax lot with the oldest acquired date so that we can adjust the units for that
        // one in case the
        // number of units needs and adjustment
        if (oldestTaxLotLine != null) {
          if (oldestTaxLotLine.getLotAcquiredDate().after(taxLotLine.getLotAcquiredDate())) {
            oldestTaxLotLine = taxLotLine;
          }
        } else {
          oldestTaxLotLine = taxLotLine;
        }
      }
    }

    // compare with the negated number of units on the transaction line because the units on the tax
    // lots have been negated
    if (totalComputedTaxLotUnits.compareTo(
            transLine.getTransactionUnits().bigDecimalValue().negate())
        != 0) {
      BigDecimal difUnits =
          transLine.getTransactionUnits().bigDecimalValue().subtract(totalComputedTaxLotUnits);
      oldestTaxLotLine.setLotUnits(oldestTaxLotLine.getLotUnits().add(difUnits.negate()));

      BigDecimal difAmount =
          transLine.getTransactionAmount().bigDecimalValue().subtract(totalComputedCost);
      oldestTaxLotLine.setLotHoldingCost(
          oldestTaxLotLine.getLotHoldingCost().add(difAmount.negate()));
    }
  }
  public BigDecimal calculateEntropy(Map<Integer, AttributeValue> attributeValues)
      throws MLException {
    BigDecimal attributeEntropyresult = new BigDecimal(0);

    for (AttributeValue attributeValue : attributeValues.values()) {
      int attributeCount = attributeValue.getAttributeValueCount();

      BigDecimal innerResult = new BigDecimal(0);
      for (Integer corrospondingClassifiedCount : attributeValue.getClassifiedCountMap().values()) {

        BigDecimal fraction =
            BigDecimal.valueOf(corrospondingClassifiedCount)
                .divide(new BigDecimal(attributeCount), globalMathContext);
        BigDecimal logFraction =
            BigDecimal.valueOf(Math.log(fraction.doubleValue()))
                .divide(new BigDecimal(Math.log(2)), globalMathContext);

        innerResult = innerResult.add(fraction.multiply(logFraction, globalMathContext));
      }
      innerResult = innerResult.negate();
      attributeValue.setEntropy(innerResult);

      BigDecimal attributeGlobalFraction =
          BigDecimal.valueOf(attributeValue.getAttributeValueCount())
              .divide(new BigDecimal(size()), globalMathContext);

      attributeEntropyresult =
          attributeEntropyresult.add(attributeGlobalFraction.multiply(innerResult));
    }

    return attributeEntropyresult;
  }
Пример #3
0
 public void recalculateEndAmount() {
   BigDecimal startAmount = statement.getStartAmount();
   BigDecimal difference = statement.getTotalIncome().subtract(statement.getTotalExpence());
   difference = difference.negate();
   statement.setEndAmount(startAmount.subtract(difference));
   statement = statementRepository.saveStatement(statement);
 }
Пример #4
0
 /** Evaluate the result of negate computation */
 @Override
 public String negate(String[] args) {
   BigDecimal number1, result;
   number1 = new BigDecimal(args[0]);
   result = number1.negate();
   return result.toString();
 }
  public MrpLine createMrpLine(
      Product product,
      int maxLevel,
      MrpLineType mrpLineType,
      BigDecimal qty,
      LocalDate maturityDate,
      BigDecimal cumulativeQty,
      Location location,
      Model... models) {

    MrpLine mrpLine = new MrpLine();

    mrpLine.setProduct(product);
    mrpLine.setMaxLevel(maxLevel);
    mrpLine.setMrpLineType(mrpLineType);
    if (mrpLineType.getTypeSelect() == MrpLineTypeRepository.TYPE_OUT) {
      mrpLine.setQty(qty.negate());
    } else {
      mrpLine.setQty(qty);
    }
    mrpLine.setMaturityDate(maturityDate);
    mrpLine.setCumulativeQty(cumulativeQty);
    mrpLine.setLocation(location);

    mrpLine.setMinQty(this.getMinQty(product, location));

    this.createMrpLineOrigins(mrpLine, models);

    return mrpLine;
  }
Пример #6
0
 private void updateFundShare(EtfReportInfo etfReportInfo) throws AccountException {
   BigDecimal fundShare = etfReportInfo.getFillShare();
   if (ETFTradeTypeConsts.ETF_ADMIN_REDEEM.equals(etfReportInfo.getTradeType())) {
     fundShare = fundShare.negate();
   }
   fundService.updateFundShare(etfReportInfo.getFundId(), fundShare);
 }
Пример #7
0
  public String toString(byte[] bytes) {
    BigInteger mantissa = ZERO;
    for (int blockoffset = 8; blockoffset >= 0; blockoffset -= 4) {
      for (int byteidx = 0; byteidx < 4; byteidx++) {
        mantissa = mantissa.multiply(BYTESHIFT_FACTOR);
        int idx = blockoffset + byteidx;
        mantissa = mantissa.add(new BigInteger(String.valueOf(bytes[idx] & 0xff), 10));
      }
    }

    // The exponent is stored negative by .NET so we change it back here !!!
    int exponent = -bytes[13] & 0x1f;

    boolean negative = bytes[12] != 0;

    BigDecimal result = new BigDecimal(mantissa);

    if (exponent < 0) {
      for (int i = exponent; i < 0; i++) {
        result = result.divide(TEN, BigDecimal.ROUND_HALF_DOWN);
      }
    } else {
      for (int i = 0; i < exponent; i++) {
        result = result.multiply(TEN);
      }
    }

    if (negative) {
      result = result.negate();
    }
    return result.toString();
  }
Пример #8
0
  @Override
  protected void prepareForm(final ActionContext context) throws Exception {
    final HttpServletRequest request = context.getRequest();
    final EditCreditLimitForm form = context.getForm();
    final long id = form.getMemberId();
    if (id <= 0L) {
      throw new ValidationException();
    }
    final Member member = elementService.load(id, Element.Relationships.USER);
    final CreditLimitDTO creditLimit = accountService.getCreditLimits(member);

    // Transform positive to negative values to pass to the JSP
    Map<? extends AccountType, BigDecimal> limitPerType = creditLimit.getLimitPerType();
    final Map<AccountType, BigDecimal> newLimitPerType = new HashMap<AccountType, BigDecimal>();
    for (final AccountType accountType : limitPerType.keySet()) {
      BigDecimal limit = limitPerType.get(accountType);
      if (limit != null && limit.compareTo(new BigDecimal(0)) == 1) {
        limit = limit.negate();
      }
      newLimitPerType.put(accountType, limit);
    }
    limitPerType = newLimitPerType;
    creditLimit.setLimitPerType(limitPerType);

    request.setAttribute("member", member);
    request.setAttribute("limits", creditLimit.getEntries());
  }
 private void adjustIncomingPosition(Queue<PositionElement> longs, Queue<PositionElement> shorts) {
   if (mIncomingPosition.signum() == 1) {
     longs.add(new PositionElement(mIncomingPosition, mClosingPrice));
   } else if (mIncomingPosition.signum() == -1) {
     shorts.add(new PositionElement(mIncomingPosition.negate(), mClosingPrice));
   }
 }
Пример #10
0
  public void createRateVariances(MPPCostCollector cc) {
    final I_M_Product product;
    if (cc.isCostCollectorType(X_PP_Cost_Collector.COSTCOLLECTORTYPE_ActivityControl)) {
      final I_AD_WF_Node node = cc.getPP_Order_Node().getAD_WF_Node();
      product = MProduct.forS_Resource_ID(cc.getCtx(), node.getS_Resource_ID(), null);
    } else if (cc.isCostCollectorType(X_PP_Cost_Collector.COSTCOLLECTORTYPE_ComponentIssue)) {
      final I_PP_Order_BOMLine bomLine = cc.getPP_Order_BOMLine();
      product = MProduct.get(cc.getCtx(), bomLine.getM_Product_ID());
    } else {
      return;
    }

    I_PP_Cost_Collector ccrv = null; // Cost Collector - Rate Variance
    for (MAcctSchema as : getAcctSchema(cc)) {
      for (I_M_CostElement element : getCostElements(cc.getCtx())) {
        final MCostDetail cd = getCostDetail(cc, element.getM_CostElement_ID());
        if (cd == null) {
          continue;
        }

        //
        final BigDecimal qty = cd.getQty();
        final BigDecimal priceStd = getProductStandardCostPrice(cc, product, as, element);
        final BigDecimal priceActual =
            getProductActualCostPriceOrZero(cc, product, as, element, cc.get_TrxName());
        final BigDecimal amtStd = roundCost(priceStd.multiply(qty), as.getC_AcctSchema_ID());
        final BigDecimal amtActual = roundCost(priceActual.multiply(qty), as.getC_AcctSchema_ID());
        if (amtStd.compareTo(amtActual) == 0) {
          continue;
        }

        //
        if (ccrv == null) {
          ccrv =
              createVarianceCostCollector(cc, X_PP_Cost_Collector.COSTCOLLECTORTYPE_RateVariance);
        }
        //
        createVarianceCostDetail(ccrv, amtActual.negate(), qty.negate(), cd, null, as, element);
        createVarianceCostDetail(ccrv, amtStd, qty, cd, null, as, element);
      }
    }
    //
    if (ccrv != null) {
      Services.get(IDocActionBL.class)
          .processEx(ccrv, DocAction.ACTION_Complete, DocAction.STATUS_Completed);
    }
  }
Пример #11
0
 public void createMethodVariances(MPPCostCollector cc) {
   if (!cc.isCostCollectorType(X_PP_Cost_Collector.COSTCOLLECTORTYPE_ActivityControl)) return;
   //
   final int std_resource_id = cc.getPP_Order_Node().getAD_WF_Node().getS_Resource_ID();
   final int actual_resource_id = cc.getS_Resource_ID();
   if (std_resource_id == actual_resource_id) {
     return;
   }
   //
   I_PP_Cost_Collector ccmv = null; // Cost Collector - Method Change Variance
   final RoutingService routingService =
       RoutingServiceFactory.get().getRoutingService(cc.getAD_Client_ID());
   for (I_C_AcctSchema as : getAcctSchema(cc)) {
     for (I_M_CostElement element : getCostElements(cc.getCtx())) {
       final I_M_Product resourcePStd =
           MProduct.forS_Resource_ID(cc.getCtx(), std_resource_id, null);
       final I_M_Product resourcePActual =
           MProduct.forS_Resource_ID(cc.getCtx(), actual_resource_id, null);
       final BigDecimal priceStd =
           getProductActualCostPrice(cc, resourcePStd, as, element, cc.get_TrxName());
       final BigDecimal priceActual =
           getProductActualCostPrice(cc, resourcePActual, as, element, cc.get_TrxName());
       if (priceStd.compareTo(priceActual) == 0) {
         continue;
       }
       //
       if (ccmv == null) {
         ccmv =
             createVarianceCostCollector(
                 cc, X_PP_Cost_Collector.COSTCOLLECTORTYPE_MethodChangeVariance);
       }
       //
       final BigDecimal qty = routingService.getResourceBaseValue(cc.getS_Resource_ID(), cc);
       final BigDecimal amtStd = priceStd.multiply(qty);
       final BigDecimal amtActual = priceActual.multiply(qty);
       //
       createVarianceCostDetail(ccmv, amtActual, qty, null, resourcePActual, as, element);
       createVarianceCostDetail(
           ccmv, amtStd.negate(), qty.negate(), null, resourcePStd, as, element);
     }
   }
   //
   if (ccmv != null) {
     Services.get(IDocActionBL.class)
         .processEx(ccmv, DocAction.ACTION_Complete, DocAction.STATUS_Completed);
   }
 }
 /** Helper method that updates two arrays of long and short position elements based on a trade. */
 private BigDecimal processTrade(
     Queue<PositionElement> longs, Queue<PositionElement> shorts, Trade<?> trade) {
   BigDecimal total = BigDecimal.ZERO;
   Queue<PositionElement> source, dest;
   BigDecimal remaining;
   BigDecimal quantity = trade.getQuantity();
   BigDecimal price = trade.getPrice();
   if (quantity.signum() == 1) {
     // buy
     remaining = quantity;
     source = shorts;
     dest = longs;
   } else {
     // sell
     remaining = quantity.negate();
     source = longs;
     dest = shorts;
   }
   while (remaining.signum() == 1 && !source.isEmpty()) {
     PositionElement element = source.peek();
     int compare = element.quantity.compareTo(remaining);
     BigDecimal priceDifference = price.subtract(element.price);
     if (source == shorts) {
       // negate the price difference for closing short positions
       // since realized gains happen when price has decreased
       priceDifference = priceDifference.negate();
     }
     if (compare == 0) {
       // position element is closed
       total = total.add(priceDifference.multiply(remaining));
       source.remove();
       remaining = BigDecimal.ZERO;
     } else if (compare > 0) {
       total = total.add(priceDifference.multiply(remaining));
       element.quantity = element.quantity.subtract(remaining);
       remaining = BigDecimal.ZERO;
     } else if (compare < 0) {
       total = total.add(priceDifference.multiply(element.quantity));
       source.remove();
       remaining = remaining.subtract(element.quantity);
     }
   }
   if (remaining.signum() == 1) {
     dest.add(new PositionElement(remaining, price));
   }
   return total;
 }
  /**
   * Constructor
   *
   * @param account Credit account
   * @param investmentAccount Debit / Investment account
   * @param securityNode Security for the transaction
   * @param price Price of shares
   * @param quantity Number of shares
   * @param exchangeRate Exchange rate for the credit account (May be ONE, but may not be null and
   *     must be greater than ZERO)
   */
  TransactionEntryBuyX(
      final Account account,
      final Account investmentAccount,
      final SecurityNode securityNode,
      final BigDecimal price,
      final BigDecimal quantity,
      final BigDecimal exchangeRate) {

    assert investmentAccount.memberOf(AccountGroup.INVEST);
    assert exchangeRate != null && exchangeRate.signum() == 1;

    setSecurityNode(securityNode);
    setPrice(price);
    setQuantity(quantity);

    setDebitAccount(investmentAccount);
    setCreditAccount(account);

    if (investmentAccount.equals(account)) { // transaction against the cash balance

      BigDecimal amount =
          price
              .multiply(quantity)
              .setScale(investmentAccount.getCurrencyNode().getScale(), MathConstants.roundingMode)
              .negate();

      setCreditAmount(amount);
      setDebitAmount(amount);
    } else { // transaction against a different account

      setDebitAmount(BigDecimal.ZERO);

      byte scale = getCreditAccount().getCurrencyNode().getScale();

      if (account.getCurrencyNode().equals(investmentAccount.getCurrencyNode())) {
        setCreditAmount(
            price.multiply(quantity.negate()).setScale(scale, MathConstants.roundingMode));
      } else { // currency exchange
        setCreditAmount(
            price
                .multiply(quantity.negate())
                .multiply(exchangeRate)
                .setScale(scale, MathConstants.roundingMode));
      }
    }
  }
Пример #14
0
 public static BigDecimal operator_minus(Number x) {
   BigDecimal xValue = numberToBigDecimal(x);
   if (xValue == null) {
     return xValue;
   } else {
     return xValue.negate();
   }
 }
Пример #15
0
public abstract class BigMath {

  public static final BigDecimal ZERO = new BigDecimal("0", MathContext.DECIMAL128);
  public static final BigDecimal ONE = new BigDecimal("1", MathContext.DECIMAL128);
  public static final BigDecimal TWO = new BigDecimal("2", MathContext.DECIMAL128);
  public static final BigDecimal THREE = new BigDecimal("3", MathContext.DECIMAL128);
  public static final BigDecimal FOUR = new BigDecimal("4", MathContext.DECIMAL128);
  public static final BigDecimal FIVE = new BigDecimal("5", MathContext.DECIMAL128);
  public static final BigDecimal SIX = new BigDecimal("6", MathContext.DECIMAL128);
  public static final BigDecimal SEVEN = new BigDecimal("7", MathContext.DECIMAL128);
  public static final BigDecimal EIGHT = new BigDecimal("8", MathContext.DECIMAL128);
  public static final BigDecimal NINE = new BigDecimal("9", MathContext.DECIMAL128);
  public static final BigDecimal TEN = new BigDecimal("10", MathContext.DECIMAL128);
  public static final BigDecimal ELEVEN = new BigDecimal("11", MathContext.DECIMAL128);
  public static final BigDecimal TWELVE = new BigDecimal("12", MathContext.DECIMAL128);
  public static final BigDecimal HUNDRED = new BigDecimal("100", MathContext.DECIMAL128);
  public static final BigDecimal THOUSAND = new BigDecimal("1000", MathContext.DECIMAL128);

  public static final BigDecimal NEG = ONE.negate();

  public static final BigDecimal HALF = ONE.divide(TWO, MathContext.DECIMAL128);
  public static final BigDecimal THIRD = ONE.divide(THREE, MathContext.DECIMAL128);
  public static final BigDecimal QUARTER = ONE.divide(FOUR, MathContext.DECIMAL128);
  public static final BigDecimal FITH = ONE.divide(FIVE, MathContext.DECIMAL128);
  public static final BigDecimal SIXTH = ONE.divide(SIX, MathContext.DECIMAL128);
  public static final BigDecimal SEVENTH = ONE.divide(SEVEN, MathContext.DECIMAL128);
  public static final BigDecimal EIGHTH = ONE.divide(EIGHT, MathContext.DECIMAL128);
  public static final BigDecimal NINTH = ONE.divide(NINE, MathContext.DECIMAL128);
  public static final BigDecimal TENTH = ONE.divide(TEN, MathContext.DECIMAL128);
  public static final BigDecimal ELEVENTH = ONE.divide(ELEVEN, MathContext.DECIMAL128);
  public static final BigDecimal TWELFTH = ONE.divide(TWELVE, MathContext.DECIMAL128);
  public static final BigDecimal HUNDREDTH = ONE.divide(HUNDRED, MathContext.DECIMAL128);
  public static final BigDecimal THOUSANDTH = ONE.divide(THOUSAND, MathContext.DECIMAL128);

  public static final BigDecimal E =
      new BigDecimal(
          "2.71828182845904523536028747135266249775724709369996", MathContext.DECIMAL128);
  public static final BigDecimal PI =
      new BigDecimal(
          "3.14159265358979323846264338327950288419716939937511", MathContext.DECIMAL128);

  public static final BigDecimal HALF_PI = HALF.multiply(PI, MathContext.DECIMAL128);
  public static final BigDecimal TWO_PI = TWO.multiply(PI, MathContext.DECIMAL128);

  public static final BigDecimal SQRT_TWO = BigFunction.SQRT.invoke(TWO);
  public static final BigDecimal SQRT_PI = BigFunction.SQRT.invoke(PI);
  public static final BigDecimal SQRT_TWO_PI = BigFunction.SQRT.invoke(TWO.multiply(PI));

  public static final BigDecimal VERY_NEGATIVE =
      new BigDecimal(Long.MIN_VALUE, MathContext.DECIMAL128);
  public static final BigDecimal VERY_POSITIVE =
      new BigDecimal(Long.MAX_VALUE, MathContext.DECIMAL128);

  private BigMath() {
    super();
  }
}
  /**
   * Populate.
   *
   * @param source the source
   * @param target the target
   * @throws ConversionException the conversion exception
   */
  public void populate(final BasePackage source, final List<PriceBreakDownViewData> target)
      throws ConversionException {

    final PriceBreakDownViewData basicPrice = new PriceBreakDownViewData();
    final PriceBreakDownViewData extrasPrice = new PriceBreakDownViewData();
    final PriceBreakDownViewData onlineDiscount = new PriceBreakDownViewData();
    final PriceBreakDownViewData totalPrice = new PriceBreakDownViewData();

    BigDecimal viewDataBasicPrice = priceCalculationService.calculateBasicCost(source);

    BigDecimal viewDataOnlineDiscountPrice =
        source.getDiscount().getPrice().getAmount().getAmount();
    if (viewDataOnlineDiscountPrice.signum() == -1) {
      viewDataOnlineDiscountPrice = viewDataOnlineDiscountPrice.negate();
    }
    final String defaultCurrencyCode = currencyResolver.getSiteCurrency();
    basicPrice.setDescription(getDescription("BASICHOLIDAY"));
    if (!PackageUtilityService.isMulticomThirdPartyFlight(
            packageComponentService.getFlightItinerary(source))
        && viewDataOnlineDiscountPrice.compareTo(BigDecimal.ZERO) > 0) {
      viewDataBasicPrice =
          viewDataBasicPrice.add(viewDataOnlineDiscountPrice).setScale(TWO, RoundingMode.HALF_UP);
      onlineDiscount.setDescription(getDescription("ONLINEDISCOUNT"));

      onlineDiscount.setPrice(viewDataOnlineDiscountPrice.setScale(TWO, RoundingMode.HALF_UP));
      onlineDiscount.setCurrencyAppendedPrice(
          "-"
              + " "
              + CurrencyUtils.getCurrencySymbol(defaultCurrencyCode)
              + (viewDataOnlineDiscountPrice.setScale(TWO, RoundingMode.HALF_UP)).toString());
      target.add(onlineDiscount);
    }
    basicPrice.setPrice(viewDataBasicPrice.setScale(TWO, RoundingMode.HALF_UP));
    basicPrice.setCurrencyAppendedPrice(
        CurrencyUtils.getCurrencySymbol(defaultCurrencyCode)
            + viewDataBasicPrice.setScale(TWO, RoundingMode.HALF_UP).toString());
    target.add(basicPrice);
    extrasPrice.setDescription(getDescription("OPTION&EXTRAS"));
    extrasPrice.setPrice(priceCalculationService.calculateExtraFacilitiesTotalCost(source));
    extrasPrice.setCurrencyAppendedPrice(
        CurrencyUtils.getCurrencySymbol(defaultCurrencyCode)
            + extrasPrice.getPrice().setScale(TWO, RoundingMode.HALF_UP));

    totalPrice.setDescription(getDescription("TOTALPRICE"));
    totalPrice.setPrice(
        source.getPrice().getAmount().getAmount().setScale(TWO, RoundingMode.HALF_UP));
    totalPrice.setCurrencyAppendedPrice(
        CurrencyUtils.getCurrencySymbol(defaultCurrencyCode)
            + (source.getPrice().getAmount().getAmount().setScale(TWO, RoundingMode.HALF_UP))
                .toString());
    target.add(extrasPrice);

    populateCardChargesIfApplicable(source.getBookingDetails(), target);
    populatePromotionalChargesIfApplicable(source.getPromotionalDiscount(), target);
    target.add(totalPrice);
  }
Пример #17
0
 public void createActivityControl(MPPCostCollector cc) {
   if (!cc.isCostCollectorType(X_PP_Cost_Collector.COSTCOLLECTORTYPE_ActivityControl)) return;
   //
   final I_M_Product product = MProduct.forS_Resource_ID(cc.getCtx(), cc.getS_Resource_ID(), null);
   final RoutingService routingService =
       RoutingServiceFactory.get().getRoutingService(cc.getAD_Client_ID());
   final BigDecimal qty = routingService.getResourceBaseValue(cc.getS_Resource_ID(), cc);
   for (MAcctSchema as : getAcctSchema(cc)) {
     for (I_M_CostElement element : getCostElements(cc.getCtx())) {
       if (!isActivityControlElement(element)) {
         continue;
       }
       final CostDimension d =
           new CostDimension(
               product,
               as,
               as.getM_CostType_ID(),
               0, // AD_Org_ID,
               0, // M_ASI_ID
               element.getM_CostElement_ID());
       final BigDecimal price =
           getResourceActualCostRate(cc, cc.getS_Resource_ID(), d, cc.get_TrxName());
       BigDecimal costs = price.multiply(qty);
       if (costs.scale() > as.getCostingPrecision())
         costs = costs.setScale(as.getCostingPrecision(), RoundingMode.HALF_UP);
       //
       MCostDetail cd =
           new MCostDetail(
               as,
               0, // AD_Org_ID,
               d.getM_Product_ID(),
               0, // M_AttributeSetInstance_ID,
               element.getM_CostElement_ID(),
               costs.negate(),
               qty.negate(),
               "", // Description,
               cc.get_TrxName());
       cd.setPP_Cost_Collector_ID(cc.getPP_Cost_Collector_ID());
       cd.saveEx();
       processCostDetail(cd);
     }
   }
 }
Пример #18
0
  public void withdraw(BigDecimal amount) {
    if (BigDecimal.ZERO.compareTo(amount) == 0) {
      throw new IllegalArgumentException("Amount must be greater than zero.");
    }

    if (sumTransactions().compareTo(amount) < 0) {
      throw new IllegalArgumentException("Customer doesn't have enough money to cover withdrawal");
    }
    // TBD watch the sign direction on these
    transactions.add(new Transaction(amount.negate(), Transaction.Type.WITHDRAWAL));
  }
  /**
   * Sets the transaction line amount to be the total amount of all tax lot lines times negative 1.
   * This is applied in case the transaction sub type is non-cash.
   *
   * @param transactionLine
   */
  private void setTransactionLineTotal(EndowmentTransactionLine transactionLine) {
    List<EndowmentTransactionTaxLotLine> taxLots = transactionLine.getTaxLotLines();
    BigDecimal totalAmount = BigDecimal.ZERO;
    if (taxLots != null && taxLots.size() > 0) {
      for (EndowmentTransactionTaxLotLine taxLot : taxLots) {
        totalAmount = totalAmount.add(taxLot.getLotHoldingCost());
      }
    }

    totalAmount = totalAmount.negate();

    transactionLine.setTransactionAmount(new KualiDecimal(totalAmount));
  }
  public void generarItemCuentaCorriente(MovimientoProveedor m) throws ExcepcionGeneralSistema {

    if (m.getCondicionDePago() == null) {
      throw new ExcepcionGeneralSistema("La condición de pago no puede estar vacía");
    }

    if (m.getItemTotal() == null || m.getItemTotal().isEmpty()) {
      throw new ExcepcionGeneralSistema(
          "Item total no fue generado, nada para agregar a la cuenta corriente");
    }

    m.getItemCuentaCorriente().clear();

    BigDecimal importeTotal = m.getItemTotal().get(0).getImporte();
    //
    //        System.err.println("importeTotal para cuenta corriente"+importeTotal);

    for (ItemCondicionPagoProveedor icp : m.getCondicionDePago().getCuotas()) {

      BigDecimal impoteCuota =
          importeTotal.multiply(icp.getPorcentaje()).divide(new BigDecimal(100), RoundingMode.UP);
      Calendar fechaVencimiento = Calendar.getInstance();
      fechaVencimiento.add(Calendar.DAY_OF_YEAR, icp.getDiasDePago());

      AplicacionCuentaCorrienteProveedor icc = new AplicacionCuentaCorrienteProveedor();
      icc.setMovimiento(m);
      icc.setMovimientoAplicacion(m);
      icc.setCuota(icp.getCuotas());
      icc.setProveedor(m.getProveedor());
      icc.setNroSubcuenta(m.getProveedorCuentaCorriente().getNrocta());
      icc.setCodigoImputacion("CC");
      icc.setMonedaSecundaria(m.getMonedaSecundaria());
      icc.setCotizacion(m.getCotizacion());

      if (m.getComprobante().getSignoAplicacionCuentaCorriente().equals("+")) {

        icc.setImporte(impoteCuota);
        icc.setImporteSecundario(impoteCuota.divide(m.getCotizacion(), RoundingMode.UP));

      } else {

        icc.setImporte(importeTotal.negate());
        icc.setImporteSecundario((impoteCuota.divide(m.getCotizacion(), RoundingMode.UP)).negate());
      }

      icc.setFechaAplicacion(new Date());
      icc.setFechaVencimiento(fechaVencimiento.getTime());

      m.getItemCuentaCorriente().add(icc);
    }
  }
Пример #21
0
 /**
  * Add the adjustment amount on the item specified by the targetId.
  *
  * @param adjustementDate date of the adjustment
  * @param amount amount of the adjustment
  * @param targetId item that has been adjusted
  */
 public void addAdjustment(
     final LocalDate adjustementDate, final BigDecimal amount, final UUID targetId) {
   // TODO we should really be using findNode(adjustementDate, new SearchCallback() instead but
   // wrong dates in test
   // creates test panic.
   final NodeInterval node =
       findNode(
           new SearchCallback() {
             @Override
             public boolean isMatch(final NodeInterval curNode) {
               return ((ItemsNodeInterval) curNode).getItemsInterval().containsItem(targetId);
             }
           });
   Preconditions.checkNotNull(
       node, "Cannot add adjustement for item = " + targetId + ", date = " + adjustementDate);
   ((ItemsNodeInterval) node).setAdjustment(amount.negate(), targetId);
 }
Пример #22
0
    @Override
    public void afterTextChanged(Editable editable) {
      BigDecimal imbalance = BigDecimal.ZERO;

      for (View splitItem : mSplitItemViewList) {
        SplitViewHolder viewHolder = (SplitViewHolder) splitItem.getTag();
        BigDecimal amount = viewHolder.getAmountValue().abs();
        if (viewHolder.splitTypeSwitch.isChecked()) {
          imbalance = imbalance.subtract(amount);
        } else {
          imbalance = imbalance.add(amount);
        }
      }

      TransactionsActivity.displayBalance(
          mImbalanceTextView, new Money(imbalance.negate(), mCommodity));
    }
Пример #23
0
  /**
   * Sum transaction fees
   *
   * @param account account to calculate fees against
   * @return transaction fees
   */
  private BigDecimal getFees(final Account account) {
    BigDecimal fees = BigDecimal.ZERO;

    getLock().readLock().lock();

    try {
      for (TransactionEntry e : transactionEntries) {
        if (e.getTransactionTag() == TransactionTag.INVESTMENT_FEE) {
          fees = fees.add(e.getAmount(account));
        }
      }
    } finally {
      getLock().readLock().unlock();
    }

    return fees.negate();
  }
Пример #24
0
 /**
  * Extracts the value from a literal.
  *
  * <p>Cases:
  *
  * <ul>
  *   <li>If the node is a character literal, a chain of string literals, or a CAST of a character
  *       literal, returns the value as a {@link NlsString}.
  *   <li>If the node is a numeric literal, or a negated numeric literal, returns the value as a
  *       {@link BigDecimal}.
  *   <li>If the node is a {@link SqlIntervalQualifier}, returns its {@link TimeUnitRange}.
  *   <li>If the node is INTERVAL_DAY_TIME in {@link SqlTypeFamily}, returns its sign multiplied by
  *       its millisecond equivalent value
  *   <li>If the node is INTERVAL_YEAR_MONTH in {@link SqlTypeFamily}, returns its sign multiplied
  *       by its months equivalent value
  *   <li>Otherwise the behavior is not specified.
  * </ul>
  */
 public static Comparable value(SqlNode node) {
   if (node instanceof SqlLiteral) {
     SqlLiteral literal = (SqlLiteral) node;
     switch (literal.getTypeName().getFamily()) {
       case CHARACTER:
         return (NlsString) literal.value;
       case NUMERIC:
         return (BigDecimal) literal.value;
       case INTERVAL_YEAR_MONTH:
         final SqlIntervalLiteral.IntervalValue valMonth =
             (SqlIntervalLiteral.IntervalValue) literal.value;
         return valMonth.getSign() * SqlParserUtil.intervalToMonths(valMonth);
       case INTERVAL_DAY_TIME:
         final SqlIntervalLiteral.IntervalValue valTime =
             (SqlIntervalLiteral.IntervalValue) literal.value;
         return valTime.getSign() * SqlParserUtil.intervalToMillis(valTime);
     }
   }
   if (SqlUtil.isLiteralChain(node)) {
     assert node instanceof SqlCall;
     final SqlLiteral literal = SqlLiteralChainOperator.concatenateOperands((SqlCall) node);
     assert SqlTypeUtil.inCharFamily(literal.getTypeName());
     return (NlsString) literal.value;
   }
   if (node instanceof SqlIntervalQualifier) {
     SqlIntervalQualifier qualifier = (SqlIntervalQualifier) node;
     return qualifier.timeUnitRange;
   }
   switch (node.getKind()) {
     case CAST:
       assert node instanceof SqlCall;
       return value(((SqlCall) node).operand(0));
     case MINUS_PREFIX:
       assert node instanceof SqlCall;
       Comparable o = value(((SqlCall) node).operand(0));
       if (o instanceof BigDecimal) {
         BigDecimal bigDecimal = (BigDecimal) o;
         return bigDecimal.negate();
       }
       // fall through
     default:
       throw Util.newInternal("invalid literal: " + node);
   }
 }
Пример #25
0
  /**
   * Adds the specified dayTime duration.
   *
   * @param add value to be added
   */
  private void add(final BigDecimal add) {
    // normalized modulo: sc % 60  vs.  (-sc + sc % 60 + 60 + sc) % 60
    final BigDecimal sc = sec().add(add);
    sec =
        sc.signum() >= 0
            ? sc.remainder(BD60)
            : sc.negate().add(sc.remainder(BD60)).add(BD60).add(sc).remainder(BD60);

    final long mn = Math.max(min(), 0) + div(sc.longValue(), 60);
    min = (byte) mod(mn, 60);
    final long ho = Math.max(hou, 0) + div(mn, 60);
    hou = (byte) mod(ho, 24);
    final long da = div(ho, 24);

    final long[] ymd = ymd(days().add(BigDecimal.valueOf(da)));
    yea = ymd[0];
    mon = (byte) ymd[1];
    day = (byte) ymd[2];
  }
Пример #26
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
    assert actionBar != null;
    actionBar.setTitle(R.string.title_split_editor);
    setHasOptionsMenu(true);

    mCalculatorKeyboard =
        new CalculatorKeyboard(getActivity(), mKeyboardView, R.xml.calculator_keyboard);
    mSplitItemViewList = new ArrayList<>();

    // we are editing splits for a new transaction.
    // But the user may have already created some splits before. Let's check
    List<String> splitStrings = getArguments().getStringArrayList(UxArgument.SPLIT_LIST);
    List<Split> splitList = new ArrayList<>();
    if (splitStrings != null) {
      for (String splitString : splitStrings) {
        splitList.add(Split.parseSplit(splitString));
      }
    }

    initArgs();
    if (!splitList.isEmpty()) {
      // aha! there are some splits. Let's load those instead
      loadSplitViews(splitList);
      mImbalanceWatcher.afterTextChanged(null);
    } else {
      final String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID);
      Split split =
          new Split(new Money(mBaseAmount.abs(), Commodity.getInstance(currencyCode)), mAccountUID);
      AccountType accountType = mAccountsDbAdapter.getAccountType(mAccountUID);
      TransactionType transactionType =
          Transaction.getTypeForBalance(accountType, mBaseAmount.signum() < 0);
      split.setType(transactionType);
      View view = addSplitView(split);
      view.findViewById(R.id.input_accounts_spinner).setEnabled(false);
      view.findViewById(R.id.btn_remove_split).setVisibility(View.GONE);
      TransactionsActivity.displayBalance(
          mImbalanceTextView, new Money(mBaseAmount.negate(), mCommodity));
    }
  }
Пример #27
0
  public static synchronized Payment processSingleOSalesPayment(
      BigDecimal amount,
      OtherSalesAcDoc invoice,
      String remark,
      Enums.PaymentType type,
      User user) {
    if (amount.compareTo(invoice.calculateDueAmount().abs()) > 0) {
      return null;
    } else {
      Payment payment = new Payment();
      payment.setRemark(remark);
      payment.setPaymentType(type);
      payment.setCreatedOn(new java.util.Date());
      payment.setCreatedBy(user);

      OtherSalesAcDoc doc = new OtherSalesAcDoc();
      doc.setReference(invoice.getReference());
      doc.setStatus(Enums.AcDocStatus.ACTIVE);
      doc.setDocIssueDate(new java.util.Date());
      doc.setCreatedBy(user);
      doc.setCreatedOn(new java.util.Date());
      doc.setAgent(invoice.getAgent());
      doc.setCustomer(invoice.getCustomer());
      doc.setParent(invoice);
      doc.setPayment(payment);

      if (invoice.calculateDueAmount().compareTo(new BigDecimal("0.00")) == 1) {
        // Make payment
        doc.setType(Enums.AcDocType.PAYMENT);
        doc.setDocumentedAmount(amount.negate()); // Payment saves as negative
      } else if (invoice.calculateDueAmount().compareTo(new BigDecimal("0.00")) == -1) {
        // Make refund
        doc.setType(Enums.AcDocType.REFUND);
        doc.setDocumentedAmount(amount);
      } else {
        // Do nothing
        return null;
      }

      payment.addOtherDocument(doc);
      return payment;
    }
  }
  public BigDecimal calculateHeaderEntropy(Map<Integer, AttributeValue> attributeValues)
      throws MLException {
    BigDecimal headerEntropyresult = new BigDecimal(0);

    for (AttributeValue attributeValue : attributeValues.values()) {

      BigDecimal fraction =
          BigDecimal.valueOf(attributeValue.getAttributeValueCount())
              .divide(new BigDecimal(size()), globalMathContext);
      BigDecimal logFraction =
          BigDecimal.valueOf(Math.log(fraction.doubleValue()))
              .divide(new BigDecimal(Math.log(2)), globalMathContext);

      headerEntropyresult =
          headerEntropyresult.add(fraction.multiply(logFraction, globalMathContext));
    }

    return headerEntropyresult.negate();
  }
Пример #29
0
  @Override
  protected List<AccountDelta> caculateFill(
      AccountDeltaCaculatorParameter parameter, String securityTypeCode, BigDecimal balance) {
    List<AccountDelta> result = new LinkedList<AccountDelta>();
    if (SecurityTypeConsts.CURRENCY.equals(securityTypeCode)) {
      result.add(createAccountDelta(balance, AccountTypeConsts.POSITION));
      // 回购到期是日初做的,需要知道,日初的日期(t0Day)
      Date t1Day = businessDayService.getBusinessDayDefault(parameter.getT0Day(), 1);
      result.add(accountDeltaFactory.create(AccountTypeConsts.AVAILABLE, balance, t1Day));
      return result;
    }

    if (SecurityTypeConsts.REPO.equals(securityTypeCode)) {
      Date theoryDay = parameter.getBusinessDay();
      result.add(
          accountDeltaFactory.create(AccountTypeConsts.POSITION, balance.negate(), theoryDay));
    }
    return result;
  }
Пример #30
0
  @Override
  public void capitalize(Deposit deposit) throws DepositCapitalizationIllegalStateException {

    System.out.println(
        "capitalization of #"
            .concat(deposit.getId().toString())
            .concat(" next capitalization ")
            .concat(deposit.getNextCapitalization().toString()));

    BigDecimal saldo = billingSystemUtils.getDepositSaldo(deposit.getId());

    if (saldo.compareTo(BigDecimal.ZERO) < 1) {
      System.out.println("Нет денег - нет прибыли");
      throw new DepositCapitalizationIllegalStateException(
          "На счету нет денег. Капитализация невозможна");
    }

    if (deposit.getPercent() == null || deposit.getPercent().compareTo(BigDecimal.ZERO) < 1) {
      throw new DepositCapitalizationIllegalStateException(
          "Не задана процентная ставка. Каитализация невозможна");
    }

    DepositCalculation depositCalculationMonth =
        new DepositCalculation(saldo, 1, deposit.getDepositorFormType());
    depositCalculationMonth.percents = deposit.getPercent();

    BigDecimal sumToAdd =
        depositCalculationService.calculateSumInTheEnd(depositCalculationMonth).add(saldo.negate());

    billingSystemUtils.doDepositPayInMonthlyProfit(
        deposit.getId(), sumToAdd, deposit.getNextCapitalization());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(deposit.getNextCapitalization());
    calendar.add(Calendar.MONTH, 1);

    deposit.setNextCapitalization(calendar.getTime());

    entityManager.merge(deposit);
  }