public static function price_for_display($price)
 {
     $currency = ShopConfig::get_site_currency();
     $field = new Money("Price");
     $field->setAmount($price);
     $field->setCurrency($currency);
     return $field;
 }
示例#2
0
 public function testCanSetAmount()
 {
     // Arrange
     $a = new Money(1);
     // Act
     $a->setAmount(123);
     // Assert
     $this->assertEquals(123, $a->getAmount());
 }
 public function testSetValueAsMoney()
 {
     $o = new MoneyFieldTest_Object();
     $f = new MoneyField('MyMoney', 'MyMoney');
     $m = new Money();
     $m->setAmount(123456.78);
     $m->setCurrency('EUR');
     $f->setValue($m);
     $f->saveInto($o);
     $this->assertEquals(123456.78, $o->MyMoney->getAmount());
     $this->assertEquals('EUR', $o->MyMoney->getCurrency());
 }
 public function testAddCompositedExtraFields()
 {
     $obj = new ManyManyListTest_ExtraFields();
     $obj->write();
     $money = new Money();
     $money->setAmount(100);
     $money->setCurrency('USD');
     // the actual test is that this does not generate an error in the sql.
     $obj->Clients()->add($obj, array('Worth' => $money, 'Reference' => 'Foo'));
     $check = $obj->Clients()->First();
     $this->assertEquals('Foo', $check->Reference, 'Basic scalar fields should exist');
     $this->assertInstanceOf('Money', $check->Worth, 'Composite fields should exist on the record');
     $this->assertEquals(100, $check->Worth->getAmount());
 }
 /**
  * Calculate the {@link Variation} price difference based on current request. 
  * Current seleted options are passed in POST vars, if a matching Variation can 
  * be found, the price difference of that Variation is returned for display on the Product 
  * page.
  * 
  * TODO return the total here as well
  * 
  * @param SS_HTTPRequest $request
  * @return String JSON encoded string of price difference
  */
 function variationprice(SS_HTTPRequest $request)
 {
     $data = array();
     $product = $this->data();
     $variations = $product->Variations();
     $attributeOptions = $request->postVar('Options');
     //Filter variations to match attribute ID and option ID
     $variationOptions = array();
     if ($variations && $variations->exists()) {
         foreach ($variations as $variation) {
             $options = $variation->Options();
             if ($options) {
                 foreach ($options as $option) {
                     $variationOptions[$variation->ID][$option->AttributeID] = $option->ID;
                 }
             }
         }
     }
     $variation = null;
     foreach ($variationOptions as $variationID => $options) {
         if ($options == $attributeOptions) {
             $variation = $variations->find('ID', $variationID);
             break;
         }
     }
     $data['totalPrice'] = $product->Amount->Nice();
     if ($variation) {
         if ($variation->Amount->getAmount() == 0) {
             $data['priceDifference'] = 0;
         } else {
             if ($variation->Amount->getAmount() > 0) {
                 $data['priceDifference'] = '(+' . $variation->Amount->Nice() . ')';
                 $newTotal = new Money();
                 $newTotal->setCurrency($product->Amount->getCurrency());
                 $newTotal->setAmount($product->Amount->getAmount() + $variation->Amount->getAmount());
                 $data['totalPrice'] = $newTotal->Nice();
             } else {
                 //Variations have been changed so only positive values, so this is unnecessary
                 //$data['priceDifference'] = '(' . $variation->Amount->Nice() . ')';
             }
         }
     }
     return json_encode($data);
 }
 /**
  * Returns the price for this shipping fee.
  * 
  * @return Money
  *
  * @author Sascha Koehler <*****@*****.**>
  * @since 13.03.2012
  */
 public function getCalculatedPrice()
 {
     $priceObj = new Money();
     $priceObj->setAmount($this->getPriceAmount());
     $priceObj->setCurrency($this->getPriceCurrency());
     return $priceObj;
 }
 /**
  * @return Money
  */
 public function PromoSavings()
 {
     $currency = method_exists('ShopConfig', 'get_site_currency') ? ShopConfig::get_site_currency() : Payment::site_currency();
     $field = new Money("PromoSavings");
     $field->setAmount($this->calculatePromoSavings());
     $field->setCurrency($currency);
     return $field;
 }
 function NormalPrice()
 {
     $normalPrice = new Money();
     $normalPrice->setAmount((int) $this->owner->Price);
     return $normalPrice;
 }
 public function testToCurrency()
 {
     $USD = new Money();
     $USD->setLocale('en_US');
     $USD->setAmount(53292.18);
     $this->assertSame('$53,292.18', $USD->Nice());
     $this->assertSame('$ 53.292,18', $USD->Nice(array('format' => 'de_AT')));
 }
 /**
  * Get Amount for this modifier so that it can be saved into an {@link Order} {@link Modification}.
  * Get the FlatFeeTaxRate and multiply the rate by the Order subtotal.
  * 
  * @see Modification
  * @param Order $order
  * @param Int $value ID for a {@link FlatFeeShippingRate} 
  * @return Money
  */
 public function Amount($order, $value)
 {
     $currency = Modification::currency();
     $amount = new Money();
     $amount->setCurrency($currency);
     $taxRate = DataObject::get_by_id('FlatFeeTaxRate', $value);
     if ($taxRate && $taxRate->exists()) {
         $amount->setAmount($order->SubTotal->getAmount() * ($taxRate->Rate / 100));
     } else {
         user_error("Cannot find flat tax rate for that ID.", E_USER_WARNING);
         //TODO return meaningful error to browser in case error not shown
         return;
     }
     return $amount;
 }
 /**
  * Returns the charges and discounts for the shopping cart total for
  * this payment method.
  * 
  * @param SilvercartShoppingCart $silvercartShoppingCart The shopping cart object
  * @param string                 $priceType              'gross' or 'net'
  *
  * @return mixed boolean|DataObject
  * 
  * @author Sascha Koehler <*****@*****.**>,
  *         Sebastian Diel <*****@*****.**>
  * @since 16.11.2013
  */
 public function getChargesAndDiscountsForTotal(SilvercartShoppingCart $silvercartShoppingCart, $priceType = false)
 {
     $handlingCosts = new Money();
     $handlingCosts->setAmount(0);
     $handlingCosts->setCurrency(SilvercartConfig::DefaultCurrency());
     if ($priceType === false) {
         $priceType = SilvercartConfig::PriceType();
     }
     if ($this->useSumModification && $this->sumModificationImpact == 'totalValue') {
         $excludedPositions = array();
         switch ($this->sumModificationValueType) {
             case 'percent':
                 $amount = $silvercartShoppingCart->getAmountTotal(array(), false, true);
                 $modificationValue = $amount->getAmount() / 100 * $this->sumModificationValue;
                 $index = 1;
                 foreach ($silvercartShoppingCart->SilvercartShoppingCartPositions() as $position) {
                     if ($position->SilvercartProductID > 0 && $position->SilvercartProduct() instanceof SilvercartProduct && $position->SilvercartProduct()->ExcludeFromPaymentDiscounts) {
                         $modificationValue -= $position->getPrice()->getAmount() / 100 * $this->sumModificationValue;
                         $excludedPositions[] = $index;
                     }
                     $index++;
                 }
                 break;
             case 'absolute':
             default:
                 $modificationValue = $this->sumModificationValue;
         }
         if (count($excludedPositions) > 0) {
             if (count($excludedPositions) == 1) {
                 $this->sumModificationLabel .= ' (' . sprintf(_t('SilvercartPaymentMethod.ExcludedPosition'), implode(', ', $excludedPositions)) . ')';
             } else {
                 $this->sumModificationLabel .= ' (' . sprintf(_t('SilvercartPaymentMethod.ExcludedPositions'), implode(', ', $excludedPositions)) . ')';
             }
         }
         if ($this->sumModificationImpactType == 'charge') {
             $handlingCostAmount = $modificationValue;
         } else {
             $handlingCostAmount = "-" . $modificationValue;
         }
         if (SilvercartConfig::PriceType() == 'gross') {
             $shoppingCartTotal = $silvercartShoppingCart->getAmountTotal(array(), false, true);
         } else {
             $shoppingCartTotal = $silvercartShoppingCart->getAmountTotalNetWithoutVat(array(), false, true);
             $taxRate = $silvercartShoppingCart->getMostValuableTaxRate();
             $handlingCostAmount = round($handlingCostAmount / (100 + $taxRate->Rate) * 100, 4);
         }
         if ($handlingCostAmount < 0 && $shoppingCartTotal->getAmount() < $handlingCostAmount * -1) {
             $handlingCostAmount = $shoppingCartTotal->getAmount() * -1;
         }
         $handlingCosts->setAmount($handlingCostAmount);
     }
     $this->extend('updateChargesAndDiscountsForTotal', $handlingCosts);
     if ($handlingCosts->getAmount() == 0) {
         $handlingCosts = false;
     }
     return $handlingCosts;
 }
 /**
  * Get Amount for this modifier so that it can be saved into an {@link Order} {@link Modification}.
  * 
  * @see Modification
  * @param Order $order
  * @param Int $value ID for a {@link FlatFeeShippingRate} 
  * @return Money
  */
 public function Amount($order, $value)
 {
     $optionID = $value;
     $amount = new Money();
     $currency = Modification::currency();
     $amount->setCurrency($currency);
     $flatFeeShippingRates = DataObject::get('FlatFeeShippingRate');
     if ($flatFeeShippingRates && $flatFeeShippingRates->exists()) {
         $shippingRate = $flatFeeShippingRates->find('ID', $optionID);
         if ($shippingRate) {
             $amount->setAmount($shippingRate->Amount->getAmount());
         } else {
             user_error("Cannot find flat fee rate for that ID.", E_USER_WARNING);
             //TODO return meaningful error to browser in case error not shown
             return;
         }
     }
     return $amount;
 }
