示例#1
0
 public function addMoney(Money $m)
 {
     if ($this->currency() == $m->currency()) {
         return new Money($this->amount() + $m->amount(), $this->currency());
     }
     return MoneyBag::create($this, $m);
 }
示例#2
0
 /**
  * Converts Money from base to counter currency.
  *
  * @param Money $money
  * @param int   $roundingMode
  *
  * @return Money
  *
  * @throws \InvalidArgumentException If $money's currency is not equal to base currency
  */
 public function convert(Money $money, $roundingMode = Money::ROUND_HALF_UP)
 {
     if (!$money->getCurrency()->equals($this->baseCurrency)) {
         throw new \InvalidArgumentException('The Money has the wrong currency');
     }
     return $money->convert($this->counterCurrency, $this->conversionRatio, $roundingMode);
 }
示例#3
0
 /**
  * @param money $amount
  * @return money
  */
 public function add(Money $amount)
 {
     if (!$this->currency->equals($amount->getCurrency())) {
         throw new \InvalidArgumentException('Currency mismatch');
     }
     return new Money($this->currency, $this->amount + $amount->getValue());
 }
示例#4
0
 public function testShouldFail()
 {
     $a = new Money(9);
     //$b = $a->negate();
     //$this->assertEquals(-9, $b->getAmount());
     $this->assertEquals(-8, $a->getAmount());
 }
 public static function price_for_display($price)
 {
     $currency = ShopConfig::get_site_currency();
     $field = new Money("Price");
     $field->setAmount($price);
     $field->setCurrency($currency);
     return $field;
 }
 /** @return Money */
 public function convert(Money $money)
 {
     if (!$money->getCurrency()->equals($this->counterCurrency)) {
         throw new InvalidArgumentException("The Money has the wrong currency");
     }
     // @todo add rounding mode?
     return new Money((int) round($money->getAmount() * $this->ratio), $this->baseCurrency);
 }
示例#7
0
 public function testCanBeNegated()
 {
     // Arrange
     $a = new Money(1);
     // Act
     $b = $a->negate();
     // Assert
     $this->assertEquals(-1, $b->getAmount());
 }
示例#8
0
 public function testSubstractionResult()
 {
     // Arrange
     $a = new Money();
     // Act
     $b = $a->substraction(2, 1);
     // Assert
     $this->assertEquals(1, $b);
 }
示例#9
0
 public function testAdd()
 {
     // Arrange
     $a = new Money(600);
     // Act
     $a->add(66);
     // Assert
     $this->assertEquals(666, $a->getAmount());
 }
示例#10
0
 /**
  * @covers ::evaluate
  */
 public function testStringAmount()
 {
     $money = new Money();
     $money->setValue(['amount' => '50', 'currency' => 'XTS']);
     $this->assertTrue($money->isValid());
     $obj = $money->evaluate();
     $this->assertInstanceOf('SebastianBergmann\\Money\\Money', $obj);
     $this->assertSame(50, $obj->getAmount());
     $this->assertEquals(new \SebastianBergmann\Money\Currency('XTS'), $obj->getCurrency());
 }
示例#11
0
 public function credit($methodId, $typeId, $marketId, $presenterId, $userId, Money $cost, $entryUser, $referenceId)
 {
     $result = $this->saveCreate(array("ProductCredit" => array("market_id" => $marketId, "user_id" => $userId, "presenter_id" => $presenterId, "product_credit_type_id" => $typeId, "product_credit_entry_type_id" => $methodId, "product_credit_status_type_id" => self::STATUS_SETTLED, "entry_user" => $entryUser, "amount" => (string) $cost->makePositive(), "reference_id" => $referenceId)));
     if ($result) {
         syslog(LOG_DEBUG, "Credit\tLedger {$this->id}\t{$marketId} {$presenterId}\t{$userId}\t{$cost}");
     } else {
         syslog(LOG_DEBUG, "CreditERROR\tLedger\t{$marketId} {$presenterId}\t{$userId}\t{$cost}");
     }
     return $result;
 }
