Inheritance: extends RepositoryBase
	/**
	 * Test cart preview total product count when the same product is used multiple times
	 */
	public function testCartPreviewCount_DuplicateProducts()
	{
		$cart_srl = 774;
		$cart = new Cart($cart_srl);

		// Make sure we start with 4 products
		$this->assertEquals(4, count($cart->getProducts()));

		// Add one new product to cart (of the same type as one that already is in the cart)
		$product_repository = new ProductRepository();
		$product = $product_repository->getProduct(133);
		$cart->addProduct($product, 1);

		// Make sure new product was added to cart
		$cart = new Cart($cart_srl);
		$this->assertEquals(5, $cart->count(TRUE));

		$cart_preview = new CartPreview($cart, 2);

		$cart_preview_products = $cart_preview->getProducts();
		$this->assertEquals(2, count($cart_preview_products));

		$cart_products_count = $cart_preview->getCartProductsCount();
		$this->assertEquals(5, $cart_products_count);
	}
 /**
  * @return bool
  * @throws CException
  */
 public function run()
 {
     $category = $this->categoryRepository->getByAlias($this->slug);
     if (null === $category) {
         return false;
     }
     $this->render($this->view, ['category' => $category, 'products' => $this->productRepository->getListForCategory($category, $this->limit)]);
 }
Example #3
0
 public function actionView($slug)
 {
     $producer = Producer::model()->getBySlug($slug);
     if (!$producer) {
         throw new CHttpException(404, Yii::t('StoreModule.store', 'Page not found!'));
     }
     $this->render('view', ['brand' => $producer, 'products' => $this->productRepository->getByBrandProvider($producer)]);
 }
Example #4
0
 /**
  * @param $name
  * @throws CHttpException
  */
 public function actionView($name)
 {
     $product = $this->productRepository->getBySlug($name);
     if (null === $product) {
         throw new CHttpException(404, Yii::t('StoreModule.catalog', 'Product was not found!'));
     }
     $this->render('view', ['product' => $product]);
 }
Example #5
0
 /**
  * @param $path
  * @throws CHttpException
  */
 public function actionView($path)
 {
     $category = StoreCategory::model()->published()->findByPath($path);
     if (null === $category) {
         throw new CHttpException(404);
     }
     $data = Yii::app()->getRequest()->getQueryString() ? $this->productRepository->getByFilter($this->attributeFilter->getMainAttributesForSearchFromQuery(Yii::app()->getRequest(), [AttributeFilter::MAIN_SEARCH_PARAM_CATEGORY => [$category->id]]), $this->attributeFilter->getTypeAttributesForSearchFromQuery(Yii::app()->getRequest())) : $this->productRepository->getListForCategory($category);
     $this->render('view', ['dataProvider' => $data, 'category' => $category]);
 }
Example #6
0
 /**
  * @param string $name Product slug
  * @param string $category Product category path
  * @throws CHttpException
  */
 public function actionView($name, $category = null)
 {
     $product = $this->productRepository->getBySlug($name);
     if (null === $product || isset($product->category) && $product->category->path !== $category || !isset($product->category) && !is_null($category)) {
         throw new CHttpException(404, Yii::t('StoreModule.catalog', 'Product was not found!'));
     }
     Yii::app()->eventManager->fire(StoreEvents::PRODUCT_OPEN, new ProductOpenEvent($product));
     $this->render('view', ['product' => $product]);
 }
