Java Code Examples for java.math.BigDecimal#ONE

The following examples show how to use java.math.BigDecimal#ONE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CrfUtilities.java    From CRF with MIT License 6 votes vote down vote up
/**
 * Returns \Sum_{i=0}^{k-1}{\theta_i*f_i(x,j,s,s')}, where k is the number of features, \theta_i is parameter number i,
 * f_i is feature number i, x is the given sentence, j is the index of the token, s is the tag of token number j,
 * and s' is the tag of token number j-1.
 * <BR>
 * This function is also given a set of features for which <b>it is not known</b> that they return zero for (x,j,s,s').
 * See {@link #getActiveFeatureIndexes(CrfFeaturesAndFilters, Object[], int, Object, Object)}.
 *  
 * @param model the CRF model: holds the features and the parameters.
 * @param sentence a sentence (sequence of tokens)
 * @param tokenIndex token index
 * @param currentTag tag of the token in tokenIndex
 * @param previousTag tag of the token in tokenIndex-1
 * @param knownActiveFeatureIndexes a set of features for which <b>it is not known</b> that they return zero for (x,j,s,s').
 * @return \Sum_{i=0}^{k-1}{\theta_i*f_i(x,j,s,s')}
 */
public static <K,G> BigDecimal oneTokenSumWeightedFeatures(CrfModel<K, G> model, K[] sentence, int tokenIndex, G currentTag, G previousTag, Set<Integer> knownActiveFeatureIndexes)
{
	BigDecimal sum = BigDecimal.ZERO;
	for (int index : knownActiveFeatureIndexes)
	{
		CrfFilteredFeature<K, G> feature = model.getFeatures().getFilteredFeatures()[index];
		BigDecimal featureValue = BigDecimal.ZERO;
		if (feature.isWhenNotFilteredIsAlwaysOne())
		{
			featureValue = BigDecimal.ONE;
		}
		else
		{
			featureValue = big(feature.getFeature().value(sentence,tokenIndex,currentTag,previousTag));
		}
		
		BigDecimal weightedValue = safeMultiply(model.getParameters().get(index), featureValue);
		sum = safeAdd(sum, weightedValue);
	}
	return sum;
}
 
Example 2
Source File: BOMNode.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public BOMNode(GenericValue product, LocalDispatcher dispatcher, GenericValue userLogin) {
    this.product = product;
    this.delegator = product.getDelegator();
    this.dispatcher = dispatcher;
    this.userLogin = userLogin;
    children = new LinkedList<GenericValue>();
    childrenNodes = new LinkedList<BOMNode>();
    parentNode = null;
    productForRules = null;
    bomTypeId = null;
    quantityMultiplier = BigDecimal.ONE;
    scrapFactor = BigDecimal.ONE;
    // Now we initialize the fields used in breakdowns
    depth = 0;
    quantity = BigDecimal.ZERO;
}
 
