Example #1
0
 /**
  * @return Order
  */
 public function getOrder()
 {
     if ($this->order_id && !$this->order) {
         $this->order = Product::getById($this->order_id);
     }
     return $this->product;
 }
Example #2
0
 public function indexAction()
 {
     $this->view->Title = 'Đặt hàng';
     $this->view->headTitle($this->view->Title);
     $id = $this->getRequest()->getParam("id_product");
     $Product = Product::getById($id);
     if ($this->getRequest()->isPost()) {
         $request = $this->getRequest()->getParams();
         $error = $this->_checkForm($request);
         if (count($error) == 0) {
             $Contact = new Contact();
             $Contact->merge($request);
             $Contact->created_date = date("Y-m-d H:i:s");
             $Contact->save();
             //$_SESSION['msg'] = "Yêu cầu đặt hàng của bạn đã được gửi, xin trân thành cảm ơn!";
             My_Plugin_Libs::setSplash('<b>Yêu cầu đặt hàng của bạn đã được gửi, xin trân thành cảm ơn!</b>');
             $this->_redirect($this->_helper->url('index', 'contact', 'default'));
         }
         if (count($error)) {
             $this->view->error = $error;
         }
     }
     $this->view->Product = $Product;
     $this->view->Contact = $Contact;
 }
Example #3
0
 public function detailsAction()
 {
     $id = $this->getRequest()->getParam("product_id");
     $Product = Product::getById($id);
     $this->view->Product = $Product;
     $this->view->Title = $Product->product_name;
     $this->view->headTitle($this->view->Title);
 }
Example #4
0
 function getProducts()
 {
     $ProductID = $this->f3->get('PARAMS.ProductID');
     $p = new Product($this->db);
     //$products = $product->all();
     if (isset($ProductID)) {
         $products = $p->getById($ProductID);
     } else {
         $products = $p->all();
     }
     echo $this->utils->successResponse($p, $products);
 }
Example #5
0
 function editProduct($post)
 {
     $ProductID = $this->f3->get('PARAMS.ProductID');
     $post = json_decode($this->f3->get('BODY'), true);
     $p = new Product($this->db);
     $products = $p->getById($this->userID, $ProductID);
     $product = $products[0];
     $product->ProductName = $post['ProductName'];
     $product->ProductDesc = filter_var($post['ProductDesc'], FILTER_SANITIZE_STRING);
     $product->ProductPrice = $post['ProductPrice'];
     if ($this->debug) {
         $this->utils->debug(__METHOD__, $product->cast());
     }
     $product->save();
     echo $this->utils->successResponse($product, null);
 }
Example #6
0
 public function testResolveProductHasManyProductCategoriesFromPost()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $category1 = ProductCategoryTestHelper::createProductCategoryByName('Test Product Category');
     $category2 = ProductCategoryTestHelper::createProductCategoryByName('Test Product Category2');
     $product = ProductTestHelper::createProductByNameForOwner('I am testing products', $super);
     $postData = array('categoryIds' => $category1->id . ',' . $category2->id);
     // Not Coding Standard
     $id = $product->id;
     $product->forget();
     unset($product);
     $product = Product::getById($id);
     $categories = ProductCategoriesUtil::resolveProductHasManyProductCategoriesFromPost($product, $postData);
     $this->assertEquals(count($categories), 2);
     $this->assertEquals($categories[$category1->id]->id, $category1->id);
 }
 public function testSuperUserEditProductPortletControllerAction()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $products = Product::getAll();
     $this->assertEquals(1, count($products));
     $superProductId = self::getModelIdByModelNameAndName('Product', 'My Product 1');
     $this->setGetArray(array('attribute' => 'sellPrice', 'item' => $superProductId, 'value' => '300.54'));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/update', true);
     //Save product.
     $superProduct = Product::getById($superProductId);
     $this->assertEquals(300.54, $superProduct->sellPrice->value);
     $this->setGetArray(array('attribute' => 'sellPrice', 'item' => $superProductId, 'value' => '3000.54'));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/update', true);
     //Save product.
     $superProduct = Product::getById($superProductId);
     $this->assertEquals(3000.54, $superProduct->sellPrice->value);
     $this->setGetArray(array('attribute' => 'quantity', 'item' => $superProductId, 'value' => '10'));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/update', true);
     //Save product.
     $superProduct = Product::getById($superProductId);
     $this->assertEquals(10, $superProduct->quantity);
 }