Example #7
0
 public static function setValuesForTemplate($module_srl)
 {
     $productRepo = new ProductRepository();
     $maxPrice = $productRepo->getMaxPrice($module_srl);
     $minPrice = 0;
     $priceFilter = array($minPrice, Context::get(self::TO_PRICE_MIN) ? Context::get(self::TO_PRICE_MIN) : $minPrice, Context::get(self::TO_PRICE_MAX) ? Context::get(self::TO_PRICE_MAX) : $maxPrice, $maxPrice);
     Context::set('priceFilter', $priceFilter);
     $attributeRepo = new AttributeRepository();
     $catSrls = array();
     if (is_numeric($catSrl = Context::get('category_srl'))) {
         $catSrls[] = $catSrl;
     } elseif (Context::get('type') == 'category' && ($slug = Context::get('identifier'))) {
         //friendly url
         $cRepo = new CategoryRepository();
         $cat = $cRepo->getCategoryByFriendlyUrl($slug);
         $catSrls[] = $cat->category_srl;
     }
     $attrs = $attributeRepo->getFilterAttributes($module_srl, $catSrls);
     foreach ($attrs as $i => $attribute) {
         /** @var $attribute Attribute */
         if ($attribute->isNumeric()) {
             $min = $attribute->getMinValue();
             $min |= 0;
             //if there is no max value for this attribute unset it
             if (!($max = (int) $attribute->getMaxValue())) {
                 unset($attrs[$i]);
                 continue;
             }
             $attribute->setMeta('min', $min);
             $attribute->setMeta('max', $max);
             $minKey = str_replace('SRL', $attribute->attribute_srl, self::TO_ATTRIBUTE_NUMERIC_MIN);
             if (isset($_GET[$minKey]) && is_numeric($minValue = $_GET[$minKey])) {
                 $attribute->setMeta('minValue', $minValue);
             }
             $maxKey = str_replace('SRL', $attribute->attribute_srl, self::TO_ATTRIBUTE_NUMERIC_MAX);
             if (isset($_GET[$maxKey]) && is_numeric($maxValue = $_GET[$maxKey])) {
                 $attribute->setMeta('maxValue', $maxValue);
             }
         } elseif ($attribute->isSelect()) {
             $key = str_replace('SRL', $attribute->attribute_srl, self::TO_ATTRIBUTE_SELECT);
             if (isset($_GET[$key]) && ($val = $_GET[$key])) {
                 $attribute->setMeta('filterValue', $val);
             }
         } elseif ($attribute->isMultipleSelect()) {
             $key = str_replace('SRL', $attribute->attribute_srl, self::TO_ATTRIBUTE_SELECT_MULTIPLE);
             if (isset($_GET[$key]) && ($val = $_GET[$key])) {
                 $values = explode(self::SEPARATOR_MULTIPLE, $val);
                 $attribute->setMeta('filterValues', $values);
             }
         }
     }
     Context::set('filter_attributes', $attrs);
 }