示例#13
0
 /**
  * Package the amcount and currency into a Money object.
  * @return Money
  */
 protected function getMoney()
 {
     $money = new Money("Amount");
     $money->setAmount($this->amount);
     $money->setCurrency($this->currency);
     return $money;
 }
 /**
  * Calculate the total paid for this order, only 'Success' payments
  * are considered.
  * 
  * @return Money With value and currency of total paid
  */
 function TotalPaid()
 {
     $paid = 0;
     if ($this->Payments()) {
         foreach ($this->Payments() as $payment) {
             if ($payment->Status == 'Success') {
                 $paid += $payment->Amount->getAmount();
             }
         }
     }
     $totalPaid = new Money();
     $totalPaid->setAmount($paid);
     $totalPaid->setCurrency($this->Total->getCurrency());
     return $totalPaid;
 }
 /**
  * Change product price after it is in the cart, check that price has not changed in cart
  */
 function testAddProductToCartChangePrice()
 {
     $productA = $this->objFromFixture('Product', 'productA');
     $this->logInAs('admin');
     $productA->doPublish();
     $this->logOut();
     $productALink = $productA->Link();
     $this->get(Director::makeRelative($productALink));
     $this->submitForm('AddToCartForm_AddToCartForm', null, array('Quantity' => 1));
     $order = CartControllerExtension::get_current_order();
     $items = $order->Items();
     $firstItem = $items->First();
     $firstProduct = clone $productA;
     $this->assertEquals(1, $order->Items()->Count());
     $this->assertEquals($productA->Amount->getAmount(), $firstItem->Amount->getAmount());
     $this->assertEquals($productA->Amount->getCurrency(), $firstItem->Amount->getCurrency());
     $newAmount = new Money();
     $newAmount->setAmount(72.34);
     $newAmount->setCurrency('NZD');
     $this->logInAs('admin');
     $productA->Amount->setValue($newAmount);
     $productA->doPublish();
     $this->logOut();
     $productALink = $productA->Link();
     $this->get(Director::makeRelative($productALink));
     $this->submitForm('AddToCartForm_AddToCartForm', null, array('Quantity' => 1));
     $order = CartControllerExtension::get_current_order();
     $items = $order->Items();
     $firstItem = $items->First();
     $secondItem = $items->Last();
     $this->assertEquals(2, $order->Items()->Count());
     $this->assertEquals($firstProduct->Amount->getAmount(), $firstItem->Amount->getAmount());
     $this->assertEquals($firstProduct->Amount->getCurrency(), $firstItem->Amount->getCurrency());
     $this->assertEquals($newAmount->getAmount(), $secondItem->Amount->getAmount());
     $this->assertEquals($newAmount->getCurrency(), $secondItem->Amount->getCurrency());
 }
 /**
  * price sum of this position
  *
  * @param boolean $forSingleProduct Indicates wether the price for the total
  *                                  quantity of products should be returned
  *                                  or for one product only.
  * @param boolean $priceType        'gross' or 'net'. If undefined it'll be automatically chosen.
  * 
  * @return Money the price sum
  * 
  * @author Sebastian Diel <*****@*****.**>,
  *         Sascha Koehler <*****@*****.**>
  * @since 19.11.2014
  */
 public function getPrice($forSingleProduct = false, $priceType = false)
 {
     $priceKey = (string) $forSingleProduct . '-' . (string) $priceType;
     if (!array_key_exists($priceKey, $this->prices)) {
         $pluginPriceObj = SilvercartPlugin::call($this, 'overwriteGetPrice', array($forSingleProduct), false, 'DataObject');
         if ($pluginPriceObj !== false) {
             return $pluginPriceObj;
         }
         $product = $this->SilvercartProduct();
         $price = 0;
         if ($product && $product->getPrice($priceType)->getAmount()) {
             if ($forSingleProduct) {
                 $price = $product->getPrice($priceType)->getAmount();
             } else {
                 $price = $product->getPrice($priceType)->getAmount() * $this->Quantity;
             }
         }
         $priceObj = new Money();
         $priceObj->setAmount($price);
         $priceObj->setCurrency(SilvercartConfig::DefaultCurrency());
         $this->extend('updatePrice', $priceObj);
         $this->prices[$priceKey] = $priceObj;
     }
     return $this->prices[$priceKey];
 }
 /**
  * Returns the Price formatted by locale.
  *
  * @return string
  *
  * @author Sascha Koehler <*****@*****.**>
  * @since 31.01.2011
  */
 public function PriceFormatted()
 {
     $priceObj = new Money();
     $priceObj->setAmount($this->getPriceAmount());
     $priceObj->setCurrency($this->price->getCurrency());
     return $priceObj->Nice();
 }
 /**
  * Returns tax amounts included in the shoppingcart separated by tax rates
  * without fee taxes.
  *
  * @param array $excludeModules              An array of registered modules that shall not
  *                                           be taken into account.
  * @param array $excludeShoppingCartPosition Positions that shall not be counted
  *
  * @return ArrayList
  */
 public function getTaxRatesWithoutFeesAndCharges($excludeModules = array(), $excludeShoppingCartPosition = false)
 {
     $positions = $this->SilvercartShoppingCartPositions();
     $taxes = new ArrayList();
     $registeredModules = $this->callMethodOnRegisteredModules('ShoppingCartPositions', array(SilvercartCustomer::currentUser()->getCart(), SilvercartCustomer::currentUser(), true), $excludeModules, $excludeShoppingCartPosition);
     // products
     foreach ($positions as $position) {
         $taxRate = $position->SilvercartProduct()->getTaxRate();
         $originalTaxRate = $position->SilvercartProduct()->getTaxRate(true);
         if (!$taxes->find('Rate', $taxRate)) {
             $taxes->push(new DataObject(array('Rate' => $taxRate, 'OriginalRate' => $originalTaxRate, 'AmountRaw' => (double) 0.0)));
         }
         $taxSection = $taxes->find('Rate', $taxRate);
         $taxSection->AmountRaw += $position->getTaxAmount();
     }
     // Registered Modules
     foreach ($registeredModules as $moduleName => $moduleOutput) {
         foreach ($moduleOutput as $modulePosition) {
             $taxRate = $modulePosition->TaxRate;
             if (!$taxes->find('Rate', $taxRate)) {
                 $taxes->push(new DataObject(array('Rate' => $taxRate, 'OriginalRate' => $taxRate, 'AmountRaw' => (double) 0.0)));
             }
             $taxSection = $taxes->find('Rate', $taxRate);
             $taxAmount = $modulePosition->TaxAmount;
             $taxSection->AmountRaw = round($taxSection->AmountRaw + $taxAmount, 4);
         }
     }
     foreach ($taxes as $tax) {
         $taxObj = new Money();
         $taxObj->setAmount($tax->AmountRaw);
         $taxObj->setCurrency(SilvercartConfig::DefaultCurrency());
         $tax->Amount = $taxObj;
     }
     return $taxes;
 }
 public function testToCurrency()
 {
     $USD = new Money();
     $USD->setCurrency('USD');
     $USD->setLocale('en_US');
     $EGP = new Money();
     $EGP->setCurrency('EGP');
     $EGP->setLocale('ar_EG');
     $USD->setAmount(53292.18);
     $this->assertSame('$53,292.18', $USD->Nice());
     $USD->setAmount(53292.18);
     $this->assertSame('$٥٣,٢٩٢.١٨', $USD->Nice(array('script' => 'Arab')));
     $USD->setAmount(53292.18);
     $this->assertSame('$ ٥٣.٢٩٢,١٨', $USD->Nice(array('script' => 'Arab', 'format' => 'de_AT')));
     $USD->setAmount(53292.18);
     $this->assertSame('$ 53.292,18', $USD->Nice(array('format' => 'de_AT')));
     $EGP->setAmount(53292.18);
     $this->assertSame('ج.م.‏ 53٬292٫18', $EGP->Nice());
     $EGP->setAmount(53292.18);
     $this->assertSame('ج.م.‏ ٥٣٬٢٩٢٫١٨', $EGP->Nice(array('script' => 'Arab')));
     $EGP->setAmount(53292.18);
     $this->assertSame('ج.م.‏ ٥٣.٢٩٢,١٨', $EGP->Nice(array('script' => 'Arab', 'format' => 'de_AT')));
     $EGP->setAmount(53292.18);
     $this->assertSame('ج.م.‏ 53.292,18', $EGP->Nice(array('format' => 'de_AT')));
     $USD = new Money();
     $USD->setLocale('en_US');
     $USD->setAmount(53292.18);
     $this->assertSame('$53,292.18', $USD->Nice());
     /*
     try {
     	$this->assertSame('$ 53,292.18', $USD->Nice('nocontent'));
     	$this->fail("No currency expected");
     } catch (Exception $e) {
     	$this->assertContains("has to be numeric", $e->getMessage());
     }
     */
     $INR = new Money();
     $INR->setLocale('de_AT');
     $INR->setCurrency('INR');
     $INR->setAmount(1.2);
     $this->assertSame('Rs. 1,20', $INR->Nice());
     $INR->setAmount(1);
     $this->assertSame('Re. 1,00', $INR->Nice());
     $INR->setAmount(0);
     $this->assertSame('Rs. 0,00', $INR->Nice());
     $INR->setAmount(-3);
     $this->assertSame('-Rs. 3,00', $INR->Nice());
 }
 /**
  * Get unit price for this item including item options price and quantity.
  * 
  * @return Money Item total inclusive of item options prices and quantity
  */
 public function Total()
 {
     $amount = $this->Amount->getAmount();
     foreach ($this->ItemOptions() as $itemOption) {
         $amount += $itemOption->Amount->getAmount();
     }
     $amount = $amount * $this->Quantity;
     $subTotal = new Money();
     $subTotal->setAmount($amount);
     $subTotal->setCurrency($this->Amount->getCurrency());
     return $subTotal;
 }