Example 3
Source File: ItemGiftPromotionAction.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public BigDecimal testDiscountValue(final Map<String, Object> context) {
    final ItemPromotionActionContext ctx = getPromotionActionContext(context);
    final CartItem cartItem = getShoppingCartItem(context);
    final BigDecimal giftQty = BigDecimal.ONE.multiply(ctx.getMultiplier(cartItem.getQty())).setScale(0, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
    if (MoneyUtils.isPositive(giftQty)) {
        final BigDecimal giftValue = getAmountValue(context, giftQty);
        final BigDecimal itemValue = nullSafeItemPriceForCalculation(cartItem);
        if (MoneyUtils.isPositive(giftValue) && MoneyUtils.isPositive(itemValue)) {
            return giftValue.divide(itemValue, RoundingMode.HALF_UP);
        }
        return BigDecimal.ONE; // Assume 100% as we have no price to compare
    }
    return BigDecimal.ZERO; // no gift
}
 
Example 4
Source File: PDecimal.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder,
        Integer maxLength, Integer scale) {
    Preconditions.checkNotNull(sortOrder);
    if (l == 0) {
        return null;
    }
    if (actualType == PDecimal.INSTANCE) {
        if (sortOrder == SortOrder.DESC) {
            b = SortOrder.invert(b, o, new byte[l], 0, l);
            o = 0;
        }
        return toBigDecimal(b, o, l);
    } else if (equalsAny(actualType, PDate.INSTANCE, PTime.INSTANCE, PUnsignedDate.INSTANCE,
            PUnsignedTime.INSTANCE, PLong.INSTANCE, PUnsignedLong.INSTANCE, PInteger.INSTANCE,
            PUnsignedInt.INSTANCE, PSmallint.INSTANCE, PUnsignedSmallint.INSTANCE, PTinyint.INSTANCE,
            PUnsignedTinyint.INSTANCE)) {
        return BigDecimal.valueOf(actualType.getCodec().decodeLong(b, o, sortOrder));
    } else if (equalsAny(actualType, PFloat.INSTANCE, PUnsignedFloat.INSTANCE)) {
        return BigDecimal.valueOf(actualType.getCodec().decodeFloat(b, o, sortOrder));
    } else if (equalsAny(actualType, PDouble.INSTANCE, PUnsignedDouble.INSTANCE)) {
        return BigDecimal.valueOf(actualType.getCodec().decodeDouble(b, o, sortOrder));
    } else if (equalsAny(actualType, PTimestamp.INSTANCE, PUnsignedTimestamp.INSTANCE)) {
        long millisPart = DateUtil.getCodecFor(actualType).decodeLong(b, o, sortOrder);
        int nanoPart = PUnsignedInt.INSTANCE.getCodec().decodeInt(b, o + Bytes.SIZEOF_LONG, sortOrder);
        BigDecimal nanosPart = BigDecimal.valueOf(
                (nanoPart % QueryConstants.MILLIS_TO_NANOS_CONVERTOR)
                / QueryConstants.MILLIS_TO_NANOS_CONVERTOR);
        return BigDecimal.valueOf(millisPart).add(nanosPart);
    } else if (actualType == PBoolean.INSTANCE) {
        return (Boolean) PBoolean.INSTANCE.toObject(b, o, l, actualType, sortOrder) ?
                BigDecimal.ONE :
                    BigDecimal.ZERO;
    }
    return throwConstraintViolationException(actualType, this);
}
 
Example 5
Source File: ProductEntry.java    From fingen with Apache License 2.0 5 votes vote down vote up
public ProductEntry() {
    super();
    mProductID = -1;
    mQuantity = BigDecimal.ONE;
    mPrice = BigDecimal.ZERO;
    mCategoryID = -1;
    mProjectID = -1;
    mTransactionID = -1;
}
 
Example 6
Source File: CommonCachedRowSetTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void createDataTypesRows(RowSet crs) throws SQLException {

        Integer aInteger = 100;
        String aChar = "Oswald Cobblepot";
        Long aLong = Long.MAX_VALUE;
        Short aShort = Short.MAX_VALUE;
        Double aDouble = Double.MAX_VALUE;
        BigDecimal aBigDecimal = BigDecimal.ONE;
        Boolean aBoolean = false;
        Float aFloat = Float.MAX_VALUE;
        Byte aByte = Byte.MAX_VALUE;
        Date aDate = Date.valueOf(LocalDate.now());
        Time aTime = Time.valueOf(LocalTime.now());
        Timestamp aTimeStamp = Timestamp.valueOf(LocalDateTime.now());
        Array aArray = new StubArray("INTEGER", new Object[1]);
        Ref aRef = new SerialRef(new StubRef("INTEGER", query));
        byte[] bytes = new byte[10];
        crs.moveToInsertRow();
        crs.updateInt(1, aInteger);
        crs.updateString(2, aChar);
        crs.updateString(3, aChar);
        crs.updateLong(4, aLong);
        crs.updateBoolean(5, aBoolean);
        crs.updateShort(6, aShort);
        crs.updateDouble(7, aDouble);
        crs.updateBigDecimal(8, aBigDecimal);
        crs.updateFloat(9, aFloat);
        crs.updateByte(10, aByte);
        crs.updateDate(11, aDate);
        crs.updateTime(12, aTime);
        crs.updateTimestamp(13, aTimeStamp);
        crs.updateBytes(14, bytes);
        crs.updateArray(15, aArray);
        crs.updateRef(16, aRef);
        crs.updateDouble(17, aDouble);
        crs.insertRow();
        crs.moveToCurrentRow();

    }
 
