コード例 #1
0
 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));
   }
 }
コード例 #2
0
 public boolean isZeroToAllocate() {
   return amount.signum() == 0 && discountAmt.signum() == 0 && writeOffAmt.signum() == 0
   // NOTE: don't check the OverUnderAmt because that amount is not affecting allocation,
   // so an allocation is Zero with our without the over/under amount.
   // && overUnderAmt.signum() == 0
   ;
 }
コード例 #3
0
 /** Calculate Commission */
 public void calculateCommission() {
   MCommissionDetail[] details = getDetails();
   BigDecimal ConvertedAmt = Env.ZERO;
   BigDecimal ActualQty = Env.ZERO;
   for (int i = 0; i < details.length; i++) {
     MCommissionDetail detail = details[i];
     BigDecimal amt = detail.getConvertedAmt();
     if (amt == null) amt = Env.ZERO;
     ConvertedAmt = ConvertedAmt.add(amt);
     ActualQty = ActualQty.add(detail.getActualQty());
   }
   setConvertedAmt(ConvertedAmt);
   setActualQty(ActualQty);
   //
   MCommissionLine cl = new MCommissionLine(getCtx(), getC_CommissionLine_ID(), get_TrxName());
   //	Qty
   BigDecimal qty = getActualQty().subtract(cl.getQtySubtract());
   if (cl.isPositiveOnly() && qty.signum() < 0) qty = Env.ZERO;
   qty = qty.multiply(cl.getQtyMultiplier());
   //	Amt
   BigDecimal amt = getConvertedAmt().subtract(cl.getAmtSubtract());
   if (cl.isPositiveOnly() && amt.signum() < 0) amt = Env.ZERO;
   amt = amt.multiply(cl.getAmtMultiplier());
   //
   setCommissionAmt(amt.add(qty));
 } //	calculateCommission
コード例 #4
0
  @Override
  public int calculateQtyLUForTotalQtyCUs(
      final I_M_HU_LUTU_Configuration lutuConfiguration,
      final BigDecimal qtyCUsTotal,
      final I_C_UOM qtyCUsTotalUOM) {
    Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null");

    if (qtyCUsTotal == null || qtyCUsTotal.signum() <= 0) {
      return 0;
    }

    if (isNoLU(lutuConfiguration)) {
      return 0;
    }

    //
    // Calculate how many CUs we need for an LU
    final BigDecimal qtyCUsPerLU =
        lutuConfiguration.getQtyCU().multiply(lutuConfiguration.getQtyTU());
    if (qtyCUsPerLU.signum() <= 0) {
      return 0;
    }

    //
    // Convert the total QtyCU to our internal capacity UOM, to be able to compute using same UOM.
    final Quantity qtyCUsTotal_Converted =
        convertQtyToLUTUConfigurationUOM(qtyCUsTotal, qtyCUsTotalUOM, lutuConfiguration);

    //
    // Calculate how many LUs we need for given total QtyCU (converted to our capacity UOM)
    final int qtyLUs =
        qtyCUsTotal_Converted.getQty().divide(qtyCUsPerLU, 0, RoundingMode.UP).intValueExact();
    return qtyLUs;
  }