示例#21
0
 /**
  * returns carts net value including all editional costs
  *
  * @return Money amount
  * 
  * @deprecated Use property AmountTotal instead
  */
 public function getAmountNet()
 {
     user_error('SilvercartOrder::getAmountNet() is marked as deprecated! Use property AmountTotal instead.', E_USER_ERROR);
     $amountNet = $this->AmountGrossTotal->getAmount() - $this->Tax->getAmount();
     $amountNetObj = new Money();
     $amountNetObj->setAmount($amountNet);
     $amountNetObj->setCurrency(SilvercartConfig::DefaultCurrency());
     return $amountNetObj;
 }
 /**
  * Try to save a Variation with a negative price difference
  * 
  * @see Variation::validate()
  */
 function testNegativeVariationPrice()
 {
     $this->loginAs('admin');
     $smallRedShortsVariation = $this->objFromFixture('Variation', 'shortsSmallRedCotton');
     $originalAmount = $smallRedShortsVariation->Amount;
     $this->assertTrue($originalAmount->getAmount() >= 0);
     $newAmount = new Money();
     $newAmount->setAmount(-1);
     $newAmount->setCurrency($originalAmount->getCurrency());
     $smallRedShortsVariation->Amount = $newAmount;
     $errorMessage = null;
     try {
         $smallRedShortsVariation->write();
     } catch (Exception $e) {
         $errorMessage = $e->getMessage();
     }
     //Make sure there is an error when trying to save
     $this->assertTrue($errorMessage != null);
 }