Example 7
Source File: ValidatorTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testValidationExpirationNull() {
    EventModification.AdditionalService invalid = new EventModification.AdditionalService(0, BigDecimal.ONE, true, 1, 100, 1, VALID_INCEPTION, null, BigDecimal.TEN, AdditionalService.VatType.INHERITED, Collections.emptyList(), singletonList(title), singletonList(description), AdditionalService.AdditionalServiceType.DONATION, null);
    assertFalse(Validator.validateAdditionalService(invalid, errors).isSuccess());
    assertTrue(errors.hasFieldErrors());
    assertNotNull(errors.getFieldError("additionalServices"));
}
 
Example 8
Source File: BigDecimalCalculations.java    From oopsla15-artifact with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compute the cosine of x to a given scale
 * @param x the value of x
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal cos(BigDecimal x, int scale)
{
    if (x.signum() == 0)
    	return BigDecimal.ONE;
    if (x.abs().compareTo(sincosNormalizePoint) >= 0 ) {
     x = x.remainder(twoPI, new MathContext(scale + 1));
    }
    if (x.signum() == -1)
        return cosTaylor(x.negate(), scale);
    else 
    	return cosTaylor(x, scale);
}
 
Example 9
Source File: CollectionAndCollectionTest.java    From tddl with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayAndSet() {
    Convertor intSet = helper.getConvertor(int[].class, Set.class);
    Convertor integerSet = helper.getConvertor(Integer[].class, Set.class);

    int[] intArray = new int[] { 1, 2 };
    Integer[] integerArray = new Integer[] { 1, 2 };
    Set intSetValue = (Set) intSet.convert(intArray, Set.class);
    Set integerSetValue = (Set) integerSet.convert(integerArray, Set.class);
    assertEquals(intSetValue.size(), intArray.length);
    assertEquals(intSetValue.iterator().next(), intArray[0]);
    assertEquals(integerSetValue.size(), integerArray.length);
    assertEquals(integerSetValue.iterator().next(), integerArray[0]);
    // 测试不同类型转化, common对象
    Set<BigInteger> intSetValueOther = (Set) intSet.convertCollection(intArray, Set.class, BigInteger.class); // int强制转为BigInteger
    Set<BigDecimal> integerSetValueOther = (Set) integerSet.convertCollection(intArray, Set.class, BigDecimal.class); // int强制转为BigDecimal
    assertEquals(intSetValueOther.size(), intArray.length);
    assertEquals(intSetValueOther.iterator().next().intValue(), intArray[0]);
    assertEquals(integerSetValueOther.size(), integerArray.length);

    // BigDecimal & BigInteger
    Convertor bigDecimalSet = helper.getConvertor(BigDecimal[].class, HashSet.class);
    Convertor bigIntegerSet = helper.getConvertor(BigInteger[].class, LinkedHashSet.class);

    BigDecimal[] bigDecimalArray = new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ONE };
    BigInteger[] bigIntegerArray = new BigInteger[] { BigInteger.ZERO, BigInteger.ONE };
    Set bigDecimalSetValue = (Set) bigDecimalSet.convert(bigDecimalArray, HashSet.class);
    Set bigIntegerSetValue = (Set) bigIntegerSet.convert(bigIntegerArray, LinkedHashSet.class);
    assertEquals(bigDecimalSetValue.size(), bigDecimalArray.length);
    assertEquals(bigDecimalSetValue.iterator().next(), bigDecimalArray[0]);
    assertEquals(bigIntegerSetValue.size(), bigIntegerArray.length);
    assertEquals(bigIntegerSetValue.iterator().next(), bigIntegerArray[0]);

}
 
