public function getCartItem()
 {
     $cart_item = new CartItem($this->getNodeId());
     $cart_item->setDescription($this->getTitle());
     $cart_item->setAttribute('image_id', $this->getAttribute('image_id'));
     return $cart_item;
 }
 /**
  * Exports the object as an array.
  *
  * You can specify the key type of the array by passing one of the class
  * type constants.
  *
  * @param     string  $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME,
  *                    TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
  *                    Defaults to TableMap::TYPE_PHPNAME.
  * @param     boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE.
  * @param     array $alreadyDumpedObjects List of objects to skip to avoid recursion
  * @param     boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE.
  *
  * @return array an associative array containing the field names (as keys) and field values
  */
 public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false)
 {
     if (isset($alreadyDumpedObjects['LegacyCartItemAttributeCombination'][serialize($this->getPrimaryKey())])) {
         return '*RECURSION*';
     }
     $alreadyDumpedObjects['LegacyCartItemAttributeCombination'][serialize($this->getPrimaryKey())] = true;
     $keys = LegacyCartItemAttributeCombinationTableMap::getFieldNames($keyType);
     $result = array($keys[0] => $this->getCartItemId(), $keys[1] => $this->getAttributeId(), $keys[2] => $this->getAttributeAvId());
     $virtualColumns = $this->virtualColumns;
     foreach ($virtualColumns as $key => $virtualColumn) {
         $result[$key] = $virtualColumn;
     }
     if ($includeForeignObjects) {
         if (null !== $this->aCartItem) {
             $result['CartItem'] = $this->aCartItem->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true);
         }
         if (null !== $this->aAttribute) {
             $result['Attribute'] = $this->aAttribute->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true);
         }
         if (null !== $this->aAttributeAv) {
             $result['AttributeAv'] = $this->aAttributeAv->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true);
         }
     }
     return $result;
 }
Exemple #3
0
 public function getShippingCost($sessionId = null, $cartItems = null)
 {
     $session = Session::getActiveSession($sessionId);
     $sessionId = $session->getId();
     if (!is_array($cartItems)) {
         $cartItems = CartItem::getAll($sessionId);
     }
     return $this->calculateCost($session, $cartItems);
 }
Exemple #4
0
 public function loadItem()
 {
     if (empty($_POST['item_id'])) {
         throw new CHttpException(400, 'Bad Request!.');
     }
     $item = CartItem::model()->with('skus')->findByPk(intval($_POST['item_id']));
     if (empty($item)) {
         throw new CHttpException(400, 'Bad Request!.');
     }
     $item->cartProps = empty($_POST['props']) ? '' : $_POST['props'];
     return $item;
 }
Exemple #5
0
 public function checkout()
 {
     $cart = Cart::where('user_id', Auth::user()->id)->first();
     $items = $cart->cartItems;
     foreach ($items as $item) {
         CartItem::destroy($item->id);
         $productID = $item['product_id'];
         $product = Product::where('id', $productID)->first();
         if ($product->stock > 0) {
             $newStock = $product->stock;
             $newStock -= 1;
             Product::where('id', $productID)->update(['stock' => $newStock]);
             $purchase = new Purchase();
             $purchase->user_id = Auth::user()->id;
             $purchase->product_id = $productID;
             $purchase->save();
         }
     }
     $products = Product::all();
     return view('main.index', ['products' => $products]);
 }