コード例 #5
0
ファイル: MProduct.java プロジェクト: makezjdq/adempiere-1
  @Override
  protected boolean beforeSave(boolean newRecord) {
    //	Check Storage
    if (!newRecord
        && //
        ((is_ValueChanged("IsActive") && !isActive()) // 	now not active
            || (is_ValueChanged("IsStocked") && !isStocked()) // 	now not stocked
            || (is_ValueChanged("ProductType") // 	from Item
                && PRODUCTTYPE_Item.equals(get_ValueOld("ProductType"))))) {
      MStorage[] storages = MStorage.getOfProduct(getCtx(), get_ID(), get_TrxName());
      BigDecimal OnHand = Env.ZERO;
      BigDecimal Ordered = Env.ZERO;
      BigDecimal Reserved = Env.ZERO;
      for (int i = 0; i < storages.length; i++) {
        OnHand = OnHand.add(storages[i].getQtyOnHand());
        Ordered = Ordered.add(storages[i].getQtyOrdered());
        Reserved = Reserved.add(storages[i].getQtyReserved());
      }
      String errMsg = "";
      if (OnHand.signum() != 0) errMsg = "@QtyOnHand@ = " + OnHand;
      if (Ordered.signum() != 0) errMsg += " - @QtyOrdered@ = " + Ordered;
      if (Reserved.signum() != 0) errMsg += " - @QtyReserved@" + Reserved;
      if (errMsg.length() > 0) {
        log.saveError("Error", Msg.parseTranslation(getCtx(), errMsg));
        return false;
      }
    } //	storage

    // it checks if UOM has been changed , if so disallow the change if the condition is true.
    if ((!newRecord) && is_ValueChanged("C_UOM_ID") && hasInventoryOrCost()) {
      log.saveError("Error", Msg.getMsg(getCtx(), "SaveUomError"));
      return false;
    }

    //	Reset Stocked if not Item
    // AZ Goodwill: Bug Fix isStocked always return false
    // if (isStocked() && !PRODUCTTYPE_Item.equals(getProductType()))
    if (!PRODUCTTYPE_Item.equals(getProductType())) setIsStocked(false);

    //	UOM reset
    if (m_precision != null && is_ValueChanged("C_UOM_ID")) m_precision = null;

    // AttributeSetInstance reset
    if (is_ValueChanged(COLUMNNAME_M_AttributeSet_ID)) {
      MAttributeSetInstance asi =
          new MAttributeSetInstance(getCtx(), getM_AttributeSetInstance_ID(), get_TrxName());
      setM_AttributeSetInstance_ID(0);
      // Delete the old m_attributesetinstance
      try {
        asi.deleteEx(true, get_TrxName());
      } catch (AdempiereException ex) {
        log.saveError("Error", "Error deleting the AttributeSetInstance");
        return false;
      }
    }

    return true;
  } //	beforeSave
コード例 #6
0
ファイル: User.java プロジェクト: jawfy/PluginDevelopment
 public boolean canAfford(final BigDecimal cost, final boolean permcheck) {
   if (cost.signum() <= 0) {
     return true;
   }
   final BigDecimal remainingBalance = getMoney().subtract(cost);
   if (!permcheck || isAuthorized("essentials.eco.loan")) {
     return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0);
   }
   return (remainingBalance.signum() >= 0);
 }
コード例 #7
0
 /**
  * Set Amount (Callout)
  *
  * @param windowNo window
  * @param columnName changed column
  */
 private void setAmt(int windowNo, String columnName) {
   //	get values
   BigDecimal ExpenseAmt = getExpenseAmt();
   int C_Currency_From_ID = getC_Currency_ID();
   int C_Currency_To_ID = getCtx().getContextAsInt("$C_Currency_ID");
   Timestamp DateExpense = getDateExpense();
   //
   log.fine("Amt=" + ExpenseAmt + ", C_Currency_ID=" + C_Currency_From_ID);
   //	Converted Amount = Unit price
   BigDecimal ConvertedAmt = ExpenseAmt;
   //	convert if required
   if (ConvertedAmt.signum() != 0 && C_Currency_To_ID != C_Currency_From_ID) {
     ConvertedAmt =
         MConversionRate.convert(
             getCtx(),
             ConvertedAmt,
             C_Currency_From_ID,
             C_Currency_To_ID,
             DateExpense,
             0,
             getAD_Client_ID(),
             getAD_Org_ID());
   }
   setConvertedAmt(ConvertedAmt);
   log.fine("ConvertedAmt=" + ConvertedAmt);
 } //	setAmt