Example 10
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
private static BigDecimal loopShiftLimit(int n1, final int n2) {
	final long l = Long.MAX_VALUE >> (32 - Integer.numberOfLeadingZeros(n2));
	long p = 1;
	BigDecimal r = BigDecimal.ONE;
	while (n1 <= n2) {
		if (p <= l) {
			p *= n1;
		} else {
			r = r.multiply(BigDecimal.valueOf(p));
			p = n1;
		}
		n1++;
	}
	return r.multiply(BigDecimal.valueOf(p));
}
 
Example 11
Source File: TestRuntime81GHILMNOP.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the bean L.
 *
 * @return the bean 81 L
 */
private Bean81L createBeanL() {
	Bean81L result=new Bean81L();
	
	result.id=24;
	result.valueBigDecimal=BigDecimal.ONE;
	result.valueBigInteger=BigInteger.TEN;
	return result;
}
 
Example 12
Source File: ValidatorTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testValidationErrorInceptionNull() {
    EventModification.AdditionalService invalid = new EventModification.AdditionalService(0, BigDecimal.ONE, true, 1, 100, 1, null, VALID_EXPIRATION, BigDecimal.TEN, AdditionalService.VatType.INHERITED, Collections.emptyList(), singletonList(title), singletonList(description), AdditionalService.AdditionalServiceType.DONATION, null);
    assertFalse(Validator.validateAdditionalService(invalid, errors).isSuccess());
    assertTrue(errors.hasFieldErrors());
    assertNotNull(errors.getFieldError("additionalServices"));
}
 
Example 13
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal factorialSimple(int n) {
	BigDecimal result = BigDecimal.ONE;
	for (int i = 2; i <= n; i++) {
		result = result.multiply(valueOf(i));
	}
	return result;
}
 
Example 14
Source File: Readers.java    From code with Apache License 2.0 4 votes vote down vote up
/**
 * @param value to be converted to BigDecimal.  Can be a null which will return null.  Can be
 * BigDecimal in which case it will be returned as-is.  Can also be String, BigInteger,
 * Boolean (which will be returned as BigDecimal.ZERO or .ONE), byte, short, int, long, float,
 * or double.  If an unknown type is passed in, an exception will be thrown.
 *
 * @return a BigDecimal from the given input.  A best attempt will be made to support
 * as many input types as possible.  For example, if the input is a Boolean, a BigDecimal of
 * 1 or 0 will be returned.  If the input is a String "", a null will be returned. The input
 * can be a Byte, Short, Integer, Long, or BigInteger.
 */
public static BigDecimal bigDecimalFrom(Object value)
{
    if (value == null)
    {
        return null;
    }
    else if (value instanceof BigDecimal)
    {
        return (BigDecimal) value;
    }
    else if (value instanceof String)
    {
        String s = (String) value;
        if ("".equals(s.trim()))
        {
            return null;
        }
        try
        {
            return new BigDecimal(MetaUtils.removeLeadingAndTrailingQuotes(s));
        }
        catch (Exception e)
        {
            throw new JsonIoException("Could not parse '" + s + "' as BigDecimal.", e);
        }
    }
    else if (value instanceof BigInteger)
    {
        return new BigDecimal((BigInteger) value);
    }
    else if (value instanceof Boolean)
    {
        return (Boolean) value ? BigDecimal.ONE : BigDecimal.ZERO;
    }
    else if (value instanceof Long || value instanceof Integer || value instanceof Double ||
            value instanceof Short || value instanceof Byte || value instanceof Float)
    {
        return new BigDecimal(value.toString());
    }
    throw new JsonIoException("Could not convert value: " + value.toString() + " to BigInteger.");
}
 