Exemple #6
0
 public function getPaymentForm()
 {
     $form = new Form('payment_form', 'payment_form', '/Store/Payment');
     $paypalHost = 'https://' . $this->hostName . '/cgi-bin/webscr';
     $form->updateAttributes(array('action' => $paypalHost));
     $form->updateAttributes(array('onSubmit' => "return checkBeforePayment()"));
     $tid = @$_SESSION['ECommTID'];
     if ($tid) {
         $transaction = Transaction::getTransactionBasedOnTID($tid);
         $sessionId = $transaction->getSession();
         $session = Session::getActiveSession($sessionId);
         $cartItems = CartItem::getAll($sessionId);
         //$form->setConstants( array ( 'cmd' => '_cart' ) );
         $form->setConstants(array('cmd' => '_xclick'));
         $form->addElement('hidden', 'cmd');
         $form->setConstants(array('upload' => 1));
         $form->addElement('hidden', 'upload');
         //Set the ID of the transaction for this order
         $form->setConstants(array('custom' => $tid));
         $form->addElement('hidden', 'custom');
         $form->setConstants(array('currency_code' => SiteConfig::get("EComm::Currency")));
         $form->addElement('hidden', 'currency_code');
         $form->setConstants(array('business' => $this->accountEmail));
         $form->addElement('hidden', 'business');
         $form->setConstants(array('return' => "http://" . $_SERVER['HTTP_HOST'] . "/Store/IPN/&action=OrderComplete&tid={$tid}"));
         $form->addElement('hidden', 'return');
         $cartDetails = Module_EComm::getCartDetails($sessionId, $cartItems);
         $form->setConstants(array('amount' => $cartDetails["subTotal"]));
         $form->addElement('hidden', 'amount');
         $form->setConstants(array('shipping' => $cartDetails["shipping"]));
         $form->addElement('hidden', 'shipping');
         $form->setConstants(array('tax' => $cartDetails["tax"]));
         $form->addElement('hidden', 'tax');
     }
     $form->addElement('image', 'cart_submit', 'https://www.paypal.com/en_US/i/btn/x-click-but23.gif');
     return $form->display();
 }
 public static function create_from_object($object, $cart)
 {
     $item = new CartItem();
     $item->cart_id = $cart->id;
     $item->object_id = $object->id;
     $item->object_class = get_class($object);
     if (is_a($object, "EventSignup")) {
         $item->description = "{$object->event->name} {$object->event_ticket->name} Ticket (Booking ID: {$object->id})";
     } elseif (is_a($object, "EventService")) {
         $item->description = $object->service->name;
     }
     $item->save();
     return $item;
 }
Exemple #8
0
 /**
  * Add an item within an order
  *
  * @param Cart $item
  * @throws Exception
  * @return unknown
  */
 public static function addOrderItem(CartItem $item)
 {
     if (empty(self::$order)) {
         throw new Exception('The order has not been created yet', 1000);
     }
     try {
         // get the item subtotals
         $subtotals = $item->getSubtotals();
         // get the options
         $options = $item->getOptions();
         // Get the order object previously created
         $order = self::$order;
         // add a new item
         $orderitem = new OrdersItems();
         $orderitem->order_id = $order['order_id'];
         if ("domain" == $item->getType()) {
             // Create a new domain order item
             $orderitem->tld_id = !empty($options['domain']['tld']) ? $options['domain']['tld'] : null;
             $orderitem->parameters = json_encode($options);
         } else {
             $orderitem->product_id = $item->getId();
             $orderitem->parameters = json_encode(ProductsAttributes::getSystemAttributes($item->getId()));
         }
         $orderitem->status_id = Statuses::id("tobepaid", "orders");
         $orderitem->date_start = date('Y-m-d H:i:s');
         $orderitem->date_end = null;
         $orderitem->description = $item->getName();
         $orderitem->quantity = $item->getQty();
         $orderitem->price = $item->getUnitprice();
         $orderitem->billing_cycle_id = $item->getBillingid();
         $orderitem->vat = $subtotals['taxes'];
         $orderitem->percentage = $subtotals['percentage'];
         $orderitem->uuid = $item->getUid();
         // Count of the day until the expiring
         if ($item->getIsrecurring()) {
             // get the months until of the next service expiration
             $months = $subtotals['months'];
             if ($months > 0) {
                 $totmonths = intval($item->getQty() * $months);
                 // Calculate the total of the months
                 $date_end = Shineisp_Commons_Utilities::add_date(date('d-m-Y H:i:s'), null, $totmonths);
                 $orderitem->date_end = Shineisp_Commons_Utilities::formatDateIn($date_end);
             } else {
                 $orderitem->date_end = null;
             }
         }
         $orderitem->cost = $item->getCost();
         $orderitem->setupfee = $subtotals['setupfee'];
         $orderitem->subtotal = $subtotals['subtotal'];
         // Save the order item
         if ($orderitem->trySave()) {
             // Attach all the the domain to the order
             if ("domain" == $item->getType()) {
                 $domain = $options['domain']['name'];
                 $tld = $options['domain']['tld'];
                 $domainId = Domains::Create($domain, $tld, $order->customer_id, $orderitem->detail_id);
                 if (is_numeric($domainId)) {
                     $ordersitemsdomains = new OrdersItemsDomains();
                     $ordersitemsdomains->domain_id = $domainId;
                     $ordersitemsdomains->order_id = $order['order_id'];
                     $ordersitemsdomains->orderitem_id = $orderitem->detail_id;
                     $ordersitemsdomains->save();
                 }
             }
             // Update the totals of the order
             self::updateTotalsOrder($order['order_id']);
             return $orderitem;
         }
     } catch (Exception $e) {
         Shineisp_Commons_Utilities::log('There was a problem during the order creation: ' . $e->getMessage());
     }
     return false;
 }
