public function testModifierFailure() { if (!ShopTools::DBConn()->supportsTransactions()) { $this->markTestSkipped('The Database doesn\'t support transactions.'); } Config::inst()->update('Order', 'modifiers', array('OrderModifierTest_TestModifier')); $order = $this->createOrder(); $order->calculate(); $order->write(); // 408 from items + 10 from modifier + 25% from tax $this->assertEquals('522.5', $order->Total); $amounts = array(); foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string) $modifier->Amount; } $this->assertEquals(array('10', '104.5'), $amounts); OrderModifierTest_TestModifier::$value = 42; try { // Calculate will now fail! $order->calculate(); } catch (Exception $e) { } // reload order from DB $order = Order::get()->byID($order->ID); // Order Total should not have changed $this->assertEquals('522.5', $order->Total); $amounts = array(); foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string) $modifier->Amount; } $this->assertEquals(array('10', '104.5'), $amounts, 'Modifiers aren\'t allowed to change upon failure'); }
public function testPriceForDisplay() { $dp = ShopTools::price_for_display(12345.67); $dp->setCurrency("NZD"); $dp->setLocale("en_NZ"); $this->assertEquals($dp->Nice(), "\$12,345.67"); }
/** * Update the cart using data collected */ public function updatecart($data, $form) { $items = $this->cart->Items(); $updatecount = $removecount = 0; $request = $this->getRequest(); $order = ShoppingCart::curr(); if ($request && $request->isAjax() && $order) { ShopTools::install_locale($order->Locale); } $messages = array(); if (isset($data['Items']) && is_array($data['Items'])) { foreach ($data['Items'] as $itemid => $fields) { $item = $items->byID($itemid); if (!$item) { continue; } //delete lines if (isset($fields['Remove']) || isset($fields['Quantity']) && (int) $fields['Quantity'] <= 0) { $items->remove($item); $removecount++; continue; } //update quantities if (isset($fields['Quantity']) && ($quantity = Convert::raw2sql($fields['Quantity']))) { $item->Quantity = $quantity; } //update variations if (isset($fields['ProductVariationID']) && ($id = Convert::raw2sql($fields['ProductVariationID']))) { if ($item->ProductVariationID != $id) { $item->ProductVariationID = $id; } } //TODO: make updates through ShoppingCart class //TODO: combine with items that now match exactly //TODO: validate changes if ($item->isChanged()) { $item->write(); $updatecount++; } } } if ($removecount) { $messages['remove'] = _t('CartForm.REMOVED_ITEMS', "Removed {count} items.", "count is the amount that was removed", array('count' => $removecount)); } if ($updatecount) { $messages['updatecount'] = _t('CartForm.UPDATED_ITEMS', "Updated {count} items.", "count is the amount that was updated", array('count' => $updatecount)); } if (count($messages)) { $form->sessionMessage(implode(" ", $messages), "good"); } $this->extend('updateCartFormResponse', $request, $response, $form); return $response ? $response : $this->controller->redirectBack(); }
public function addtocart($data, $form) { if ($buyable = $this->getBuyable($data)) { $cart = ShoppingCart::singleton(); $request = $this->getRequest(); $order = $cart->current(); if ($request && $request->isAjax() && $order) { ShopTools::install_locale($order->Locale); } $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $data; $quantity = isset($data['Quantity']) ? (int) $data['Quantity'] : 1; $cart->add($buyable, $quantity, $saveabledata); if (!ShoppingCart_Controller::config()->direct_to_cart_page) { $form->SessionMessage($cart->getMessage(), $cart->getMessageType()); } $this->extend('updateAddToCart', $form, $buyable); $this->extend('updateAddProductFormResponse', $request, $response, $buyable, $quantity, $form); return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType()); } }
/** * 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(); $request = $this->getRequest(); $order = $cart->current(); if ($request && $request->isAjax() && $order) { ShopTools::install_locale($order->Locale); } // 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(_t('ShoppingCart.ITEMADD', "Item has been added successfully."), "good"); } else { $form->sessionMessage($cart->getMessage(), $cart->getMessageType()); } } else { $variation = null; $form->sessionMessage(_t('VariationForm.VARIATION_NOT_AVAILABLE', "That variation is not available, sorry."), "bad"); //validation fail } $this->extend('updateVariationAddToCart', $form, $variation); $this->extend('updateVariationFormResponse', $request, $response, $variation, $quantity, $form); return $response ? $response : ShoppingCart_Controller::direct(); }
protected function updateLocale($request) { $order = $this->cart->current(); if ($request && $request->isAjax() && $order) { ShopTools::install_locale($order->Locale); } }
/** * Takes an order from being a cart to awaiting payment. * * @param Member $member - assign a member to the order * * @return boolean - success/failure */ public function placeOrder() { if (!$this->order) { $this->error(_t("OrderProcessor.NoOrderStarted", "A new order has not yet been started.")); return false; } if (!$this->canPlace($this->order)) { //final cart validation return false; } if ($this->order->Locale) { ShopTools::install_locale($this->order->Locale); } // recalculate order to be sure we have the correct total $this->order->calculate(); if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionStart(); } //update status if ($this->order->TotalOutstanding(false)) { $this->order->Status = 'Unpaid'; } else { $this->order->Status = 'Paid'; } if (!$this->order->Placed) { $this->order->Placed = SS_Datetime::now()->Rfc2822(); //record placed order datetime if ($request = Controller::curr()->getRequest()) { $this->order->IPAddress = $request->getIP(); //record client IP } } // Add an error handler that throws an exception upon error, so that we can catch errors as exceptions // in the following block. set_error_handler(function ($severity, $message, $file, $line) { throw new ErrorException($message, 0, $severity, $file, $line); }, E_ALL & ~(E_STRICT | E_NOTICE)); try { //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again $items = $this->order->Items(); if ($items->exists()) { foreach ($items as $item) { $item->onPlacement(); $item->write(); } } $modifiers = $this->order->Modifiers(); if ($modifiers->exists()) { foreach ($modifiers as $modifier) { $modifier->write(); } } //add member to order & customers group if ($member = Member::currentUser()) { if (!$this->order->MemberID) { $this->order->MemberID = $member->ID; } $cgroup = ShopConfig::current()->CustomerGroup(); if ($cgroup->exists()) { $member->Groups()->add($cgroup); } } //allow decorators to do stuff when order is saved. $this->order->extend('onPlaceOrder'); $this->order->write(); } catch (Exception $ex) { // Rollback the transaction if an error occurred if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionRollback(); } $this->error($ex->getMessage()); return false; } finally { // restore the error handler, no matter what restore_error_handler(); } // Everything went through fine, complete the transaction if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionEnd(); } //remove from session $cart = ShoppingCart::curr(); if ($cart && $cart->ID == $this->order->ID) { // clear the cart, but don't write the order in the process (order is finalized and should NOT be overwritten) ShoppingCart::singleton()->clear(false); } //send confirmation if configured and receipt hasn't been sent if (self::config()->send_confirmation && !$this->order->ReceiptSent) { $this->notifier->sendConfirmation(); } //notify admin, if configured if (self::config()->send_admin_notification) { $this->notifier->sendAdminNotification(); } // Save order reference to session OrderManipulation::add_session_order($this->order); return true; //report success }
/** * Takes an order from being a cart to awaiting payment. * * @param Member $member - assign a member to the order * * @return boolean - success/failure */ public function placeOrder() { if (!$this->order) { $this->error(_t("OrderProcessor.NULL", "A new order has not yet been started.")); return false; } if (!$this->canPlace($this->order)) { //final cart validation return false; } if ($this->order->Locale) { ShopTools::install_locale($this->order->Locale); } //remove from session $cart = ShoppingCart::curr(); if ($cart && $cart->ID == $this->order->ID) { ShoppingCart::singleton()->clear(); } //update status if ($this->order->TotalOutstanding()) { $this->order->Status = 'Unpaid'; } else { $this->order->Status = 'Paid'; } if (!$this->order->Placed) { $this->order->Placed = SS_Datetime::now()->Rfc2822(); //record placed order datetime if ($request = Controller::curr()->getRequest()) { $this->order->IPAddress = $request->getIP(); //record client IP } } //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again $items = $this->order->Items(); if ($items->exists()) { foreach ($items as $item) { $item->onPlacement(); $item->write(); } } $modifiers = $this->order->Modifiers(); if ($modifiers->exists()) { foreach ($modifiers as $modifier) { $modifier->write(); } } //add member to order & customers group if ($member = Member::currentUser()) { if (!$this->order->MemberID) { $this->order->MemberID = $member->ID; } $cgroup = ShopConfig::current()->CustomerGroup(); if ($cgroup->exists()) { $member->Groups()->add($cgroup); } } //allow decorators to do stuff when order is saved. $this->order->extend('onPlaceOrder'); $this->order->write(); //send confirmation if configured and receipt hasn't been sent if (self::config()->send_confirmation && !$this->order->ReceiptSent) { $this->notifier->sendConfirmation(); } //notify admin, if configured if (self::config()->send_admin_notification) { $this->notifier->sendAdminNotification(); } // Save order reference to session OrderManipulation::add_session_order($this->order); return true; //report success }
/** * Force creating an order reference */ protected function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->getField("Reference") && in_array($this->Status, self::$placed_status)) { $this->generateReference(); } // perform status transition if ($this->isInDB() && $this->isChanged('Status')) { $this->statusTransition(empty($this->original['Status']) ? 'Cart' : $this->original['Status'], $this->Status); } // While the order is unfinished/cart, always store the current locale with the order. // We do this everytime an order is saved, because the user might change locale (language-switch). if ($this->Status == 'Cart') { $this->Locale = ShopTools::get_current_locale(); } }
/** * Force creating an order reference */ public function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->getField("Reference") && in_array($this->Status, self::$placed_status)) { $this->generateReference(); } // While the order is unfinished/cart, always store the current locale with the order. // We do this everytime an order is saved, because the user might change locale (language-switch). if ($this->Status == 'Cart') { $this->Locale = ShopTools::get_current_locale(); } }
public function testPlaceFailure() { if (!ShopTools::DBConn()->supportsTransactions()) { $this->markTestSkipped('The Database doesn\'t support transactions.'); } // Add the erroneous extension Order::add_extension('OrderProcessorTest_PlaceFailExtension'); Config::inst()->update('Product', 'order_item', 'OrderProcessorTest_CustomOrderItem'); //log out the admin user Member::currentUser()->logOut(); $joemember = $this->objFromFixture('Member', 'joebloggs'); $joemember->logIn(); $this->shoppingcart->add($this->mp3player); $cart = ShoppingCart::curr(); $cart->calculate(); $this->assertDOSContains(array(array('ClassName' => 'OrderProcessorTest_CustomOrderItem')), $cart->Items()); $versions = Product_OrderItem::get()->filter('OrderID', $cart->ID)->column('ProductVersion'); // The Product_OrderItem should not reference a product version while the order is not placed $this->assertEquals(array(0), $versions); $this->assertTrue($cart->has_extension('OrderProcessorTest_PlaceFailExtension')); // Placing the order will fail. $this->assertFalse($this->placeOrder('Joseph', 'Blog', '*****@*****.**', '100 Melrose Place', null, 'Martinsonville', 'New Mexico', null, 'EG', 'newpassword', 'newpassword', $joemember), "Member order placed successfully"); $order = Order::get()->byID($cart->ID); //update order variable to db-stored version $this->assertNotNull($this->shoppingcart->current(), "Shopping is still present"); $this->assertNotNull($order); $this->assertNull($order->Placed); $this->assertEquals($order->Status, 'Cart', 'Status should still be "Cart"'); // When order failed, everything that was written during the placement should be rolled back $versions = Product_OrderItem::get()->filter('OrderID', $cart->ID)->column('ProductVersion'); // The Product_OrderItem should still not reference a product if the rollback worked $this->assertEquals(array(0), $versions); $this->assertEquals(0, OrderProcessorTest_CustomOrderItem::get()->filter('OrderID', $cart->ID)->first()->IsPlaced); Order::remove_extension('OrderProcessorTest_PlaceFailExtension'); $this->shoppingcart->clear(false); }