Example 15
Source File: ProductAvailabilityStrategyDefaultImplTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAvailabilityModelForAlwaysOnePreorder() throws Exception {

    final int availability = SkuWarehouse.AVAILABILITY_ALWAYS;
    final BigDecimal qty = BigDecimal.ONE;
    final BigDecimal max = new BigDecimal(Integer.MAX_VALUE);

    setTestExpectations(availability, DateUtils.ldtParseSDT("2099-01-01"), qty);

    final ProductAvailabilityModel modelProduct = new ProductAvailabilityStrategyDefaultImpl(warehouseService, inventoryResolver).getAvailabilityModel(shopId, product, supplier);

    assertNotNull(modelProduct);
    assertEquals(skuCode, modelProduct.getDefaultSkuCode());
    assertEquals(SkuWarehouse.AVAILABILITY_ALWAYS, modelProduct.getAvailability());
    assertTrue(modelProduct.isAvailable());
    assertFalse(modelProduct.isInStock());
    assertTrue(modelProduct.isPerpetual());
    assertEquals(DateUtils.ldtParseSDT("2099-01-01"), modelProduct.getReleaseDate());
    assertTrue(modelProduct.getAvailableToSellQuantity(skuCode).compareTo(max) == 0);

    final ProductAvailabilityModel modelSku = new ProductAvailabilityStrategyDefaultImpl(warehouseService, inventoryResolver).getAvailabilityModel(shopId, sku, supplier);

    assertNotNull(modelSku);
    assertEquals(skuCode, modelSku.getDefaultSkuCode());
    assertEquals(SkuWarehouse.AVAILABILITY_ALWAYS, modelSku.getAvailability());
    assertTrue(modelSku.isAvailable());
    assertFalse(modelSku.isInStock());
    assertTrue(modelSku.isPerpetual());
    assertEquals(DateUtils.ldtParseSDT("2099-01-01"), modelSku.getReleaseDate());
    assertTrue(modelSku.getAvailableToSellQuantity(skuCode).compareTo(max) == 0);

    final ProductAvailabilityModel modelProductSearch = new ProductAvailabilityStrategyDefaultImpl(warehouseService, inventoryResolver).getAvailabilityModel(shopId, productSearch);

    assertNotNull(modelProductSearch);
    assertEquals(skuCode, modelProductSearch.getDefaultSkuCode());
    assertEquals(SkuWarehouse.AVAILABILITY_ALWAYS, modelProductSearch.getAvailability());
    assertTrue(modelProductSearch.isAvailable());
    assertFalse(modelProductSearch.isInStock());
    assertTrue(modelProductSearch.isPerpetual());
    assertEquals(DateUtils.ldtParseSDT("2099-01-01"), modelProductSearch.getReleaseDate());
    assertTrue(modelProductSearch.getAvailableToSellQuantity(skuCode).compareTo(max) == 0);

    final ProductAvailabilityModel modelSkuSearch = new ProductAvailabilityStrategyDefaultImpl(warehouseService, inventoryResolver).getAvailabilityModel(shopId, skuSearch);

    assertNotNull(modelSkuSearch);
    assertEquals(skuCode, modelSkuSearch.getDefaultSkuCode());
    assertEquals(SkuWarehouse.AVAILABILITY_ALWAYS, modelSkuSearch.getAvailability());
    assertTrue(modelSkuSearch.isAvailable());
    assertFalse(modelSkuSearch.isInStock());
    assertTrue(modelSkuSearch.isPerpetual());
    assertEquals(DateUtils.ldtParseSDT("2099-01-01"), modelSkuSearch.getReleaseDate());
    assertTrue(modelSkuSearch.getAvailableToSellQuantity(skuCode).compareTo(max) == 0);

    context.assertIsSatisfied();

}
 