示例#12
0
 /**
  * @param Money    $money
  * @param Currency $counterCurrency
  * @param int      $roundingMode
  *
  * @return Money
  */
 public function convert(Money $money, Currency $counterCurrency, $roundingMode = Money::ROUND_HALF_UP)
 {
     $baseCurrency = $money->getCurrency();
     $ratio = $this->exchange->quote($baseCurrency, $counterCurrency)->getConversionRatio();
     $baseCurrencySubunit = $this->currencies->subunitFor($baseCurrency);
     $counterCurrencySubunit = $this->currencies->subunitFor($counterCurrency);
     $subunitDifference = $baseCurrencySubunit - $counterCurrencySubunit;
     $ratio = $ratio / pow(10, $subunitDifference);
     $counterValue = $money->multiply($ratio, $roundingMode);
     return new Money($counterValue->getAmount(), $counterCurrency);
 }
 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());
 }
示例#14
0
 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());
 }
示例#15
0
 /**
  * @param Money|string|int|float $amount
  * @param int $precision
  * @return string
  */
 public function display($amount, $precision = 2)
 {
     $amount = Utils::toStringAmount($amount);
     $money = new Money($amount);
     if ($this->isLeftSign) {
         if ($money->isLessThan('0')) {
             return '-' . $this->sign . $money->abs()->format($precision);
         } else {
             return $this->sign . $money->format($precision);
         }
     } else {
         return $money->format($precision) . $this->sign;
     }
 }
 /**
  * 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;
 }
 public function testProductCreditSubtractions()
 {
     $presenterId = 1;
     $userId = 1;
     $this->assertEqual($this->ProductCredit->balance($presenterId, $userId), Money::fromFloat(70));
     $transactionId = $this->ProductCredit->authorize(ProductCredit::METHOD_MANUAL, ProductCredit::TYPE_PURCHASE, $presenterId, $userId, Money::fromFloat(20), "Steve", "Manual Subtraction");
     $this->assertEqual($transactionId !== false, true);
     $productCredit = $this->ProductCredit->findById($transactionId);
     unset($productCredit['ProductCredit']['id']);
     unset($productCredit['ProductCredit']['modified']);
     unset($productCredit['ProductCredit']['created']);
     $this->assertArraysEqual($productCredit, array('ProductCredit' => array('user_id' => '1', 'presenter_id' => '1', 'product_credit_type_id' => '4', 'product_credit_entry_type_id' => '2', 'product_credit_status_type_id' => '1', 'entry_user' => 'Steve', 'reference_id' => 'Manual Subtraction', 'amount' => '-20.00')));
     //Doesn't have enough money
     $this->assertEqual($this->ProductCredit->balance($presenterId, $userId), Money::fromFloat(50));
     $result = $this->ProductCredit->authorize(ProductCredit::METHOD_MANUAL, ProductCredit::TYPE_PURCHASE, $presenterId, $userId, Money::fromFloat(90), "Steve", "Manual Subtraction");
     $this->assertEqual($result, false);
     $this->assertEqual($this->ProductCredit->balance($presenterId, $userId), Money::fromFloat(50));
     //Doesn't have enough money, but somehow hacked around it
     // now you can set your expectations here
     $this->ProductCreditBadBalance->expects($this->at(0))->method('balance')->will($this->returnValue(Money::fromFloat(30000)));
     $this->ProductCreditBadBalance->expects($this->at(1))->method('balance')->will($this->returnValue(Money::fromFloat(-200)));
     $result = $this->ProductCreditBadBalance->authorize(ProductCredit::METHOD_MANUAL, ProductCredit::TYPE_PURCHASE, $presenterId, $userId, Money::fromFloat(90), "Steve", "Manual Subtraction");
     $this->assertEqual($result, false);
     $this->assertEqual($this->ProductCredit->balance($presenterId, $userId), Money::fromFloat(50));
     $productCredit = $this->ProductCredit->find("first", array("order" => "id desc"));
     unset($productCredit['ProductCredit']['id']);
     unset($productCredit['ProductCredit']['modified']);
     unset($productCredit['ProductCredit']['created']);
     $this->assertArraysEqual($productCredit, array('ProductCredit' => array('user_id' => '1', 'presenter_id' => '1', 'product_credit_type_id' => '4', 'product_credit_entry_type_id' => '2', 'product_credit_status_type_id' => '3', 'entry_user' => 'Steve', 'reference_id' => 'Manual Subtraction', 'amount' => '-90.00')));
 }
示例#18
0
 public function __construct($data = [], $connection = null)
 {
     $this->connection = $connection;
     foreach (['id', 'order_reference', 'shop_system', 'customer_number', 'service_point_reference', 'weight_in_g'] as $prop) {
         if (isset($data[$prop])) {
             $this->{$prop} = $data[$prop];
         }
     }
     foreach (['recipient', 'billing_contact'] as $prop) {
         $this->{$prop} = isset($data[$prop]) ? new Address($data[$prop]) : null;
     }
     foreach (['subtotal', 'shipping_cost', 'tax_value'] as $prop) {
         $this->{$prop} = isset($data[$prop]) ? Money::import($data[$prop]) : null;
     }
     $this->product = isset($data['product']) ? new Product($data['product'], $this->connection) : null;
     if (isset($data['items'])) {
         $this->items = [];
         foreach ($data['items'] as $item_data) {
             $this->items[] = new Item($item_data);
         }
     }
     if (isset($data['shipments'])) {
         $this->shipments = [];
         foreach ($data['shipments'] as $url) {
             $this->shipments[] = Shipment::import($url, $this->connection);
         }
     }
 }
 /**
  * Get Totals for order with previous/current month totals
  * @param $Model
  * @return array
  */
 public function partyOrderTotals($Model)
 {
     /**
      * Fields
      */
     if ($Model->hostess_market_id == Market::MARKET_UNITED_KINGDOM) {
         $fields = array('sum(Order.market_commissionable) as total, sum(Order.point_total) as points');
     } else {
         $fields = array('sum(Order.presenter_commissionable) as total, sum(Order.point_total) as points');
     }
     /**
      * Order status conditions
      */
     $status = array(Order::STATUS_ENTERED, Order::STATUS_PRINTED, Order::STATUS_SHIPPED, Order::STATUS_PROCESSING);
     /**
      * Order Total points
      */
     $total = $Model->Order->find('first', array('fields' => $fields, 'conditions' => array('Order.party_id' => $Model->id, "Order.order_status_id" => $status)));
     /**
      * Order Double points
      */
     $prev_total = $Model->Order->find('first', array('fields' => $fields, 'conditions' => array('Order.party_id' => $Model->id, 'MONTH(Order.date_completed)' => 2, "Order.order_status_id" => $status)));
     $points = (int) $total['0']['points'];
     $double_points = (int) $prev_total['0']['points'];
     /**
      * Returns array with previous month and current month points
      */
     return array("total" => Money::fromString($total['0']['total']), "points" => $points, "double_points" => $double_points, "regular_points" => $points - $double_points);
 }
 public function testAddNoUser()
 {
     $this->assertEqual($this->ShoppingCart->addItem("US-1001-00", array("qty" => 1)), array("success" => true, "count" => 1));
     $this->assertEqual($this->ShoppingCart->addItem("US-1012-00", array("qty" => 5, "US-1011-00" => array("skus" => array("US-1011-03" => 1, "US-1011-04" => 1, "US-1011-05" => 1, "US-1011-06" => 1)))), array("success" => true, "count" => 2));
     $this->assertEqual($this->ShoppingCart->getCart(), array("total" => array("subtotal" => Money::fromFloat(274), "taxes" => Money::fromFloat(0), "shipping" => Money::fromFloat(0), "total" => Money::fromFloat(274), "commissionable_total" => Money::fromFloat(274), 'productcredits' => Money::fromFloat(0), 'charge' => Money::fromFloat(274), 'usedCoupons' => array(), 'totalItemCount' => 6, 'toFreeShipping' => Money::fromFloat(-174)), "0" => array("item_id" => '1', 'sku' => 'US-1001-00', "name" => "Presenter Starter Kit", "quantity" => 1, "price" => Money::fromFloat(99.0), "subtotal" => Money::fromFloat(99.0), "taxes" => Money::fromFloat(0), "originalsubtotal" => Money::fromFloat(99.0), "discount" => Money::fromFloat(0), "discounts" => array(), "shipping" => Money::fromFloat(10), "total" => Money::fromFloat(99.0), 'image' => array('name' => 'Main', 'thumb_path' => '/img/product_images/fake_thumb.jpg', 'file_path' => '/img/product_images/fake_main.jpg'), "included" => array(), 'options' => array()), "1" => array("item_id" => '3', 'sku' => 'US-1012-00', "name" => "Minerals Pigment Set", "quantity" => 5, "price" => Money::fromFloat(35.0), "subtotal" => Money::fromFloat(175), "taxes" => Money::fromFloat(0), "shipping" => Money::fromFloat(5.0), "total" => Money::fromFloat(175), "originalsubtotal" => Money::fromFloat(175), "discount" => Money::fromFloat(0), "discounts" => array(), 'image' => array('name' => 'Main', 'thumb_path' => '/img/product_images/US-1011-00-thumb.png', 'file_path' => '/img/product_images/US-1011-00.jpg'), 'included' => array(array('name' => 'Sassy', 'shortname' => 'Sassy', 'id' => '7', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-03', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-03-thumb.jpg', 'file_path' => '/img/product_images/US-1011-03.jpg')), array('name' => 'Regal', 'shortname' => 'Regal', 'id' => '8', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-04', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-04-thumb.jpg', 'file_path' => '/img/product_images/US-1011-04.jpg')), array('name' => 'Flirty', 'shortname' => 'Flirty', 'id' => '9', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-05', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-05-thumb.jpg', 'file_path' => '/img/product_images/US-1011-05.jpg')), array('name' => 'Playful', 'shortname' => 'Playful', 'id' => '10', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-06', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-06-thumb.jpg', 'file_path' => '/img/product_images/US-1011-06.jpg'))), 'options' => array('US-1011-00' => array('skus' => array('US-1011-03' => 1, 'US-1011-04' => 1, 'US-1011-05' => 1, 'US-1011-06' => 1))))));
     $this->assertEqual($this->ShoppingCart->getCart("84003"), array("total" => array("subtotal" => Money::fromFloat(274), "taxes" => Money::fromFloat(18.5), "shipping" => Money::fromFloat(0), "total" => Money::fromFloat(292.5), "commissionable_total" => Money::fromFloat(274), 'productcredits' => Money::fromFloat(0), 'charge' => Money::fromFloat(292.5), 'usedCoupons' => array(), 'totalItemCount' => 6, 'toFreeShipping' => Money::fromFloat(-174)), "0" => array("item_id" => 1, 'sku' => 'US-1001-00', "name" => "Presenter Starter Kit", "quantity" => 1, "price" => Money::fromFloat(99.0), "subtotal" => Money::fromFloat(99.0), "taxes" => Money::fromFloat(6.68), "shipping" => Money::fromFloat(10), "originalsubtotal" => Money::fromFloat(99.0), "discount" => Money::fromFloat(0), "discounts" => array(), "total" => Money::fromFloat(105.68), 'image' => array('name' => 'Main', 'thumb_path' => '/img/product_images/fake_thumb.jpg', 'file_path' => '/img/product_images/fake_main.jpg'), "included" => array(), 'options' => array()), "1" => array("item_id" => 3, 'sku' => 'US-1012-00', "name" => "Minerals Pigment Set", "quantity" => 5, "price" => Money::fromFloat(35.0), "subtotal" => Money::fromFloat(175), "taxes" => Money::fromFloat(11.81), "shipping" => Money::fromFloat(5.0), "total" => Money::fromFloat(186.81), "originalsubtotal" => Money::fromFloat(175), "discount" => Money::fromFloat(0), "discounts" => array(), 'image' => array('name' => 'Main', 'thumb_path' => '/img/product_images/US-1011-00-thumb.png', 'file_path' => '/img/product_images/US-1011-00.jpg'), "included" => array(array('name' => 'Sassy', 'shortname' => 'Sassy', 'id' => '7', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-03', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-03-thumb.jpg', 'file_path' => '/img/product_images/US-1011-03.jpg')), array('name' => 'Regal', 'shortname' => 'Regal', 'id' => '8', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-04', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-04-thumb.jpg', 'file_path' => '/img/product_images/US-1011-04.jpg')), array('name' => 'Flirty', 'shortname' => 'Flirty', 'id' => '9', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-05', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-05-thumb.jpg', 'file_path' => '/img/product_images/US-1011-05.jpg')), array('name' => 'Playful', 'shortname' => 'Playful', 'id' => '10', 'item_type_id' => '1', 'children_qty_required' => null, 'qty_required' => null, 'qty_purchased' => (int) 1, 'sku' => 'US-1011-06', 'image' => array('name' => 'main', 'thumb_path' => '/img/product_images/US-1011-06-thumb.jpg', 'file_path' => '/img/product_images/US-1011-06.jpg'))), 'options' => array('US-1011-00' => array('skus' => array('US-1011-03' => 1, 'US-1011-04' => 1, 'US-1011-05' => 1, 'US-1011-06' => 1))))));
 }
 public function testProcessOrderLedgerPayments()
 {
     PHPUnit_Framework_Error_Warning::$enabled = FALSE;
     $result = $this->Payment->processOrderPayments("Test Order #13123", array(array("type" => "ledger", "presenter_id" => 1, "user_id" => 1, "amount" => Money::fromFloat(60)), array("type" => "creditcard", "amount" => Money::fromFloat(30), "cardholder" => "Test wohoo", "billingzip" => "84003", "cardnum" => "4068758923310472", "carexp" => "12/2015", "cardcode" => "962")));
     $this->assertTrue($result['success']);
     $this->assertTrue(!empty($result['payments'][0]['transaction_id']) && strlen($result['payments'][0]['transaction_id']) == 17);
 }
 public function orderCreate($country_id, $presenterId, $userId, $hostmarket_id, $partyId)
 {
     $address = array("first_name" => "testing", "last_name" => "last", "address1" => "Some address 1", "address2" => "Some address 2", "address3" => "Some address 3", "city" => "Awesome city", "state_id" => 20, "postal_code" => "84003", "email_address" => "*****@*****.**", "country_id" => $country_id);
     $promoterId = 2;
     //$presenterId = 141683; // from presenter , we get market_id for orders
     $items = array(array("sku" => "US-2005-00", "qty" => 1, options => array("US-1092-00" => array("skus" => array("US-1082-01" => 1, "US-1083-03" => 1)))));
     $coupons = array();
     $productCredits = Money::fromFloat(0.0);
     //20.00//29.00//29.00//45.00//29.00//90.00//75.00//175.00//58.00
     //$prices = $this->Order->getOrderCosts($address['postal_code'], $items,null, $coupons);
     $prices = $this->Order->getOrderCosts($address['postal_code'], $items, $productCredits, $coupons);
     //$prices = $this->getOrderCosts($address['country_id'], $items,null, $coupons);
     //echo "<pre>";
     //print_r($prices);exit;
     $insert_order = TRUE;
     //    $result = $this->createOrder($promoterId, $presenterId, $userId, $partyId, $items, $address,Order::TYPE_PRODUCT,null, $coupons,FALSE,$insert_order);
     $result = $this->Order->createOrder($promoterId, $presenterId, $userId, $partyId, $items, $address, Order::TYPE_PRODUCT, $productCredits, $coupons, FALSE);
     //    $result = $this->Order->createOrder($promoterId, $presenterId, $userId, $partyId, $items, $address,Order::TYPE_PRODUCT,$productCredits, $coupons,FALSE);//$insert_order
     $orderId = $this->Order->id;
     debug($orderId);
     //  debug($result);
     //   exit;
     $orderPaymentResult = array("success" => false, "payments" => array(array('type' => 'creditcard', 'amount' => $prices['total']['total'], "transaction_id" => "Wohootest", "identifier" => "3123", 'cardholder' => 'Test wohoo', 'billingzip' => '84003', 'cardnum' => '123123123', 'carexp' => '12/2015', 'cardcode' => '962', 'status' => 'failed')));
     $result = $this->Order->finalize($orderPaymentResult);
     debug($prices['total']['total']);
     $orderPaymentResult = array("success" => true, "payments" => array(array('type' => 'creditcard', 'transaction_id' => 'Wohootest', 'amount' => $prices['total']['total'], 'cardholder' => 'Test wohoo', 'billingzip' => '84003', 'cardnum' => '123123123', 'carexp' => '12/2015', 'cardcode' => '962', 'status' => 'success', "identifier" => "3123")));
     $result = $this->Order->finalize($orderPaymentResult);
     return $orderId;
 }