Example #8
0
 /**
  * check and update stocks
  * @return array
  */
 public function checkAndUpdateStocks()
 {
     $products = $this->order->getProducts();
     $productRepo = new ProductRepository();
     /** @var $orderProduct OrderProduct */
     $productsEmptyStocks = array();
     foreach ($products as $orderProduct) {
         /** @var $product SimpleProduct */
         $product = $productRepo->getProduct($orderProduct->product_srl, false);
         if ($orderProduct->quantity == $product->qty) {
             $productsEmptyStocks[] = $product;
         }
         $product->substractFromStock($orderProduct->quantity);
     }
     return $productsEmptyStocks;
 }
 /**
  * @throws CHttpException
  */
 public function actionAjaxProductSearch()
 {
     if (!Yii::app()->getRequest()->getQuery('q')) {
         throw new CHttpException(404);
     }
     $data = [];
     $model = $this->productRepository->searchByName(Yii::app()->getRequest()->getQuery('q'));
     foreach ($model as $product) {
         $data[] = ['id' => $product->id, 'name' => $product->name . ($product->sku ? " ({$product->sku}) " : ' ') . $product->getPrice() . ' ' . Yii::t('StoreModule.store', Yii::app()->getModule('store')->currency), 'thumb' => $product->image ? $product->getImageUrl(50, 50) : ''];
     }
     Yii::app()->ajax->raw($data);
 }
 /** @test */
 public function product_management()
 {
     // Acessa a funcionalidade produtos e retorna a representação do DOM da página
     $crawler = $this->client->request('GET', 'product');
     // Verifica se existe uma variável chamada 'products'
     $this->assertViewHas('products');
     // Verifica se a lista de produtos contém produtos ao checar a existência dos botões de gerenciamento
     $link_editar = $crawler->filter('a.link-editar');
     $link_remover = $crawler->filter('a.link-remover');
     $this->assertGreaterThan(0, count($link_editar), 'Nenhum botao editar encontrado!');
     $this->assertGreaterThan(0, count($link_remover), 'Nenhum botao remover encontrado!');
     // Se a lista está preenchida
     if (count($link_editar) > 0) {
         // Pega o link do primeiro botão editar
         $url_editar = $link_editar->first()->attr('href');
         // Acessa a funcionalidade product/edit/{id} e retorna a representação do DOM da página
         $crawler = $this->client->request('GET', $url_editar);
         // Verifica se o status retornado é 200
         $this->assertResponseOk();
         // Pega o ID do produto ao ler o valor do hidden field do form
         $product_id = $crawler->filter('input[name=id]')->attr('value');
         // Cria nova instancia do repositório de produtos
         $productRepo = new ProductRepository();
         // Atualiza o produto
         $update_result = $productRepo->updateProduct(array('id' => $product_id, 'name' => 'Product Name', 'description' => 'Product Description', 'price' => '2.456,89', 'free_shipping' => 1));
         // Certifica-se de que a atualização foi feita com sucesso
         $this->assertTrue($update_result);
     }
     // Se a lista está preenchida
     if (count($link_remover) > 0) {
         // Pega o link do primeiro botão remover
         $url_remover = $link_remover->first()->attr('href');
         // Acessa o link
         $this->call('GET', $url_remover);
         // Verifica se é redirecionado para a lista de produtos
         $this->assertRedirectedTo('product');
     }
 }
 /**
  * Формирование списка категорий с товарами
  * @param  array $data массив категорий
  * @return boolean
  */
 private function createCatalogTree(array $data)
 {
     $this->activeLevel++;
     foreach ($data as $node) {
         //Добавление категории и декорирование ячейки
         $this->activeList->mergeCells('A' . $this->activeRow . ':D' . $this->activeRow)->setCellValue('A' . $this->activeRow, $this->addTabs($node['label']))->getStyle('A' . $this->activeRow . ':D' . $this->activeRow)->applyFromArray($this->getLevelStyle());
         $this->activeRow++;
         if (count($node['items'])) {
             //Если есть подкатегории используем рекурсию
             $this->createCatalogTree($node['items']);
         } else {
             //В противном случае тащим все товары категории
             $storeCategory = StoreCategory::model()->findByPk($node['id']);
             $dataProvider = $this->productRepository->getListForCategory($storeCategory);
             //И пишем их в таблицу
             foreach ($dataProvider->data as $product) {
                 $this->writeProductRow($product);
                 $this->activeRow++;
             }
         }
     }
     $this->activeLevel--;
     return true;
 }
Example #12
0
 /**
  * Path to the product image thumbnail
  *
  * @param int    $width
  * @param int    $height
  * @param string $thumbnail_type
  * @return mixed|string
  */
 function getThumbnailPath($width = 80, $height = 0, $thumbnail_type = '')
 {
     if ($this->product) {
         if ($this->product->parent_product_srl) {
             $productRepo = new ProductRepository();
             $parent_product = $productRepo->getProduct($this->product->parent_product_srl);
             return $parent_product->getPrimaryImage()->getThumbnailPath($width, $height, $thumbnail_type);
         } else {
             return $this->product->getPrimaryImage()->getThumbnailPath($width, $height, $thumbnail_type);
         }
     } else {
         return '';
     }
 }
Example #13
0
    public function dispShopSearch()
    {
        $product_repository = new ProductRepository();
        $page = Context::get('page');
        $search = Context::get('q');
        $args = new stdClass();
        $args->module_srl = $this->module_srl;
        FrontFilters::work($args);
        $args->sku = $search;
        $args->title = $search;
        $args->description = $search;
        $args->page = $page;
        $category_srl = Context::get('search_category_srl');
        if($category_srl) $args->category_srls = array($category_srl);

        $output = $product_repository->getProductList($args);
        Context::set('products', $output->products);
        Context::set('page_navigation', $output->page_navigation);
        Context::set('search_value', $search);

        $this->loadShopCategoryTree();

        $this->setTemplateFile("product_search.html");
    }