Example #8
0
 /**
  * Processes the Order
  *
  * Verifies all data, updates and stores it in the database, and
  * initializes payment
  * @return  boolean         True on successs, false otherwise
  */
 static function process()
 {
     global $objDatabase, $_ARRAYLANG;
     // FOR TESTING ONLY (repeatedly process/store the order, also disable self::destroyCart())
     //$_SESSION['shop']['order_id'] = NULL;
     // Verify that the order hasn't yet been saved
     // (and has thus not yet been confirmed)
     if (isset($_SESSION['shop']['order_id'])) {
         return \Message::error($_ARRAYLANG['TXT_ORDER_ALREADY_PLACED']);
     }
     // No more confirmation
     self::$objTemplate->hideBlock('shopConfirm');
     // Store the customer, register the order
     $customer_ip = $_SERVER['REMOTE_ADDR'];
     $customer_host = substr(@gethostbyaddr($_SERVER['REMOTE_ADDR']), 0, 100);
     $customer_browser = substr(getenv('HTTP_USER_AGENT'), 0, 100);
     $new_customer = false;
     //\DBG::log("Shop::process(): E-Mail: ".$_SESSION['shop']['email']);
     if (self::$objCustomer) {
         //\DBG::log("Shop::process(): Existing User username ".$_SESSION['shop']['username'].", email ".$_SESSION['shop']['email']);
     } else {
         // Registered Customers are required to be logged in!
         self::$objCustomer = Customer::getRegisteredByEmail($_SESSION['shop']['email']);
         if (self::$objCustomer) {
             \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_REGISTERED_EMAIL']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'login') . '?redirect=' . base64_encode(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'confirm')));
         }
         // Unregistered Customers are stored as well, as their information is needed
         // nevertheless.  Their active status, however, is set to false.
         self::$objCustomer = Customer::getUnregisteredByEmail($_SESSION['shop']['email']);
         if (!self::$objCustomer) {
             self::$objCustomer = new Customer();
             // Currently, the e-mail address is set as the user name
             $_SESSION['shop']['username'] = $_SESSION['shop']['email'];
             //\DBG::log("Shop::process(): New User username ".$_SESSION['shop']['username'].", email ".$_SESSION['shop']['email']);
             self::$objCustomer->username($_SESSION['shop']['username']);
             self::$objCustomer->email($_SESSION['shop']['email']);
             // Note that the password is unset when the Customer chooses
             // to order without registration.  The generated one
             // defaults to length 8, fulfilling the requirements for
             // complex passwords.  And it's kept absolutely secret.
             $password = empty($_SESSION['shop']['password']) ? \User::make_password() : $_SESSION['shop']['password'];
             //\DBG::log("Password: $password (session: {$_SESSION['shop']['password']})");
             if (!self::$objCustomer->password($password)) {
                 \Message::error($_ARRAYLANG['TXT_INVALID_PASSWORD']);
                 \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'account'));
             }
             self::$objCustomer->active(empty($_SESSION['shop']['dont_register']));
             $new_customer = true;
         }
     }
     // Update the Customer object from the session array
     // (whether new or not -- it may have been edited)
     self::$objCustomer->gender($_SESSION['shop']['gender']);
     self::$objCustomer->firstname($_SESSION['shop']['firstname']);
     self::$objCustomer->lastname($_SESSION['shop']['lastname']);
     self::$objCustomer->company($_SESSION['shop']['company']);
     self::$objCustomer->address($_SESSION['shop']['address']);
     self::$objCustomer->city($_SESSION['shop']['city']);
     self::$objCustomer->zip($_SESSION['shop']['zip']);
     self::$objCustomer->country_id($_SESSION['shop']['countryId']);
     self::$objCustomer->phone($_SESSION['shop']['phone']);
     self::$objCustomer->fax($_SESSION['shop']['fax']);
     $arrGroups = self::$objCustomer->getAssociatedGroupIds();
     $usergroup_id = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_reseller', 'Shop');
     if (empty($usergroup_id)) {
         //\DBG::log("Shop::process(): ERROR: Missing reseller group");
         \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_USERGROUP_INVALID']);
         \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', ''));
     }
     if (!in_array($usergroup_id, $arrGroups)) {
         //\DBG::log("Shop::process(): Customer is not in Reseller group (ID $usergroup_id)");
         // Not a reseller.  See if she's a final customer
         $usergroup_id = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_customer', 'Shop');
         if (empty($usergroup_id)) {
             //\DBG::log("Shop::process(): ERROR: Missing final customer group");
             \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_USERGROUP_INVALID']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', ''));
         }
         if (!in_array($usergroup_id, $arrGroups)) {
             //\DBG::log("Shop::process(): Customer is not in final customer group (ID $usergroup_id), either");
             // Neither one, add to the final customer group (default)
             $arrGroups[] = $usergroup_id;
             self::$objCustomer->setGroups($arrGroups);
             //\DBG::log("Shop::process(): Added Customer to final customer group (ID $usergroup_id): ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
         } else {
             //\DBG::log("Shop::process(): Customer is a final customer (ID $usergroup_id) already: ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
         }
     } else {
         //\DBG::log("Shop::process(): Customer is a Reseller (ID $usergroup_id) already: ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
     }
     // Insert or update the customer
     //\DBG::log("Shop::process(): Storing Customer: ".var_export(self::$objCustomer, true));
     if (!self::$objCustomer->store()) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_ERROR_STORING']);
     }
     // Authenticate new Customer
     if ($new_customer) {
         // Fails for "unregistered" Customers!
         if (self::$objCustomer->auth($_SESSION['shop']['username'], $_SESSION['shop']['password'], false, true)) {
             if (!self::_authenticate()) {
                 return \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_ERROR_STORING']);
             }
         }
     }
     //die();
     // Clear the ship-to country if there is no shipping
     if (!Cart::needs_shipment()) {
         $_SESSION['shop']['countryId2'] = 0;
     }
     $shipper_id = empty($_SESSION['shop']['shipperId']) ? null : $_SESSION['shop']['shipperId'];
     $payment_id = empty($_SESSION['shop']['paymentId']) ? null : $_SESSION['shop']['paymentId'];
     $objOrder = new Order();
     $objOrder->customer_id(self::$objCustomer->id());
     $objOrder->billing_gender($_SESSION['shop']['gender']);
     $objOrder->billing_firstname($_SESSION['shop']['firstname']);
     $objOrder->billing_lastname($_SESSION['shop']['lastname']);
     $objOrder->billing_company($_SESSION['shop']['company']);
     $objOrder->billing_address($_SESSION['shop']['address']);
     $objOrder->billing_city($_SESSION['shop']['city']);
     $objOrder->billing_zip($_SESSION['shop']['zip']);
     $objOrder->billing_country_id($_SESSION['shop']['countryId']);
     $objOrder->billing_phone($_SESSION['shop']['phone']);
     $objOrder->billing_fax($_SESSION['shop']['fax']);
     $objOrder->billing_email($_SESSION['shop']['email']);
     $objOrder->currency_id($_SESSION['shop']['currencyId']);
     $objOrder->sum($_SESSION['shop']['grand_total_price']);
     $objOrder->date_time(date(ASCMS_DATE_FORMAT_INTERNATIONAL_DATETIME));
     $objOrder->status(0);
     $objOrder->company($_SESSION['shop']['company2']);
     $objOrder->gender($_SESSION['shop']['gender2']);
     $objOrder->firstname($_SESSION['shop']['firstname2']);
     $objOrder->lastname($_SESSION['shop']['lastname2']);
     $objOrder->address($_SESSION['shop']['address2']);
     $objOrder->city($_SESSION['shop']['city2']);
     $objOrder->zip($_SESSION['shop']['zip2']);
     $objOrder->country_id($_SESSION['shop']['countryId2']);
     $objOrder->phone($_SESSION['shop']['phone2']);
     $objOrder->vat_amount($_SESSION['shop']['vat_price']);
     $objOrder->shipment_amount($_SESSION['shop']['shipment_price']);
     $objOrder->shipment_id($shipper_id);
     $objOrder->payment_id($payment_id);
     $objOrder->payment_amount($_SESSION['shop']['payment_price']);
     $objOrder->ip($customer_ip);
     $objOrder->host($customer_host);
     $objOrder->lang_id(FRONTEND_LANG_ID);
     $objOrder->browser($customer_browser);
     $objOrder->note($_SESSION['shop']['note']);
     if (!$objOrder->insert()) {
         // $order_id is unset!
         return \Message::error($_ARRAYLANG['TXT_SHOP_ORDER_ERROR_STORING']);
     }
     $order_id = $objOrder->id();
     $_SESSION['shop']['order_id'] = $order_id;
     // The products will be tested one by one below.
     // If any single one of them requires delivery, this
     // flag will be set to true.
     // This is used to determine the order status at the
     // end of the shopping process.
     $_SESSION['shop']['isDelivery'] = false;
     // Try to redeem the Coupon, if any
     $coupon_code = isset($_SESSION['shop']['coupon_code']) ? $_SESSION['shop']['coupon_code'] : null;
     //\DBG::log("Cart::update(): Coupon Code: $coupon_code");
     $items_total = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach (Cart::get_products_array() as $arrProduct) {
         $objProduct = Product::getById($arrProduct['id']);
         if (!$objProduct) {
             unset($_SESSION['shop']['order_id']);
             return \Message::error($_ARRAYLANG['TXT_ERROR_LOOKING_UP_ORDER']);
         }
         $product_id = $arrProduct['id'];
         $name = $objProduct->name();
         $priceOptions = !empty($arrProduct['optionPrice']) ? $arrProduct['optionPrice'] : 0;
         $quantity = $arrProduct['quantity'];
         $price = $objProduct->get_custom_price(self::$objCustomer, $priceOptions, $quantity);
         $item_total = $price * $quantity;
         $items_total += $item_total;
         $productVatId = $objProduct->vat_id();
         $vat_rate = $productVatId && Vat::getRate($productVatId) ? Vat::getRate($productVatId) : '0.00';
         // Test the distribution method for delivery
         $productDistribution = $objProduct->distribution();
         if ($productDistribution == 'delivery') {
             $_SESSION['shop']['isDelivery'] = true;
         }
         $weight = $productDistribution == 'delivery' ? $objProduct->weight() : 0;
         // grams
         if ($weight == '') {
             $weight = 0;
         }
         // Add to order items table
         $result = $objOrder->insertItem($order_id, $product_id, $name, $price, $quantity, $vat_rate, $weight, $arrProduct['options']);
         if (!$result) {
             unset($_SESSION['shop']['order_id']);
             // TODO: Verify error message set by Order::insertItem()
             return false;
         }
         // Store the Product Coupon, if applicable.
         // Note that it is not redeemed yet (uses=0)!
         if ($coupon_code) {
             $objCoupon = Coupon::available($coupon_code, $item_total, self::$objCustomer->id(), $product_id, $payment_id);
             if ($objCoupon) {
                 //\DBG::log("Shop::process(): Got Coupon for Product ID $product_id: ".var_export($objCoupon, true));
                 if (!$objCoupon->redeem($order_id, self::$objCustomer->id(), $price * $quantity, 0)) {
                     // TODO: Do something if the Coupon does not work
                     \DBG::log("Shop::process(): ERROR: Failed to store Coupon for Product ID {$product_id}");
                 }
                 $coupon_code = null;
             }
         }
     }
     // foreach product in cart
     // Store the Global Coupon, if applicable.
     // Note that it is not redeemed yet (uses=0)!
     //\DBG::log("Shop::process(): Looking for global Coupon $coupon_code");
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $items_total, self::$objCustomer->id(), null, $payment_id);
         if ($objCoupon) {
             //\DBG::log("Shop::process(): Got global Coupon: ".var_export($objCoupon, true));
             if (!$objCoupon->redeem($order_id, self::$objCustomer->id(), $items_total, 0)) {
                 \DBG::log("Shop::process(): ERROR: Failed to store global Coupon");
             }
         }
     }
     \Message::restore();
     $processor_id = Payment::getProperty($_SESSION['shop']['paymentId'], 'processor_id');
     $processor_name = PaymentProcessing::getPaymentProcessorName($processor_id);
     // other payment methods
     PaymentProcessing::initProcessor($processor_id);
     // TODO: These arguments are no longer valid.  Set them up later?
     //            Currency::getActiveCurrencyCode(),
     //            FWLanguage::getLanguageParameter(FRONTEND_LANG_ID, 'lang'));
     // if the processor is Internal_LSV, and there is account information,
     // store the information.
     if ($processor_name == 'internal_lsv') {
         if (!self::lsv_complete()) {
             // Missing mandatory data; return to payment
             unset($_SESSION['shop']['order_id']);
             \Message::error($_ARRAYLANG['TXT_ERROR_ACCOUNT_INFORMATION_NOT_AVAILABLE']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'payment'));
         }
         $query = "\n                INSERT INTO " . DBPREFIX . "module_shop" . MODULE_INDEX . "_lsv (\n                    order_id, holder, bank, blz\n                ) VALUES (\n                    {$order_id},\n                    '" . contrexx_raw2db($_SESSION['shop']['account_holder']) . "',\n                    '" . contrexx_raw2db($_SESSION['shop']['account_bank']) . "',\n                    '" . contrexx_raw2db($_SESSION['shop']['account_blz']) . "'\n                )";
         $objResult = $objDatabase->Execute($query);
         if (!$objResult) {
             // Return to payment
             unset($_SESSION['shop']['order_id']);
             \Message::error($_ARRAYLANG['TXT_ERROR_INSERTING_ACCOUNT_INFORMATION']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'payment'));
         }
     }
     $_SESSION['shop']['order_id_checkin'] = $order_id;
     $strProcessorType = PaymentProcessing::getCurrentPaymentProcessorType();
     // Test whether the selected payment method can be
     // considered an instant or deferred one.
     // This is used to set the order status at the end
     // of the shopping process.
     // TODO: Invert this flag, as it may no longer be present after paying
     // online using one of the external payment methods!  Ensure that it is set
     // instead when paying "deferred".
     $_SESSION['shop']['isInstantPayment'] = false;
     if ($strProcessorType == 'external') {
         // For the sake of simplicity, all external payment
         // methods are considered to be 'instant'.
         // All currently implemented internal methods require
         // further action from the merchant, and thus are
         // considered to be 'deferred'.
         $_SESSION['shop']['isInstantPayment'] = true;
     }
     // Send the Customer login separately, as the password possibly
     // won't be available later
     if (!empty($_SESSION['shop']['password'])) {
         self::sendLogin(self::$objCustomer->email(), $_SESSION['shop']['password']);
     }
     // Show payment processing page.
     // Note that some internal payments are redirected away
     // from this page in checkOut():
     // 'internal', 'internal_lsv'
     self::$objTemplate->setVariable('SHOP_PAYMENT_PROCESSING', PaymentProcessing::checkOut());
     // Clear the order ID.
     // The order may be resubmitted and the payment retried.
     unset($_SESSION['shop']['order_id']);
     // Custom.
     // Enable if Discount class is customized and in use.
     //self::showCustomerDiscount(Cart::get_price());
     return true;
 }
 public function testUpdateRelatedCatalogItemOnAProductBySellPriceCriteria()
 {
     $super = User::getByUsername('super');
     $contactStates = ContactState::getAll();
     //Create workflow
     $workflow = new Workflow();
     $workflow->setDescription('aDescription');
     $workflow->setIsActive(true);
     $workflow->setOrder(1);
     $workflow->setModuleClassName('ProductsModule');
     $workflow->setName('myFirstProductWorkflow');
     $workflow->setTriggerOn(Workflow::TRIGGER_ON_NEW_AND_EXISTING);
     $workflow->setType(Workflow::TYPE_ON_SAVE);
     $workflow->setTriggersStructure('1');
     //Add Trigger
     $trigger = new TriggerForWorkflowForm('ProductsModule', 'Product', Workflow::TYPE_ON_SAVE);
     $trigger->attributeIndexOrDerivedType = 'sellPrice';
     $trigger->value = 600;
     $trigger->operator = 'greaterThanOrEqualTo';
     $workflow->addTrigger($trigger);
     //Add action
     $currencies = Currency::getAll();
     $action = new ActionForWorkflowForm('Product', Workflow::TYPE_ON_SAVE);
     $action->type = ActionForWorkflowForm::TYPE_UPDATE_RELATED;
     $action->relation = 'productTemplate';
     $attributes = array('description' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 'Set Price'), 'priceFrequency' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 2), 'listPrice' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 800, 'currencyId' => $currencies[0]->id), 'cost' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 700, 'currencyId' => $currencies[0]->id));
     $action->setAttributes(array(ActionForWorkflowForm::ACTION_ATTRIBUTES => $attributes));
     $workflow->addAction($action);
     //Create the saved Workflow
     $savedWorkflow = new SavedWorkflow();
     SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
     $saved = $savedWorkflow->save();
     $this->assertTrue($saved);
     $productTemplate = ProductTemplateTestHelper::createProductTemplateByName('superProductTemplate');
     $productTemplates = ProductTemplate::getByName('superProductTemplate');
     $product = ProductTestHelper::createProductByNameForOwner('Test Product', $super);
     $this->assertTrue($product->id > 0);
     $product->productTemplate = $productTemplates[0];
     //Change product sell price
     $product->sellPrice->value = 650;
     $this->assertTrue(WorkflowTriggersUtil::areTriggersTrueBeforeSave($workflow, $product));
     $saved = $product->save();
     $this->assertTrue($saved);
     $productId = $product->id;
     $product->forget();
     $product = Product::getById($productId);
     $this->assertEquals('Set Price', $product->productTemplate->description);
     $this->assertEquals(2, $product->productTemplate->priceFrequency);
     $this->assertEquals(700, $product->productTemplate->cost->value);
     $this->assertEquals(800, $product->productTemplate->listPrice->value);
 }
 /**
  * @deletes selected products.
  */
 public function testMassDeleteActionsForSelectedIds()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $products = Product::getAll();
     $this->assertEquals(13, count($products));
     $superProductId = self::getModelIdByModelNameAndName('Product', 'My Product 1');
     $superProductId2 = self::getModelIdByModelNameAndName('Product', 'My Product 2');
     $superProductId3 = self::getModelIdByModelNameAndName('Product', 'My Product 3');
     $superProductId4 = self::getModelIdByModelNameAndName('Product', 'My Product 4');
     $superProductId5 = self::getModelIdByModelNameAndName('Product', 'My Product 5');
     $superProductId6 = self::getModelIdByModelNameAndName('Product', 'My Product 6');
     $superProductId7 = self::getModelIdByModelNameAndName('Product', 'My Product 7');
     $superProductId8 = self::getModelIdByModelNameAndName('Product', 'My Product 8');
     $superProductId9 = self::getModelIdByModelNameAndName('Product', 'My Product 9');
     $superProductId10 = self::getModelIdByModelNameAndName('Product', 'My Product 10');
     $superProductId11 = self::getModelIdByModelNameAndName('Product', 'My Product 11');
     $superProductId12 = self::getModelIdByModelNameAndName('Product', 'My Product 12');
     //Load Model MassDelete Views.
     //MassDelete view for single selected ids
     $this->setGetArray(array('selectedIds' => '5,6,7,8,9', 'selectAll' => ''));
     // Not Coding Standard
     $this->resetPostArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('products/default/massDelete');
     $this->assertFalse(strpos($content, '<strong>5</strong>&#160;Products selected for removal') === false);
     //MassDelete view for all result selected ids
     $this->setGetArray(array('selectAll' => '1'));
     $this->resetPostArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('products/default/massDelete');
     $this->assertFalse(strpos($content, '<strong>13</strong>&#160;Products selected for removal') === false);
     //MassDelete for selected Record Count
     $products = Product::getAll();
     $this->assertEquals(13, count($products));
     //MassDelete for selected ids for paged scenario
     $superProduct1 = Product::getById($superProductId);
     $superProduct2 = Product::getById($superProductId2);
     $superProduct3 = Product::getById($superProductId3);
     $superProduct4 = Product::getById($superProductId4);
     $superProduct5 = Product::getById($superProductId5);
     $superProduct6 = Product::getById($superProductId6);
     $superProduct7 = Product::getById($superProductId7);
     $pageSize = Yii::app()->pagination->getForCurrentUserByType('massDeleteProgressPageSize');
     $this->assertEquals(5, $pageSize);
     //MassDelete for selected ids for page 1
     $this->setGetArray(array('selectedIds' => $superProductId . ',' . $superProductId2 . ',' . $superProductId3 . ',' . $superProductId4 . ',' . $superProductId5 . ',' . $superProductId6 . ',' . $superProductId7, 'selectAll' => '', 'massDelete' => '', 'Product_page' => 1));
     $this->setPostArray(array('selectedRecordCount' => 7));
     $this->runControllerWithExitExceptionAndGetContent('products/default/massDelete');
     //MassDelete for selected Record Count
     $products = Product::getAll();
     $this->assertEquals(8, count($products));
     //MassDelete for selected ids for page 2
     $this->setGetArray(array('selectedIds' => $superProductId . ',' . $superProductId2 . ',' . $superProductId3 . ',' . $superProductId4 . ',' . $superProductId5 . ',' . $superProductId6 . ',' . $superProductId7, 'selectAll' => '', 'massDelete' => '', 'Product_page' => 2));
     $this->setPostArray(array('selectedRecordCount' => 7));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/massDeleteProgress');
     //MassDelete for selected Record Count
     $products = Product::getAll();
     $this->assertEquals(6, count($products));
 }