コード例 #8
0
  /**
   * Write a BigDecimal value to the output stream.
   *
   * @param value The BigDecimal value to write.
   * @throws IOException
   */
  void write(BigDecimal value) throws IOException {

    if (value == null) {
      write((byte) 0);
    } else {
      byte signum = (byte) (value.signum() < 0 ? 0 : 1);
      BigInteger bi = value.unscaledValue();
      byte mantisse[] = bi.abs().toByteArray();
      byte len = (byte) (mantisse.length + 1);

      if (len > getMaxDecimalBytes()) {
        // Should never happen now as value is normalized elsewhere
        throw new IOException("BigDecimal to big to send");
      }

      if (socket.serverType == Driver.SYBASE) {
        write((byte) len);
        // Sybase TDS5 stores MSB first opposite sign!
        // length, prec, scale already sent in parameter descriptor.
        write((byte) ((signum == 0) ? 1 : 0));

        for (int i = 0; i < mantisse.length; i++) {
          write((byte) mantisse[i]);
        }
      } else {
        write((byte) len);
        write((byte) signum);

        for (int i = mantisse.length - 1; i >= 0; i--) {
          write((byte) mantisse[i]);
        }
      }
    }
  }
コード例 #9
0
  // TODO: Convert this to use one of the new text classes?
  public static String listKits(final IEssentials ess, final User user) throws Exception {
    try {
      final ConfigurationSection kits = ess.getSettings().getKits();
      final StringBuilder list = new StringBuilder();
      for (String kitItem : kits.getKeys(false)) {
        if (user == null) {
          list.append(" ").append(capitalCase(kitItem));
        } else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) {
          String cost = "";
          String name = capitalCase(kitItem);
          BigDecimal costPrice =
              new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
          if (costPrice.signum() > 0) {
            cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
          }

          Kit kit = new Kit(kitItem, ess);
          if (kit.getNextUse(user) != 0) {
            name = tl("kitDelay", name);
          }

          list.append(" ").append(name).append(cost);
        }
      }
      return list.toString().trim();
    } catch (Exception ex) {
      throw new Exception(tl("kitError"), ex);
    }
  }
コード例 #10
0
ファイル: ArgCheck.java プロジェクト: ravikiranj/challenges
 /** Checks that the given number is not negative. */
 public static void nonNegative(BigDecimal n, String argName) {
   nonNull(n, argName);
   if (n.signum() < 0) {
     throw new IllegalArgumentException(
         "Argument \"" + argName + "\" must be non-negative. Got " + n);
   }
 }
コード例 #11
0
 @Override
 public Byte unmarshal(BigDecimal v) throws Exception {
   if (v.signum() == 0) return ZERO; // always valid
   BigDecimal vv =
       v.setScale(scale, allowRounding ? RoundingMode.HALF_EVEN : RoundingMode.UNNECESSARY);
   return vv.unscaledValue().byteValue();
 }
コード例 #12
0
  public static double toDouble(Object a) throws HsqlException {

    double value;

    if (a instanceof java.lang.Double) {
      return ((Double) a).doubleValue();
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = (BigDecimal) a;

      value = bd.doubleValue();

      int signum = bd.signum();
      BigDecimal bdd = new BigDecimal(value + signum);

      if (bdd.compareTo(bd) != signum) {
        throw Error.error(ErrorCode.X_22003);
      }
    } else if (a instanceof Number) {
      value = ((Number) a).doubleValue();
    } else {
      throw Error.error(ErrorCode.X_22501);
    }

    return value;
  }
コード例 #13
0
 /**
  * Create shipment/receipt line
  *
  * @param invoice
  * @param invoiceLine
  * @return shipment/receipt line
  */
 private MInOutLine createLine(MInvoice invoice, MInvoiceLine invoiceLine) {
   BigDecimal qtyMatched = invoiceLine.getMatchedQty();
   BigDecimal qtyInvoiced = invoiceLine.getQtyInvoiced();
   BigDecimal qtyNotMatched = qtyInvoiced.subtract(qtyMatched);
   // If is fully matched don't create anything
   if (qtyNotMatched.signum() == 0) {
     return null;
   }
   MInOut inout = getCreateHeader(invoice);
   MInOutLine sLine = new MInOutLine(inout);
   sLine.setInvoiceLine(
       invoiceLine,
       0, //	Locator
       invoice.isSOTrx() ? qtyNotMatched : Env.ZERO);
   sLine.setQtyEntered(qtyNotMatched);
   sLine.setMovementQty(qtyNotMatched);
   if (invoice.isCreditMemo()) {
     sLine.setQtyEntered(sLine.getQtyEntered().negate());
     sLine.setMovementQty(sLine.getMovementQty().negate());
   }
   sLine.saveEx();
   //
   invoiceLine.setM_InOutLine_ID(sLine.getM_InOutLine_ID());
   invoiceLine.saveEx();
   //
   return sLine;
 }