Example 16
Source File: VM14Splitter.java    From ldparteditor with MIT License 4 votes vote down vote up
private List<GData3> splitTri2(Vertex v1, Vertex v2, Vertex v3, int fractions, GData3 g) {

        ArrayList<GData3> result = new ArrayList<GData3>(fractions);

        Vector3d A = new Vector3d(v1);
        Vector3d B = new Vector3d(v2);
        Vector3d C = new Vector3d(v3);

        BigDecimal step = BigDecimal.ONE.divide(new BigDecimal(fractions), Threshold.mc);
        BigDecimal cur = BigDecimal.ZERO;
        BigDecimal next = BigDecimal.ZERO;
        for (int i = 0; i < fractions; i++) {
            if (i == fractions - 1) {
                next = BigDecimal.ONE;
            } else {
                next = next.add(step);
            }

            BigDecimal oneMinusCur = BigDecimal.ONE.subtract(cur);
            BigDecimal oneMinusNext = BigDecimal.ONE.subtract(next);

            if (i == 0) {
                result.add(new GData3(g.colourNumber, g.r, g.g, g.b, g.a,

                        v1.X,
                        v1.Y,
                        v1.Z,

                        A.X.multiply(oneMinusNext).add(B.X.multiply(next)),
                        A.Y.multiply(oneMinusNext).add(B.Y.multiply(next)),
                        A.Z.multiply(oneMinusNext).add(B.Z.multiply(next)),

                        A.X.multiply(oneMinusNext).add(C.X.multiply(next)),
                        A.Y.multiply(oneMinusNext).add(C.Y.multiply(next)),
                        A.Z.multiply(oneMinusNext).add(C.Z.multiply(next)),

                        View.DUMMY_REFERENCE, linkedDatFile, true));
            } else {
                result.add(new GData3(g.colourNumber, g.r, g.g, g.b, g.a,

                        A.X.multiply(oneMinusNext).add(C.X.multiply(next)),
                        A.Y.multiply(oneMinusNext).add(C.Y.multiply(next)),
                        A.Z.multiply(oneMinusNext).add(C.Z.multiply(next)),

                        A.X.multiply(oneMinusCur).add(C.X.multiply(cur)),
                        A.Y.multiply(oneMinusCur).add(C.Y.multiply(cur)),
                        A.Z.multiply(oneMinusCur).add(C.Z.multiply(cur)),

                        A.X.multiply(oneMinusCur).add(B.X.multiply(cur)),
                        A.Y.multiply(oneMinusCur).add(B.Y.multiply(cur)),
                        A.Z.multiply(oneMinusCur).add(B.Z.multiply(cur)),

                        View.DUMMY_REFERENCE, linkedDatFile, true));
                result.add(new GData3(g.colourNumber, g.r, g.g, g.b, g.a,

                        A.X.multiply(oneMinusCur).add(B.X.multiply(cur)),
                        A.Y.multiply(oneMinusCur).add(B.Y.multiply(cur)),
                        A.Z.multiply(oneMinusCur).add(B.Z.multiply(cur)),

                        A.X.multiply(oneMinusNext).add(B.X.multiply(next)),
                        A.Y.multiply(oneMinusNext).add(B.Y.multiply(next)),
                        A.Z.multiply(oneMinusNext).add(B.Z.multiply(next)),

                        A.X.multiply(oneMinusNext).add(C.X.multiply(next)),
                        A.Y.multiply(oneMinusNext).add(C.Y.multiply(next)),
                        A.Z.multiply(oneMinusNext).add(C.Z.multiply(next)),

                        View.DUMMY_REFERENCE, linkedDatFile, true));
            }

            cur = next;
        }

        return result;
    }
 