Example #11
0
 /**
  * Returns an array with all placeholders and their values to be
  * replaced in any shop mailtemplate for the given order ID.
  *
  * You only have to set the 'substitution' index value of your MailTemplate
  * array to the array returned.
  * Customer data is not included here.  See {@see Customer::getSubstitutionArray()}.
  * Note that this method is now mostly independent of the current session.
  * The language of the mail template is determined by the browser
  * language range stored with the order.
  * @access  private
  * @static
  * @param   integer $order_id     The order ID
  * @param   boolean $create_accounts  If true, creates User accounts
  *                                    and Coupon codes.  Defaults to true
  * @return  array                 The array with placeholders as keys
  *                                and values from the order on success,
  *                                false otherwise
  */
 static function getSubstitutionArray($order_id, $create_accounts = true)
 {
     global $_ARRAYLANG;
     /*
                 $_ARRAYLANG['TXT_SHOP_URI_FOR_DOWNLOAD'].":\r\n".
                 'http://'.$_SERVER['SERVER_NAME'].
                 "/index.php?section=download\r\n";
     */
     $objOrder = Order::getById($order_id);
     if (!$objOrder) {
         // Order not found
         return false;
     }
     $lang_id = $objOrder->lang_id();
     if (!intval($lang_id)) {
         $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id);
     }
     $status = $objOrder->status();
     $customer_id = $objOrder->customer_id();
     $customer = Customer::getById($customer_id);
     $payment_id = $objOrder->payment_id();
     $shipment_id = $objOrder->shipment_id();
     $arrSubstitution = array('CUSTOMER_COUNTRY_ID' => $objOrder->billing_country_id(), 'LANG_ID' => $lang_id, 'NOW' => date(ASCMS_DATE_FORMAT_DATETIME), 'TODAY' => date(ASCMS_DATE_FORMAT_DATE), 'ORDER_ID' => $order_id, 'ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order_id), 'ORDER_DATE' => date(ASCMS_DATE_FORMAT_DATE, strtotime($objOrder->date_time())), 'ORDER_TIME' => date(ASCMS_DATE_FORMAT_TIME, strtotime($objOrder->date_time())), 'ORDER_STATUS_ID' => $status, 'ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $status], 'MODIFIED' => date(ASCMS_DATE_FORMAT_DATETIME, strtotime($objOrder->modified_on())), 'REMARKS' => $objOrder->note(), 'ORDER_SUM' => sprintf('% 9.2f', $objOrder->sum()), 'CURRENCY' => Currency::getCodeById($objOrder->currency_id()));
     $arrSubstitution += $customer->getSubstitutionArray();
     if ($shipment_id) {
         $arrSubstitution += array('SHIPMENT' => array(0 => array('SHIPMENT_NAME' => sprintf('%-40s', Shipment::getShipperName($shipment_id)), 'SHIPMENT_PRICE' => sprintf('% 9.2f', $objOrder->shipment_amount()))), 'SHIPPING_ADDRESS' => array(0 => array('SHIPPING_COMPANY' => $objOrder->company(), 'SHIPPING_TITLE' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHIPPING_FIRSTNAME' => $objOrder->firstname(), 'SHIPPING_LASTNAME' => $objOrder->lastname(), 'SHIPPING_ADDRESS' => $objOrder->address(), 'SHIPPING_ZIP' => $objOrder->zip(), 'SHIPPING_CITY' => $objOrder->city(), 'SHIPPING_COUNTRY_ID' => $objOrder->country_id(), 'SHIPPING_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHIPPING_PHONE' => $objOrder->phone())));
     }
     if ($payment_id) {
         $arrSubstitution += array('PAYMENT' => array(0 => array('PAYMENT_NAME' => sprintf('%-40s', Payment::getNameById($payment_id)), 'PAYMENT_PRICE' => sprintf('% 9.2f', $objOrder->payment_amount()))));
     }
     $arrItems = $objOrder->getItems();
     if (!$arrItems) {
         \Message::warning($_ARRAYLANG['TXT_SHOP_ORDER_WARNING_NO_ITEM']);
     }
     // Deduct Coupon discounts, either from each Product price, or
     // from the items total.  Mind that the Coupon has already been
     // stored with the Order, but not redeemed yet.  This is done
     // in this method, but only if $create_accounts is true.
     $coupon_code = NULL;
     $coupon_amount = 0;
     $objCoupon = Coupon::getByOrderId($order_id);
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
     }
     $orderItemCount = 0;
     $total_item_price = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach ($arrItems as $item) {
         $product_id = $item['product_id'];
         $objProduct = Product::getById($product_id);
         if (!$objProduct) {
             //die("Product ID $product_id not found");
             continue;
         }
         //DBG::log("Orders::getSubstitutionArray(): Item: Product ID $product_id");
         $product_name = substr($item['name'], 0, 40);
         $item_price = $item['price'];
         $quantity = $item['quantity'];
         // TODO: Add individual VAT rates for Products
         //            $orderItemVatPercent = $objResultItem->fields['vat_percent'];
         // Decrease the Product stock count,
         // applies to "real", shipped goods only
         $objProduct->decreaseStock($quantity);
         $product_code = $objProduct->code();
         // Pick the order items attributes
         $str_options = '';
         // Any attributes?
         if ($item['attributes']) {
             $str_options = '  ';
             // '[';
             $attribute_name_previous = '';
             foreach ($item['attributes'] as $attribute_name => $arrAttribute) {
                 //DBG::log("Attribute /$attribute_name/ => ".var_export($arrAttribute, true));
                 // NOTE: The option price is optional and may be left out
                 foreach ($arrAttribute as $arrOption) {
                     $option_name = $arrOption['name'];
                     $option_price = $arrOption['price'];
                     $item_price += $option_price;
                     // Recognize the names of uploaded files,
                     // verify their presence and use the original name
                     $option_name_stripped = ShopLibrary::stripUniqidFromFilename($option_name);
                     $path = Order::UPLOAD_FOLDER . $option_name;
                     if ($option_name != $option_name_stripped && \File::exists($path)) {
                         $option_name = $option_name_stripped;
                     }
                     if ($attribute_name != $attribute_name_previous) {
                         if ($attribute_name_previous) {
                             $str_options .= '; ';
                         }
                         $str_options .= $attribute_name . ': ' . $option_name;
                         $attribute_name_previous = $attribute_name;
                     } else {
                         $str_options .= ', ' . $option_name;
                     }
                     // TODO: Add proper formatting with sprintf() and language entries
                     if ($option_price != 0) {
                         $str_options .= ' ' . Currency::formatPrice($option_price) . ' ' . Currency::getActiveCurrencyCode();
                     }
                 }
             }
             //                $str_options .= ']';
         }
         // Product details
         $arrProduct = array('PRODUCT_ID' => $product_id, 'PRODUCT_CODE' => $product_code, 'PRODUCT_QUANTITY' => $quantity, 'PRODUCT_TITLE' => $product_name, 'PRODUCT_OPTIONS' => $str_options, 'PRODUCT_ITEM_PRICE' => sprintf('% 9.2f', $item_price), 'PRODUCT_TOTAL_PRICE' => sprintf('% 9.2f', $item_price * $quantity));
         //DBG::log("Orders::getSubstitutionArray($order_id, $create_accounts): Adding article: ".var_export($arrProduct, true));
         $orderItemCount += $quantity;
         $total_item_price += $item_price * $quantity;
         if ($create_accounts) {
             // Add an account for every single instance of every Product
             for ($instance = 1; $instance <= $quantity; ++$instance) {
                 $validity = 0;
                 // Default to unlimited validity
                 // In case there are protected downloads in the cart,
                 // collect the group IDs
                 $arrUsergroupId = array();
                 if ($objProduct->distribution() == 'download') {
                     $usergroupIds = $objProduct->usergroup_ids();
                     if ($usergroupIds != '') {
                         $arrUsergroupId = explode(',', $usergroupIds);
                         $validity = $objProduct->weight();
                     }
                 }
                 // create an account that belongs to all collected
                 // user groups, if any.
                 if (count($arrUsergroupId) > 0) {
                     // The login names are created separately for
                     // each product instance
                     $username = self::usernamePrefix . "_{$order_id}_{$product_id}_{$instance}";
                     $userEmail = $username . '-' . $arrSubstitution['CUSTOMER_EMAIL'];
                     $userpass = \User::make_password();
                     $objUser = new \User();
                     $objUser->setUsername($username);
                     $objUser->setPassword($userpass);
                     $objUser->setEmail($userEmail);
                     $objUser->setAdminStatus(false);
                     $objUser->setActiveStatus(true);
                     $objUser->setGroups($arrUsergroupId);
                     $objUser->setValidityTimePeriod($validity);
                     $objUser->setFrontendLanguage(FRONTEND_LANG_ID);
                     $objUser->setBackendLanguage(FRONTEND_LANG_ID);
                     $objUser->setProfile(array('firstname' => array(0 => $arrSubstitution['CUSTOMER_FIRSTNAME']), 'lastname' => array(0 => $arrSubstitution['CUSTOMER_LASTNAME']), 'company' => array(0 => $arrSubstitution['CUSTOMER_COMPANY']), 'address' => array(0 => $arrSubstitution['CUSTOMER_ADDRESS']), 'zip' => array(0 => $arrSubstitution['CUSTOMER_ZIP']), 'city' => array(0 => $arrSubstitution['CUSTOMER_CITY']), 'country' => array(0 => $arrSubstitution['CUSTOMER_COUNTRY_ID']), 'phone_office' => array(0 => $arrSubstitution['CUSTOMER_PHONE']), 'phone_fax' => array(0 => $arrSubstitution['CUSTOMER_FAX'])));
                     if (!$objUser->store()) {
                         \Message::error(implode('<br />', $objUser->getErrorMsg()));
                         return false;
                     }
                     if (empty($arrProduct['USER_DATA'])) {
                         $arrProduct['USER_DATA'] = array();
                     }
                     $arrProduct['USER_DATA'][] = array('USER_NAME' => $username, 'USER_PASS' => $userpass);
                 }
                 //echo("Instance $instance");
                 if ($objProduct->distribution() == 'coupon') {
                     if (empty($arrProduct['COUPON_DATA'])) {
                         $arrProduct['COUPON_DATA'] = array();
                     }
                     //DBG::log("Orders::getSubstitutionArray(): Getting code");
                     $code = Coupon::getNewCode();
                     //DBG::log("Orders::getSubstitutionArray(): Got code: $code, calling Coupon::addCode($code, 0, 0, 0, $item_price)");
                     Coupon::storeCode($code, 0, 0, 0, $item_price, 0, 0, 10000000000.0, true);
                     $arrProduct['COUPON_DATA'][] = array('COUPON_CODE' => $code);
                 }
             }
             // Redeem the *product* Coupon, if possible for the Product
             if ($coupon_code) {
                 $objCoupon = Coupon::available($coupon_code, $item_price * $quantity, $customer_id, $product_id, $payment_id);
                 if ($objCoupon) {
                     $coupon_code = NULL;
                     $coupon_amount = $objCoupon->getDiscountAmount($item_price, $customer_id);
                     if ($create_accounts) {
                         $objCoupon->redeem($order_id, $customer_id, $item_price * $quantity);
                     }
                 }
                 //\DBG::log("Orders::getSubstitutionArray(): Got Product Coupon $coupon_code");
             }
         }
         if (empty($arrSubstitution['ORDER_ITEM'])) {
             $arrSubstitution['ORDER_ITEM'] = array();
         }
         $arrSubstitution['ORDER_ITEM'][] = $arrProduct;
     }
     $arrSubstitution['ORDER_ITEM_SUM'] = sprintf('% 9.2f', $total_item_price);
     $arrSubstitution['ORDER_ITEM_COUNT'] = sprintf('% 4u', $orderItemCount);
     // Redeem the *global* Coupon, if possible for the Order
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $total_item_price, $customer_id, null, $payment_id);
         if ($objCoupon) {
             $coupon_amount = $objCoupon->getDiscountAmount($total_item_price, $customer_id);
             if ($create_accounts) {
                 $objCoupon->redeem($order_id, $customer_id, $total_item_price);
             }
         }
     }
     \Message::restore();
     // Fill in the Coupon block with proper discount and amount
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
         //\DBG::log("Orders::getSubstitutionArray(): Coupon $coupon_code, amount $coupon_amount");
     }
     if ($coupon_amount) {
         //\DBG::log("Orders::getSubstitutionArray(): Got Order Coupon $coupon_code");
         $arrSubstitution['DISCOUNT_COUPON'][] = array('DISCOUNT_COUPON_CODE' => sprintf('%-40s', $coupon_code), 'DISCOUNT_COUPON_AMOUNT' => sprintf('% 9.2f', -$coupon_amount));
     } else {
         //\DBG::log("Orders::getSubstitutionArray(): No Coupon for Order ID $order_id");
     }
     Products::deactivate_soldout();
     if (Vat::isEnabled()) {
         //DBG::log("Orders::getSubstitutionArray(): VAT amount: ".$objOrder->vat_amount());
         $arrSubstitution['VAT'] = array(0 => array('VAT_TEXT' => sprintf('%-40s', Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']), 'VAT_PRICE' => $objOrder->vat_amount()));
     }
     return $arrSubstitution;
 }
 /**
  * @depends testEditOfTheProductForTheTagCloudFieldAfterRemovingAllTagsPlacedForProductsModule
  */
 public function testEditOfTheProductForTheCustomFieldsPlacedForProductsModule()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     //Set the date and datetime variable values here.
     $date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
     $dateAssert = date('Y-m-d');
     $datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
     $datetimeAssert = date('Y-m-d H:i:') . "00";
     $baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
     //Retrieve the account id, the super user id and product Id.
     $accountId = self::getModelIdByModelNameAndName('Account', 'superAccount');
     $superUserId = $super->id;
     $explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP;
     $product = Product::getByName('myEditProduct');
     $productId = $product[0]->id;
     //Edit a new Product based on the custom fields.
     $this->setGetArray(array('id' => $productId));
     $this->setPostArray(array('Product' => array('name' => 'myEditProduct', 'owner' => array('id' => $superUserId), 'type' => 1, 'sellPrice' => array('currency' => array('id' => $baseCurrency->id), 'value' => 200), 'account' => array('id' => $accountId), 'quantity' => 10, 'priceFrequency' => 2, 'stage' => array('value' => 'Open'), 'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission), 'checkboxCstm' => '0', 'currencyCstm' => array('value' => 40, 'currency' => array('id' => $baseCurrency->id)), 'decimalCstm' => '12', 'dateCstm' => $date, 'datetimeCstm' => $datetime, 'picklistCstm' => array('value' => 'b'), 'multiselectCstm' => array('values' => array('gg', 'hh')), 'tagcloudCstm' => array('values' => array('reading', 'surfing')), 'countrylistCstm' => array('value' => 'aaaa'), 'statelistCstm' => array('value' => 'aaa1'), 'citylistCstm' => array('value' => 'ab1'), 'integerCstm' => '11', 'phoneCstm' => '259-784-2069', 'radioCstm' => array('value' => 'e'), 'textCstm' => 'This is a test Edit Text', 'textareaCstm' => 'This is a test Edit TextArea', 'urlCstm' => 'http://wwww.abc-edit.com')));
     $this->runControllerWithRedirectExceptionAndGetUrl('products/default/edit');
     //Check the details if they are saved properly for the custom fields.
     $productId = self::getModelIdByModelNameAndName('Product', 'myEditProduct');
     $product = Product::getById($productId);
     //Retrieve the permission of the product.
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($product);
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
     $this->assertEquals($product->name, 'myEditProduct');
     $this->assertEquals($product->quantity, 10);
     $this->assertEquals($product->sellPrice->value, 200.0);
     $this->assertEquals($product->account->id, $accountId);
     $this->assertEquals($product->type, 1);
     $this->assertEquals($product->stage->value, 'Open');
     $this->assertEquals($product->owner->id, $superUserId);
     $this->assertEquals(1, count($readWritePermitables));
     $this->assertEquals(0, count($readOnlyPermitables));
     $this->assertEquals($product->checkboxCstm, '0');
     $this->assertEquals($product->currencyCstm->value, 40);
     $this->assertEquals($product->currencyCstm->currency->id, $baseCurrency->id);
     $this->assertEquals($product->dateCstm, $dateAssert);
     $this->assertEquals($product->datetimeCstm, $datetimeAssert);
     $this->assertEquals($product->decimalCstm, '12');
     $this->assertEquals($product->picklistCstm->value, 'b');
     $this->assertEquals($product->integerCstm, 11);
     $this->assertEquals($product->phoneCstm, '259-784-2069');
     $this->assertEquals($product->radioCstm->value, 'e');
     $this->assertEquals($product->textCstm, 'This is a test Edit Text');
     $this->assertEquals($product->textareaCstm, 'This is a test Edit TextArea');
     $this->assertEquals($product->urlCstm, 'http://wwww.abc-edit.com');
     $this->assertEquals($product->dateCstm, $dateAssert);
     $this->assertEquals($product->datetimeCstm, $datetimeAssert);
     $this->assertEquals($product->countrylistCstm->value, 'aaaa');
     $this->assertEquals($product->statelistCstm->value, 'aaa1');
     $this->assertEquals($product->citylistCstm->value, 'ab1');
     $this->assertContains('gg', $product->multiselectCstm->values);
     $this->assertContains('hh', $product->multiselectCstm->values);
     $this->assertContains('reading', $product->tagcloudCstm->values);
     $this->assertContains('surfing', $product->tagcloudCstm->values);
     $metadata = CalculatedDerivedAttributeMetadata::getByNameAndModelClassName('calcnumber', 'Product');
     $testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $product);
     $this->assertEquals(132, intval(str_replace(',', '', $testCalculatedValue)));
     // Not Coding Standard
 }
Example #13
0
 /**
  * Store any Products that have been modified.
  *
  * Takes the Product data directly from the various fields of the
  * $_POST array.  Only updates the database records for Products that
  * have at least one of their values changed.
  * @return  boolean                     True on success, false otherwise.
  * @global  array       $_ARRAYLANG     Language array
  */
 function update_products()
 {
     global $_ARRAYLANG;
     $arrError = array();
     foreach (array_keys($_POST['product_id']) as $product_id) {
         $product_code = contrexx_input2raw($_POST['identifier'][$product_id]);
         $product_code_old = contrexx_input2raw($_POST['identifierOld'][$product_id]);
         $ord = intval($_POST['ord'][$product_id]);
         $ord_old = intval($_POST['ordOld'][$product_id]);
         $discount_active = isset($_POST['discount_active'][$product_id]) ? 1 : 0;
         $special_offer_old = $_POST['specialOfferOld'][$product_id];
         $discount_price = floatval($_POST['discount_price'][$product_id]);
         $discountOld = floatval($_POST['discountOld'][$product_id]);
         $normalprice = floatval($_POST['price1'][$product_id]);
         $normalpriceOld = floatval($_POST['price1Old'][$product_id]);
         $resellerprice = floatval($_POST['price2'][$product_id]);
         $resellerpriceOld = floatval($_POST['price2Old'][$product_id]);
         $stock = intval($_POST['stock'][$product_id]);
         $stockOld = intval($_POST['stockOld'][$product_id]);
         //            $status = (isset($_POST['active'][$product_id]) ? 1 : 0);
         //            $statusOld = $_POST['activeOld'][$product_id];
         $vat_id = isset($_POST['taxId'][$product_id]) ? intval($_POST['taxId'][$product_id]) : 0;
         $vat_id_old = intval($_POST['taxIdOld'][$product_id]);
         $shownOnStartpage = empty($_POST['shownonstartpage'][$product_id]) ? 0 : 1;
         $shownOnStartpageOld = empty($_POST['shownonstartpageOld'][$product_id]) ? 0 : 1;
         // This is used when the Product name can be edited right on the overview
         $name = isset($_POST['name'][$product_id]) ? contrexx_input2raw($_POST['name'][$product_id]) : null;
         $nameOld = isset($_POST['nameOld'][$product_id]) ? contrexx_input2raw($_POST['nameOld'][$product_id]) : null;
         /*  Distribution and weight have been removed from the overview due to the
             changes made to the delivery options.
                     $distribution = $_POST['distribution'][$product_id];
                     $distributionOld = $_POST['distributionOld'][$product_id];
                     $weight = $_POST['weight'][$product_id];
                     $weightOld = $_POST['weightOld'][$product_id];
                     // Flag used to determine whether the record has to be
                     // updated in the database
                     $updateProduct = false;
                     // Check whether the weight was changed
                     if ($weight != $weightOld) {
                         // Changed.
                         // If it's empty, set to NULL and don't complain.
                         // The NULL weight will be silently ignored by the database.
                         if ($weight == '') {
                             $weight = 'NULL';
                         } else {
                             // Check the format
                             $weight = Weight::getWeight($weight);
                             // The NULL weight will be silently ignored by the database.
                             if ($weight === 'NULL') {
                                 // 'NULL', the format was invalid. cast error
                                 \Message::error($_ARRAYLANG['TXT_WEIGHT_INVALID_IGNORED']);
                             } else {
                                 // If getWeight() returns any other value, the format
                                 // is valid.  Verify that the numeric value has changed
                                 // as well; might be that the user simply removed the
                                 // unit ('g').
                                 if ($weight != Weight::getWeight($weightOld)) {
                                     // Really changed
                                     $updateProduct = true;
                                 }
                                 // Otherwise, the new amd old values are the same.
                             }
                         }
                     }
                     if ($updateProduct === false) {
                         // reset the weight to the old and, hopefully, correct value,
                         // in case the record is updated anyway
                         $weight = Weight::getWeight($weightOld);
                     }
         */
         // Check if any one value has been changed
         if ($product_code != $product_code_old || $ord != $ord_old || $discount_active != $special_offer_old || $discount_price != $discountOld || $normalprice != $normalpriceOld || $resellerprice != $resellerpriceOld || $stock != $stockOld || $vat_id != $vat_id_old || $shownOnStartpage != $shownOnStartpageOld || $name != $nameOld) {
             $arrProducts = array(Product::getById($product_id));
             if (!is_array($arrProducts)) {
                 continue;
             }
             foreach ($arrProducts as $objProduct) {
                 if (!$objProduct) {
                     $arrError[$product_code] = true;
                     continue;
                 }
                 $objProduct->code($product_code);
                 $objProduct->ord($ord);
                 $objProduct->discount_active($discount_active);
                 $objProduct->discountprice($discount_price);
                 $objProduct->price($normalprice);
                 $objProduct->resellerprice($resellerprice);
                 $objProduct->stock($stock);
                 //                    $objProduct->active($status);
                 $objProduct->vat_id($vat_id);
                 //                    $objProduct->distribution($distribution);
                 //                    $objProduct->weight($weight);
                 $objProduct->shown_on_startpage($shownOnStartpage);
                 // This is used when the Product name can be edited right on the overview
                 // Note: No need to check whether it is valid; if it's set
                 // to null above name() will do nothing but return the
                 // current name
                 $objProduct->name($name);
                 if (!$objProduct->store()) {
                     $arrError[$product_code] = true;
                 }
             }
         }
     }
     if (empty($arrError)) {
         \Message::ok($_ARRAYLANG['TXT_DATA_RECORD_UPDATED_SUCCESSFUL']);
         return true;
     }
     \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_UPDATING_RECORD']);
     return false;
 }
Example #14
0
 /**
  * Returns a string with HTML options for any menu
  *
  * Includes Products with the given active status only if $active is
  * not null.  The options' values are the Product IDs.
  * The sprintf() format for the options defaults to "%2$s", possible
  * values are:
  *  - %1$u: The Product ID
  *  - %2$s: The Product name
  * @static
  * @param   integer   $selected     The optional preselected Product ID
  * @param   boolean   $active       Optional.  Include active (true) or
  *                                  inactive (false) Products only.
  *                                  Ignored if null.  Defaults to null
  * @param   string    $format       The optional sprintf() format
  * @param   boolean   $showAllOptions Show all options and not only the selected
  * @return  array                   The HTML options string on success,
  *                                  null otherwise
  * @global  ADONewConnection
  * @author  Reto Kohli <*****@*****.**>
  */
 static function getMenuoptions($selected = null, $active = null, $format = '%2$s', $showAllOptions = true)
 {
     global $_ARRAYLANG;
     $arrName = array(0 => $_ARRAYLANG['TXT_SHOP_PRODUCT_NONE']) + self::getNameArray($active, $format);
     if ($arrName === false) {
         return null;
     }
     if ($selected && !$showAllOptions) {
         $arrName = array();
         $product = Product::getById($selected);
         $arrName[$product->id()] = $product->name();
     }
     return \Html::getOptions($arrName, $selected);
 }
 /**
  * Copies the product
  * @param int $id
  */
 public function actionCopy($id)
 {
     $copyToProduct = new Product();
     $postVariableName = get_class($copyToProduct);
     if (!isset($_POST[$postVariableName])) {
         $product = Product::getById((int) $id);
         ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($product);
         ProductZurmoCopyModelUtil::copy($product, $copyToProduct);
     }
     $this->processEdit($copyToProduct);
 }
Example #16
0
<?php

require_once 'config/config.conf.php';
try {
    $id = !empty($_GET['id']) ? intval($_GET['id']) : 0;
    if (empty($id)) {
        throw new Exception('Undefined product id');
    }
    $bindings = array(':id' => $id);
    $product = Product::getById($id);
    if (empty($product)) {
        throw new Exception('Undefined product');
    }
    $bindings[':category'] = $product->getCategory();
    $related_products = Product::getList('SELECT * FROM product WHERE category = :category AND id != :id LIMIT 3', $bindings);
    $smarty = new Smarty();
    $tpl_vars = array('pages' => $pages, 'current_page' => $current_page, 'product' => $product, 'related_products' => $related_products);
    $smarty->assign($tpl_vars);
    $smarty->display('product.tpl');
} catch (Exception $e) {
    exit($e->getMessage());
}
Example #17
0
 public function deleteAction()
 {
     $Product = Product::getById($this->getRequest()->getParam('id'));
     if ($Product) {
         if ($this->getRequest()->isPost()) {
             $filename = "uploads/" . str_replace("", "-", $Product->product_name) . "/" . $Product->product_images;
             if (is_file($filename)) {
                 chmod($filename, 0777);
                 @unlink($filename);
             }
             $Product->delete();
             $this->Member->log('Sản phẩm: ' . $Product->product_name . '(' . $this->getRequest()->getParam('id') . ')', 'Xóa');
             My_Plugin_Libs::setSplash('Sản phẩm: <b>' . $Product->product_name . '</b> đã được xóa khỏi hệ thống.');
             $this->_redirect($this->_helper->url('index', 'product', 'admin'));
         }
         $this->view->Product = $Product;
     }
 }
 /**
  * @depends testRegularUserControllerActionsWithElevationToAccessAndCreate
  */
 public function testRegularUserControllerActionsWithElevationToModels()
 {
     //Create product owned by user super.
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $product = ProductTestHelper::createProductByNameForOwner('productForElevationToModelTest', $super);
     //Test nobody, access to edit and details should fail.
     $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/delete');
     //give nobody access to read
     Yii::app()->user->userModel = $super;
     $product->addPermissions($nobody, Permission::READ);
     $this->assertTrue($product->save());
     //Now the nobody user can access the details view.
     Yii::app()->user->userModel = $nobody;
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     //Test nobody, access to edit should fail.
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/delete');
     $productId = $product->id;
     $product->forget();
     $product = Product::getById($productId);
     //give nobody access to read and write
     Yii::app()->user->userModel = $super;
     $product->addPermissions($nobody, Permission::READ_WRITE_CHANGE_PERMISSIONS);
     //TODO :Its wierd that giving opportunity errors
     $this->assertTrue($product->save());
     //Now the nobody user should be able to access the edit view and still the details view.
     Yii::app()->user->userModel = $nobody;
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/edit');
     $productId = $product->id;
     $product->forget();
     $product = Product::getById($productId);
     //revoke nobody access to read
     Yii::app()->user->userModel = $super;
     $product->addPermissions($nobody, Permission::READ_WRITE_CHANGE_PERMISSIONS, Permission::DENY);
     $this->assertTrue($product->save());
     //Test nobody, access to detail should fail.
     Yii::app()->user->userModel = $nobody;
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //create some roles
     Yii::app()->user->userModel = $super;
     $parentRole = new Role();
     $parentRole->name = 'AAA';
     $this->assertTrue($parentRole->save());
     $childRole = new Role();
     $childRole->name = 'BBB';
     $this->assertTrue($childRole->save());
     $userInParentRole = User::getByUsername('confused');
     $userInChildRole = User::getByUsername('nobody');
     $childRole->users->add($userInChildRole);
     $this->assertTrue($childRole->save());
     $parentRole->users->add($userInParentRole);
     $parentRole->roles->add($childRole);
     $this->assertTrue($parentRole->save());
     //create product owned by super
     $product2 = ProductTestHelper::createProductByNameForOwner('testingParentRolePermission', $super);
     //Test userInParentRole, access to details and edit should fail.
     Yii::app()->user->userModel = $userInParentRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //give userInChildRole access to READ
     Yii::app()->user->userModel = $super;
     $product2->addPermissions($userInChildRole, Permission::READ);
     $this->assertTrue($product2->save());
     //Test userInChildRole, access to details should not fail.
     Yii::app()->user->userModel = $userInChildRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     //Test userInParentRole, access to details should not fail.
     Yii::app()->user->userModel = $userInParentRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     $productId = $product2->id;
     $product2->forget();
     $product2 = Product::getById($productId);
     //give userInChildRole access to read and write
     Yii::app()->user->userModel = $super;
     $product2->addPermissions($userInChildRole, Permission::READ_WRITE_CHANGE_PERMISSIONS);
     $this->assertTrue($product2->save());
     //Test userInChildRole, access to edit should not fail.
     Yii::app()->user->userModel = $userInChildRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/edit');
     //Test userInParentRole, access to edit should not fail.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername($userInParentRole->username);
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/edit');
     $productId = $product2->id;
     $product2->forget();
     $product2 = Product::getById($productId);
     //revoke userInChildRole access to read and write
     Yii::app()->user->userModel = $super;
     $product2->addPermissions($userInChildRole, Permission::READ_WRITE_CHANGE_PERMISSIONS, Permission::DENY);
     $this->assertTrue($product2->save());
     //Test userInChildRole, access to detail should fail.
     Yii::app()->user->userModel = $userInChildRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //Test userInParentRole, access to detail should fail.
     Yii::app()->user->userModel = $userInParentRole;
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product2->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //clear up the role relationships between users so not to effect next assertions
     $parentRole->users->remove($userInParentRole);
     $parentRole->roles->remove($childRole);
     $this->assertTrue($parentRole->save());
     $childRole->users->remove($userInChildRole);
     $this->assertTrue($childRole->save());
     //create some groups and assign users to groups
     Yii::app()->user->userModel = $super;
     $parentGroup = new Group();
     $parentGroup->name = 'AAA';
     $this->assertTrue($parentGroup->save());
     $childGroup = new Group();
     $childGroup->name = 'BBB';
     $this->assertTrue($childGroup->save());
     $userInChildGroup = User::getByUsername('confused');
     $userInParentGroup = User::getByUsername('nobody');
     $childGroup->users->add($userInChildGroup);
     $this->assertTrue($childGroup->save());
     $parentGroup->users->add($userInParentGroup);
     $parentGroup->groups->add($childGroup);
     $this->assertTrue($parentGroup->save());
     $parentGroup->forget();
     $childGroup->forget();
     $parentGroup = Group::getByName('AAA');
     $childGroup = Group::getByName('BBB');
     //Add access for the confused user to Products and creation of Products.
     $userInChildGroup->setRight('ProductsModule', ProductsModule::RIGHT_ACCESS_PRODUCTS);
     $userInChildGroup->setRight('ProductsModule', ProductsModule::RIGHT_CREATE_PRODUCTS);
     $this->assertTrue($userInChildGroup->save());
     //create product owned by super
     $product3 = ProductTestHelper::createProductByNameForOwner('testingParentGroupPermission', $super);
     //Test userInParentGroup, access to details and edit should fail.
     Yii::app()->user->userModel = $userInParentGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //Test userInChildGroup, access to details and edit should fail.
     Yii::app()->user->userModel = $userInChildGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //give parentGroup access to READ
     Yii::app()->user->userModel = $super;
     $product3->addPermissions($parentGroup, Permission::READ);
     $this->assertTrue($product3->save());
     //Test userInParentGroup, access to details should not fail.
     Yii::app()->user->userModel = $userInParentGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     //Test userInChildGroup, access to details should not fail.
     Yii::app()->user->userModel = $userInChildGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/details');
     $productId = $product3->id;
     $product3->forget();
     $product3 = Product::getById($productId);
     //give parentGroup access to read and write
     Yii::app()->user->userModel = $super;
     $product3->addPermissions($parentGroup, Permission::READ_WRITE_CHANGE_PERMISSIONS);
     $this->assertTrue($product3->save());
     //Test userInParentGroup, access to edit should not fail.
     Yii::app()->user->userModel = $userInParentGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/edit');
     //Test userInChildGroup, access to edit should not fail.
     Yii::app()->user->userModel = $userInChildGroup;
     $this->logoutCurrentUserLoginNewUserAndGetByUsername($userInChildGroup->username);
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerWithNoExceptionsAndGetContent('products/default/edit');
     $productId = $product3->id;
     $product3->forget();
     $product3 = Product::getById($productId);
     //revoke parentGroup access to read and write
     Yii::app()->user->userModel = $super;
     $product3->addPermissions($parentGroup, Permission::READ_WRITE_CHANGE_PERMISSIONS, Permission::DENY);
     $this->assertTrue($product3->save());
     //Test userInChildGroup, access to detail should fail.
     Yii::app()->user->userModel = $userInChildGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //Test userInParentGroup, access to detail should fail.
     Yii::app()->user->userModel = $userInParentGroup;
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/details');
     $this->setGetArray(array('id' => $product3->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('products/default/edit');
     //clear up the role relationships between users so not to effect next assertions
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $userInParentGroup->forget();
     $userInChildGroup->forget();
     $childGroup->forget();
     $parentGroup->forget();
     $userInParentGroup = User::getByUsername('nobody');
     $userInChildGroup = User::getByUsername('confused');
     $childGroup = Group::getByName('BBB');
     $parentGroup = Group::getByName('AAA');
     //clear up the role relationships between users so not to effect next assertions
     $parentGroup->users->remove($userInParentGroup);
     $parentGroup->groups->remove($childGroup);
     $this->assertTrue($parentGroup->save());
     $childGroup->users->remove($userInChildGroup);
     $this->assertTrue($childGroup->save());
 }
Example #19
0
 /**
  * Returns an array of items contained in this Order
  * @global  ADONewConnection    $objDatabase
  * @global  array               $_ARRAYLANG
  * @return  array                               The items array on success,
  *                                              false otherwise
  * @todo    Let items be handled by their own class
  */
 function getItems()
 {
     global $objDatabase, $_ARRAYLANG;
     $query = "\n            SELECT `id`, `product_id`, `product_name`,\n                   `price`, `quantity`, `vat_rate`, `weight`\n              FROM `" . DBPREFIX . "module_shop" . MODULE_INDEX . "_order_items`\n             WHERE `order_id`=?";
     $objResult = $objDatabase->Execute($query, array($this->id));
     if (!$objResult) {
         return self::errorHandler();
     }
     $arrProductOptions = $this->getOptionArray();
     $items = array();
     while (!$objResult->EOF) {
         $item_id = $objResult->fields['id'];
         $product_id = $objResult->fields['product_id'];
         $name = $objResult->fields['product_name'];
         $price = $objResult->fields['price'];
         $quantity = $objResult->fields['quantity'];
         $vat_rate = $objResult->fields['vat_rate'];
         // Get missing product details
         $objProduct = Product::getById($product_id);
         if (!$objProduct) {
             \Message::warning(sprintf($_ARRAYLANG['TXT_SHOP_PRODUCT_NOT_FOUND'], $product_id));
             $objProduct = new Product('', 0, $name, '', $price, 0, 0, 0, $product_id);
         }
         $code = $objProduct->code();
         $distribution = $objProduct->distribution();
         $vat_id = $objProduct->vat_id();
         $weight = '0';
         if ($distribution != 'download') {
             $weight = $objResult->fields['weight'];
         }
         $item = array('product_id' => $product_id, 'quantity' => $quantity, 'name' => $name, 'price' => $price, 'item_id' => $item_id, 'code' => $code, 'vat_id' => $vat_id, 'vat_rate' => $vat_rate, 'weight' => $weight, 'attributes' => array());
         if (isset($arrProductOptions[$item_id])) {
             $item['attributes'] = $arrProductOptions[$item_id];
         }
         $items[] = $item;
         $objResult->MoveNext();
     }
     return $items;
 }
 public function testFilteredResultsByStageForProductPortlet()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     ProductTestHelper::createProductStagesIfDoesNotExist();
     $superProductId = self::getModelIdByModelNameAndName('Product', 'My Product 1');
     $product = Product::getById($superProductId);
     $product->account = $account;
     $product->stage->value = 'Open';
     $this->assertTrue($product->save());
     ProductTestHelper::createProductByNameForOwner("My Product 2", $super);
     $superProductId2 = self::getModelIdByModelNameAndName('Product', 'My Product 2');
     $product = Product::getById($superProductId2);
     $product->account = $account;
     $product->stage->value = 'Won';
     $this->assertTrue($product->save());
     $portlet = new Portlet();
     $portlet->column = 1;
     $portlet->position = 1;
     $portlet->layoutId = 'AccountDetailsAndRelationsView';
     $portlet->user = $super;
     $portlet->viewType = 'ProductsForAccountRelatedList';
     $this->assertTrue($portlet->save());
     $this->setGetArray(array('id' => $account->id, 'portletParams' => array('relationModuleId' => 'accounts', 'relationModelId' => $account->id), 'ProductsConfigurationForm' => array('filteredByStage' => 'Open'), 'redirectUrl' => Yii::app()->createUrl('accounts/default/details', array('id' => $account->id)), 'portletId' => $portlet->id, 'uniqueLayoutId' => 'AccountDetailsAndRelationsView_' . $portlet->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/defaultPortlet/modalRefresh');
     $this->assertContains('My Product 1', $content);
     $this->assertNotContains('My Product 2', $content);
     $this->setGetArray(array('id' => $account->id, 'portletParams' => array('relationModuleId' => 'accounts', 'relationModelId' => $account->id), 'ProductsConfigurationForm' => array('filteredByStage' => 'All'), 'redirectUrl' => Yii::app()->createUrl('accounts/default/details', array('id' => $account->id)), 'portletId' => $portlet->id, 'uniqueLayoutId' => 'AccountDetailsAndRelationsView_' . $portlet->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/defaultPortlet/modalRefresh');
     $this->assertContains('My Product 1', $content);
     $this->assertContains('My Product 2', $content);
     $this->setGetArray(array('id' => $account->id, 'portletParams' => array('relationModuleId' => 'accounts', 'relationModelId' => $account->id), 'ProductsConfigurationForm' => array('filteredByStage' => 'Won'), 'redirectUrl' => Yii::app()->createUrl('accounts/default/details', array('id' => $account->id)), 'portletId' => $portlet->id, 'uniqueLayoutId' => 'AccountDetailsAndRelationsView_' . $portlet->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/defaultPortlet/modalRefresh');
     $this->assertNotContains('My Product 1', $content);
     $this->assertContains('My Product 2', $content);
 }
Example #21
0
  * Количество единиц товара может быть отрицательным, что означает удаление из корзины
  * ajax=true указывает на необходимость вернуть JSON с данными, иначе будет сделан редирект
  */
 $app->page('/buy', function (Product $product, $count = 1, $ajax = false) use($app) {
     $basket = $app->session('basket') ?: array();
     $count = (int) $count;
     $basket[$product->id] = isset($basket[$product->id]) ? $basket[$product->id] + $count : $count;
     if ($basket[$product->id] <= 0) {
         unset($basket[$product->id]);
     }
     $basketTotalItems = 0;
     $basketTotalPrice = 0;
     if (is_array($basket)) {
         foreach ($basket as $basketProductId => $basketProductCount) {
             $basketTotalItems += $basketProductCount;
             $basketTotalPrice += Product::getById($basketProductId)->price * $basketProductCount;
         }
     }
     $app->session('basket', $basket);
     $app->session('basketTotalItems', $basketTotalItems);
     $app->session('basketTotalPrice', $basketTotalPrice);
     if ($ajax) {
         return json_encode(array('ok' => true, 'productId' => $product->id, 'productName' => $product->name, 'productNewCount' => isset($basket[$product->id]) ? $basket[$product->id] : 0, 'basketTotalItems' => $basketTotalItems, 'basketTotalPrice' => $basketTotalPrice, 'basketTotalPriceFormatted' => Product::formatPrice($basketTotalPrice), 'aprtData' => array('pageType' => $count > 0 ? \Actionpay\APRT::PAGETYPE_CART_ADD : \Actionpay\APRT::PAGETYPE_CART_REMOVE, 'currentProduct' => array('id' => $product->id, 'name' => $product->name, 'price' => $product->price))));
     } else {
         $app->redirect($_SERVER['HTTP_REFERER'] ?: '/');
         return '';
     }
 });
 /**
  * http://demoshop.actionpay.ru/basket
  * Страница корзины
Example #22
0
 public function testCreateAndGetProductById()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $contacts = Contact::getAll();
     $accounts = Account::getByName('superAccount');
     $opportunities = Opportunity::getByName('superOpportunity');
     $productTemplates = ProductTemplate::getByName('superProductTemplate');
     $account = $accounts[0];
     $user = $account->owner;
     $product = new Product();
     $product->name = 'Product 1';
     $product->owner = $user;
     $product->description = 'Description';
     $product->quantity = 2;
     $product->stage->value = 'Open';
     $product->account = $accounts[0];
     $product->contact = $contacts[0];
     $product->opportunity = $opportunities[0];
     $product->productTemplate = $productTemplates[0];
     $product->priceFrequency = ProductTemplate::PRICE_FREQUENCY_ONE_TIME;
     $product->sellPrice->value = 200;
     $product->type = ProductTemplate::TYPE_PRODUCT;
     $this->assertTrue($product->save());
     $id = $product->id;
     $product->forget();
     unset($product);
     $product = Product::getById($id);
     $this->assertEquals('Product 1', $product->name);
     $this->assertEquals(2, $product->quantity);
     $this->assertEquals('Description', $product->description);
     $this->assertEquals('Open', $product->stage->value);
     $this->assertEquals($user->id, $product->owner->id);
     $this->assertTrue($product->contact->isSame($contacts[0]));
     $this->assertTrue($product->account->isSame($accounts[0]));
     $this->assertTrue($product->opportunity->isSame($opportunities[0]));
     $this->assertTrue($product->productTemplate->isSame($productTemplates[0]));
     $this->assertEquals(ProductTemplate::PRICE_FREQUENCY_ONE_TIME, $product->priceFrequency);
     $this->assertEquals(200, $product->sellPrice->value);
     $this->assertEquals(ProductTemplate::TYPE_PRODUCT, $product->type);
 }
Example #23
0
 /**
  * Updates values in the session array with the current Cart contents,
  * and returns an array of Product data
  *
  * Called right after a Product has been added by {@see add_product()} or
  * quantities changed by {@see update_quantity()}.
  * Also computes the new count of items in the cart and calculates the
  * amount.
  * Stores details of the Products in the Cart in $products.
  * Note that the $objCustomer parameter is mandatory, but may be empty
  * in case it is a new Customer shopping.
  * @param   Customer    $objCustomer          The Customer
  * @global  ADONewConnection  $objDatabase    Database connection object
  * @return  boolean                           True on success,
  *                                            false otherwise
  * @static
  */
 static function update($objCustomer)
 {
     global $_ARRAYLANG;
     //DBG::log("Cart::update(): Cart: ".var_export($_SESSION['shop']['cart'], true));
     if (empty($_SESSION['shop']['cart'])) {
         self::init();
         return true;
         //self::get_products_array();
     }
     // No shipment by default.  Only if at least one Product with
     // type "delivery" is encountered, it is switched on.
     $_SESSION['shop']['cart']['shipment'] = false;
     $total_discount_amount = 0;
     $coupon_code = isset($_SESSION['shop']['coupon_code']) ? $_SESSION['shop']['coupon_code'] : '';
     $payment_id = isset($_SESSION['shop']['paymentId']) ? $_SESSION['shop']['paymentId'] : 0;
     $customer_id = $objCustomer ? $objCustomer->id() : 0;
     //DBG::log("Cart::update(): Coupon Code: $coupon_code");
     self::$products = array();
     $items = 0;
     $total_price = 0;
     $total_vat_amount = 0;
     $total_weight = 0;
     $total_discount_amount = 0;
     //DBG::log("Cart::update(): Products: ".var_export($products, true));
     // Loop 1: Collect necessary Product data
     $products = $_SESSION['shop']['cart']['items']->toArray();
     foreach ($products as $cart_id => &$product) {
         $objProduct = Product::getById($product['id']);
         if (!$objProduct) {
             unset($products[$cart_id]);
             continue;
         }
         // Check minimum order quantity, when set
         // Do not add error message if it's an AJAX request
         if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') && $product['quantity'] != 0 && $product['quantity'] < $objProduct->minimum_order_quantity()) {
             \Message::error($objProduct->name() . ': ' . $_ARRAYLANG['TXT_SHOP_MINIMUM_ORDER_QUANTITY_ERROR']);
         }
         // Limit Products in the cart to the stock available if the
         // stock_visibility is enabled.
         if ($objProduct->stock_visible() && $product['quantity'] > $objProduct->stock()) {
             $product['quantity'] = $objProduct->stock();
         }
         // Remove Products with quatities of zero or less
         if ($product['quantity'] <= 0) {
             unset($products[$cart_id]);
             continue;
         }
         $options_price = 0;
         // Array!
         $options_strings = Attributes::getAsStrings($product['options'], $options_price);
         //DBG::log("Cart::update(): options_price $options_price");
         /* Replaced by Attributes::getAsStrings()
                     foreach ($product['options'] as $attribute_id => $arrOptionIds) {
                         $objAttribute = Attribute::getById($attribute_id);
                         // Should be tested!
                         if (!$objAttribute) {
                             unset($product['options'][$attribute_id]);
                             continue;
                         }
                         $arrOptions = $objAttribute->getOptionArray();
                         foreach ($arrOptionIds as $option_id) {
                             $arrOption = null;
                             // Note that the options are indexed starting from 1!
                             // For types 4..7, the value entered in the text box is
                             // stored in $option_id.  Overwrite the value taken from
                             // the database.
                             if ($objAttribute->getType() >= Attribute::TYPE_TEXT_OPTIONAL) {
                                 $arrOption = current($arrOptions);
                                 $arrOption['value'] = $option_id;
                             } else {
                                 $arrOption = $arrOptions[$option_id];
                             }
                             if (!is_array($arrOption)) continue;
                             $option_value = ShopLibrary::stripUniqidFromFilename($arrOption['value']);
                             $path = Order::UPLOAD_FOLDER.$arrOption['value'];
                             if (   $option_value != $arrOption['value']
                                 && File::exists($path)) {
                                 $option_value =
                                     '<a href="$path" target="uploadimage">'.
                                     $option_value.'</a>';
                             }
                             $options .= " [$option_value]";
                             $options_price += $arrOption['price'];
                         }
                     }
                     if ($options_price != 0) {
                         $product['optionPrice'] = $options_price;
                     }
          */
         $quantity = $product['quantity'];
         $items += $quantity;
         $itemprice = $objProduct->get_custom_price($objCustomer, $options_price, $quantity);
         $price = $itemprice * $quantity;
         $handler = $objProduct->distribution();
         $itemweight = $handler == 'delivery' ? $objProduct->weight() : 0;
         // Requires shipment if the distribution type is 'delivery'
         if ($handler == 'delivery') {
             //DBG::log("Cart::update(): Product ID ".$objProduct->id()." needs delivery");
             $_SESSION['shop']['cart']['shipment'] = true;
         }
         $weight = $itemweight * $quantity;
         $vat_rate = Vat::getRate($objProduct->vat_id());
         $total_price += $price;
         $total_weight += $weight;
         self::$products[$cart_id] = array('id' => $objProduct->id(), 'product_id' => $objProduct->code(), 'cart_id' => $cart_id, 'title' => empty($_GET['remoteJs']) ? $objProduct->name() : htmlspecialchars(strtolower(CONTREXX_CHARSET) == 'utf-8' ? $objProduct->name() : utf8_encode($objProduct->name()), ENT_QUOTES, CONTREXX_CHARSET), 'options' => $product['options'], 'options_long' => $options_strings[0], 'options_cart' => $options_strings[1], 'price' => Currency::formatPrice($price), 'quantity' => $quantity, 'itemprice' => Currency::formatPrice($itemprice), 'vat_rate' => $vat_rate, 'itemweight' => $itemweight, 'weight' => $weight, 'group_id' => $objProduct->group_id(), 'article_id' => $objProduct->article_id(), 'product_images' => $objProduct->pictures(), 'minimum_order_quantity' => $objProduct->minimum_order_quantity());
         //DBG::log("Cart::update(): Loop 1: Product: ".var_export(self::$products[$cart_id], true));
     }
     $_SESSION['shop']['cart']['items'] = $products;
     // Loop 2: Calculate Coupon discounts and VAT
     $objCoupon = null;
     $hasCoupon = false;
     $discount_amount = 0;
     foreach (self::$products as $cart_id => &$product) {
         $discount_amount = 0;
         $product['discount_amount'] = 0;
         // Coupon:  Either the payment ID or the code are needed
         if ($payment_id || $coupon_code) {
             $objCoupon = Coupon::available($coupon_code, $total_price, $customer_id, $product['id'], $payment_id);
             if ($objCoupon) {
                 $hasCoupon = true;
                 //DBG::log("Cart::update(): PRODUCT; Coupon available: $coupon_code, Product ID {$product['id']}");
                 //DBG::log("Cart::update(): Loop 2: Product: ".var_export($product, true));
                 $discount_amount = $objCoupon->getDiscountAmount($product['price'], $customer_id);
                 if ($objCoupon->discount_amount() > 0 && $total_discount_amount + $discount_amount > $objCoupon->discount_amount()) {
                     //DBG::log("Cart::update(): COUPON prelimit: PRODUCT: price ".$product['price'].", coupon discount amount ".$objCoupon->discount_amount().", discount_amount $discount_amount, total discount amount $total_discount_amount");
                     $discount_amount = $objCoupon->discount_amount() - $total_discount_amount;
                     //DBG::log("Cart::update(): COUPON postlimit: PRODUCT: price ".$product['price'].", coupon discount amount ".$objCoupon->discount_amount().", discount_amount $discount_amount, total discount amount $total_discount_amount");
                 }
                 $total_discount_amount += $discount_amount;
                 //                    $product['price'] = Currency::formatPrice(
                 //                        $product['price'] - $discount_amount);
                 $product['discount_amount'] = $discount_amount;
                 // UNUSED
                 //                        $arrProduct['coupon_string'] =
                 //                            $objCoupon->getString($discount_amount);
                 //DBG::log("Cart::update(): PRODUCT: price ".$product['price'].", discount_amount $discount_amount, total discount $total_discount_amount");
             }
         }
         // Calculate the amount if it's excluded; we might add it later:
         // - If it's included, we don't care.
         // - If it's disabled, it's set to zero.
         $vat_amount = Vat::amount($product['vat_rate'], $product['price'] - $product['discount_amount']);
         if (!Vat::isIncluded()) {
             self::$products[$cart_id]['price'] += $vat_amount;
             self::$products[$cart_id]['price'] = Currency::formatPrice(self::$products[$cart_id]['price']);
         }
         $total_vat_amount += $vat_amount;
         self::$products[$cart_id]['vat_amount'] = Currency::formatPrice($vat_amount);
     }
     // Global Coupon:  Either the payment ID or the code are needed
     if (!$objCoupon && ($payment_id || $coupon_code)) {
         $discount_amount = 0;
         //DBG::log("Cart::update(): GLOBAL; Got Coupon code $coupon_code");
         $total_price_incl_vat = $total_price;
         if (!Vat::isIncluded()) {
             $total_price_incl_vat += $total_vat_amount;
         }
         $objCoupon = Coupon::available($coupon_code, $total_price_incl_vat, $customer_id, 0, $payment_id);
         if ($objCoupon) {
             $hasCoupon = true;
             $discount_amount = $objCoupon->getDiscountAmount($total_price_incl_vat, $customer_id);
             $total_discount_amount = $discount_amount;
             //DBG::log("Cart::update(): GLOBAL; Coupon available: $coupon_code");
             //DBG::log("Cart::update(): GLOBAL; total price $total_price, discount_amount $discount_amount, total discount $total_discount_amount");
         }
     }
     if ($objCoupon) {
         //DBG::log("Cart::update(): Got Coupon ".var_export($objCoupon, true));
         $total_price -= $discount_amount;
         //DBG::log("Cart::update(): COUPON; total price $total_price, discount_amount $discount_amount, total discount $total_discount_amount");
     }
     if ($hasCoupon) {
         \Message::clear();
     }
     $_SESSION['shop']['cart']['total_discount_amount'] = $total_discount_amount;
     $_SESSION['shop']['cart']['total_price'] = Currency::formatPrice($total_price);
     $_SESSION['shop']['cart']['total_vat_amount'] = Currency::formatPrice($total_vat_amount);
     //DBG::log("Cart::update(): Updated Cart (session): VAT amount: ".$_SESSION['shop']['cart']['total_vat_amount']);
     $_SESSION['shop']['cart']['total_items'] = $items;
     $_SESSION['shop']['cart']['total_weight'] = $total_weight;
     // In grams!
     //DBG::log("Cart::update(): Updated Cart (session): ".var_export($_SESSION['shop']['cart'], true));
     return true;
 }