コード例 #14
0
ファイル: VNumber.java プロジェクト: kimhatrung/Adempiere
 /**
  * Return Editor value
  *
  * @return value value (big decimal or integer)
  */
 public Object getValue() {
   if (m_text == null || m_text.getText() == null || m_text.getText().length() == 0) return null;
   String value = m_text.getText();
   //	return 0 if text deleted
   if (value == null || value.length() == 0) {
     if (!m_modified) return null;
     if (m_displayType == DisplayType.Integer) return new Integer(0);
     return Env.ZERO;
   }
   if (value.equals(".") || value.equals(",") || value.equals("-")) value = "0";
   // arboleda - solve bug [ 1759771 ] Parse exception when you enter ".." in a numeric field
   if (value.equals("..")) {
     value = "0";
     m_text.setText(".");
   }
   try {
     Number number = m_format.parse(value);
     value = number.toString(); // 	converts it to US w/o thousands
     BigDecimal bd = new BigDecimal(value);
     if (m_displayType == DisplayType.Integer) return new Integer(bd.intValue());
     if (bd.signum() == 0) return bd;
     return bd.setScale(m_format.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP);
   } catch (Exception e) {
     log.log(Level.SEVERE, "Value=" + value, e);
   }
   m_text.setText(m_format.format(0));
   if (m_displayType == DisplayType.Integer) return new Integer(0);
   return Env.ZERO;
 } //	getValue
コード例 #15
0
    public final Row range(final BigDecimal aValue) {

      switch (type) {
        case E:
          final int tmpSignum = aValue.signum();
          if (tmpSignum == 1) {
            this.upper(this.getLowerLimit().add(aValue));
          } else if (tmpSignum == -1) {
            this.lower(this.getUpperLimit().add(aValue));
          }

          break;

        case L:
          this.lower(this.getUpperLimit().subtract(aValue.abs()));

          break;

        case G:
          this.upper(this.getLowerLimit().add(aValue.abs()));

          break;

        case N:
          this.level(null);
          this.weight(ONE);

          break;

        default:
          break;
      }

      return this;
    }
コード例 #16
0
ファイル: MOrderLine.java プロジェクト: metasfresh/metasfresh
  /**
   * Before Delete
   *
   * @return true if it can be deleted
   */
  @Override
  protected boolean beforeDelete() {
    // R/O Check - Something delivered. etc.
    if (Env.ZERO.compareTo(getQtyDelivered()) != 0) {
      throw new AdempiereException("@DeleteError@ @QtyDelivered@=" + getQtyDelivered());
    }
    if (Env.ZERO.compareTo(getQtyInvoiced()) != 0) {
      throw new AdempiereException("@DeleteError@ @QtyInvoiced@=" + getQtyInvoiced());
    }
    if (Env.ZERO.compareTo(getQtyReserved()) != 0) {
      // metas: attempt to unreserve stock
      BigDecimal oldVal = getQtyOrdered();
      if (oldVal.signum() != 0) {
        setQty(Env.ZERO);
        setLineNetAmt(Env.ZERO);
        saveEx(get_TrxName());
      }

      if (!getParent().reserveStock(null, new MOrderLine[] {this})) {
        throw new AdempiereException("@DeleteError@ @QtyReserved@=" + getQtyReserved());
      }
      // metas end
    }

    // UnLink All Requisitions
    MRequisitionLine.unlinkC_OrderLine_ID(getCtx(), get_ID(), get_TrxName());

    return true;
  } // beforeDelete