Example 17
Source File: IncomingDocAsInvoiceViewModel_Test.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Test
public void save_works() {
    // given
    IncomingInvoice incomingInvoice = new IncomingInvoice();
    IncomingInvoiceItem invoiceItem = new IncomingInvoiceItem();
    invoiceItem.setInvoice(incomingInvoice);
    invoiceItem.setIncomingInvoiceType(IncomingInvoiceType.CAPEX);
    incomingInvoice.getItems().add(invoiceItem);
    IncomingDocAsInvoiceViewModel viewModel = new IncomingDocAsInvoiceViewModel();
    viewModel.setDomainObject(incomingInvoice);
    viewModel.stateTransitionService = mockStateTransitionService;
    viewModel.orderItemRepository = mockOrderItemRepository;
    viewModel.orderItemInvoiceItemLinkRepository = mockOrderItemInvoiceItemLinkRepository;

    IncomingInvoiceType newIncomingInvoiceType = IncomingInvoiceType.CAPEX;
    Property newProperty = new Property();
    Organisation newBuyer = new Organisation();
    Organisation newSeller = new Organisation();
    BankAccount newBankAccount = new BankAccount();
    String newInvoiceNumber = "1234";
    LocalDate newDateReceived = new LocalDate();
    LocalDate newInvoiceDate = new LocalDate();
    LocalDate newDueDate = new LocalDate();
    PaymentMethod newPaymentMethod = PaymentMethod.DIRECT_DEBIT;
    Currency newCurrency = new Currency();
    Order order = new Order();
    OrderItem newOrderItem = new OrderItem();
    newOrderItem.setOrdr(order);
    String newDescription = "Description";
    BigDecimal newNetAmount = BigDecimal.ONE;
    BigDecimal newVatAmount = BigDecimal.ONE;
    Tax newTax = new Tax();
    BigDecimal newGrossAmount = BigDecimal.ONE;
    Charge newCharge = new Charge();
    newOrderItem.setCharge(newCharge);
    String newPeriod = "F2019";

    viewModel.setIncomingInvoiceType(newIncomingInvoiceType);
    viewModel.setProperty(newProperty);
    viewModel.setBuyer(newBuyer);
    viewModel.setSeller(newSeller);
    viewModel.setBankAccount(newBankAccount);
    viewModel.setInvoiceNumber(newInvoiceNumber);
    viewModel.setDateReceived(newDateReceived);
    viewModel.setInvoiceDate(newInvoiceDate);
    viewModel.setDueDate(newDueDate);
    viewModel.setPaymentMethod(newPaymentMethod);
    viewModel.setCurrency(newCurrency);
    viewModel.setOrderItem(newOrderItem);
    viewModel.setDescription(newDescription);
    viewModel.setNetAmount(newNetAmount);
    viewModel.setVatAmount(newVatAmount);
    viewModel.setTax(newTax);
    viewModel.setGrossAmount(newGrossAmount);
    viewModel.setCharge(newCharge);
    viewModel.setPeriod(newPeriod);

    // expecting
    context.checking(new Expectations() {{
        oneOf(mockStateTransitionService).trigger(incomingInvoice, IncomingInvoiceApprovalStateTransition.class, null, null, null);
        oneOf(mockOrderItemRepository).findUnique(order, newCharge, 0);
        will(returnValue(newOrderItem));
        oneOf(mockOrderItemInvoiceItemLinkRepository).findOrCreateLink(newOrderItem, invoiceItem, BigDecimal.ONE);
    }});

    // when
    viewModel.save();

    // then
    assertThat(incomingInvoice.getType()).isEqualTo(newIncomingInvoiceType);
    assertThat(incomingInvoice.getProperty()).isEqualTo(newProperty);
    assertThat(incomingInvoice.getBuyer()).isEqualTo(newBuyer);
    assertThat(incomingInvoice.getSeller()).isEqualTo(newSeller);
    assertThat(incomingInvoice.getBankAccount()).isEqualTo(newBankAccount);
    assertThat(incomingInvoice.getInvoiceNumber()).isEqualTo(newInvoiceNumber);
    assertThat(incomingInvoice.getDateReceived()).isEqualTo(newDateReceived);
    assertThat(incomingInvoice.getInvoiceDate()).isEqualTo(newInvoiceDate);
    assertThat(incomingInvoice.getDueDate()).isEqualTo(newDueDate);
    assertThat(incomingInvoice.getPaymentMethod()).isEqualTo(newPaymentMethod);
    assertThat(incomingInvoice.getCurrency()).isEqualTo(newCurrency);
    assertThat(incomingInvoice.getDescriptionSummary()).isEqualTo(newDescription);
    assertThat(incomingInvoice.getItems().first().getDescription()).isEqualTo(newDescription);
    assertThat(incomingInvoice.getItems().first().getNetAmount()).isEqualTo(newNetAmount);
    assertThat(incomingInvoice.getItems().first().getVatAmount()).isEqualTo(newVatAmount);
    assertThat(incomingInvoice.getItems().first().getTax()).isEqualTo(newTax);
    assertThat(incomingInvoice.getItems().first().getGrossAmount()).isEqualTo(newGrossAmount);
    assertThat(incomingInvoice.getItems().first().getCharge()).isEqualTo(newCharge);

}
 