示例#23
0
 public function __construct($data = [])
 {
     foreach (['id', 'description', 'sku', 'weight_in_g', 'quantity'] as $prop) {
         if (isset($data[$prop])) {
             $this->{$prop} = $data[$prop];
         }
     }
     $this->value = isset($data['value']) ? Money::import($data['value']) : null;
 }
示例#24
0
 function create($ctx)
 {
     _render('form');
     if (isset($_POST['f']) && $_POST['f']) {
         $_POST['f']['create_time'] = date('Y-m-d H:i:s');
         $_POST['f']['pay_amount'] = Money::yuan2fen($_POST['f']['pay_amount']);
         Tactics::save($_POST['f']);
         _redirect($this->_list_url());
     }
 }
示例#25
0
 public static function currency($value, $decimal = 0, $country = NULL, $vat = FALSE)
 {
     switch ($country) {
         case "id":
             $money = new Money("Rp ", 0.1, ",", ".");
             break;
         case "us":
             $money = new Money("\$ ", 0.2, ".", ",");
             break;
         default:
             $money = new Money("");
     }
     $money->setDecimal(0);
     if (strip_tags(!isset($_POST['export']))) {
         return $money->display($value);
     } else {
         return $value;
     }
 }
 /**
  * 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;
 }
示例#27
0
 /**
  * @param Money $price
  * @param User $bidder
  */
 public function addBid(Money $price, User $bidder)
 {
     if ($this->owner->equals($bidder)) {
         throw new InvalidArgumentException("You may not bid on your own auction");
     }
     if (!$this->currentPrice->isLessThan($price)) {
         throw new InvalidArgumentException("Your bid must be higher than the current");
     }
     if ($this->wasEnded()) {
         throw new LogicException("You may not bid on a ended auction");
     }
     $this->currentPrice = $price;
 }