コード例 #17
0
ファイル: DecBase.java プロジェクト: charleso/naca
  public static DecBase toDec(BigDecimal bd) {
    boolean bPositive = true;

    if (bd.signum() < 0) bPositive = false;

    String sValue = bd.abs().unscaledValue().toString();
    int nScale = bd.scale();
    if (sValue.length() > nScale) {
      String sInt = sValue.substring(0, sValue.length() - nScale);
      String sDec = sValue.substring(sValue.length() - nScale);
      DecBase dec = new DecBase(sInt, sDec);
      dec.setPositive(bPositive);
      return dec;
    } else {
      String sDec = new String();
      int nNbLeadingZeros = nScale - sValue.length();
      for (int n = 0; n < nNbLeadingZeros; n++) {
        sDec = sDec + "0";
      }
      sDec = sDec + sValue;

      DecBase dec = new DecBase(0, sDec);
      dec.setPositive(bPositive);
      return dec;
    }
  }
コード例 #18
0
 /** 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;
 }
コード例 #19
0
ファイル: MGoal.java プロジェクト: WilkerDiaz/Compiere
 /** Calculate Performance Goal as multiplier */
 public void setGoalPerformance() {
   BigDecimal MeasureTarget = getMeasureTarget();
   BigDecimal MeasureActual = getMeasureActual();
   BigDecimal GoalPerformance = Env.ZERO;
   if (MeasureTarget.signum() != 0)
     GoalPerformance = MeasureActual.divide(MeasureTarget, 6, BigDecimal.ROUND_HALF_UP);
   super.setGoalPerformance(GoalPerformance);
 } //	setGoalPerformance
コード例 #20
0
ファイル: Money2.java プロジェクト: eneveu/guava-by-example
 public Money2(BigDecimal amount, Currency currency) {
   Preconditions.checkNotNull(amount, "amount must not be null");
   Preconditions.checkNotNull(currency, "currency must not be null");
   Preconditions.checkArgument(
       amount.signum() >= 0, "amount must be positive, but was %S", amount);
   this.amount = amount;
   this.currency = currency;
 }
コード例 #21
0
  /**
   * 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);
  }
コード例 #22
0
  private final void subtractFromQtyToSupplyRemaining(final BigDecimal qtySupplied) {
    this.qtyNetReqRemaining = qtyNetReqRemaining.subtract(qtySupplied);

    // enforce class invariant: qtyNetReqRemaining >= 0 !
    Check.assume(
        qtyNetReqRemaining.signum() >= 0,
        "qtyNetReqRemaining >= 0 but it was {} after subtracting {}",
        qtyNetReqRemaining,
        qtySupplied);
  }
  /**
   * Create Facts (the accounting logic) for PJI
   *
   * <pre>
   *  Issue
   *      ProjectWIP      DR
   *      Inventory               CR
   *  </pre>
   *
   * Project Account is either Asset or WIP depending on Project Type
   *
   * @param as accounting schema
   * @return Fact
   */
  public ArrayList<Fact> createFacts(MAcctSchema as) {
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    setC_Currency_ID(as.getC_Currency_ID());

    MProject project = new MProject(getCtx(), m_issue.getC_Project_ID(), getTrxName());
    String ProjectCategory = project.getProjectCategory();
    MProduct product = MProduct.get(getCtx(), m_issue.getM_Product_ID());

    //  Line pointers
    FactLine dr = null;
    FactLine cr = null;

    //  Issue Cost
    BigDecimal costs = null;
    BigDecimal total = Env.ZERO;
    if (m_issue.getM_InOutLine_ID() != 0) costs = getPOCost(as);
    else if (m_issue.getS_TimeExpenseLine_ID() != 0) costs = getLaborCost(as);
    if (costs == null) // 	standard Product Costs
    {
      for (MCostDetail cost : m_line.getCostDetail(as)) {
        if (!MCostDetail.existsCost(cost)) continue;

        costs = MCostDetail.getTotalCost(cost, as);
        total = total.add(costs);
      }
    }

    if (total == null || total.signum() == 0) {
      p_Error = "Resubmit - No Costs for " + product.getName();
      log.log(Level.WARNING, p_Error);
      return null;
    }

    //  Project         DR
    int acctType = ACCTTYPE_ProjectWIP;
    if (MProject.PROJECTCATEGORY_AssetProject.equals(ProjectCategory))
      acctType = ACCTTYPE_ProjectAsset;
    dr = fact.createLine(m_line, getAccount(acctType, as), as.getC_Currency_ID(), costs, null);
    dr.setQty(m_line.getQty().negate());

    //  Inventory               CR
    acctType = ProductCost.ACCTTYPE_P_Asset;
    if (product.isService()) acctType = ProductCost.ACCTTYPE_P_Expense;
    cr =
        fact.createLine(
            m_line, m_line.getAccount(acctType, as), as.getC_Currency_ID(), null, costs);
    cr.setM_Locator_ID(m_line.getM_Locator_ID());
    cr.setLocationFromLocator(m_line.getM_Locator_ID(), true); // from Loc
    //
    ArrayList<Fact> facts = new ArrayList<Fact>();
    facts.add(fact);
    return facts;
  } //  createFact
