/** * */ public function Confirm() { $auth = new Auth(); $shop = new ShoppingCart(); $user = $auth->id(); $myShop = $shop->all(); $objDetails = new DetalleCompra(); $total = 0; if (empty($myShop)) { return false; } foreach ($myShop as $key => $val) { $total += $val->precio * $val->cantidad; } $result_insert = $this->create($user, $total); if ($result_insert->success) { foreach ($myShop as $k => $v) { try { $objDetails->create($result_insert->id, $v->id_prod, $v->name, $v->cantidad, $v->precio, $v->talle, $v->color); //$stock = new TempStock(); //echo $stock->removeTempStock($user,$v->id_prod,$v->id_talle,$v->id_color,$v->type); } catch (Exception $e) { echo $e->getMessage(); } } $auth->restPoints($total); $auth->sumConsumed($total); $shop->removeAll(); return true; } }
public function render() { if (isset($_POST["clearCart"])) { setcookie("shoppingCart", ""); } if (isset($_GET["remove"])) { $myArray = json_decode($_COOKIE["shoppingCart"]); $i = 0; foreach ($myArray as $index) { if ($index->ID == $_GET["remove"]) { unset($myArray[$i]); $myArray = array_values($myArray); break; } $i++; } setcookie("shoppingCart", json_encode($myArray)); } $htmlcontent = "Der Warenkorb enthält keine Produkte"; if (isset($_COOKIE["shoppingCart"])) { $myArray = json_decode($_COOKIE["shoppingCart"]); //$htmlcontent = $htmlcontent. "Warenkorb:" .print_r(array_values($myArray)); include_once 'classes/class.shoppingcart.php'; $myCart = new ShoppingCart($myArray); $htmlcontent = $myCart->displayCart(); } return $htmlcontent; }
public function testComputesReducedVatForTheRightCountry() { $shoppingCart = new ShoppingCart(new Austria()); $article = new Article(new ArticleName('Test'), new ArticleDescription(''), new Euro(1000), new ArticleTypeReduced()); $shoppingCart->add($article); $shoppingCart->add($article); $this->assertEquals(new Money(2200, new Currency('EUR')), $shoppingCart->total()); }
/** * Create a {@link ShoppingCart} object and give * it some test {@link OrderItem} objects. * * @return object ShoppingCart */ public static function createCartWithItems() { $item1 = new ProductVariation_OrderItem(array('ProductVariationID' => 2, 'Version' => 1)); $item2 = new ProductVariation_OrderItem(array('ProductVariationID' => 1, 'Version' => 1)); $cart = new ShoppingCart(); $cart->addItem(2, $item1); $cart->addItem(1, $item2); return $cart; }
public function actionAddToCart($id) { $cart = new ShoppingCart(); $model = Product::findOne($id); if ($model) { $cart->put($model, 1); return $this->redirect(['cart-view']); } throw new NotFoundHttpException(); }
private function priceIncludingVat(Article $article) : Money { if ($article->type() instanceof ArticleTypeNormal) { $taxFactor = 1 + $this->country->vat() / 100; } else { $taxFactor = 1 + $this->country->reducedVat() / 100; } $price = (int) ($article->price()->amount() * $taxFactor); return new Euro($price); }
public function checkPoints() { $user = Auth::User(); $ShoppingCart = new ShoppingCart(); $ShoppingCart->all(); $credit = $user->dblCredito; $total = $ShoppingCart->getTotal(); if ($credit - $total < 0) { return false; } else { return true; } }
function setStoreInfo($storeID, $storeInfo) { if (class_exists("ShoppingCart")) { $Store = new ShoppingCart(); $Store->setStoreID($storeID); $storeInfo = $Store->getStoreInformation(); return $storeInfo; } else { $ErrorMsgs[] = "The ShoppingCart class is not available!"; echo '<p>' . $ErrorMsgs[0] . '</p>'; return NULL; } }
protected function afterLogin($fromCookie) { if (!$fromCookie) { // Assign the user to the cart, if logged in Yii::app()->shoppingcart->assignCustomer(Yii::app()->user->id); // If the user is not a guest user, then update the tax destination // for the user's cart to display correct product prices. We can't // do this for guest users since it will reset their cart to the // store default, which is generally not what we want, especially // not in tax-inclusive environments when the shipping destination // is in a notax region. if ($this->getIsGuest() !== true) { Yii::app()->shoppingcart->setTaxCodeByDefaultShippingAddress(); } // Since we have successfully logged in, see if we have a cart in progress $cartInProgressFound = Yii::app()->shoppingcart->loginMerge(); // Recalculate and update the cart if prices of any cart items have changed if ($cartInProgressFound === true) { Yii::app()->shoppingcart->verifyPrices(); Yii::log("Cart ID is " . Yii::app()->shoppingcart->id, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__); } // Display no-tax message if the customer's default shipping address is // in no-tax destination in tax-inclusive mode if (Yii::app()->params['TAX_INCLUSIVE_PRICING'] == 1) { ShoppingCart::displayNoTaxMessage(); } } else { Yii::log("User Login using cookie", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__); } }
function testCalculations() { $mp3player = $this->objFromFixture('Product', 'mp3player'); $this->get(ShoppingCart::add_item_link($mp3player->ID)); $cart = ShoppingCart::current_order(); $this->assertEquals($cart->Total(), 215); }
public function doAddItemToCart($data) { $product = Product::get()->byID($data['ProductID']); $customisations = array(); foreach ($data as $key => $value) { if (!(strpos($key, 'customise') === false) && $value) { $custom_data = explode("_", $key); if ($custom_item = ProductCustomisation::get()->byID($custom_data[1])) { $modify_price = 0; // Check if the current selected option has a price modification if ($custom_item->Options()->exists()) { $option = $custom_item->Options()->filter("Title", $value)->first(); $modify_price = $option ? $option->ModifyPrice : 0; } $customisations[] = array("Title" => $custom_item->Title, "Value" => $value, "ModifyPrice" => $modify_price); } } } if ($product) { $cart = ShoppingCart::create(); $cart->add($product, $data['Quantity'], $customisations); $cart->save(); // Clear any postage data that has been set Session::clear("Commerce.PostageID"); $message = _t('Commerce.AddedItemToCart', 'Added item to your shopping cart'); $message .= ' <a href="' . $cart->Link() . '">'; $message .= _t('Commerce.ViewCart', 'View cart'); $message .= '</a>'; $this->controller->setSessionMessage("success", $message); } return $this->controller->redirectBack(); }
protected function checkoutconfig() { $config = new CheckoutComponentConfig(ShoppingCart::curr(), true); $config->addComponent($comp = new CouponCheckoutComponent()); $comp->setValidWhenBlank(true); return $config; }
function dopayment($data, $form) { $SQLData = Convert::raw2sql($data); if (isset($SQLData['OrderID'])) { if ($orderID = intval($SQLData['OrderID'])) { $order = Order::get_by_id_if_can_view($orderID); if ($order && $order->canPay()) { if (EcommercePayment::validate_payment($order, $form, $data)) { $payment = EcommercePayment::process_payment_form_and_return_next_step($order, $form, $data); } if ($payment) { ShoppingCart::singleton()->submit(); $order->tryToFinaliseOrder(); return $payment; } else { //error messages are set in validation return $this->controller->redirectBack(); } } else { $form->sessionMessage(_t('OrderForm.NO_PAYMENTS_CAN_BE_MADE_FOR_THIS_ORDER', 'No payments can be made for this order.'), 'bad'); return $this->controller->redirectBack(); } } } $form->sessionMessage(_t('OrderForm.COULDNOTPROCESSPAYMENT', 'Sorry, we could not find the Order for payment.'), 'bad'); $this->controller->redirectBack(); return false; }
/** * Tries to create an order item with a non-existent version. */ function testProductVersionDoesNotExist() { $currentorder = ShoppingCart::current_order(); $brokenitem = new Product_OrderItem(array("ProductID" => $productSocks->ID, "ProductVersion" => 99999)); $this->assertEquals($brokenitem->UnitPrice(), null); //TODO: what should happen here??? }
/** * Clear the cart, and session variables on member logout */ public function memberLoggedOut() { if (Member::config()->login_joins_cart) { ShoppingCart::singleton()->clear(); OrderManipulation::clear_session_order_ids(); } }
/** * Handles form submission * @param array $data * @return bool|\SS_HTTPResponse */ public function addtocart(array $data) { $groupedProduct = $this->getController()->data(); if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) { $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad'); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } $cart = ShoppingCart::singleton(); foreach ($data['Product'] as $id => $prodReq) { if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) { $prod = Product::get()->byID($id); if ($prod && $prod->exists()) { $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $prodReq; $buyable = $prod; if (isset($prodReq['Attributes'])) { $buyable = $prod->getVariationByAttributes($prodReq['Attributes']); if (!$buyable || !$buyable->exists()) { $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad"); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } if (!$cart->add($buyable, (int) $prodReq['Quantity'], $saveabledata)) { $this->sessionMessage($cart->getMessage(), $cart->getMessageType()); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } } } $this->extend('updateGroupCartResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType()); }
function testCart() { $cart = $this->objFromFixture("Order", "cart"); ShoppingCart::singleton()->setCurrent($cart); $page = new Page_Controller(); $this->assertEquals("\$8.00", (string) $page->renderWith("CartTestTemplate")); }
public static function SetCartId() { //Если Id корзины не задан if (self::$_mCartId == '') { // Если в сеансе есть Id корзины, получаем его оттуда if (isset($_SESSION['cart_id'])) { self::$_mCartId = $_SESSION['cart_id']; } elseif (isset($_COOKIE['cart_id'])) { self::$_mCartId = $_COOKIE['cart_id']; $_SESSION['cart_id'] = self::$_mCartId; //регенерируем cookie-файл, чтобы он //действовал 7 дней (604800 секунд) setcookie('cart_id', self::$_mCartId, time() + 604800); } else { /* Генерируем id корзины и сохраняем его в элементе класса $_mCartId, сеансе и cookie-файле (при последующих вызовах $_mCartId будет получать значение из сеанса) */ self::$_mCartId = md5(uniqid(rand(), TRUE)); // Сохраняем id корзины в сеансе $_SESSION['cart_id'] = self::$_mCartId; // cookie-файл будет действовать 7 дней (604800 секунд) setcookie('cart_id', self::$_mCartId, time() + 604800); } } }
/** * Adds a given product to the cart. If a hidden field is passed * (ValidateVariant) then simply a validation of the user including that * product is done and the users cart isn't actually changed. * * @return mixed */ public function addtocart($data, $form) { if ($variation = $this->getBuyable($data)) { $quantity = isset($data['Quantity']) && is_numeric($data['Quantity']) ? (int) $data['Quantity'] : 1; $cart = ShoppingCart::singleton(); // if we are in just doing a validation step then check if ($this->request->requestVar('ValidateVariant')) { $message = ''; $success = false; try { $success = $variation->canPurchase(null, $data['Quantity']); } catch (ShopBuyableException $e) { $message = get_class($e); // added hook to update message $this->extend('updateVariationAddToCartMessage', $e, $message, $variation); } $ret = array('Message' => $message, 'Success' => $success, 'Price' => $variation->dbObject('Price')->TrimCents()); $this->extend('updateVariationAddToCartAjax', $ret, $variation, $form); return json_encode($ret); } if ($cart->add($variation, $quantity)) { $form->sessionMessage("Successfully added to cart.", "good"); } else { $form->sessionMessage($cart->getMessage(), $cart->getMessageType()); } } else { $variation = null; $form->sessionMessage("That variation is not available, sorry.", "bad"); //validation fail } $this->extend('updateVariationAddToCart', $form, $variation); $request = $this->getRequest(); $this->extend('updateVariationFormResponse', $request, $response, $variation, $quantity, $form); return $response ? $response : ShoppingCart_Controller::direct(); }
public function testOffsitePaymentWithGatewayCallback() { //set up cart $cart = ShoppingCart::singleton()->setCurrent($this->objFromFixture("Order", "cart"))->current(); //collect checkout details $cart->update(array('FirstName' => 'Foo', 'Surname' => 'Bar', 'Email' => '*****@*****.**')); $cart->write(); //pay for order with external gateway $processor = OrderProcessor::create($cart); $this->setMockHttpResponse('PaymentExpress/Mock/PxPayPurchaseSuccess.txt'); $response = $processor->makePayment("PaymentExpress_PxPay", array()); //gateway responds (in a different session) $oldsession = $this->mainSession; $this->mainSession = new TestSession(); ShoppingCart::singleton()->clear(); $this->setMockHttpResponse('PaymentExpress/Mock/PxPayCompletePurchaseSuccess.txt'); $this->getHttpRequest()->query->replace(array('result' => 'abc123')); $identifier = $response->getPayment()->Identifier; $response = $this->get("paymentendpoint/{$identifier}/complete"); //reload cart as new order $order = Order::get()->byId($cart->ID); $this->assertFalse($order->isCart(), "order is no longer in cart"); $this->assertTrue($order->isPaid(), "order is paid"); //bring back client session $this->mainSession = $oldsession; $response = $this->get("paymentendpoint/{$identifier}/complete"); $this->assertNull(Session::get("shoppingcartid"), "cart session id should be removed"); $this->assertNotEquals(404, $response->getStatusCode(), "We shouldn't get page not found"); $this->markTestIncomplete("Should assert other things"); }
public static function getCartsOfOwner($cartowner = 'notset') { if ($cartowner == 'notset') { $cartowner = Yii::app()->User->getState('cartowner'); } return ShoppingCart::model()->findAll('cartowner = :cartowner', array(':cartowner' => $cartowner)); }
/** * Get the cart, and do last minute calculation if necessary. */ public function Cart() { $order = ShoppingCart::curr(); if (!$order || !$order->Items() || !$order->Items()->exists()) { return false; } return $order; }
function Order() { if ($orderID = Director::urlParam('Action')) { return DataObject::get_by_id('Order', $orderID); } else { return ShoppingCart::current_order(); } }
/** * @TODO Where is this method used? * @return Order */ function Order() { if ($this->ID) { return DataObject::get_by_id('Order', $this->OrderID); } else { return ShoppingCart::current_order(); } }
public function init() { parent::init(); // If no shopping cart doesn't exist, redirect to base if (!ShoppingCart::create()->getItems()->exists()) { return $this->redirect(ShoppingCart::config()->url_segment); } }
function shippingmethod() { $form = $this->ShippingMethodForm(); $cart = ShoppingCart::singleton()->current(); if ($cart->ShippingMethodID) { $form->loadDataFrom($cart); } return array('OrderForm' => $form); }
/** * Redirect back to start of checkout if no cart started */ public function onAfterInit() { $action = $this->owner->getRequest()->param('Action'); $steps = $this->getSteps(); if (!ShoppingCart::curr() && !empty($action) && isset($steps[$action])) { Controller::curr()->redirect($this->owner->Link()); return; } }
function setUp() { parent::setUp(); ShopTest::setConfiguration(); $this->cartpage = $this->objFromFixture("CartPage", "cart"); $this->cartpage->publish('Stage', 'Live'); ShoppingCart::singleton()->setCurrent($this->objFromFixture("Order", "cart")); //set the current cart }
public function setUp() { parent::setUp(); ShopTest::setConfiguration(); //reset config $this->cart = ShoppingCart::singleton(); $this->product = $this->objFromFixture('Product', 'mp3player'); $this->product->publish('Stage', 'Live'); }
/** * Check to see if the shopping cart only contains downloadable * products. * * @return Boolean */ public function onlyDownloadable() { $cart = ShoppingCart::get(); foreach ($cart->getItems() as $item) { if (!$item->FindStockItem() instanceof DownloadableProduct) { return false; } } return true; }