Example #14
0
 public function testCount()
 {
     $cRepo = new CartRepository();
     $pRepo = new ProductRepository();
     $cart = $cRepo->getCart(NULL, 14);
     $cart->emptyCart();
     $cart->addProduct($pRepo->getProduct(130));
     $cart->addProduct($pRepo->getProduct(132));
     $this->assertEquals(2, $cart->count());
 }
 /**
  * cart add product
  * @return Object
  */
 public function procShopToolCartAddProduct()
 {
     $cartRepository = new CartRepository();
     if ($product_srl = Context::get('product_srl')) {
         $productsRepo = new ProductRepository();
         if ($product = $productsRepo->getProduct($product_srl))
         {
             if (!($product instanceof SimpleProduct)) {
                 return new Object(-1, 'msg_invalid_request');
             }
             $logged_info = Context::get('logged_info');
             $cart = $cartRepository->getCart($this->module_info->module_srl, NULL, $logged_info->member_srl, session_id(), TRUE);
             $quantity = (is_numeric(Context::get('quantity')) && Context::get('quantity') > 0 ? Context::get('quantity') : 1);
             try {
                 $cart->addProduct($product, $quantity);
             }
             catch (Exception $e) {
                 return new Object(-1, $e->getMessage());
             }
         }
         else return new Object(-1, 'msg_invalid_request');
     }
     else return new Object(-1, 'msg_invalid_request');
     $shop = $this->model->getShop($this->module_srl);
     $this->setRedirectUrlIfNoReferer(getSiteUrl($shop->domain));
 }
Example #16
0
 /**
  * @return mixed
  */
 public function products()
 {
     return $this->productRepository->getByIds(array_keys($this->getData()));
 }
Example #17
0
 /**
  * substract from stock when a product is bought
  * @param $qty
  * @throws ShopException
  */
 public function substractFromStock($qty)
 {
     if ($qty > $this->qty) {
         throw new ShopException("You do not have enough items in stock to ship this order. Go and update stocks for product {$this->product_srl} !");
     }
     $this->qty -= $qty;
     $this->repo->updateProduct($this);
 }
Example #18
0
<?php

include "../models/ProductRepository.php";
$config = (include "../db/config.php");
$db = new PDO($config["db"], $config["username"], $config["password"]);
$db->exec("set names utf8");
$products = new ProductRepository($db);
switch ($_SERVER["REQUEST_METHOD"]) {
    case "GET":
        $result = $products->getAll();
        break;
    case "POST":
        $result = $products->insert(array(id => intval($_POST["id"]), name => $_POST["name"], category => intval($_POST["category"]), weight => $_POST["weight"]));
        break;
    case "PUT":
        parse_str(file_get_contents("php://input"), $_PUT);
        $result = $products->update(array(id => intval($_PUT["id"]), name => $_PUT["name"], category => intval($_PUT["category"]), weight => $_PUT["weight"]));
        break;
    case "DELETE":
        parse_str(file_get_contents("php://input"), $_DELETE);
        $result = $products->remove(array(id => intval($_DELETE["id"]), name => $_DELETE["name"], category => intval($_DELETE["category"]), weight => $_DELETE["weight"]));
        break;
}
header("Content-Type: application/json");
echo json_encode($result);
Example #19
0
		public function testProductCountUpdatesOnProductUpdate()
		{
			$module_srl = 1001;

			$product_repository = new ProductRepository();

			$product = new SimpleProduct();
			$product->product_srl = 12;
			$product->title = "Some product";
			$product->member_srl = 4;
			$product->module_srl = $module_srl;
			$product->product_type = 'simple';
			$product->sku = 'some-product';
			$product->friendly_url = $product->sku;
			$product->price = 100;
			$product->categories[] = 1000;
			$product->categories[] = 1002;
			$product_repository->insertProduct($product);

			// Check that count was increased
			$category_repository = new CategoryRepository();
			$category = $category_repository->getCategory(1000);
			$this->assertEquals(1, $category->product_count);
			// Check that count was increased
			$category = $category_repository->getCategory(1002);
			$this->assertEquals(1, $category->product_count);
			// Check that count was increased
			$category = $category_repository->getCategory(1008);
			$this->isNull($category->product_count);

			// Delete product
			$args = new stdClass();
			$args->module_srl = $module_srl;
			$products = $product_repository->getAllProducts($args);
			$this->assertNotNull($products);

			$product = array_shift($products);
			$product->categories = array(1002, 1008);
			$product_repository->updateProduct($product);

			// Check that count was decreased
			$category_repository = new CategoryRepository();
			$category = $category_repository->getCategory(1000);
			$this->assertEquals(0, $category->product_count);
			// Check that count was decreased
			$category = $category_repository->getCategory(1002);
			$this->assertEquals(1, $category->product_count);
			// Check that count was increased
			$category = $category_repository->getCategory(1008);
			$this->assertEquals(1, $category->product_count);
		}