コード例 #24
0
ファイル: BaseOffer.java プロジェクト: kshilov/restapi
  public BaseOffer(
      PayMethod payMethod,
      CpaPolicy cpaPolicy,
      BigDecimal cost,
      BigDecimal cost2,
      BigDecimal percent,
      String title,
      boolean autoApprove,
      boolean reentrant,
      String code,
      int holdDays) {

    checkNotNull(payMethod);
    if (payMethod == PayMethod.CPA) checkNotNull(cpaPolicy);

    if (payMethod == PayMethod.CPC
        || (payMethod == PayMethod.CPA && cpaPolicy == CpaPolicy.FIXED)) {
      checkNotNull(cost);
      checkArgument(cost.signum() == 1);
    } else if (payMethod == PayMethod.CPA && cpaPolicy == CpaPolicy.DOUBLE_FIXED) {
      checkNotNull(cost2);
      checkArgument(cost2.signum() == 1);
    } else {
      checkNotNull(percent);
      checkArgument(percent.signum() == 1);
    }

    this.payMethod = payMethod;
    this.cpaPolicy = cpaPolicy;
    this.cost = cost;
    this.cost2 = cost2;
    this.percent = percent;

    this.title = title;
    this.autoApprove = autoApprove;
    this.reentrant = reentrant;
    this.code = code;
    this.holdDays = holdDays;
  }
コード例 #25
0
  @Override
  public int calculateQtyLUForTotalQtyTUs(
      final I_M_HU_LUTU_Configuration lutuConfiguration, final BigDecimal qtyTUsTotal) {
    Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null");

    if (qtyTUsTotal == null || qtyTUsTotal.signum() <= 0) {
      return 0;
    }

    if (isNoLU(lutuConfiguration)) {
      return 0;
    }

    final BigDecimal qtyTUsPerLU = lutuConfiguration.getQtyTU();
    if (qtyTUsPerLU.signum() == 0) {
      // Qty TU not available => cannot compute
      return 0;
    }

    final int qtyLU = qtyTUsTotal.divide(qtyTUsPerLU, 0, RoundingMode.UP).intValueExact();
    return qtyLU;
  }
コード例 #26
0
  /* package */ final BigDecimal calculateQtyToMove(
      final BigDecimal qtyToMoveRequested, final BigDecimal networkLineTransferPercent) {
    Check.assumeNotNull(qtyToMoveRequested, "qtyToMoveRequested not null");
    Check.assumeNotNull(networkLineTransferPercent, "networkLineTransferPercent not null");

    if (networkLineTransferPercent.signum() == 0) {
      return BigDecimal.ZERO;
    } else if (networkLineTransferPercent.signum() < 0) {
      throw new LiberoException(
          "NetworkLine's TransferPercent shall not be negative"
              + "\nQtyToMove: "
              + qtyToMoveRequested
              + "\nTransfer Percent: "
              + networkLineTransferPercent);
    } else if (networkLineTransferPercent.compareTo(Env.ONEHUNDRED) == 0) {
      return qtyToMoveRequested;
    }
    final BigDecimal networkLineTransferPercentMultiplier =
        networkLineTransferPercent.divide(Env.ONEHUNDRED, 4, RoundingMode.HALF_UP);

    final BigDecimal qtyToMove = qtyToMoveRequested.multiply(networkLineTransferPercentMultiplier);
    return qtyToMove;
  }