Exemple #9
0
 /**
  * Calculates pending order qty to count against available
  * inventory by searching for Requested or Awaiting Processing orders
  * Because we have our cart table and our documents table, we have to get both numbers
  */
 public function CalculateReservedInventory()
 {
     //Pending orders not yet converted to Invoice
     $intReservedA = $this->getDbConnection()->createCommand("SELECT SUM(qty) FROM " . CartItem::model()->tableName() . " AS a\n\t\t\t\t\tLEFT JOIN " . Cart::model()->tableName() . " AS b ON a.cart_id=b.id\n\t\t\t\t\tLEFT JOIN " . Document::model()->tableName() . " AS c ON b.document_id=c.id\n\t\t\t\t\tWHERE\n\t\t\t\t\ta.product_id=" . $this->id . " AND b.cart_type=" . CartType::order . "\n\t\t\t\t\tAND (b.status='" . OrderStatus::Requested . "' OR b.status='" . OrderStatus::AwaitingProcessing . "'\n\t\t\t\t\t\tOR b.status='" . OrderStatus::Downloaded . "')\n\t\t\t\t\tAND (c.status IS NULL OR c.status='" . OrderStatus::Requested . "');")->queryScalar();
     if (empty($intReservedA)) {
         $intReservedA = 0;
     }
     //Unattached orders (made independently in Lightspeed)
     $intReservedB = $this->getDbConnection()->createCommand("SELECT SUM(qty) from " . DocumentItem::model()->tableName() . " AS a\n\t\t\t\t\tLEFT JOIN " . Document::model()->tableName() . " AS b ON a.document_id=b.id\n\t\t\t\t\tWHERE\n\t\t\t\t\ta.product_id=" . $this->id . " AND b.order_type=" . CartType::order . "\n\t\t\t\t\tAND cart_id IS NULL AND left(order_str,3)='WO-' AND (b.status='" . OrderStatus::Requested . "');")->queryScalar();
     if (empty($intReservedB)) {
         $intReservedB = 0;
     }
     return $intReservedA + $intReservedB;
 }
 public function actionDeleteitem()
 {
     if (Yii::app()->user->isGuest) {
         _xls_404();
     }
     $model = new WishlistEditForm();
     if (isset($_POST['WishlistEditForm'])) {
         $model->attributes = $_POST['WishlistEditForm'];
         if ($model->validate()) {
             $strCode = $model->code;
             $intRow = $model->id;
             //Make sure code we've been passed is valid
             $objWishlist = Wishlist::model()->findByAttributes(array('gift_code' => $strCode));
             if (!$objWishlist->Visible) {
                 _xls_404();
             }
             $objWishrow = WishlistItem::model()->findByAttributes(array('id' => $intRow, 'registry_id' => $objWishlist->id));
             if (!is_null($objWishrow->cart_item_id)) {
                 CartItem::model()->updateByPk($objWishrow->cart_item_id, array('wishlist_item' => null));
             }
             if (!$objWishrow->delete()) {
                 Yii::log('Error deleting wish list item ' . print_r($objWishrow->getErrors(), true), 'error', 'application.' . __CLASS__ . '.' . __FUNCTION__);
                 $response_array['status'] = 'error';
                 $response_array['errormsg'] = print_r($objWishrow->getErrors(), true);
             } else {
                 $response_array = array('status' => "success", 'code' => $objWishlist->gift_code, 'id' => $objWishrow->id, 'reload' => true);
             }
         } else {
             $response_array['status'] = 'error';
             $response_array['errormsg'] = print_r($model->getErrors(), true);
         }
         echo json_encode($response_array);
     }
 }
 public function cart_items($reload = true)
 {
     if ($reload || !$this->cart_items_cache) {
         $id = mysql_real_escape_string($this->id);
         $this->cart_items_cache = CartItem::find_all("cart_items.object_class = 'EventService' AND cart_items.object_id = '{$id}'");
     }
     return $this->cart_items_cache;
 }
 /**
  * Remove product
  *
  * @param string $passkey
  * @param string $intRowid
  * @return string
  */
 public function remove_product($passkey, $intRowid)
 {
     if (!$this->check_passkey($passkey)) {
         return self::FAIL_AUTH;
     }
     $product = Product::Load($intRowid);
     if (!$product) {
         //_xls_log("SOAP ERROR : Product id does not exist $intRowid .");
         //We were asked to delete a product that was apparently already deleted, so just ignore
         return self::OK;
     }
     try {
         $this->remove_product_images($passkey, $intRowid);
         $this->remove_product_qty_pricing($passkey, $intRowid);
         $this->remove_related_products($passkey, $intRowid);
         $gifts = GiftRegistryItems::LoadArrayByProductId($intRowid);
         foreach ($gifts as $gift) {
             $gift->Delete();
         }
         $citems = CartItem::LoadArrayByProductId($intRowid);
         foreach ($citems as $item) {
             if ($item->Cart && in_array($item->Cart->Type, array(CartType::cart, CartType::giftregistry, CartType::quote, CartType::saved))) {
                 $item->Delete();
             }
         }
         $product->Delete();
     } catch (Exception $e) {
         Yii::log("SOAP ERROR : Error deleting Product " . $product->code . " " . $e, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
         return self::UNKNOWN_ERROR;
     }
     return self::OK;
 }
 public function testNullDescription()
 {
     $cartItem = new CartItem('foo name', 1, 99);
     $this->assertNull($cartItem->getDescription());
 }
 /**
  * Product lookup and optional delete, shows inventory numbers
  */
 public function actionProducts()
 {
     if (isset($_POST['pk']) && isset($_POST['name']) && isset($_POST['value'])) {
         if ($_POST['name'] == 'code' && $_POST['value'] == "") {
             $items = CartItem::model()->findAll("product_id=" . $_POST['pk'] . " AND (cart_type=" . CartType::order . " OR cart_type=" . CartType::awaitpayment . ")");
             if ($items) {
                 echo "You cannot delete a product that has been used on an order";
             } else {
                 _dbx("set foreign_key_checks=0;");
                 Product::model()->updateAll(array('image_id' => null), 'id =' . $_POST['pk']);
                 Images::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 ProductCategoryAssn::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 ProductRelated::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 ProductRelated::model()->deleteAllByAttributes(array('related_id' => $_POST['pk']));
                 ProductTags::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 ProductQtyPricing::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 ProductText::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 WishlistItem::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 TaskQueue::model()->deleteAllByAttributes(array('product_id' => $_POST['pk']));
                 Product::model()->deleteByPk($_POST['pk']);
                 _dbx("set foreign_key_checks=1;");
                 echo "delete";
             }
         } else {
             echo Yii::t('admin', 'You cannot change a product code here. Delete the code to remove it manually from the Web Store database');
         }
     } else {
         $model = new Product();
         if (isset($_GET['q'])) {
             $model->code = $_GET['q'];
         }
         $this->render("products", array('model' => $model));
     }
 }
 /**
  * Setter for cartItem
  *
  * @param CartItem $cartItem
  * @return CartItemDetail
  */
 public function setCartItem(CartItem $cartItem)
 {
     $this->cartItem = $cartItem;
     $cartItem->addCartItemDetailList($this);
     return $this;
 }
 function testShutdown()
 {
     $item1 = new CartItem(1);
     $item2 = new CartItem(2);
     $item1->setAmount(10);
     $item2->setAmount(20);
     $this->cart_handler->addItem($item1);
     $this->cart_handler->addItem($item2);
     $time = time();
     $this->user->setReturnValue('getId', 1000);
     $this->cart_handler->_dbCartHandler();
     $this->db->sqlSelect('cart');
     $arr = $this->db->getArray();
     $this->assertEqual(sizeof($arr), 1);
     $record = reset($arr);
     $this->assertEqual($record['user_id'], 1000);
     $this->assertEqual($record['cart_id'], 10);
     //???
     $this->assertTrue($record['last_activity_time'] >= $time);
     $this->assertEqual($record['cart_items'], serialize($this->cart_handler->getItems()));
 }
 public function checkout(Request $request)
 {
     $token = $request->input('stripeToken');
     //Retriieve cart information
     $cart = Cart::where('user_id', Auth::user()->id)->first();
     $items = $cart->cartItems;
     $total = 0;
     foreach ($items as $item) {
         $total += $item->product->price;
     }
     if (Auth::user()->charge($total * 100, ['source' => $token, 'receipt_email' => Auth::user()->email])) {
         $order = new Order();
         $order->total_paid = $total;
         $order->user_id = Auth::user()->id;
         $order->save();
         foreach ($items as $item) {
             $orderItem = new OrderItem();
             $orderItem->order_id = $order->id;
             $orderItem->product_id = $item->product->id;
             $orderItem->file_id = $item->product->file->id;
             $orderItem->save();
             CartItem::destroy($item->id);
         }
         return redirect('/order/' . $order->id);
     } else {
         return redirect('/cart');
     }
 }
Exemple #18
0
 public function completeOrder($tid)
 {
     $transaction = Transaction::getTransactionBasedOnTID($tid);
     $user = new User($transaction->getUser());
     $order = new Order();
     $order->setTid($transaction->getTid());
     $order->setUser($transaction->getUser());
     $order->setCustomerName($user->getName());
     $order->setUserEmail($user->getEmail());
     $order->setPhone($transaction->getPhone());
     $order->setShippingStreet($transaction->getShippingStreet());
     $order->setShippingCity($transaction->getShippingCity());
     $order->setShippingPostal($transaction->getShippingPostal());
     $order->setShippingProvince($transaction->getShippingProvince());
     $order->setShippingCountry($transaction->getShippingCountry());
     $order->setBillingStreet($transaction->getBillingStreet());
     $order->setBillingCity($transaction->getBillingCity());
     $order->setBillingPostal($transaction->getBillingPostal());
     $order->setBillingProvince($transaction->getBillingProvince());
     $order->setBillingCountry($transaction->getBillingCountry());
     $order->setCostSubtotal($transaction->getCostSubtotal());
     $order->setCostTax($transaction->getCostTax());
     $order->setCostShipping($transaction->getCostShipping());
     $order->setCostTotal($transaction->getCostTotal());
     $order->setIp($transaction->getIp());
     $order->setShippingClass($transaction->getShippingClass());
     $order->setPaymentClass($transaction->getPaymentClass());
     $order->setDeliveryInstructions($transaction->getDeliveryInstructions());
     $order->setStatus('Pending');
     $order->save();
     $cartItems = CartItem::getAll($transaction->getSession());
     foreach ($cartItems as $cartItem) {
         $product = new Product($cartItem->getProduct());
         $orderDetail = new OrderDetail();
         $orderDetail->setOrderNb($order->getId());
         $orderDetail->setProduct($product->getId());
         $orderDetail->setProductName($product->getName());
         $orderDetail->setQuantity($cartItem->getQuantity());
         $orderDetail->save();
         $cartItem->delete();
     }
     $transaction->delete();
     //Send an email to the user
     $this->sendEmailOrderComplete($order->getId());
     return true;
 }
Exemple #19
0
 function isEqualTo(CartItem $item)
 {
     //TODO
     return $this == $item || $this->getItem() === $item->getItem();
 }
Exemple #20
0
 /**
  * TODO: Five different return types... WS-4319
  * Attempt to add product to cart. If product cannot be added, the error string is returned.
  * Otherwise, the row id is returned.
  *
  * @param $objProduct
  * @param int $intQuantity
  * @param int $mixCartType
  * @param null $intGiftItemId
  * @param bool $strDescription
  * @param bool $fltSell
  * @param bool $fltDiscount
  * @return CartItem|string|string[]|true|void
  * @throws Exception
  */
 public function AddProduct($objProduct, $intQuantity = 1, $mixCartType = 0, $intGiftItemId = null, $strDescription = false, $fltSell = false, $fltDiscount = false)
 {
     if ($mixCartType == 0) {
         $mixCartType = CartType::cart;
     }
     if (_xls_get_conf('PRICE_REQUIRE_LOGIN') && Yii::app()->user->isGuest) {
         return Yii::t('cart', "You must log in to {button}", array('{button}' => Yii::t('product', 'Add to Cart')));
     }
     if ($objProduct->IsMaster) {
         return Yii::t('cart', "Please choose options before selecting {button}", array('{button}' => Yii::t('product', 'Add to Cart')));
     }
     // Verify inventory
     if (!$objProduct->getIsAddable() && $mixCartType == CartType::cart) {
         return Yii::t('cart', _xls_get_conf('INVENTORY_ZERO_NEG_TITLE', 'This item is not currently available'));
     }
     // Ensure product is Saleable
     if (!$objProduct->web && $mixCartType == CartType::cart) {
         return Yii::t('cart', 'Selected product is no longer available for ordering. Thank you for your understanding.');
     }
     //Todo Replace with CEvent
     if (function_exists('_custom_before_add_to_cart')) {
         _custom_before_add_to_cart($objProduct, $intQuantity);
     }
     $objItem = false;
     //Items to use
     $intTaxIn = $this->tax_code_id > 0 && _xls_get_conf('TAX_INCLUSIVE_PRICING') ? 1 : 0;
     if ($strDescription == false) {
         $strDescription = $objProduct->Title;
     }
     if ($fltSell == false) {
         $fltSell = $objProduct->getPriceValue(1, $intTaxIn);
     }
     if ($fltDiscount == false) {
         $fltDiscount = 0;
     }
     foreach ($this->cartItems as $item) {
         if ($item->product_id == $objProduct->id && $item->code == $objProduct->OriginalCode && $item->description == $strDescription && $item->sell_discount == $fltDiscount && $item->cart_type == $mixCartType && $item->wishlist_item == $intGiftItemId) {
             $objItem = $item;
             break;
         }
     }
     // If our Cart isn't saved to the db at this point, save it
     if (is_null($this->id)) {
         if (!$this->save()) {
             throw new Exception(sprintf("Unable to save cart before adding this first product: %s\n%s", $objProduct->code, print_r($this->getErrors(), true)));
         }
         Yii::app()->user->setState('cartid', $this->id);
     }
     if (!$objItem) {
         $objItem = new CartItem();
         if ($objProduct->id) {
             $objItem->product_id = $objProduct->id;
         }
         $objItem->cart_id = $this->id;
         $objItem->code = $objProduct->OriginalCode;
         $objItem->cart_type = $mixCartType;
         $objItem->datetime_added = new CDbExpression('NOW()');
         $objItem->sell_base = $fltSell;
         $objItem->sell_discount = $fltDiscount;
         $objItem->description = $strDescription;
         $objItem->tax_in = $intTaxIn;
         if ($intGiftItemId > 0) {
             $objItem->wishlist_item = $intGiftItemId;
         }
     }
     $objItem->qty = $objItem->qty ? $objItem->qty : 0;
     $objItem->sell_total = $objItem->sell_base * $objItem->qty;
     if ($objItem->save() === false) {
         throw new Exception('Unable to save item: ' . print_r($objItem->getErrors(), true));
     }
     $retVal = $this->UpdateItemQuantity($objItem, $intQuantity + $objItem->qty);
     if (!$retVal instanceof CartItem) {
         return $retVal;
     }
     $objItem->cart_id = $this->id;
     $this->recalculateAndSave();
     //Todo change to CEvent
     if (function_exists('_custom_after_add_to_cart')) {
         _custom_after_add_to_cart($objProduct, $intQuantity);
     }
     return $objItem->id;
 }
Exemple #21
0
 /**
  * Calculate the subtotal for each product in the cart
  *
  * @param integer $id        	
  * @param integer $qty        	
  * @param boolean $isvatfree        	
  * @return ArrayObject
  */
 private function calcSubtotal(CartItem $item, $isvatfree = false)
 {
     foreach ($this->items as $item) {
         $isrecurring = false;
         $months = 0;
         $percentage = 0;
         $tax = 0;
         if ("domain" == $item->getType()) {
             $item->setIsrecurring(true);
             // Get the billyng cycle / term / recurring period price
             if ($item->getTerm()) {
                 $priceInfo = ProductsTranches::getTranchebyId($item->getTerm());
                 $item->setBillingid($priceInfo['BillingCycle']['billing_cycle_id']);
                 $months = $priceInfo['BillingCycle']['months'];
             } else {
                 $priceInfo = BillingCycle::getDefaultDomainBillingCycle();
                 $item->setBillingid($priceInfo['billing_cycle_id']);
                 $months = $priceInfo['months'];
             }
             $unitprice = $item->getUnitPrice();
             $setupfee = 0;
             // Calculate the price per Quantity
             $subtotal = $unitprice * $item->getQty();
             // check the taxes
             if (Taxes::get_percentage($item->getTaxId())) {
                 $percentage = Taxes::get_percentage($item->getTaxId());
                 $tax = $subtotal * $percentage / 100;
                 $price = $subtotal * (100 + $percentage) / 100;
             }
         } else {
             // Get all the product information
             $product = Products::getAllInfo($item->getId());
             // Check the type of the product and get the price information
             if ($product['ProductsAttributesGroups']['isrecurring']) {
                 $item->setIsrecurring(true);
                 // Get the billyng cycle / term / recurring period price
                 $priceInfo = ProductsTranches::getTranchebyId($item->getTerm());
                 // Price multiplier
                 $months = $priceInfo['BillingCycle']['months'];
                 $unitprice = $priceInfo['price'];
                 $setupfee = $priceInfo['setupfee'];
                 // Calculate the price per the months per Quantity
                 $subtotal = $unitprice * $months * $item->getQty();
                 $item->setBillingid($priceInfo['BillingCycle']['billing_cycle_id']);
             } else {
                 $item->setIsrecurring(false);
                 $unitprice = $product['price_1'];
                 $setupfee = $product['setupfee'];
                 // Calculate the price per Quantity
                 $subtotal = $unitprice * $item->getQty();
             }
             // check the taxes for each product
             if (!empty($product['tax_id']) && !$isvatfree) {
                 if (!empty($product['Taxes']['percentage']) && is_numeric($product['Taxes']['percentage'])) {
                     $percentage = $product['Taxes']['percentage'];
                     $tax = $subtotal * $percentage / 100;
                     $price = $subtotal * (100 + $percentage) / 100;
                 }
             }
         }
         // ... and add the setup fees
         $price = $subtotal + $setupfee;
         $item->setSubtotals(array('months' => $months, 'subtotal' => $subtotal, 'setupfee' => $setupfee, 'price' => $price, 'taxes' => $tax, 'percentage' => $percentage));
     }
     return $this->items;
 }
 public function add_item($object)
 {
     CartItem::create_from_object($object, $this);
 }
 protected static function get_fields()
 {
     return implode(', ', array(self::select_fields(), DiscountCode::select_fields(), Cart::select_fields(), CartItem::select_fields(), EventSignup::select_fields(), EventService::select_fields(), User::select_fields()));
 }
Exemple #24
0
 /**
  * In version v1, at least 1 item (e.g. “credit charge”) and at most 2 items
  * must be in the cart (e.g. “purchase for my shop” and “shipment costs”).
  * The limit is caused by the graphic layout of the payment gateway, in another
  * version the limit will be much higher.
  *
  * @param CartItem $cartItem
  */
 public function addCartItem(CartItem $cartItem)
 {
     $this->cart[] = $cartItem;
     $this->totalAmount += $cartItem->getAmount();
 }
 /**
  * Ajax receiver function to Add To Cart.
  * This function adds to the cart and then returns a JSON encoded string of
  * the cart contents.  This is typically used by the Cart Display widget.
  * This routine will always send back all the info, but some people may
  * choose to only have some details like the total and item count display.
  */
 public function actionAddToCart()
 {
     if (Yii::app()->request->isAjaxRequest) {
         $intProductId = Yii::app()->getRequest()->getParam('id');
         $strSize = Yii::app()->getRequest()->getParam('product_size');
         $strColor = Yii::app()->getRequest()->getParam('product_color');
         if (isset($strSize) || isset($strColor)) {
             // We passed a size and or color selection, so get the right item
             $objProduct = Product::LoadChildProduct($intProductId, $strSize, $strColor);
             if ($objProduct instanceof Product) {
                 $intProductId = $objProduct->id;
             }
         }
         $intQty = Yii::app()->getRequest()->getParam('qty');
         $intWishId = Yii::app()->getRequest()->getParam('wishid');
         if (!isset($intWishId)) {
             $intWishId = null;
         }
         $intCount = Yii::app()->shoppingcart->item_count;
         $intRowId = Yii::app()->shoppingcart->addProduct($intProductId, $intQty, $intWishId);
         if ($intRowId) {
             if (!is_numeric($intRowId)) {
                 //We got back an error message, not a rowid
                 if (is_array($intRowId)) {
                     $message = $intRowId['errorMessage'];
                 } else {
                     $message = $intRowId;
                 }
                 Yii::log("Error attempting to add product " . $intProductId . ": " . $message, 'error', 'application . ' . __CLASS__ . " . " . __FUNCTION__);
                 $arrReturn['action'] = "alert";
                 $arrReturn['errormsg'] = Yii::t('global', $message);
             } else {
                 Yii::log("Added item " . $intProductId . " as cart_items id " . $intRowId, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                 $objCart = Yii::app()->shoppingcart;
                 $objCartItem = CartItem::model()->findByPk($intRowId);
                 //If this was a result of a Wish List add, update that record
                 if (!is_null($intWishId)) {
                     WishlistItem::model()->updateByPk($intWishId, array('cart_item_id' => $intRowId));
                 }
                 $arrReturn['action'] = "success";
                 $arrReturn['totalItemCount'] = Yii::app()->shoppingcart->totalItemCount;
                 if ($intWishId !== null) {
                     $arrReturn['purchaseStatus'] = WishlistItem::model()->findByPk($intWishId)->PurchaseStatus;
                 }
                 $strCartfile = Yii::app()->getRequest()->getParam('cart');
                 $strCartfile = empty($strCartfile) ? "_sidecart" : $strCartfile;
                 $arrReturn['shoppingcart'] = $this->renderPartial('/site/' . $strCartfile, array('objCartItem' => $objCartItem), true);
             }
             $this->renderJSON($arrReturn);
         } else {
             Yii::log("Error attempting to add product " . $intProductId . " for qty " . $intQty, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
         }
     }
 }