Example #20
0
<?php

$product_repo = new ProductRepository();
$e = $product_repo->get_by_id($_GET['id']);
if (is_null($e)) {
    header('location:index.php?page=aproduct');
}
?>
<h3>Edit Product</h3>
<form method="post" action="<?php 
$_SERVER['PHP_SELF'];
?>
">
  <div class="form-group">
    <input type="text" class="form-control" id="name" name="name" placeholder="Name" value="<?php 
echo $e->get_name();
?>
">
  </div>
  <div class="form-group">
    <input type="text" class="form-control" id="description" name="description" placeholder="Description" value="<?php 
echo $e->get_description();
?>
">
  </div>
  <div class="form-group">
    <input type="text" class="form-control" id="sell_price" name="sell_price" placeholder="Sell Price" value="<?php 
echo $e->get_sell_price();
?>
">
  </div>
Example #21
0
 /**
  * @inheritdoc
  */
 public function getData()
 {
     return ProductRepository::getData();
 }
Example #22
0
	/**
	 * Test inserting product attributes
	 *
	 * Each category has associated a set of attributes
	 * (e.g. All books have the Author attribute, All T-Shirts have Color)
	 * Based on the category a product is in, it can have values for these attributes.
	 *
	 * This test checks that if Color is provided for a product in the Books
	 * category it will not be added.
	 *
	 *
	 * @author Corina Udrescu (dev@xpressengine.org)
	 */
	public function testInsertProductAttributeSkipsAttributesNotInScope()
	{
		$repository = new ProductRepository();
		$product = $repository->getProduct(1);

		$product->attributes[self::ATTRIBUTE_AUTHOR] = "J. K. Rowling";
		$product->attributes[self::ATTRIBUTE_PUBLISH_YEAR] = 2003;
		$product->attributes[self::ATTRIBUTE_COLOR] = "Blue";

		$repository->updateProduct($product);

		$new_product = $repository->getProduct(1);

		$this->assertEquals(2, count($new_product->attributes));

		$this->assertFalse(array_key_exists(self::ATTRIBUTE_COLOR, $new_product->attributes));
		$this->assertEquals("J. K. Rowling", $new_product->attributes[self::ATTRIBUTE_AUTHOR]);
		$this->assertEquals(2003, $new_product->attributes[self::ATTRIBUTE_PUBLISH_YEAR]);
	}
Example #23
0
<table class="table table-bordered table-stiped table-hover">
	<tr>
		<th style="text-align:center" colspan="8"><h3>Product List<a href="index.php?page=aproduct&m=add" class="btn btn-xs btn-primary pull-right"><span class="glyphicon glyphicon-plus"></span></a></h3></th>
	</tr>
	<tr>
		<th>Id</th>
		<th>Name</th>
		<th>Description</th>
		<th>Sell Price</th>
		<th>Cost Price</th>
		<th>Photo</th>
		<th>Status</th>
		<th>Action</th>
	</tr>
<?php 
$product_repo = new ProductRepository();
foreach ($product_repo->get_all() as $product) {
    ?>
	<tr class="<?php 
    echo $product->get_status() ? "" : "danger";
    ?>
">
		<td><?php 
    echo $product->get_id();
    ?>
</td>
		<td><?php 
    echo $product->get_name();
    ?>
</td>
		<td><?php 
Example #24
0
 public function productStillAvailable($product, $checkIfInStock = true)
 {
     if ($product instanceof SimpleProduct) {
         if (!$product->isPersisted()) {
             throw new ShopException('Product not persisted');
         }
     } elseif (is_numeric($product)) {
         $pRepo = new ProductRepository();
         $product = $pRepo->getProduct($product);
     } else {
         throw new ShopException('Invalid input');
     }
     return $product && $product->isAvailable($checkIfInStock);
 }