/**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      ConnectionInterface $con
  * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws PropelException
  * @see save()
  */
 protected function doSave(ConnectionInterface $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their corresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aCartItem !== null) {
             if ($this->aCartItem->isModified() || $this->aCartItem->isNew()) {
                 $affectedRows += $this->aCartItem->save($con);
             }
             $this->setCartItem($this->aCartItem);
         }
         if ($this->aAttribute !== null) {
             if ($this->aAttribute->isModified() || $this->aAttribute->isNew()) {
                 $affectedRows += $this->aAttribute->save($con);
             }
             $this->setAttribute($this->aAttribute);
         }
         if ($this->aAttributeAv !== null) {
             if ($this->aAttributeAv->isModified() || $this->aAttributeAv->isNew()) {
                 $affectedRows += $this->aAttributeAv->save($con);
             }
             $this->setAttributeAv($this->aAttributeAv);
         }
         if ($this->isNew() || $this->isModified()) {
             // persist changes
             if ($this->isNew()) {
                 $this->doInsert($con);
             } else {
                 $this->doUpdate($con);
             }
             $affectedRows += 1;
             $this->resetModified();
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
 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;
 }
Esempio n. 3
0
 /**
  * All the cart functionalities are handled here
  * 
  * Add a product to the cart, remove a product from the cart, checkout, etc
  * @return string
  */
 public function handleCart($action)
 {
     switch ($action) {
         case 'Add':
             //Add a new product to the cart
             $productId = e(@$_REQUEST["productId"]);
             $product = new Product($productId);
             if (!$product->getId()) {
                 return $this->smarty->fetch("Error.tpl");
             }
             require_once 'plugins/products/ECommProduct.php';
             $hookResults = ECommProduct::clientPluginHooks("BeforeAddToCart", $product, $this);
             //Add the product to cart
             $session = Session::getActiveSession();
             $cartItem = new CartItem();
             $cartItem->setSession($session->getId());
             $cartItem->setProduct($productId);
             $cartItem->setQuantity(@$_REQUEST["quantity"]);
             $cartItem->setTransaction(0);
             $cartItem->save();
             $hookResults = ECommProduct::clientPluginHooks("AfterAddToCart", $cartItem, $this);
             $returnURL = @$_REQUEST["returnURL"];
             if (!$returnURL) {
                 $returnURL = "/Store/";
             }
             $this->smarty->assign('returnURL', $returnURL);
             return $this->smarty->fetch("ProductAddedToCart.tpl");
         case 'Details':
             //Get the details of the cart for an ajax call, it will have the format: "subTotal tax shipping total"
             $cartDetails = Module_EComm::getCartDetails();
             return $cartDetails["subTotal"] . " " . $cartDetails["tax"] . " " . $cartDetails["shipping"] . " " . $cartDetails["total"];
             break;
         case 'Delete':
             //Delete an item from the cart
             $cartItem = new CartItem(@$_REQUEST["id"]);
             if ($cartItem->getId()) {
                 if ($cartItem->getSession() == @$_SESSION["ECommSessionId"]) {
                     $cartItem->delete();
                     return "True";
                 }
             }
             return "Could not be deleted";
             break;
         case 'Display':
             //Display the cart (before the checkout page)
             $session = Session::getActiveSession();
             $sessionId = $session->getId();
             $cartProducts = CartItem::getAll($sessionId);
             $cartDetails = Module_EComm::getCartDetails($sessionId, $cartProducts);
             $this->smarty->assign('cartProducts', $cartProducts);
             $this->smarty->assign('cartDetails', $cartDetails);
             $auth_container = new User();
             $auth = new Auth($auth_container, null, 'authInlineHTML');
             $auth->start();
             if ($auth->checkAuth()) {
                 $this->smarty->assign('loggedIn', 1);
             }
             $user = Module::factory("User");
             $form = $user->getUserAddEditForm('/Store/Cart/&action=Checkout&createAccount=1');
             $form->removeElement('a_group');
             //In case the administrator is logged in, remove this element because it is not needed
             $form->removeElement('a_status');
             //In case the administrator is logged in, remove this element because it is not needed
             $form->removeElement('section');
             //Remove the section hidden variable from here
             $form->removeElement('action');
             //Remove the action hidden variable from here
             $this->smarty->assign('user_form', $form);
             $this->smarty->assign('userExist', @$_REQUEST["userExist"]);
             $this->smarty->assign('loginFail', @$_REQUEST["loginFail"]);
             return $this->smarty->fetch("DisplayCart.tpl");
             break;
         case 'displayCartProduct':
             //Display a product in a cart (similar to display a product from the database but without the option of adding to cart and with some other differences)
             $cartItem = new CartItem(@$_REQUEST["cartItemId"]);
             if ($cartItem->getId()) {
                 if ($cartItem->getSession() == @$_SESSION["ECommSessionId"]) {
                     //Make sure the owner of this item is viewing it
                     $product = $cartItem->getCartItemProduct();
                     $this->smarty->assign('cartItem', $cartItem);
                     require_once 'plugins/products/ECommProduct.php';
                     $hookResults = ECommProduct::clientPluginHooks("BeforeDisplayCartItem", $cartItem, $this);
                     $html = "";
                     foreach ($hookResults as $key => $val) {
                         $html .= @$val['HTML'];
                     }
                     $this->smarty->assign('html', $html);
                     $this->smarty->assign('returnURL', '/Store/Cart/&action=' . @$_REQUEST["returnURL"]);
                     return $this->smarty->fetch("DisplayCartItem.tpl");
                 }
             }
             return "Item could not be displayed";
             break;
         case 'Checkout':
             //Display the checkout page
             if (@$_REQUEST["createAccount"] == 1) {
                 //Create a new user
                 $user = Module::factory("User");
                 $form = $user->getUserAddEditForm();
                 //Then try to log the user in using their username and password
                 $auth_container = new CMSAuthContainer();
                 $auth = new Auth($auth_container, null, 'authInlineHTML');
                 //First, log the current user out (if exists)
                 unset($_SESSION['authenticated_user']);
                 $auth->logout();
                 //And then, log the new user in using the new username and password
                 $_POST["username"] = @$_REQUEST["a_username"];
                 $_POST["password"] = @$_REQUEST["a_password"];
                 $_POST["doLogin"] = "******";
                 $auth->start();
                 if (!$auth->checkAuth()) {
                     //The login did not happen successfully, which means creating a new user was not successful
                     header('Location: /Store/Cart/&action=Display&userExist=1');
                     exit;
                 }
                 $this->sendEmailAccountCreated();
             }
             $auth_container = new User();
             $auth = new Auth($auth_container, null, 'authInlineHTML');
             $auth->start();
             if (!$auth->checkAuth()) {
                 //You need to login to access this page
                 header('Location: /Store/Cart/&action=Display&loginFail=1');
                 //Invalid username or password
                 exit;
             }
             //From this point on, the user is actually logged in
             $userId = $_SESSION['authenticated_user']->getId();
             require_once 'plugins/shipping/ECommShipping.php';
             require_once 'plugins/payment/ECommPayment.php';
             $this->smarty->assign('username', $_SESSION['authenticated_user']->getUsername());
             $session = Session::getActiveSession();
             $session->setUser($userId);
             //Set the default shipping class and payment option, if empty
             if (!$session->getShippingClass()) {
                 $session->setShippingClass(ECommShipping::getDefaultPlugIn());
             }
             if (!$session->getPaymentClass()) {
                 $session->setPaymentClass(ECommPayment::getDefaultPlugIn());
             }
             $session->save();
             $sessionId = $session->getId();
             $cartProducts = CartItem::getAll($sessionId);
             $cartDetails = Module_EComm::getCartDetails($sessionId, $cartProducts);
             $this->smarty->assign('cartProducts', $cartProducts);
             $this->smarty->assign('cartDetails', $cartDetails);
             $userDetails = UserDetails::getUserDetailsBasedOnUserId($userId);
             $this->smarty->assign('userDetails', $userDetails);
             $ECommShipping = new ECommShipping();
             $this->smarty->assign('shippingClass', $ECommShipping);
             $this->smarty->assign('selectedShipping', $session->getShippingClass());
             $this->smarty->assign('shippingClassDetails', $ECommShipping->getPlugin($session->getShippingClass())->getShippingDetails());
             $ECommPayment = new ECommPayment();
             $this->smarty->assign('paymentClass', $ECommPayment);
             $this->smarty->assign('selectedPayment', $session->getPaymentClass());
             $this->smarty->assign('paymentClassDetails', $ECommPayment->getPlugin($session->getPaymentClass())->getPaymentDetails());
             $this->smarty->assign('paymentForm', $ECommPayment->getPlugin($session->getPaymentClass())->getPaymentForm());
             return $this->smarty->fetch("Checkout.tpl");
             break;
         case 'ShippingChange':
             //Change the shipping class through an ajax call. It returns the details of the new shipping class so it is displayed for the end user
             if (@$_REQUEST["shippingClass"]) {
                 $session = Session::getActiveSession();
                 $session->setShippingClass($_REQUEST["shippingClass"]);
                 $session->save();
             }
             require_once 'plugins/shipping/ECommShipping.php';
             $ECommShipping = new ECommShipping();
             return $ECommShipping->getPlugin(@$_REQUEST["shippingClass"])->getShippingDetails();
             break;
         case 'PaymentChange':
             //Change the payment class as an ajax call. Returns the details of the new payment method to be displayed to the end user
             if (@$_REQUEST["paymentClass"]) {
                 $session = Session::getActiveSession();
                 $session->setPaymentClass($_REQUEST["paymentClass"]);
                 $session->save();
             }
             require_once 'plugins/payment/ECommPayment.php';
             $ECommPayment = new ECommPayment();
             $details = $ECommPayment->getPlugin(@$_REQUEST["paymentClass"])->getPaymentDetails();
             $form = $ECommPayment->getPlugin(@$_REQUEST["paymentClass"])->getPaymentForm();
             //This will return the details and the form separated by a new line.
             //The details must not contain any new line and neither must the form
             //The ajax call will split the result by \n. The first will will be the details and the second line will be the form
             return str_replace("\n", " ", $details) . "\n" . str_replace("\n", " ", $form);
             break;
         case 'Address':
             //Change the address or the phone number of the end user in an ajax call
             $userId = $_SESSION['authenticated_user']->getId();
             if (!$userId) {
                 //If the user is not logged in, don't do anything
                 return "";
             }
             $userDetails = UserDetails::getUserDetailsBasedOnUserId($userId);
             $adr_type = @$_REQUEST['adr_type'];
             if ($adr_type == "phone_number") {
                 //Change the phone number
                 $form = new Form('phone_addedit', 'post', '/Store/Cart/&action=Address');
                 $form->addElement('text', 'number', 'Phone Number', array('value' => $userDetails->getPhoneNumber()));
                 $form->setConstants(array('adr_type' => $adr_type));
                 $form->addElement('hidden', 'adr_type');
                 $form->addElement('submit', 'submit', 'Submit');
                 if (isset($_REQUEST['submit'])) {
                     $userDetails->setPhoneNumber(trim($_REQUEST['number']));
                     $userDetails->save();
                     $this->smarty->assign('phoneNumber', $userDetails->getPhoneNumber());
                     return $this->smarty->fetch('PhoneNumber.tpl');
                 } else {
                     return $form->display();
                 }
             } else {
                 //Change the shipping address or billing address
                 $address = $userDetails->getAddress($adr_type);
                 $form = $address->getAddEditForm();
                 $form->addElement('submit', 'submit', 'Submit');
                 $form->updateAttributes(array('action' => '/Store/Cart/&action=Address'));
                 $form->setConstants(array('adr_type' => $adr_type));
                 $form->addElement('hidden', 'adr_type');
                 if (isset($_REQUEST['submit'])) {
                     $userDetails->setAddress($adr_type, $address);
                     $userDetails->save();
                     $this->smarty->assign('address', $address);
                     $this->smarty->assign('adr_type', $adr_type);
                     return $this->smarty->fetch('Address.tpl');
                 } else {
                     return $form->display();
                 }
             }
             break;
         case 'CheckBeforePayment':
             //This action is called when the user clicks on the "Buy now" button
             //Mmake sure that they can checkout in an ajax call before redirecting the user to the payment
             //For example, the shipping address must be present, the billing address, etc
             //If the user can checkout, return "0" to the ajax call. Right after doing that, there will be another ajax call to refresh the payment form and then submitting the form
             $session = Session::getActiveSession();
             $cartDetails = Module_EComm::getCartDetails();
             $canPurchase = Module_EComm::canUserCheckOut($session, $cartDetails);
             if ($canPurchase == "0") {
                 //The user can checkout
                 //Create a new transaction and fill it with all the details that the user has enetered
                 $userDetails = UserDetails::getUserDetailsBasedOnUserId($session->getUser());
                 $shippingAddress = $userDetails->getAddress('shipping_address');
                 $billingAddress = $userDetails->getAddress('billing_address');
                 //Proceed to payment:
                 //Create a transaction entity
                 //and change the session so the user won't mess up with it
                 //First, create a random transaction number (30 digits)
                 $tid = Transaction::generateNewTID();
                 $transaction = new Transaction();
                 $transaction->setTid($tid);
                 $transaction->setSession($session->getId());
                 $transaction->setUser($session->getUser());
                 $transaction->setPhone($userDetails->getPhoneNumber());
                 $transaction->setShippingStreet($shippingAddress->getStreetAddress());
                 $transaction->setShippingCity($shippingAddress->getCity());
                 $transaction->setShippingPostal($shippingAddress->getPostalCode());
                 $transaction->setShippingProvince($shippingAddress->getStateName());
                 $transaction->setShippingCountry($shippingAddress->getCountryName());
                 $transaction->setBillingStreet($billingAddress->getStreetAddress());
                 $transaction->setBillingCity($billingAddress->getCity());
                 $transaction->setBillingPostal($billingAddress->getPostalCode());
                 $transaction->setBillingProvince($billingAddress->getStateName());
                 $transaction->setBillingCountry($billingAddress->getCountryName());
                 $transaction->setCostSubtotal((double) $cartDetails["subTotal"]);
                 $transaction->setCostTax((double) $cartDetails["tax"]);
                 $transaction->setCostShipping((double) $cartDetails["shipping"]);
                 $transaction->setCostTotal((double) $cartDetails["total"]);
                 $transaction->setIp($session->getIpAddress());
                 $transaction->setShippingClass($session->getShippingClass());
                 $transaction->setPaymentClass($session->getPaymentClass());
                 $transaction->setDeliveryInstructions(@$_REQUEST["deliveryInstructions"]);
                 $transaction->save();
                 $_SESSION['ECommTID'] = $tid;
                 //Store $tid in PHP session so when the payment form is generated, we can include it there.
                 //After creating the transaction, regenerate the session ID to prevent users from messing up with the session after proceeding to payment
                 //The user will be assigned a new session. So, their cart will be empty. They can add new items to the cart if they want, and that will not affect their transaction
                 $session->reGenerateSession();
             }
             return $canPurchase;
             break;
     }
 }
Esempio n. 4
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;
 }