Example 18
Source File: InventoryServices.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Get Inventory Available for a Product based on the list of associated products.  The final ATP and QOH will
 * be the minimum of all the associated products' inventory divided by their ProductAssoc.quantity
 */
public static Map<String, Object> getProductInventoryAvailableFromAssocProducts(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    List<GenericValue> productAssocList = UtilGenerics.checkList(context.get("assocProducts"));
    String facilityId = (String) context.get("facilityId");
    String statusId = (String) context.get("statusId");

    BigDecimal availableToPromiseTotal = BigDecimal.ZERO;
    BigDecimal quantityOnHandTotal = BigDecimal.ZERO;

    Boolean useEntityCache = (Boolean) context.get("useEntityCache"); // SCIPIO
    Boolean useInventoryCache = (Boolean) context.get("useInventoryCache"); // SCIPIO

    if (UtilValidate.isNotEmpty(productAssocList)) {
        // minimum QOH and ATP encountered
        BigDecimal minQuantityOnHandTotal = null;
        BigDecimal minAvailableToPromiseTotal = null;

        // loop through each associated product.
        for (GenericValue productAssoc : productAssocList) {
            String productIdTo = productAssoc.getString("productIdTo");
            BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity");

            // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0
            if (assocQuantity == null) {
                Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo") + "] has no quantity, assuming 1.0", module);
                assocQuantity = BigDecimal.ONE;
            }

            // figure out the inventory available for this associated product
            Map<String, Object> resultOutput = null;
            try {
                Map<String, String> inputMap = UtilMisc.toMap("productId", productIdTo, "statusId", statusId,
                        "useEntityCache", useEntityCache, "useInventoryCache", useInventoryCache); // SCIPIO: useInventoryCache
                if (facilityId != null) {
                    inputMap.put("facilityId", facilityId);
                    resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", inputMap);
                } else {
                    resultOutput = dispatcher.runSync("getProductInventoryAvailable", inputMap);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problems getting inventory available by facility", module);
                return ServiceUtil.returnError(e.getMessage());
            }

            // Figure out what the QOH and ATP inventory would be with this associated product
            BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal");
            BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal");
            BigDecimal tmpQuantityOnHandTotal = currentQuantityOnHandTotal.divideToIntegralValue(assocQuantity, generalRounding);
            BigDecimal tmpAvailableToPromiseTotal = currentAvailableToPromiseTotal.divideToIntegralValue(assocQuantity, generalRounding);

            // reset the minimum QOH and ATP quantities if those quantities for this product are less
            if (minQuantityOnHandTotal == null || tmpQuantityOnHandTotal.compareTo(minQuantityOnHandTotal) < 0) {
                minQuantityOnHandTotal = tmpQuantityOnHandTotal;
            }
            if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) {
                minAvailableToPromiseTotal = tmpAvailableToPromiseTotal;
            }

            if (Debug.verboseOn()) {
                Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal +
                        "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = " + minAvailableToPromiseTotal, module);
            }
        }
        // the final QOH and ATP quantities are the minimum of all the products
        quantityOnHandTotal = minQuantityOnHandTotal;
        availableToPromiseTotal = minAvailableToPromiseTotal;
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("availableToPromiseTotal", availableToPromiseTotal);
    result.put("quantityOnHandTotal", quantityOnHandTotal);
    return result;
}
 
Example 19
Source File: ValueMetaBase.java    From hop with Apache License 2.0 4 votes vote down vote up
protected BigDecimal convertBooleanToBigNumber( Boolean bool ) {
  if ( bool == null ) {
    return null;
  }
  return bool.booleanValue() ? BigDecimal.ONE : BigDecimal.ZERO;
}
 
Example 20
Source File: PowerNIterator.java    From big-math with MIT License 4 votes vote down vote up
public PowerNIterator(BigDecimal x, MathContext mathContext) {
	this.x = x;
	this.mathContext = mathContext;
	
	powerOfX = BigDecimal.ONE;
}