示例#28
0
 public function testIsGreaterThan()
 {
     $base = Money::fromPennies(1000);
     $less = Money::fromPennies(999.99);
     $equal = Money::fromPennies(1000);
     $more = Money::fromPennies(1001);
     $this->assertFalse($less->isEqualOrGreaterThan($base));
     $this->assertFalse($less->isGreaterThan($base));
     $this->assertTrue($equal->isEqualOrGreaterThan($base));
     $this->assertFalse($equal->isGreaterThan($base));
     $this->assertTrue($more->isEqualOrGreaterThan($base));
     $this->assertTrue($more->isGreaterThan($base));
 }
示例#29
0
 public function main()
 {
     $db = ConnectionManager::getDataSource('default');
     $result = $db->query("Select date_sub(now(), interval 2 second) as timestamp");
     $twoSecondsAgo = $result[0][0]["timestamp"];
     $since = $this->SystemSetting->getSystemSetting("commission_load", "0000-00-00");
     $newPresenters = $this->Presenter->findChanges($twoSecondsAgo, $since);
     foreach ($newPresenters as $presenter) {
         $eligibleRaceToStart = $presenter['Presenter']['default_locale'] == 'es_US';
         if ($eligibleRaceToStart) {
             $result = $this->AdminUserAudit->query("Select count(*) as changes\r\n                    from admin_user_audits\r\n                    Where reference_id = " . (int) $presenter['Presenter']['id'] . " and reference_name = 'presenters.default_locale' and notes = 'Admin3 sponsor default locale change' ");
             if ($result[0][0]['changes'] == 0) {
                 $eligibleRaceToStart = true;
             } else {
                 $eligibleRaceToStart = false;
             }
         }
         //getTypeId requires presenter_sequence_id
         $presenterRank = $this->PresenterType->getRecognizedStatus($presenter['Presenter']['id']);
         if ($presenterRank['id'] >= 8) {
             //To get on the Wall of Influence in USD, earn 83333.33 in one month. Alter for other markets
             $goalForWall = $this->Market->getPayPegRate($presenter['Presenter']['market_id']) * 83333.33;
             $wallInfluence = $this->RoyaltiesEarned->isWallInfluence($presenter['Presenter']['id'], $goalForWall);
         } else {
             $wallInfluence = false;
         }
         $result = CommissionAPI::write("presenter/" . $presenter['Presenter']['id'], array("parentId" => $presenter['Presenter']['id'] == 1 ? 0 : $presenter['Presenter']['sponsor_id'], "date" => date("c", strtotime($presenter['Presenter']['consent_to_agreements'])), "name" => $presenter['User']['first_name'] . " " . $presenter['User']['last_name'], "presenter_id" => $presenter['Presenter']['presenter_sequence_id'], "image" => $presenter['User']['largeimage'], "terminated_date" => $presenter['Presenter']['terminated_date'], "timestamp" => date("c", strtotime($presenter['Presenter']['_auditdate'])), "cat1" => $eligibleRaceToStart ? $presenter['Presenter']['default_locale'] : '', "wallInfluence" => $wallInfluence));
     }
     $newOrders = $this->Order->findChanges($twoSecondsAgo, $since);
     foreach ($newOrders as $order) {
         $presenterId = $order['Order']['presenter_id'];
         if ($presenterId == 0) {
             continue;
         }
         $status = "rejected";
         //if(in_array($order['Order']['order_status_id'], array(3,4,5,8))) { MIKEFIX
         if ($this->Order->isCommissionable($order['Order']['order_status_id'])) {
             $status = "accepted";
         }
         $result = CommissionAPI::write("order/" . $order['Order']['id'], array("parentId" => $presenterId, "state" => $status, "date" => date("c", strtotime($order['Order']['date_completed'])), "retail" => Money::fromString($order['Order']['commissionable_total'])->intVal(), "wholesale" => Money::fromString($order['Order']['commissionable_total'])->times(0.75)->intVal(), "timestamp" => date("c", strtotime($order['Order']['_auditdate']))));
     }
     $this->SystemSetting->saveSetting("commission_load", $twoSecondsAgo);
     print "Done";
 }