コード例 #27
0
 /** Set initial value to display */
 public NumberPickerBuilder setCurrentNumber(BigDecimal number) {
   if (number != null) {
     if (number.signum() >= 0) {
       this.currentSignValue = NumberPicker.SIGN_POSITIVE;
     } else {
       this.currentSignValue = NumberPicker.SIGN_NEGATIVE;
       number = number.abs();
     }
     BigDecimal[] numberInput = number.divideAndRemainder(BigDecimal.ONE);
     this.currentNumberValue = numberInput[0].intValue();
     this.currentDecimalValue = numberInput[1].doubleValue();
   }
   return this;
 }
コード例 #28
0
  public void validate(FacesContext context, UIComponent component, Object value)
      throws ValidatorException {
    log.info("validate - value = " + value);
    if (value != null) {
      // Check if value is a BigDecimal
      if (!(value instanceof BigDecimal)) {
        log.info("validate - value is not a BigDecimal (" + value.getClass().getName() + ")");
        throw new ValidatorException(
            new FacesMessage("Las cantidades monetarias deben ser de tipo BigDecimal"));
      }

      // Check if it has no more than 2 decimal digits
      BigDecimal bd = (BigDecimal) value;
      if (bd.scale() > 2) {
        log.info("validate - value has more than 2 decimals (" + value + ")");
        throw new ValidatorException(
            new FacesMessage("Las cantidades monetarias no pueden tener mas de dos decimales"));
      }
      AccountEntryBean bean = (AccountEntryBean) FacesUtils.getBean("accountEntryBean");
      AccountEntryType type = bean.getType();
      AccountEntryGroup group = type.getGroup();

      if (group.getId() == ConfigurationUtil.getDefault().getCostId()) {
        if (bd.signum() != -1) {
          log.info("validate - value cost is negative (" + value + ")");
          throw new ValidatorException(new FacesMessage("La cantidad debe ser negativa"));
        }
      }
      if (group.getId() == ConfigurationUtil.getDefault().getIncomeId()) {
        if (bd.signum() != 1) {
          log.info("validate - value incom is positive (" + value + ")");
          throw new ValidatorException(new FacesMessage("La cantidad debe ser positiva"));
        }
      }
    }
  }
コード例 #29
0
 private BigDecimal pushDigit(int digit) {
   if (clearOnDigit || operand1 == null) {
     if (negativeNumber) operand1 = BigDecimal.valueOf(-digit);
     else operand1 = BigDecimal.valueOf(digit);
   } else {
     operand1 = operand1.multiply(TEN);
     if (operand1.signum() == -1) {
       operand1 = operand1.subtract(BigDecimal.valueOf(digit));
     } else {
       operand1 = operand1.add(BigDecimal.valueOf(digit));
     }
   }
   clearOnDigit = negativeNumber = false;
   return operand1;
 }
コード例 #30
0
  public static Decimal38SparseHolder getDecimal38Holder(DrillBuf buf, String decimal) {

    Decimal38SparseHolder dch = new Decimal38SparseHolder();

    BigDecimal bigDecimal = new BigDecimal(decimal);

    dch.scale = bigDecimal.scale();
    dch.precision = bigDecimal.precision();
    Decimal38SparseHolder.setSign(bigDecimal.signum() == -1, dch.start, dch.buffer);
    dch.start = 0;
    dch.buffer = buf.reallocIfNeeded(dch.maxPrecision * DecimalUtility.INTEGER_SIZE);
    DecimalUtility.getSparseFromBigDecimal(
        bigDecimal, dch.buffer, dch.start, dch.scale, dch.precision, dch.nDecimalDigits);

    return dch;
  }