示例#30
0
 public function calculateRewards(Money $amount, $points, $hostess_market_id)
 {
     $reward = $this->find("first", array("conditions" => array("points_min <=" => $points), "order" => "points_min desc"));
     // 		$excess = $amount->toFloat() - (float)$reward['PartyReward']['price_min'];
     // 		$range = (float)$reward['PartyReward']['price_max'] - (float)$reward['PartyReward']['price_min'];
     $excess = $points - (int) $reward['PartyReward']['points_min'];
     $range = (int) $reward['PartyReward']['points_max'] - (double) $reward['PartyReward']['points_min'];
     if ($range <= 0) {
         $ratio = "0";
     } else {
         $ratio = round($excess / $range, 2) + (int) $reward['PartyReward']['half_price_coupons'];
     }
     $product_credit_percentage = (int) $reward['PartyReward']['product_credit_percentage'] / 100;
     $rewards = $this->calculateRewardPoints($points, $hostess_market_id, $product_credit_percentage);
     //Kudos Start
     //$kudosData = $this->Kudos->checkPartyPoints($points);
     //Kudos End
     return array("Order Total" => $amount, "Points Total" => $rewards['Party Points'], "Points Needed" => (int) $reward['PartyReward']['points_max'] - $points + 1, "Progress Ratio" => $ratio, "Reward Points" => $rewards['Reward Points'], "Reward Peg Rates" => $this->rewardPegRates, "Free Product" => $reward['PartyReward']['product_credit_percentage'] . "%", "Free Product Credits" => $rewards['Free Product Credits'], "Half-Price Items" => $reward['PartyReward']['half_price_coupons'], "free_product_credits" => Money::fromFloat($rewards['Free Product Credits']), "half_price_item" => $reward['PartyReward']['half_price_coupons']);
 }