public function viewsupplier()
    {
        global $cookie;
        $supplier = $this->loadObject();
        echo '<h2>' . $supplier->name . '</h2>';
        $products = $supplier->getProductsLite(intval($cookie->id_lang));
        echo '<h3>' . $this->l('Total products:') . ' ' . sizeof($products) . '</h3>';
        foreach ($products as $product) {
            $product = new Product($product['id_product'], false, intval($cookie->id_lang));
            echo '<hr />';
            if (!$product->hasAttributes()) {
                echo '
				<table border="0" cellpadding="0" cellspacing="0" class="table width3">
					<tr>
						<th><a href="index.php?tab=AdminCatalog&id_product=' . $product->id . '&addproduct&token=' . Tools::getAdminToken('AdminCatalog' . intval(Tab::getIdFromClassName('AdminCatalog')) . intval($cookie->id_employee)) . '" target="_blank">' . $product->name . '</a></th>
						' . (!empty($product->reference) ? '<th width="150">' . $this->l('Ref:') . ' ' . $product->reference . '</th>' : '') . '
						' . (!empty($product->ean13) ? '<th width="120">' . $this->l('EAN13:') . ' ' . $product->ean13 . '</th>' : '') . '
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="50">' . $this->l('Qty:') . ' ' . $product->quantity . '</th>' : '') . '
					</tr>
				</table>';
            } else {
                echo '
				<h3><a href="index.php?tab=AdminCatalog&id_product=' . $product->id . '&addproduct&token=' . Tools::getAdminToken('AdminCatalog' . intval(Tab::getIdFromClassName('AdminCatalog')) . intval($cookie->id_employee)) . '" target="_blank">' . $product->name . '</a></h3>
				<table border="0" cellpadding="0" cellspacing="0" class="table" style="width: 600px;">
	                	<tr>
		                    <th>' . $this->l('Attribute name') . '</th>
		                    <th width="80">' . $this->l('Reference') . '</th>
		                    <th width="80">' . $this->l('EAN13') . '</th>
		                   ' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="40">' . $this->l('Quantity') . '</th>' : '') . '
	                	</tr>';
                /* Build attributes combinaisons */
                $combinaisons = $product->getAttributeCombinaisons(intval($cookie->id_lang));
                foreach ($combinaisons as $k => $combinaison) {
                    $combArray[$combinaison['id_product_attribute']]['reference'] = $combinaison['reference'];
                    $combArray[$combinaison['id_product_attribute']]['ean13'] = $combinaison['ean13'];
                    $combArray[$combinaison['id_product_attribute']]['quantity'] = $combinaison['quantity'];
                    $combArray[$combinaison['id_product_attribute']]['attributes'][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute']);
                }
                $irow = 0;
                foreach ($combArray as $id_product_attribute => $product_attribute) {
                    $list = '';
                    foreach ($product_attribute['attributes'] as $attribute) {
                        $list .= $attribute[0] . ' - ' . $attribute[1] . ', ';
                    }
                    $list = rtrim($list, ', ');
                    echo '
					<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . ' >
						<td>' . stripslashes($list) . '</td>
						<td>' . $product_attribute['reference'] . '</td>
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<td>' . $product_attribute['ean13'] . '</td>' : '') . '
						<td class="right">' . $product_attribute['quantity'] . '</td>
					</tr>';
                }
                unset($combArray);
                echo '</table>';
                echo '</td></tr></table>';
            }
        }
    }
Example #2
0
 public function ajaxProcessDeleteProductAttribute()
 {
     if (!Combination::isFeatureActive()) {
         return;
     }
     if ($this->tabAccess['delete'] === '1') {
         $id_product = (int) Tools::getValue('id_product');
         $id_product_attribute = (int) Tools::getValue('id_product_attribute');
         if ($id_product && Validate::isUnsignedId($id_product) && Validate::isLoadedObject($product = new Product($id_product))) {
             $product->deleteAttributeCombination((int) $id_product_attribute);
             $product->checkDefaultAttributes();
             if (!$product->hasAttributes()) {
                 $product->cache_default_attribute = 0;
                 $product->update();
             } else {
                 Product::updateDefaultAttribute($id_product);
             }
             $json = array('status' => 'ok', 'message' => $this->_conf[1]);
         } else {
             $json = array('status' => 'error', 'message' => $this->l('You cannot delete this attribute.'));
         }
     } else {
         $json = array('status' => 'error', 'message' => $this->l('You do not have permission to delete this.'));
     }
     die(Tools::jsonEncode($json));
 }
Example #3
0
    if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
        $id_product_old = $product->id;
        for ($i = 1; $i <= $quantity; $i++) {
            echo $i;
            unset($product->id);
            unset($product->id_product);
            $product->indexed = 0;
            $product->active = 0;
            if (!$product->add()) {
                echo "Parent_F:" . $product->id . " ";
            }
            if (!Category::duplicateProductCategories($id_product_old, $product->id)) {
                echo "Cat_F:" . $product->id . " ";
            }
            if (($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) {
                if ($product->hasAttributes()) {
                    Product::updateDefaultAttribute($product->id);
                }
                if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) {
                    echo 'An error occurred while copying images.';
                } else {
                    echo ' done. ';
                }
            } else {
                echo 'An error occurred while duplicating some object properties.';
            }
        }
    }
}
if ($Version >= 15000) {
    $type = Tools::getValue('context_type');
 /**
  * @param Product $obj
  * @throws Exception
  * @throws SmartyException
  */
 public function initFormQuantities($obj)
 {
     if (!$this->default_form_language) {
         $this->getLanguages();
     }
     $data = $this->createTemplate($this->tpl_form);
     $data->assign('default_form_language', $this->default_form_language);
     if ($obj->id) {
         if ($this->product_exists_in_shop) {
             // Get all id_product_attribute
             $attributes = $obj->getAttributesResume($this->context->language->id);
             if (empty($attributes)) {
                 $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => '');
             }
             // Get available quantities
             $available_quantity = array();
             $product_designation = array();
             foreach ($attributes as $attribute) {
                 // Get available quantity for the current product attribute in the current shop
                 $available_quantity[$attribute['id_product_attribute']] = isset($attribute['id_product_attribute']) && $attribute['id_product_attribute'] ? (int) $attribute['quantity'] : (int) $obj->quantity;
                 // Get all product designation
                 $product_designation[$attribute['id_product_attribute']] = rtrim($obj->name[$this->context->language->id] . ' - ' . $attribute['attribute_designation'], ' - ');
             }
             $show_quantities = true;
             $shop_context = Shop::getContext();
             $shop_group = new ShopGroup((int) Shop::getContextShopGroupID());
             // if we are in all shops context, it's not possible to manage quantities at this level
             if (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_ALL) {
                 $show_quantities = false;
             } elseif (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_GROUP) {
                 // if quantities are not shared between shops of the group, it's not possible to manage them at group level
                 if (!$shop_group->share_stock) {
                     $show_quantities = false;
                 }
             } else {
                 // if quantities are shared between shops of the group, it's not possible to manage them for a given shop
                 if ($shop_group->share_stock) {
                     $show_quantities = false;
                 }
             }
             $data->assign('ps_stock_management', Configuration::get('PS_STOCK_MANAGEMENT'));
             $data->assign('has_attribute', $obj->hasAttributes());
             // Check if product has combination, to display the available date only for the product or for each combination
             if (Combination::isFeatureActive()) {
                 $data->assign('countAttributes', (int) Db::getInstance()->getValue('SELECT COUNT(id_product) FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int) $obj->id));
             } else {
                 $data->assign('countAttributes', false);
             }
             // if advanced stock management is active, checks associations
             $advanced_stock_management_warning = false;
             if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $obj->advanced_stock_management) {
                 $p_attributes = Product::getProductAttributesIds($obj->id);
                 $warehouses = array();
                 if (!$p_attributes) {
                     $warehouses[] = Warehouse::getProductWarehouseList($obj->id, 0);
                 }
                 foreach ($p_attributes as $p_attribute) {
                     $ws = Warehouse::getProductWarehouseList($obj->id, $p_attribute['id_product_attribute']);
                     if ($ws) {
                         $warehouses[] = $ws;
                     }
                 }
                 $warehouses = Tools::arrayUnique($warehouses);
                 if (empty($warehouses)) {
                     $advanced_stock_management_warning = true;
                 }
             }
             if ($advanced_stock_management_warning) {
                 $this->displayWarning($this->l('If you wish to use the advanced stock management, you must:'));
                 $this->displayWarning('- ' . $this->l('associate your products with warehouses.'));
                 $this->displayWarning('- ' . $this->l('associate your warehouses with carriers.'));
                 $this->displayWarning('- ' . $this->l('associate your warehouses with the appropriate shops.'));
             }
             $pack_quantity = null;
             // if product is a pack
             if (Pack::isPack($obj->id)) {
                 $items = Pack::getItems((int) $obj->id, Configuration::get('PS_LANG_DEFAULT'));
                 // gets an array of quantities (quantity for the product / quantity in pack)
                 $pack_quantities = array();
                 foreach ($items as $item) {
                     /** @var Product $item */
                     if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) {
                         $pack_id_product_attribute = Product::getDefaultAttribute($item->id, 1);
                         $pack_quantities[] = Product::getQuantity($item->id, $pack_id_product_attribute) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1);
                     }
                 }
                 // gets the minimum
                 if (count($pack_quantities)) {
                     $pack_quantity = $pack_quantities[0];
                     foreach ($pack_quantities as $value) {
                         if ($pack_quantity > $value) {
                             $pack_quantity = $value;
                         }
                     }
                 }
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && !Warehouse::getPackWarehouses((int) $obj->id)) {
                     $this->displayWarning($this->l('You must have a common warehouse between this pack and its product.'));
                 }
             }
             $data->assign(array('attributes' => $attributes, 'available_quantity' => $available_quantity, 'pack_quantity' => $pack_quantity, 'stock_management_active' => Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'product_designation' => $product_designation, 'product' => $obj, 'show_quantities' => $show_quantities, 'order_out_of_stock' => Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'pack_stock_type' => Configuration::get('PS_PACK_STOCK_TYPE'), 'token_preferences' => Tools::getAdminTokenLite('AdminPPreferences'), 'token' => $this->token, 'languages' => $this->_languages, 'id_lang' => $this->context->language->id));
         } else {
             $this->displayWarning($this->l('You must save the product in this shop before managing quantities.'));
         }
     } else {
         $this->displayWarning($this->l('You must save this product before managing quantities.'));
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
 public function ajaxProcessDeleteProductAttribute()
 {
     if (!Combination::isFeatureActive()) {
         return;
     }
     if ($this->tabAccess['delete'] === '1') {
         $id_product = (int) Tools::getValue('id_product');
         $id_product_attribute = (int) Tools::getValue('id_product_attribute');
         if ($id_product && Validate::isUnsignedId($id_product) && Validate::isLoadedObject($product = new Product($id_product))) {
             if (($depends_on_stock = StockAvailable::dependsOnStock($id_product)) && StockAvailable::getQuantityAvailableByProduct($id_product, $id_product_attribute)) {
                 $json = array('status' => 'error', 'message' => $this->l('It is not possible to delete a combination while it still has some quantities in the Advanced Stock Management. You must delete its stock first.'));
             } else {
                 $product->deleteAttributeCombination((int) $id_product_attribute);
                 $product->checkDefaultAttributes();
                 Tools::clearColorListCache((int) $product->id);
                 if (!$product->hasAttributes()) {
                     $product->cache_default_attribute = 0;
                     $product->update();
                 } else {
                     Product::updateDefaultAttribute($id_product);
                 }
                 if ($depends_on_stock && !Stock::deleteStockByIds($id_product, $id_product_attribute)) {
                     $json = array('status' => 'error', 'message' => $this->l('Error while deleting the stock'));
                 } else {
                     $json = array('status' => 'ok', 'message' => $this->_conf[1], 'id_product_attribute' => (int) $id_product_attribute);
                 }
             }
         } else {
             $json = array('status' => 'error', 'message' => $this->l('You cannot delete this attribute.'));
         }
     } else {
         $json = array('status' => 'error', 'message' => $this->l('You do not have permission to delete this.'));
     }
     die(json_encode($json));
 }
Example #6
0
    public function viewmanufacturer()
    {
        global $cookie;
        $manufacturer = $this->loadObject();
        echo '<h2>' . $manufacturer->name . '</h2>';
        $products = $manufacturer->getProductsLite(intval($cookie->id_lang));
        $addresses = $manufacturer->getAddresses(intval($cookie->id_lang));
        echo '<h3>' . $this->l('Total addresses:') . ' ' . sizeof($addresses) . '</h3>';
        echo '<hr />';
        foreach ($addresses as $addresse) {
            echo '
				<h3></h3>
				<table border="0" cellpadding="0" cellspacing="0" class="table" style="width: 600px;">
					<tr>
						<th><b>' . $addresse['firstname'] . ' ' . $addresse['lastname'] . '</b></th>
					</tr>
					<tr>
						<td>
							<div style="padding:5px; float:left; width:350px;">
								' . $addresse['address1'] . '<br />
								' . ($addresse['address2'] ? $addresse['address2'] . '<br />' : '') . '
								' . $addresse['postcode'] . ' ' . $addresse['city'] . '<br />
								' . ($addresse['state'] ? $addresse['state'] . '<br />' : '') . '
								<b>' . $addresse['country'] . '</b><br />
								</div>
							<div style="padding:5px; float:left;">
								' . ($addresse['phone'] ? $addresse['phone'] . '<br />' : '') . '
								' . ($addresse['phone_mobile'] ? $addresse['phone_mobile'] . '<br />' : '') . '
							</div>
							' . ($addresse['other'] ? '<div style="padding:5px; clear:both;"><br /><i>' . $addresse['other'] . '</i></div>' : '') . '
						</td>
					</tr>
				</table>';
        }
        if (!sizeof($addresses)) {
            echo 'No address for this manufacturer.';
        }
        echo '<br /><br />';
        echo '<h3>' . $this->l('Total products:') . ' ' . sizeof($products) . '</h3>';
        foreach ($products as $product) {
            $product = new Product($product['id_product'], false, intval($cookie->id_lang));
            echo '<hr />';
            if (!$product->hasAttributes()) {
                echo '
				<table border="0" cellpadding="0" cellspacing="0" class="table width3">
					<tr>
						<th>' . $product->name . '</th>
						' . (!empty($product->reference) ? '<th width="150">' . $this->l('Ref:') . ' ' . $product->reference . '</th>' : '') . '
						' . (!empty($product->ean13) ? '<th width="120">' . $this->l('EAN13:') . ' ' . $product->ean13 . '</th>' : '') . '
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="50">' . $this->l('Qty:') . ' ' . $product->quantity . '</th>' : '') . '
					</tr>
				</table>';
            } else {
                echo '
				<h3>' . $product->name . '</h3>
				<table>
					<tr>
						<td colspan="2">
		            		<table border="0" cellpadding="0" cellspacing="0" class="table" style="width: 600px;">
			                	<tr>
				                    <th>' . $this->l('Attribute name') . '</th>
				                    <th width="80">' . $this->l('Reference') . '</th>
				                    <th width="80">' . $this->l('EAN13') . '</th>
				                   ' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="40">' . $this->l('Quantity') . '</th>' : '') . '
			                	</tr>';
                /* Build attributes combinaisons */
                $combinaisons = $product->getAttributeCombinaisons(intval($cookie->id_lang));
                foreach ($combinaisons as $k => $combinaison) {
                    $combArray[$combinaison['id_product_attribute']]['reference'] = $combinaison['reference'];
                    $combArray[$combinaison['id_product_attribute']]['ean13'] = $combinaison['ean13'];
                    $combArray[$combinaison['id_product_attribute']]['quantity'] = $combinaison['quantity'];
                    $combArray[$combinaison['id_product_attribute']]['attributes'][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute']);
                }
                $irow = 0;
                foreach ($combArray as $id_product_attribute => $product_attribute) {
                    $list = '';
                    foreach ($product_attribute['attributes'] as $attribute) {
                        $list .= $attribute[0] . ' - ' . $attribute[1] . ', ';
                    }
                    $list = rtrim($list, ', ');
                    echo '
					<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . ' >
						<td>' . stripslashes($list) . '</td>
						<td>' . $product_attribute['reference'] . '</td>
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<td>' . $product_attribute['ean13'] . '</td>' : '') . '
						<td class="right">' . $product_attribute['quantity'] . '</td>
					</tr>';
                }
                unset($combArray);
                echo '</table>';
            }
        }
    }
Example #7
0
    public function hookAdminStatsModules($params)
    {
        global $cookie, $currentIndex;
        $id_category = intval(Tools::getValue('id_category'));
        $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
        $this->_html = '<fieldset class="width3"><legend><img src="../modules/' . $this->name . '/logo.gif" /> ' . $this->displayName . '</legend>';
        if ($id_product = intval(Tools::getValue('id_product'))) {
            $product = new Product($id_product, false, intval($cookie->id_lang));
            $totalBought = $this->getTotalBought($product->id);
            $totalViewed = $this->getTotalViewed($product->id);
            $this->_html .= '<h3>' . $product->name . ' - ' . $this->l('Details') . '</h3>
			<p>' . $this->l('Conversion rate:') . ' ' . number_format($totalViewed ? $totalBought / $totalViewed : 0, 2) . '</p>
			<p>' . $this->l('Total bought:') . ' ' . $totalBought . '</p>
			<center>' . ModuleGraph::engine(array('type' => 'line', 'option' => '1-' . $id_product)) . '</center>
			<p>' . $this->l('Total viewed:') . ' ' . $totalViewed . '</p>
			<center>' . ModuleGraph::engine(array('type' => 'line', 'option' => '2-' . $id_product)) . '</center>';
            if ($hasAttribute = $product->hasAttributes() and $totalBought) {
                $this->_html .= '<h3 class="space">' . $this->l('Attribute sales distribution') . '</h3><center>' . ModuleGraph::engine(array('type' => 'pie', 'option' => '3-' . $id_product)) . '</center>';
            }
            if ($totalBought) {
                $sales = $this->getSales($id_product, $cookie->id_lang);
                $this->_html .= '<br class="clear" />
				<h3>' . $this->l('Sales') . '</h3>
				<div style="overflow-y: scroll; height: 600px;">
				<table class="table" border="0" cellspacing="0" cellspacing="0">
				<thead>
					<tr>
						<th>' . $this->l('Date') . '</th>
						<th>' . $this->l('Order') . '</th>
						' . ($hasAttribute ? '<th>' . $this->l('Attribute') . '</th>' : '') . '
						<th>' . $this->l('Qty') . '</th>
						<th>' . $this->l('Price') . '</th>
						<th>' . $this->l('Tax') . '</th>
					</tr>
				</thead><tbody>';
                foreach ($sales as $sale) {
                    $this->_html .= '
					<tr>
						<td>' . Tools::displayDate($sale['date_add'], intval($cookie->id_lang), false) . '</td>
						<td>' . intval($sale['id_order']) . '</td>
						' . ($hasAttribute ? '<td>' . $sale['product_name'] . '</td>' : '') . '
						<td>' . intval($sale['product_quantity']) . '</td>
						<td>' . Tools::displayprice($sale['total'], $currency) . '</td>
						<td>' . $sale['tax_name'] . '</td>
					</tr>';
                }
                $this->_html .= '</tbody></table></div>';
            }
        } else {
            $categories = Category::getCategories(intval($cookie->id_lang), true, false);
            $this->_html .= '
			<label>' . $this->l('Choose a category') . '</label>
			<div class="margin-form">
				<form action="" method="post" id="categoriesForm">
					<select name="id_category" onchange="$(\'#categoriesForm\').submit();">
						<option value="0">' . $this->l('All') . '</option>';
            foreach ($categories as $category) {
                $this->_html .= '<option value="' . $category['id_category'] . '"' . ($id_category == $category['id_category'] ? ' selected="selected"' : '') . '>' . $category['name'] . '</option>';
            }
            $this->_html .= '
					</select>
				</form>
			</div>
			<div class="clear space"></div>
			' . $this->l('Click on a product to access its statistics.') . '
			<div class="clear space"></div>
			<h2>' . $this->l('Products available') . '</h2>
			<div style="overflow-y: scroll; height: 600px;">
			<table class="table" border="0" cellspacing="0" cellspacing="0">
			<thead>
				<tr>
					<th>' . $this->l('Ref.') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Stock') . '</th>
				</tr>
			</thead><tbody>';
            foreach ($this->getProducts($cookie->id_lang) as $product) {
                $this->_html .= '<tr><td>' . $product['reference'] . '</td><td><a href="' . $currentIndex . '&token=' . Tools::getValue('token') . '&module=' . $this->name . '&id_product=' . $product['id_product'] . '">' . $product['name'] . '</a></td><td>' . $product['quantity'] . '</td></tr>';
            }
            $this->_html .= '</tbody></table></div>';
        }
        $this->_html .= '</fieldset><br />
		<fieldset class="width3"><legend><img src="../img/admin/comment.gif" /> ' . $this->l('Guide') . '</legend>
		<h2>' . $this->l('Number of purchases compared to number of viewings') . '</h2>
			<p>
				' . $this->l('After choosing a category and selecting a product available in this category, some graphs appear. Then, you can analyze them.') . '
				<ul>
					<li class="bullet">' . $this->l('If you notice that a product is successful, very purchased, but also little viewed: you should put it more prominently on your webshop front-office.') . '</li>
					<li class="bullet">' . $this->l('On the other hand, if a product knows a lot of viewings but is not really purchased: we advise you to check or modify this product\'s information, description and photography again.') . '
					</li>
				</ul>
			</p>
		</fieldset>';
        return $this->_html;
    }
Example #8
0
    public function hookAdminStatsModules()
    {
        $id_category = (int) Tools::getValue('id_category');
        $currency = Context::getContext()->currency;
        if (Tools::getValue('export')) {
            if (!Tools::getValue('exportType')) {
                $this->csvExport(array('layers' => 2, 'type' => 'line', 'option' => '42'));
            }
        }
        $this->html = '
			<div class="panel-heading">
				' . $this->displayName . '
			</div>
			<h4>' . $this->l('Guide') . '</h4>
			<div class="alert alert-warning">
				<h4>' . $this->l('Number of purchases compared to number of views') . '</h4>
				<p>
					' . $this->l('After choosing a category and selecting a product, informational graphs will appear.') . '
					<ul>
						<li class="bullet">' . $this->l('If you notice that a product is often purchased but viewed infrequently, you should display it more prominently in your Front Office.') . '</li>
						<li class="bullet">' . $this->l('On the other hand, if a product has many views but is not often purchased, we advise you to check or modify this product\'s information, description and photography again, see if you can find something better.') . '
						</li>
					</ul>
				</p>
			</div>';
        if ($id_product = (int) Tools::getValue('id_product')) {
            if (Tools::getValue('export')) {
                if (Tools::getValue('exportType') == 1) {
                    $this->csvExport(array('layers' => 2, 'type' => 'line', 'option' => '1-' . $id_product));
                } elseif (Tools::getValue('exportType') == 2) {
                    $this->csvExport(array('type' => 'pie', 'option' => '3-' . $id_product));
                }
            }
            $product = new Product($id_product, false, $this->context->language->id);
            $total_bought = $this->getTotalBought($product->id);
            $total_sales = $this->getTotalSales($product->id);
            $total_viewed = $this->getTotalViewed($product->id);
            $this->html .= '<h4>' . $product->name . ' - ' . $this->l('Details') . '</h4>
			<div class="row row-margin-bottom">
				<div class="col-lg-12">
					<div class="col-lg-8">
						' . $this->engine(array('layers' => 2, 'type' => 'line', 'option' => '1-' . $id_product)) . '
					</div>
					<div class="col-lg-4">
						<ul class="list-unstyled">
							<li>' . $this->l('Total bought') . ' ' . $total_bought . '</li>
							<li>' . $this->l('Sales (tax excluded)') . ' ' . Tools::displayprice($total_sales, $currency) . '</li>
							<li>' . $this->l('Total viewed') . ' ' . $total_viewed . '</li>
							<li>' . $this->l('Conversion rate') . ' ' . number_format($total_viewed ? $total_bought / $total_viewed : 0, 2) . '</li>
						</ul>
						<a class="btn btn-default export-csv" href="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '&export=1&exportType=1">
							<i class="icon-cloud-upload"></i> ' . $this->l('CSV Export') . '
						</a>
					</div>
				</div>
			</div>';
            if ($has_attribute = $product->hasAttributes() && $total_bought) {
                $this->html .= '<h3 class="space">' . $this->l('Attribute sales distribution') . '</h3><center>' . $this->engine(array('type' => 'pie', 'option' => '3-' . $id_product)) . '</center><br />
			<a href="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '&export=1&exportType=2"><img src="../img/admin/asterisk.gif" />' . $this->l('CSV Export') . '</a>';
            }
            if ($total_bought) {
                $sales = $this->getSales($id_product);
                $this->html .= '
				<h4>' . $this->l('Sales') . '</h4>
				<div style="overflow-y: scroll; height: ' . min(400, (count($sales) + 1) * 32) . 'px;">
					<table class="table">
						<thead>
							<tr>
								<th>
									<span class="title_box  active">' . $this->l('Date') . '</span>
								</th>
								<th>
									<span class="title_box  active">' . $this->l('Order') . '</span>
								</th>
								<th>
									<span class="title_box  active">' . $this->l('Customer') . '</span>
								</th>
								' . ($has_attribute ? '<th><span class="title_box  active">' . $this->l('Attribute') . '</span></th>' : '') . '
								<th>
									<span class="title_box  active">' . $this->l('Quantity') . '</span>
								</th>
								<th>
									<span class="title_box  active">' . $this->l('Price') . '</span>
								</th>
							</tr>
						</thead>
						<tbody>';
                $token_order = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $this->context->employee->id);
                $token_customer = Tools::getAdminToken('AdminCustomers' . (int) Tab::getIdFromClassName('AdminCustomers') . (int) $this->context->employee->id);
                foreach ($sales as $sale) {
                    $this->html .= '
						<tr>
							<td>' . Tools::displayDate($sale['date_add'], null, false) . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $sale['id_order'] . '&vieworder&token=' . $token_order . '">' . (int) $sale['id_order'] . '</a></td>
							<td align="center"><a href="?tab=AdminCustomers&id_customer=' . $sale['id_customer'] . '&viewcustomer&token=' . $token_customer . '">' . (int) $sale['id_customer'] . '</a></td>
							' . ($has_attribute ? '<td>' . $sale['product_name'] . '</td>' : '') . '
							<td>' . (int) $sale['product_quantity'] . '</td>
							<td>' . Tools::displayprice($sale['total'], $currency) . '</td>
						</tr>';
                }
                $this->html .= '
						</tbody>
					</table>
				</div>';
                $cross_selling = $this->getCrossSales($id_product, $this->context->language->id);
                if (count($cross_selling)) {
                    $this->html .= '
					<h4>' . $this->l('Cross selling') . '</h4>
					<div style="overflow-y: scroll; height: 200px;">
						<h4>' . $this->l('Cross selling') . '</h4>
						<table class="table">
							<thead>
								<tr>
									<th>
										<span class="title_box  active">' . $this->l('Product name') . '</span>
									</th>
									<th>
										<span class="title_box  active">' . $this->l('Quantity sold') . '</span>
									</th>
									<th>
										<span class="title_box  active">' . $this->l('Average price') . '</span>
									</th>
								</tr>
							</thead>
						<tbody>';
                    $token_products = Tools::getAdminToken('AdminProducts' . (int) Tab::getIdFromClassName('AdminProducts') . (int) $this->context->employee->id);
                    foreach ($cross_selling as $selling) {
                        $this->html .= '
							<tr>
								<td ><a href="?tab=AdminProducts&id_product=' . (int) $selling['id_product'] . '&addproduct&token=' . $token_products . '">' . $selling['pname'] . '</a></td>
								<td align="center">' . (int) $selling['pqty'] . '</td>
								<td align="right">' . Tools::displayprice($selling['pprice'], $currency) . '</td>
							</tr>';
                    }
                    $this->html .= '
							</tbody>
						</table>
					</div>';
                }
            }
        } else {
            $categories = Category::getCategories((int) $this->context->language->id, true, false);
            $this->html .= '
			<form action="" method="post" id="categoriesForm" class="form-horizontal">
				<div class="row row-margin-bottom">
					<label class="control-label col-lg-3" for="id_category">
						<span title="" data-toggle="tooltip" class="label-tooltip" data-original-title="' . $this->l('Click on a product to access its statistics!') . '">
							' . $this->l('Choose a category') . '
						</span>
					</label>
					<div class="col-lg-3">
						<select name="id_category" onchange="$(\'#categoriesForm\').submit();">
							<option value="0">' . $this->l('All') . '</option>';
            foreach ($categories as $category) {
                $this->html .= '<option value="' . $category['id_category'] . '"' . ($id_category == $category['id_category'] ? ' selected="selected"' : '') . '>' . $category['name'] . '</option>';
            }
            $this->html .= '
						</select>
					</div>
				</div>
			</form>
			<h4>' . $this->l('Products available') . '</h4>
			<table class="table" border="0" cellspacing="0" cellspacing="0">
				<thead>
					<tr>
						<th>
							<span class="title_box  active">' . $this->l('Reference') . '</span>
						</th>
						<th>
							<span class="title_box  active">' . $this->l('Name') . '</span>
						</th>
						<th>
							<span class="title_box  active">' . $this->l('Available quantity for sale') . '</span>
						</th>
					</tr>
				</thead>
				<tbody>';
            foreach ($this->getProducts($this->context->language->id) as $product) {
                $this->html .= '
				<tr>
					<td>' . $product['reference'] . '</td>
					<td>
						<a href="' . AdminController::$currentIndex . '&token=' . Tools::safeOutput(Tools::getValue('token')) . '&module=' . $this->name . '&id_product=' . $product['id_product'] . '">' . $product['name'] . '</a>
					</td>
					<td>' . $product['quantity'] . '</td>
				</tr>';
            }
            $this->html .= '
				</tbody>
			</table>
			<a class="btn btn-default export-csv" href="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '&export=1">
				<i class="icon-cloud-upload"></i> ' . $this->l('CSV Export') . '
			</a>';
        }
        return $this->html;
    }
 public function processDuplicate()
 {
     if (!Module::isInstalled('agilemultipleseller')) {
         parent::processDuplicate();
     } else {
         if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
             $id_product_old = $product->id;
             if (empty($product->price) && Shop::getContext() == Shop::CONTEXT_GROUP) {
                 $shops = ShopGroup::getShopsFromGroup(Shop::getContextShopGroupID());
                 foreach ($shops as $shop) {
                     if ($product->isAssociatedToShop($shop['id_shop'])) {
                         $product_price = new Product($id_product_old, false, null, $shop['id_shop']);
                         $product->price = $product_price->price;
                     }
                 }
             }
             unset($product->id);
             unset($product->id_product);
             $product->indexed = 0;
             $product->active = 0;
             if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) {
                 if ($product->hasAttributes()) {
                     Product::updateDefaultAttribute($product->id);
                 }
                 AgileSellerManager::assignObjectOwner('product', $product->id, AgileSellerManager::getObjectOwnerID('product', $id_product_old));
                 if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) {
                     $this->errors[] = Tools::displayError('An error occurred while copying images.');
                 } else {
                     Hook::exec('actionProductAdd', array('product' => $product));
                     if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) {
                         Search::indexation(false, $product->id);
                     }
                     $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=19&token=' . $this->token;
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while creating an object.');
             }
         }
     }
 }
Example #10
0
 public function hookActionUpdateQuantity($params)
 {
     $id_product = (int) $params['id_product'];
     $id_product_attribute = (int) $params['id_product_attribute'];
     $quantity = (int) $params['quantity'];
     $context = Context::getContext();
     $id_shop = (int) $context->shop->id;
     $id_lang = (int) $context->language->id;
     $product = new Product($id_product, false, $id_lang, $id_shop, $context);
     $product_has_attributes = $product->hasAttributes();
     $configuration = Configuration::getMultiple(array('MA_LAST_QTIES', 'PS_STOCK_MANAGEMENT', 'PS_SHOP_EMAIL', 'PS_SHOP_NAME'), null, null, $id_shop);
     $ma_last_qties = (int) $configuration['MA_LAST_QTIES'];
     $check_oos = $product_has_attributes && $id_product_attribute || !$product_has_attributes && !$id_product_attribute;
     if ($check_oos && $product->active == 1 && (int) $quantity <= $ma_last_qties && !(!$this->merchant_oos || empty($this->merchant_mails)) && $configuration['PS_STOCK_MANAGEMENT']) {
         $iso = Language::getIsoById($id_lang);
         $product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang);
         $template_vars = array('{qty}' => $quantity, '{last_qty}' => $ma_last_qties, '{product}' => $product_name);
         // Do not send mail if multiples product are created / imported.
         if (!defined('PS_MASS_PRODUCT_CREATION') && file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productoutofstock.txt') && file_exists(dirname(__FILE__) . '/mails/' . $iso . '/productoutofstock.html')) {
             // Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
             $merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
             foreach ($merchant_mails as $merchant_mail) {
                 Mail::Send($id_lang, 'productoutofstock', Mail::l('Product out of stock', $id_lang), $template_vars, $merchant_mail, null, (string) $configuration['PS_SHOP_EMAIL'], (string) $configuration['PS_SHOP_NAME'], null, null, dirname(__FILE__) . '/mails/', false, $id_shop);
             }
         }
     }
     if ($this->customer_qty && $quantity > 0) {
         MailAlert::sendCustomerAlert((int) $product->id, (int) $params['id_product_attribute']);
     }
 }
Example #11
0
 $qty = intval(abs(Tools::getValue('qty', 1)));
 if ($qty == 0) {
     $errors[] = Tools::displayError('null quantity');
 } elseif (!$idProduct) {
     $errors[] = Tools::displayError('product not found');
 } else {
     $producToAdd = new Product(intval($idProduct), false, intval($cookie->id_lang));
     if ((!$producToAdd->id or !$producToAdd->active) and !$delete) {
         $errors[] = Tools::displayError('product is no longer available');
     } else {
         /* Check the quantity availability */
         if ($idProductAttribute and is_numeric($idProductAttribute)) {
             if (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty(intval($idProductAttribute), intval($qty))) {
                 $errors[] = Tools::displayError('product is no longer available');
             }
         } elseif ($producToAdd->hasAttributes() and !$delete) {
             $idProductAttribute = Product::getDefaultAttribute(intval($producToAdd->id), intval($producToAdd->out_of_stock) == 2 ? !intval(Configuration::get('PS_ORDER_OUT_OF_STOCK')) : !intval($producToAdd->out_of_stock));
             if (!$idProductAttribute) {
                 Tools::redirectAdmin($link->getProductLink($producToAdd));
             } elseif (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty(intval($idProductAttribute), intval($qty))) {
                 $errors[] = Tools::displayError('product is no longer available');
             }
         } elseif (!$delete and !$producToAdd->checkQty(intval($qty))) {
             $errors[] = Tools::displayError('product is no longer available');
         }
         /* Check vouchers compatibility */
         if ($add and (intval($producToAdd->reduction_price) or intval($producToAdd->reduction_percent) or $producToAdd->on_sale)) {
             $discounts = $cart->getDiscounts();
             foreach ($discounts as $discount) {
                 if (!$discount['cumulable_reduction']) {
                     $errors[] = Tools::displayError('cannot add this product because current voucher doesn\'t allow additional discounts');
    public function viewmanufacturer()
    {
        global $cookie;
        if (!($manufacturer = $this->loadObject())) {
            return;
        }
        echo '<h2>' . $manufacturer->name . '</h2>';
        $products = $manufacturer->getProductsLite((int) $cookie->id_lang);
        $addresses = $manufacturer->getAddresses((int) $cookie->id_lang);
        echo '<h3>' . $this->l('Total addresses:') . ' ' . sizeof($addresses) . '</h3>';
        echo '<hr />';
        foreach ($addresses as $addresse) {
            echo '
				<h3></h3>
				<table border="0" cellpadding="0" cellspacing="0" class="table" style="width: 600px;">
					<tr>
						<th><b>' . $addresse['firstname'] . ' ' . $addresse['lastname'] . '</b></th>
					</tr>
					<tr>
						<td>
							<div style="padding:5px; float:left; width:350px;">
								' . $addresse['address1'] . '<br />
								' . ($addresse['address2'] ? $addresse['address2'] . '<br />' : '') . '
								' . $addresse['postcode'] . ' ' . $addresse['city'] . '<br />
								' . ($addresse['state'] ? $addresse['state'] . '<br />' : '') . '
								<b>' . $addresse['country'] . '</b><br />
								</div>
							<div style="padding:5px; float:left;">
								' . ($addresse['phone'] ? $addresse['phone'] . '<br />' : '') . '
								' . ($addresse['phone_mobile'] ? $addresse['phone_mobile'] . '<br />' : '') . '
							</div>
							' . ($addresse['other'] ? '<div style="padding:5px; clear:both;"><br /><i>' . $addresse['other'] . '</i></div>' : '') . '
						</td>
					</tr>
				</table>';
        }
        if (!sizeof($addresses)) {
            echo 'No address for this manufacturer.';
        }
        echo '<br /><br />';
        echo '<h3>' . $this->l('Total products:') . ' ' . sizeof($products) . '</h3>';
        foreach ($products as $product) {
            $product = new Product($product['id_product'], false, (int) $cookie->id_lang);
            echo '<hr />';
            if (!$product->hasAttributes()) {
                echo '
				<div style="float:right;">
					<a href="?tab=AdminCatalog&id_product=' . $product->id . '&updateproduct&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" class="button">' . $this->l('Edit') . '</a>
					<a href="?tab=AdminCatalog&id_product=' . $product->id . '&deleteproduct&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" class="button" onclick="return confirm(\'' . $this->l('Delete item #', __CLASS__, TRUE) . $product->id . ' ?\');">' . $this->l('Delete') . '</a>
				</div>
				<table border="0" cellpadding="0" cellspacing="0" class="table width3">
					<tr>
						<th>' . $product->name . '</th>
						' . (!empty($product->reference) ? '<th width="150">' . $this->l('Ref:') . ' ' . $product->reference . '</th>' : '') . '
						' . (!empty($product->ean13) ? '<th width="120">' . $this->l('EAN13:') . ' ' . $product->ean13 . '</th>' : '') . '
						' . (!empty($product->upc) ? '<th width="120">' . $this->l('UPC:') . ' ' . $product->upc . '</th>' : '') . '
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="50">' . $this->l('Qty:') . ' ' . $product->quantity . '</th>' : '') . '
					</tr>
				</table>';
            } else {
                echo '
				<div style="float:right;">
					<a href="?tab=AdminCatalog&id_product=' . $product->id . '&updateproduct&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" class="button">' . $this->l('Edit') . '</a>
					<a href="?tab=AdminCatalog&id_product=' . $product->id . '&deleteproduct&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" class="button" onclick="return confirm(\'' . $this->l('Delete item #', __CLASS__, TRUE) . $product->id . ' ?\');">' . $this->l('Delete') . '</a>
				</div>
				<h3><a href="?tab=AdminCatalog&id_product=' . $product->id . '&updateproduct&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '">' . $product->name . '</a></h3>
				<table border="0" cellpadding="0" cellspacing="0" class="table" style="width: 600px;">
					<tr>
	                    <th>' . $this->l('Attribute name') . '</th>
	                    <th width="80">' . $this->l('Reference') . '</th>
	                    <th width="80">' . $this->l('EAN13') . '</th>
						<th width="80">' . $this->l('UPC') . '</th>
	                   ' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<th class="right" width="40">' . $this->l('Quantity') . '</th>' : '') . '
                	</tr>';
                /* Build attributes combinaisons */
                $combinaisons = $product->getAttributeCombinaisons((int) $cookie->id_lang);
                foreach ($combinaisons as $k => $combinaison) {
                    $combArray[$combinaison['id_product_attribute']]['reference'] = $combinaison['reference'];
                    $combArray[$combinaison['id_product_attribute']]['ean13'] = $combinaison['ean13'];
                    $combArray[$combinaison['id_product_attribute']]['upc'] = $combinaison['upc'];
                    $combArray[$combinaison['id_product_attribute']]['quantity'] = $combinaison['quantity'];
                    $combArray[$combinaison['id_product_attribute']]['attributes'][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute']);
                }
                $irow = 0;
                foreach ($combArray as $id_product_attribute => $product_attribute) {
                    $list = '';
                    foreach ($product_attribute['attributes'] as $attribute) {
                        $list .= $attribute[0] . ' - ' . $attribute[1] . ', ';
                    }
                    $list = rtrim($list, ', ');
                    echo '
					<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . ' >
						<td>' . stripslashes($list) . '</td>
						<td>' . $product_attribute['reference'] . '</td>
						' . (Configuration::get('PS_STOCK_MANAGEMENT') ? '<td>' . $product_attribute['ean13'] . '</td><td>' . $product_attribute['upc'] . '</td>' : '') . '
						<td class="right">' . $product_attribute['quantity'] . '</td>
					</tr>';
                }
                unset($combArray);
                echo '</table>';
            }
        }
    }
Example #13
0
/**
*   Diaplay the product catalog items.
*
*   @return string      HTML for product catalog.
*/
function PAYPAL_ProductList($cat = 0, $search = '')
{
    global $_TABLES, $_CONF, $_PP_CONF, $LANG_PP, $_USER, $_PLUGINS, $_IMAGE_TYPE, $_GROUPS;
    USES_paypal_class_product();
    if (SEC_hasRights('paypal.admin')) {
        $isAdmin = true;
    } else {
        $isAdmin = false;
    }
    $my_groups = implode(',', $_GROUPS);
    $cat_name = '';
    $breadcrumbs = '';
    $img_url = '';
    $display = '';
    if ($cat != 0) {
        $breadcrumbs = PAYPAL_Breadcrumbs($cat);
        $cat = (int) $cat;
        $A = DB_fetchArray(DB_query("SELECT cat_name, image\n                FROM {$_TABLES['paypal.categories']}\n                WHERE cat_id='{$cat}' " . COM_getPermSQL('AND')), false);
        if (!empty($A)) {
            $cat_name = $A['cat_name'];
            if (!empty($A['image']) && is_file($_CONF['path_html'] . $_PP_CONF['pi_name'] . '/images/categories/' . $A['image'])) {
                $img_url = PAYPAL_URL . '/images/categories/' . $A['image'];
            }
        }
    }
    // Display categories
    if (isset($_PP_CONF['cat_columns']) && $_PP_CONF['cat_columns'] > 0) {
        $sql = "SELECT cat.cat_id, cat.cat_name, count(prod.id) AS cnt \n            FROM {$_TABLES['paypal.categories']} cat\n            LEFT JOIN {$_TABLES['paypal.products']} prod\n                ON prod.cat_id = cat.cat_id\n            WHERE cat.enabled = '1' AND cat.parent_id = '{$cat}' \n                AND prod.enabled = '1' " . COM_getPermSQL('AND', 0, 2, 'cat') . " GROUP BY cat.cat_id\n            ORDER BY cat.cat_name";
        //HAVING cnt > 0
        //echo $sql;die;
        $CT = new Template(PAYPAL_PI_PATH . '/templates');
        $CT->set_file(array('table' => 'category_table.thtml', 'row' => 'category_row.thtml', 'category' => 'category.thtml'));
        $CT->set_var('width', floor(100 / $_PP_CONF['cat_columns']));
        if ($breadcrumbs != '') {
            $CT->set_var('breadcrumbs', $breadcrumbs);
        }
        if ($img_url != '') {
            $CT->set_var('catimg_url', $img_url);
        }
        $res = DB_query($sql);
        $A = array();
        while ($C = DB_fetchArray($res, false)) {
            $A[$C['cat_id']] = array($C['cat_name'], $C['cnt']);
        }
        // Now get categories from plugins
        foreach ($_PLUGINS as $pi_name) {
            $function = 'USES_' . $pi_name . '_paypal';
            if (function_exists($function)) {
                $function();
                $function = 'plugin_paypal_getcategories_' . $pi_name;
                if (function_exists($function)) {
                    $pi_cats = $function();
                    foreach ($pi_cats as $catid => $data) {
                        $A[$catid] = $data;
                    }
                }
            }
        }
        $i = 1;
        $nrows = count($A);
        foreach ($A as $category => $info) {
            $CT->set_var(array('category_name' => $info[0], 'category_link' => PAYPAL_URL . '/index.php?category=' . urlencode($category)));
            /*if ($category == $cat) {
                  $CT->set_var('curr', 'current');
                  $cat_name = $info[0];
              } else {
                  $CT->set_var('curr', 'other');
              }*/
            $CT->parse('catrow', 'category', true);
            if ($i % $_PP_CONF['cat_columns'] == 0) {
                $CT->parse('categories', 'row', true);
                $CT->set_var('catrow', '');
            }
            $i++;
        }
        if ($nrows % $_PP_CONF['cat_columns'] != 0) {
            $CT->parse('categories', 'row', true);
        }
        $display .= $CT->parse('', 'table');
    }
    /*$sortby_opts = array(
            'name' => $LANG_PP['name'],
            'price' => $LANG_PP['price'],
            'dt_add' => $LANG_PP['dt_add'],
        );
        switch ($_REQUEST['sortby']){
        case 'name':
        case 'price':
        case 'dt_add':
            $sortby = $_REQUEST['sortby'];
            break;
        default:
            $sortby = $_PP_CONF['order'];
            break;
        }
        $sortby_options = '';
        foreach ($sortby_opts as $value=>$text) {
            $sel = $value == $sortby ? ' selected="selected"' : '';
            $sortby_options .= "<option value=\"$value\" $sel>$text</option>\n";
        }
    
        $sortdir = $_REQUEST['sortdir'] == 'DESC' ? 'DESC' : 'ASC';*/
    $sortby = $_PP_CONF['order'];
    $sortdir = 'ASC';
    // Get products from database. "c.enabled is null" is to allow products
    // with no category defined
    $sql = " FROM {$_TABLES['paypal.products']} p\n            LEFT JOIN {$_TABLES['paypal.categories']} c\n                ON p.cat_id = c.cat_id\n            WHERE p.enabled=1 \n            AND (\n                (c.enabled=1 " . COM_getPermSQL('AND', 0, 2, 'c') . ")\n                OR c.enabled IS NULL\n                )\n            AND (\n                p.track_onhand = 0 OR p.onhand > 0 OR p.oversell < 2\n                )";
    $pagenav_args = array();
    // If applicable, limit by category
    if (!empty($_REQUEST['category'])) {
        $cat_list = $_REQUEST['category'];
        $cat_list .= PAYPAL_recurseCats('PAYPAL_callbackCatCommaList', 0, $_REQUEST['category']);
        if (!empty($cat_list)) {
            $sql .= " AND c.cat_id IN ({$cat_list})";
        }
        $pagenav_args[] = 'category=' . urlencode($_REQUEST['category']);
    } else {
        $cat_list = '';
    }
    // If applicable, limit by search string
    if (!empty($_REQUEST['search_name'])) {
        $srch = DB_escapeString($_REQUEST['search_name']);
        $sql .= " AND (p.name like '%{$srch}%' OR \n                p.short_description like '%{$srch}%' OR\n                p.description like '%{$srch}%' OR\n                p.keywords like '%{$srch}%')";
        //if (!$isAdmin) $sql .= " AND p.grp_access IN ($my_groups) ";
        $pagenav_args[] = 'search_name=' . urlencode($_REQUEST['search_name']);
    }
    // If applicable, order by
    $sql .= " ORDER BY {$sortby} {$sortdir}";
    // If applicable, handle pagination of query
    if (isset($_PP_CONF['prod_per_page']) && $_PP_CONF['prod_per_page'] > 0) {
        // Count products from database
        $res = DB_query('SELECT COUNT(*) as cnt ' . $sql);
        $x = DB_fetchArray($res, false);
        if (isset($x['cnt'])) {
            $count = (int) $x['cnt'];
        } else {
            $count = 0;
        }
        // Make sure page requested is reasonable, if not, fix it
        if (!isset($_REQUEST['page']) || $_REQUEST['page'] <= 0) {
            $_REQUEST['page'] = 1;
        }
        $page = (int) $_REQUEST['page'];
        $start_limit = ($page - 1) * $_PP_CONF['prod_per_page'];
        if ($start_limit > $count) {
            $page = ceil($count / $_PP_CONF['prod_per_page']);
        }
        // Add limit for pagination (if applicable)
        if ($count > $_PP_CONF['prod_per_page']) {
            $sql .= " LIMIT {$start_limit}, {$_PP_CONF['prod_per_page']}";
        }
    }
    // Re-execute query with the limit clause in place
    $res = DB_query('SELECT DISTINCT p.id ' . $sql);
    // Create product template
    $product = new Template(PAYPAL_PI_PATH . '/templates');
    $product->set_file(array('start' => 'product_list_start.thtml', 'end' => 'product_list_end.thtml', 'product' => 'product_list_item.thtml', 'download' => 'buttons/btn_download.thtml', 'login_req' => 'buttons/btn_login_req.thtml', 'btn_details' => 'buttons/btn_details.thtml'));
    if ($nrows == 0 && COM_isAnonUser()) {
        $product->set_var('anon_and_empty', 'true');
    }
    $product->set_var(array('pi_url' => PAYPAL_URL, 'user_id' => $_USER['uid'], 'currency' => $_PP_CONF['currency']));
    if (!empty($cat_name)) {
        $product->set_var('title', $cat_name);
    } else {
        $product->set_var('title', $LANG_PP['blocktitle']);
    }
    /*$product->set_var('sortby_options', $sortby_options);
      if ($sortdir == 'DESC') {
          $product->set_var('sortdir_desc_sel', ' selected="selected"');
      } else {
          $product->set_var('sortdir_asc_sel', ' selected="selected"');
      }
      $product->set_var('sortby', $sortby);
      $product->set_var('sortdir', $sortdir);*/
    $display .= $product->parse('', 'start');
    // Create an empty product object
    $P = new Product();
    if ($_PP_CONF['ena_ratings'] == 1) {
        $PP_ratedIds = RATING_getRatedIds('paypal');
    }
    // Display each product
    while ($A = DB_fetchArray($res, false)) {
        $P->Read($A['id']);
        if ($_PP_CONF['ena_ratings'] == 1 && $P->rating_enabled == 1) {
            if (in_array($A['id'], $PP_ratedIds)) {
                $static = true;
                $voted = 1;
            } elseif (plugin_canuserrate_paypal($A['id'], $_USER['uid'])) {
                $static = false;
                $voted = 0;
            } else {
                $static = true;
                $voted = 0;
            }
            $rating_box = RATING_ratingBar('paypal', $A['id'], $P->votes, $P->rating, $voted, 5, $static, 'sm');
            $product->set_var('rating_bar', $rating_box);
        } else {
            $product->set_var('rating_bar', '');
        }
        $product->set_var(array('id' => $A['id'], 'name' => $P->name, 'short_description' => PLG_replacetags($P->short_description), 'img_cell_width' => $_PP_CONF['max_thumb_size'] + 20, 'encrypted' => '', 'item_url' => COM_buildURL(PAYPAL_URL . '/detail.php?id=' . $A['id']), 'img_cell_width' => $_PP_CONF['max_thumb_size'] + 20, 'track_onhand' => $P->track_onhand ? 'true' : '', 'qty_onhand' => $P->onhand));
        if ($P->price > 0) {
            //$product->set_var('price', COM_numberFormat($P->price, 2));
            $product->set_var('price', $P->currency->Format($P->price));
        } else {
            $product->clear_var('price');
        }
        if ($isAdmin) {
            $product->set_var('is_admin', 'true');
            $product->set_var('pi_admin_url', PAYPAL_ADMIN_URL);
            $product->set_var('edit_icon', "{$_CONF['layout_url']}/images/edit.{$_IMAGE_TYPE}");
        }
        $pic_filename = DB_getItem($_TABLES['paypal.images'], 'filename', "product_id = '{$A['id']}'");
        if ($pic_filename) {
            $product->set_var('small_pic', PAYPAL_ImageUrl($pic_filename));
        } else {
            $product->set_var('small_pic', '');
        }
        // FIXME: If a user purchased once with no expiration, this query
        // will not operate correctly
        /*$time = DB_getItem($_TABLES['paypal.purchases'], 
                      'MAX(UNIX_TIMESTAMP(expiration))',
                      "user_id = {$_USER['uid']} AND product_id ='{$A['id']}'");
          */
        $product->set_block('product', 'BtnBlock', 'Btn');
        if (!$P->hasAttributes()) {
            // Buttons only show in the list if there are no options to select
            $buttons = $P->PurchaseLinks();
            foreach ($buttons as $name => $html) {
                $product->set_var('button', $html);
                $product->parse('Btn', 'BtnBlock', true);
            }
        } else {
            if ($_PP_CONF['ena_cart']) {
                // If the product has attributes, then the cart must be
                // enabled to allow purchasing
                $button = $product->parse('', 'btn_details') . '&nbsp;';
                $product->set_var('button', $button);
                $product->parse('Btn', 'BtnBlock', true);
            }
        }
        $display .= $product->parse('', 'product');
        $product->clear_var('Btn');
    }
    // Get products from plugins.
    // For now, this hack shows plugins only on the first page, since
    // they're not included in the page calculation.
    if ($page == 1 && empty($cat_list)) {
        // Get the currency class for formatting prices
        USES_paypal_class_currency();
        $Cur = new ppCurrency($_PP_CONF['currency']);
        $product->clear_var('rating_bar');
        // no ratings for plugins (yet)
        foreach ($_PLUGINS as $pi_name) {
            $status = LGLIB_invokeService($pi_name, 'getproducts', array(), $plugin_data, $svc_msg);
            if ($status != PLG_RET_OK || empty($plugin_data)) {
                continue;
            }
            foreach ($plugin_data as $A) {
                // Reset button values
                $buttons = '';
                $product->set_var(array('id' => $A['id'], 'name' => $A['name'], 'short_description' => $A['short_description'], 'display' => '; display: none', 'small_pic' => '', 'encrypted' => '', 'item_url' => $A['url'], 'track_onhand' => ''));
                if ($A['price'] > 0) {
                    $product->set_var('price', $Cur->Format($A['price']));
                } else {
                    $product->clear_var('price');
                }
                if ($A['price'] > 0 && $_USER['uid'] == 1 && !$_PP_CONF['anon_buy']) {
                    $buttons .= $product->set_var('', 'login_req') . '&nbsp;';
                } elseif ($A['prod_type'] > PP_PROD_PHYSICAL && $A['price'] == 0) {
                    // Free items or items purchases and not expired, download.
                    $buttons .= $product->set_var('', 'download') . '&nbsp;';
                } elseif (is_array($A['buttons'])) {
                    // Buttons for everyone else
                    $product->set_block('product', 'BtnBlock', 'Btn');
                    foreach ($A['buttons'] as $type => $html) {
                        $product->set_var('button', $html);
                        $product->parse('Btn', 'BtnBlock', true);
                    }
                }
                //$product->set_var('buttons', $buttons);
                $display .= $product->parse('', 'product');
                $product->clear_var('Btn');
            }
            // foreach plugin_data
        }
        // foreach $_PLUGINS
    }
    // if page == 1
    $pagenav_args = empty($pagenav_args) ? '' : '?' . implode('&', $pagenav_args);
    // Display pagination
    if (isset($_PP_CONF['prod_per_page']) && $_PP_CONF['prod_per_page'] > 0 && $count > $_PP_CONF['prod_per_page']) {
        $product->set_var('pagination', COM_printPageNavigation(PAYPAL_URL . '/index.php' . $pagenav_args, $page, ceil($count / $_PP_CONF['prod_per_page'])));
    } else {
        $product->set_var('pagination', '');
    }
    $display .= $product->parse('', 'end');
    return $display;
}
Example #14
0
 /**
  * @param ShopgateCart $cart
  * @return array
  */
 public function checkStock(ShopgateCart $cart)
 {
     $result = array();
     foreach ($cart->getItems() as $item) {
         $cartItem = new ShopgateCartItem();
         $cartItem->setItemNumber($item->getItemNumber());
         list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item);
         /** @var ProductCore $product */
         if (version_compare(_PS_VERSION_, '1.5.2.0', '<')) {
             $product = new BWProduct($productId, true, $this->getPlugin()->getLanguageId());
         } else {
             $product = new Product($productId, $this->getPlugin()->getLanguageId());
         }
         if (empty($attributeId) && !empty($productId) && $product->hasAttributes()) {
             $result[] = $cartItem;
             continue;
         }
         $product->loadStockData();
         /**
          * validate attributes
          */
         if ($product->hasAttributes()) {
             $invalidAttribute = false;
             $message = '';
             if (!$attributeId) {
                 $cartItem->setError(ShopgateLibraryException::UNKNOWN_ERROR_CODE);
                 $cartItem->setErrorText('attributeId required');
                 $message = 'attributeId required';
                 $invalidAttribute = true;
             } else {
                 $validAttributeId = false;
                 if (version_compare(_PS_VERSION_, '1.5.0', '<')) {
                     $attributeIds = BWProduct::getProductAttributesIds($productId);
                 } else {
                     $attributeIds = $product->getProductAttributesIds($productId, true);
                 }
                 foreach ($attributeIds as $attribute) {
                     if ($attributeId == $attribute['id_product_attribute']) {
                         $validAttributeId = true;
                         continue;
                     }
                 }
                 if (!$validAttributeId) {
                     $invalidAttribute = true;
                     $message = 'invalid attributeId';
                 }
             }
             if ($invalidAttribute) {
                 $cartItem->setError(ShopgateLibraryException::UNKNOWN_ERROR_CODE);
                 $cartItem->setErrorText($message);
                 $result[] = $cartItem;
                 continue;
             }
         }
         if ($product->id) {
             if (version_compare(_PS_VERSION_, '1.5.0', '<')) {
                 $quantity = $product->getStockAvailable();
                 //getQuantityAvailableByProduct($productId, $attributeId, $this->getPlugin()->getContext()->shop->id);
             } else {
                 $quantity = StockAvailable::getQuantityAvailableByProduct($productId, $attributeId, $this->getPlugin()->getContext()->shop->id);
             }
             $cartItem->setStockQuantity($quantity);
             $cartItem->setIsBuyable($product->available_for_order && ($attributeId ? Attribute::checkAttributeQty($attributeId, ShopgateItemsCartExportJson::DEFAULT_QTY_TO_CHECK) : $product->checkQty(ShopgateItemsCartExportJson::DEFAULT_QTY_TO_CHECK)) || Product::isAvailableWhenOutOfStock($product->out_of_stock) ? 1 : 0);
         } else {
             $cartItem->setError(ShopgateLibraryException::CART_ITEM_PRODUCT_NOT_FOUND);
             $cartItem->setErrorText(ShopgateLibraryException::getMessageFor($cartItem->getError()));
         }
         $result[] = $cartItem;
     }
     return $result;
 }
Example #15
0
 /**
  * This process add or update a product in the cart
  */
 protected function processChangeProductInCart()
 {
     $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add';
     if ($this->qty == 0) {
         $this->errors[] = Tools::displayError('Null quantity.', !Tools::getValue('ajax'));
     } elseif (!$this->id_product) {
         $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax'));
     }
     $product = new Product($this->id_product, true, $this->context->language->id);
     if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
         $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax'));
         return;
     }
     $qty_to_check = $this->qty;
     $cart_products = $this->context->cart->getProducts();
     if (is_array($cart_products)) {
         foreach ($cart_products as $cart_product) {
             if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) {
                 $qty_to_check = $cart_product['cart_quantity'];
                 if (Tools::getValue('op', 'up') == 'down') {
                     $qty_to_check -= $this->qty;
                 } else {
                     $qty_to_check += $this->qty;
                 }
                 break;
             }
         }
     }
     // Check product quantity availability
     if ($this->id_product_attribute) {
         if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif ($product->hasAttributes()) {
         $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock;
         $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity);
         // @todo do something better than a redirect admin !!
         if (!$this->id_product_attribute) {
             Tools::redirectAdmin($this->context->link->getProductLink($product));
         } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif (!$product->checkQty($qty_to_check)) {
         $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
     }
     // If no errors, process product addition
     if (!$this->errors && $mode == 'add') {
         // Add cart if no cart found
         if (!$this->context->cart->id) {
             if (Context::getContext()->cookie->id_guest) {
                 $guest = new Guest(Context::getContext()->cookie->id_guest);
                 $this->context->cart->mobile_theme = $guest->mobile_theme;
             }
             $this->context->cart->add();
             if ($this->context->cart->id) {
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
         }
         // Check customizable fields
         if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) {
             $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax'));
         }
         if (!$this->errors) {
             $cart_rules = $this->context->cart->getCartRules();
             $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
             $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, Tools::getValue('op', 'up'), $this->id_address_delivery);
             if ($update_quantity < 0) {
                 // If product has attribute, minimal quantity is set with minimal quantity of attribute
                 $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity;
                 $this->errors[] = sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity);
             } elseif (!$update_quantity) {
                 $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax'));
             } elseif ((int) Tools::getValue('allow_refresh')) {
                 // If the cart rules has changed, we need to refresh the whole cart
                 $cart_rules2 = $this->context->cart->getCartRules();
                 if (count($cart_rules2) != count($cart_rules)) {
                     $this->ajax_refresh = true;
                 } elseif (count($cart_rules2)) {
                     $rule_list = array();
                     foreach ($cart_rules2 as $rule) {
                         $rule_list[] = $rule['id_cart_rule'];
                     }
                     foreach ($cart_rules as $rule) {
                         if (!in_array($rule['id_cart_rule'], $rule_list)) {
                             $this->ajax_refresh = true;
                             break;
                         }
                     }
                 } else {
                     $available_cart_rules2 = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
                     if (count($available_cart_rules2) != count($available_cart_rules)) {
                         $this->ajax_refresh = true;
                     } elseif (count($available_cart_rules2)) {
                         $rule_list = array();
                         foreach ($available_cart_rules2 as $rule) {
                             $rule_list[] = $rule['id_cart_rule'];
                         }
                         foreach ($cart_rules2 as $rule) {
                             if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                 $this->ajax_refresh = true;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     $removed = CartRule::autoRemoveFromCart();
     CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
    public function hookAdminStatsModules($params)
    {
        global $cookie, $currentIndex;
        $id_category = (int) Tools::getValue('id_category');
        $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
        if (Tools::getValue('export')) {
            if (!Tools::getValue('exportType')) {
                $this->csvExport(array('layers' => 2, 'type' => 'line', 'option' => '42'));
            }
        }
        $this->_html = '<fieldset class="width3"><legend><img src="../modules/' . $this->name . '/logo.gif" /> ' . $this->displayName . '</legend>';
        if ($id_product = (int) Tools::getValue('id_product')) {
            if (Tools::getValue('export')) {
                if (Tools::getValue('exportType') == 1) {
                    $this->csvExport(array('layers' => 2, 'type' => 'line', 'option' => '1-' . $id_product));
                } elseif (Tools::getValue('exportType') == 2) {
                    $this->csvExport(array('type' => 'pie', 'option' => '3-' . $id_product));
                }
            }
            $product = new Product($id_product, false, (int) $cookie->id_lang);
            $totalBought = $this->getTotalBought($product->id);
            $totalSales = $this->getTotalSales($product->id);
            $totalViewed = $this->getTotalViewed($product->id);
            $this->_html .= '<h3>' . $product->name . ' - ' . $this->l('Details') . '</h3>
			<p>' . $this->l('Total bought:') . ' ' . $totalBought . '</p>
			<p>' . $this->l('Sales (-Tx):') . ' ' . Tools::displayprice($totalSales, $currency) . '</p>
			<p>' . $this->l('Total viewed:') . ' ' . $totalViewed . '</p>
			<p>' . $this->l('Conversion rate:') . ' ' . number_format($totalViewed ? $totalBought / $totalViewed : 0, 2) . '</p>
			<center>' . ModuleGraph::engine(array('layers' => 2, 'type' => 'line', 'option' => '1-' . $id_product)) . '</center>
			<br />
			<p><a href="' . $_SERVER['REQUEST_URI'] . '&export=1&exportType=1"><img src="../img/admin/asterisk.gif" />' . $this->l('CSV Export') . '</a></p>';
            if ($hasAttribute = $product->hasAttributes() and $totalBought) {
                $this->_html .= '<h3 class="space">' . $this->l('Attribute sales distribution') . '</h3><center>' . ModuleGraph::engine(array('type' => 'pie', 'option' => '3-' . $id_product)) . '</center><br />
			<p><a href="' . $_SERVER['REQUEST_URI'] . '&export=1&exportType=2"><img src="../img/admin/asterisk.gif" />' . $this->l('CSV Export') . '</a></p><br />';
            }
            if ($totalBought) {
                $sales = $this->getSales($id_product, $cookie->id_lang);
                $this->_html .= '<br class="clear" />
				<h3>' . $this->l('Sales') . '</h3>
				<div style="overflow-y: scroll; height: ' . min(400, (count($sales) + 1) * 32) . 'px;">
				<table class="table" border="0" cellspacing="0" cellspacing="0">
				<thead>
					<tr>
						<th>' . $this->l('Date') . '</th>
						<th>' . $this->l('Order') . '</th>
						<th>' . $this->l('Customer') . '</th>
						' . ($hasAttribute ? '<th>' . $this->l('Attribute') . '</th>' : '') . '
						<th>' . $this->l('Qty') . '</th>
						<th>' . $this->l('Price') . '</th>
					</tr>
				</thead><tbody>';
                $tokenOrder = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
                $tokenCustomer = Tools::getAdminToken('AdminCustomers' . (int) Tab::getIdFromClassName('AdminCustomers') . (int) $cookie->id_employee);
                foreach ($sales as $sale) {
                    $this->_html .= '
					<tr>
						<td>' . Tools::displayDate($sale['date_add'], (int) $cookie->id_lang, false) . '</td>
						<td align="center"><a href="?tab=AdminOrders&id_order=' . $sale['id_order'] . '&vieworder&token=' . $tokenOrder . '">' . (int) $sale['id_order'] . '</a></td>
						<td align="center"><a href="?tab=AdminCustomers&id_customer=' . $sale['id_customer'] . '&viewcustomer&token=' . $tokenCustomer . '">' . (int) $sale['id_customer'] . '</a></td>
						' . ($hasAttribute ? '<td>' . $sale['product_name'] . '</td>' : '') . '
						<td>' . (int) $sale['product_quantity'] . '</td>
						<td>' . Tools::displayprice($sale['total'], $currency) . '</td>
					</tr>';
                }
                $this->_html .= '</tbody></table></div>';
                $crossSelling = $this->getCrossSales($id_product, $cookie->id_lang);
                if (count($crossSelling)) {
                    $this->_html .= '<br class="clear" />
					<h3>' . $this->l('Cross Selling') . '</h3>
					<div style="overflow-y: scroll; height: 200px;">
					<table class="table" border="0" cellspacing="0" cellspacing="0">
					<thead>
						<tr>
							<th>' . $this->l('Product name') . '</th>
							<th>' . $this->l('Quantity sold') . '</th>
							<th>' . $this->l('Average price') . '</th>
						</tr>
					</thead><tbody>';
                    $tokenProducts = Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee);
                    foreach ($crossSelling as $selling) {
                        $this->_html .= '
						<tr>
							<td ><a href="?tab=AdminCatalog&id_product=' . (int) $selling['id_product'] . '&addproduct&token=' . $tokenProducts . '">' . $selling['pname'] . '</a></td>
							<td align="center">' . (int) $selling['pqty'] . '</td>
							<td align="right">' . Tools::displayprice($selling['pprice'], $currency) . '</td>
						</tr>';
                    }
                    $this->_html .= '</tbody></table></div>';
                }
            }
        } else {
            $categories = Category::getCategories((int) $cookie->id_lang, true, false);
            $this->_html .= '
			<label>' . $this->l('Choose a category') . '</label>
			<div class="margin-form">
				<form action="" method="post" id="categoriesForm">
					<select name="id_category" onchange="$(\'#categoriesForm\').submit();">
						<option value="0">' . $this->l('All') . '</option>';
            foreach ($categories as $category) {
                $this->_html .= '<option value="' . $category['id_category'] . '"' . ($id_category == $category['id_category'] ? ' selected="selected"' : '') . '>' . $category['name'] . '</option>';
            }
            $this->_html .= '
					</select>
				</form>
			</div>
			<div class="clear space"></div>
			' . $this->l('Click on a product to access its statistics.') . '
			<div class="clear space"></div>
			<h2>' . $this->l('Products available') . '</h2>
			<div style="overflow-y: scroll; height: 600px;">
			<table class="table" border="0" cellspacing="0" cellspacing="0">
			<thead>
				<tr>
					<th>' . $this->l('Ref.') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Stock') . '</th>
				</tr>
			</thead><tbody>';
            foreach ($this->getProducts($cookie->id_lang) as $product) {
                $this->_html .= '<tr><td>' . $product['reference'] . '</td><td><a href="' . $currentIndex . '&token=' . Tools::getValue('token') . '&module=' . $this->name . '&id_product=' . $product['id_product'] . '">' . $product['name'] . '</a></td><td>' . $product['quantity'] . '</td></tr>';
            }
            $this->_html .= '</tbody></table><br /></div><br />
				<a href="' . $_SERVER['REQUEST_URI'] . '&export=1"><img src="../img/admin/asterisk.gif" />' . $this->l('CSV Export') . '</a><br />';
        }
        $this->_html .= '</fieldset><br />
		<fieldset class="width3"><legend><img src="../img/admin/comment.gif" /> ' . $this->l('Guide') . '</legend>
		<h2>' . $this->l('Number of purchases compared to number of viewings') . '</h2>
			<p>
				' . $this->l('After choosing a category and selecting a product, informational graphs will appear. Then, you will be able to analyze them.') . '
				<ul>
					<li class="bullet">' . $this->l('If you notice that a product is successful and often purchased, but viewed infrequently, you should put it more prominently on your webshop front-office.') . '</li>
					<li class="bullet">' . $this->l('On the other hand, if a product has many viewings but is not often purchased, we advise you to check or modify this product\'s information, description and photography again.') . '
					</li>
				</ul>
			</p>
		</fieldset>';
        return $this->_html;
    }
    /**
     * postProcess handle every checks before saving products information
     *
     * @param mixed $token
     * @return void
     */
    public function postProcess($token = null)
    {
        global $cookie, $currentIndex;
        // Add a new product
        if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) {
            if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')) {
                $this->submitAddproduct($token);
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        }
        /* Delete a product in the download folder */
        if (Tools::getValue('deleteVirtualProduct')) {
            if ($this->tabAccess['delete'] === '1') {
                $this->deleteVirtualProduct();
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('submitAddAttachments')) {
            if ($this->tabAccess['add'] === '1') {
                $languages = Language::getLanguages(false);
                $is_attachment_name_valid = false;
                foreach ($languages as $language) {
                    $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']);
                    if (strlen($attachment_name_lang) > 0) {
                        $is_attachment_name_valid = true;
                    }
                    if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) {
                        $this->_errors[] = Tools::displayError('Invalid Name');
                    } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) {
                        $this->_errors[] = Tools::displayError('Name is too long');
                    }
                    if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) {
                        $this->_errors[] = Tools::displayError('Invalid description');
                    }
                }
                if (!$is_attachment_name_valid) {
                    $this->_errors[] = Tools::displayError('Attachment Name Required');
                }
                if (empty($this->_errors)) {
                    if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) {
                        if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) {
                            $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb');
                        } else {
                            do {
                                $uniqid = sha1(microtime());
                            } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid));
                            if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) {
                                $this->_errors[] = $this->l('File copy failed');
                            }
                            @unlink($_FILES['attachment_file']['tmp_name']);
                        }
                    } elseif ((int) $_FILES['attachment_file']['error'] === 1) {
                        $max_upload = (int) ini_get('upload_max_filesize');
                        $max_post = (int) ini_get('post_max_size');
                        $upload_mb = min($max_upload, $max_post);
                        $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>';
                    }
                    if (empty($this->_errors) && isset($uniqid)) {
                        $attachment = new Attachment();
                        foreach ($languages as $language) {
                            if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) {
                                $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]);
                            }
                            if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) {
                                $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]);
                            }
                        }
                        $attachment->file = $uniqid;
                        $attachment->mime = $_FILES['attachment_file']['type'];
                        $attachment->file_name = pSQL($_FILES['attachment_file']['name']);
                        if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 128) {
                            $this->_errors[] = Tools::displayError('Invalid file extension');
                        }
                        if (!Validate::isGenericName($attachment->file_name)) {
                            $this->_errors[] = Tools::displayError('Invalid file name');
                        }
                        if (Tools::strlen($attachment->file_name) > 128) {
                            $this->_errors[] = Tools::displayError('File name too long');
                        }
                        if (!sizeof($this->_errors)) {
                            $attachment->add();
                            Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token));
                        } else {
                            $this->_errors[] = Tools::displayError('Invalid file');
                        }
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('submitAttachments')) {
            if ($this->tabAccess['edit'] === '1') {
                if ($id = (int) Tools::getValue($this->identifier)) {
                    if (Attachment::attachToProduct($id, $_POST['attachments'])) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token));
                    }
                }
            }
        } elseif (isset($_GET['duplicate' . $this->table])) {
            if ($this->tabAccess['add'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    $id_product_old = $product->id;
                    unset($product->id);
                    unset($product->id_product);
                    $product->indexed = 0;
                    $product->active = 0;
                    if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) {
                        if ($product->hasAttributes()) {
                            Product::updateDefaultAttribute($product->id);
                        }
                        if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) {
                            $this->_errors[] = Tools::displayError('An error occurred while copying images.');
                        } else {
                            Hook::addProduct($product);
                            Search::indexation(false, $product->id);
                            Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token));
                        }
                    } else {
                        $this->_errors[] = Tools::displayError('An error occurred while creating object.');
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($object = $this->loadObject())) {
                    if ($object->toggleStatus()) {
                        Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token);
                    } else {
                        $this->_errors[] = Tools::displayError('An error occurred while updating status.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (isset($_GET['delete' . $this->table])) {
            if ($this->tabAccess['delete'] === '1') {
                if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) {
                    // check if request at least one object with noZeroObject
                    if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) {
                        $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                    } else {
                        $id_category = Tools::getValue('id_category');
                        $category_url = empty($id_category) ? '' : '&id_category=' . $id_category;
                        if ($this->deleted) {
                            $object->deleteImages();
                            $object->deleted = 1;
                            if ($object->update()) {
                                Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url);
                            }
                        } elseif ($object->delete()) {
                            Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url);
                        }
                        $this->_errors[] = Tools::displayError('An error occurred during deletion.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::getValue('submitDel' . $this->table)) {
            if ($this->tabAccess['delete'] === '1') {
                if (isset($_POST[$this->table . 'Box'])) {
                    $object = new $this->className();
                    if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) {
                        $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                    } else {
                        $result = true;
                        if ($this->deleted) {
                            foreach (Tools::getValue($this->table . 'Box') as $id) {
                                $toDelete = new $this->className($id);
                                $toDelete->deleted = 1;
                                $result = $result and $toDelete->update();
                            }
                        } else {
                            $result = $object->deleteSelection(Tools::getValue($this->table . 'Box'));
                        }
                        if ($result) {
                            $id_category = Tools::getValue('id_category');
                            $category_url = empty($id_category) ? '' : '&id_category=' . $id_category;
                            Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url);
                        }
                        $this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('You must select at least one element to delete.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) {
            /* PrestaShop demo mode */
            if (_PS_MODE_DEMO_) {
                $this->_errors[] = Tools::displayError('This functionnality has been disabled.');
                return;
            }
            /* PrestaShop demo mode*/
            if ($this->tabAccess['edit'] === '1') {
                /* Delete product image */
                if (isset($_GET['deleteImage'])) {
                    $image->delete();
                    if (!Image::getCover($image->id_product)) {
                        $first_img = Db::getInstance()->getRow('
						SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image`
						WHERE `id_product` = ' . (int) $image->id_product);
                        Db::getInstance()->Execute('
						UPDATE `' . _DB_PREFIX_ . 'image`
						SET `cover` = 1
						WHERE `id_image` = ' . (int) $first_img['id_image']);
                    }
                    @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg');
                    @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg');
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token));
                } elseif (isset($_GET['editImage'])) {
                    if ($image->cover) {
                        $_POST['cover'] = 1;
                    }
                    $languages = Language::getLanguages(false);
                    foreach ($languages as $language) {
                        if (isset($image->legend[$language['id_lang']])) {
                            $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']];
                        }
                    }
                    $_POST['id_image'] = $image->id;
                    $this->displayForm();
                } elseif (isset($_GET['coverImage'])) {
                    Image::deleteCover($image->id_product);
                    $image->cover = 1;
                    if (!$image->update()) {
                        $this->_errors[] = Tools::displayError('Cannot change the product cover');
                    } else {
                        $productId = (int) Tools::getValue('id_product');
                        @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg');
                        @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg');
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token));
                    }
                } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) {
                    $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection'));
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token));
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitProductAttribute')) {
            if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) {
                    $this->_errors[] = Tools::displayError('Attribute price required.');
                }
                if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) {
                    $this->_errors[] = Tools::displayError('You must add at least one attribute.');
                }
                if (!sizeof($this->_errors)) {
                    if (!isset($_POST['attribute_wholesale_price'])) {
                        $_POST['attribute_wholesale_price'] = 0;
                    }
                    if (!isset($_POST['attribute_price_impact'])) {
                        $_POST['attribute_price_impact'] = 0;
                    }
                    if (!isset($_POST['attribute_weight_impact'])) {
                        $_POST['attribute_weight_impact'] = 0;
                    }
                    if (!isset($_POST['attribute_ecotax'])) {
                        $_POST['attribute_ecotax'] = 0;
                    }
                    if (Tools::getValue('attribute_default')) {
                        $product->deleteDefaultAttributes();
                    }
                    // Change existing one
                    if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) {
                        if ($this->tabAccess['edit'] === '1') {
                            if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) {
                                $this->_errors[] = Tools::displayError('This attribute already exists.');
                            } else {
                                $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity'));
                                if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) {
                                    $reason = new StockMvtReason((int) $id_reason);
                                    $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign;
                                    if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) {
                                        $this->_errors[] = Tools::displayError('An error occurred while updating qty.');
                                    }
                                }
                                Hook::updateProductAttribute((int) $id_product_attribute);
                            }
                        } else {
                            $this->_errors[] = Tools::displayError('You do not have permission to add here.');
                        }
                    } else {
                        if ($this->tabAccess['add'] === '1') {
                            if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) {
                                $this->_errors[] = Tools::displayError('This combination already exists.');
                            } else {
                                $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity'));
                            }
                        } else {
                            $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.');
                        }
                    }
                    if (!sizeof($this->_errors)) {
                        $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list'));
                        $product->checkDefaultAttributes();
                    }
                    if (!sizeof($this->_errors)) {
                        if (!$product->cache_default_attribute) {
                            Product::updateDefaultAttribute($product->id);
                        }
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token));
                    }
                }
            }
        } elseif (Tools::isSubmit('deleteProductAttribute')) {
            if ($this->tabAccess['delete'] === '1') {
                if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) {
                    $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute'));
                    $product->checkDefaultAttributes();
                    $product->updateQuantityProductWithAttributeQuantity();
                    if (!$product->hasAttributes()) {
                        $product->cache_default_attribute = 0;
                        $product->update();
                    } else {
                        Product::updateDefaultAttribute($id_product);
                    }
                    Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
                } else {
                    $this->_errors[] = Tools::displayError('Cannot delete attribute');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('deleteAllProductAttributes')) {
            if ($this->tabAccess['delete'] === '1') {
                if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) {
                    $product->deleteProductAttributes();
                    $product->updateQuantityProductWithAttributeQuantity();
                    if ($product->cache_default_attribute) {
                        $product->cache_default_attribute = 0;
                        $product->update();
                    }
                    Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
                } else {
                    $this->_errors[] = Tools::displayError('Cannot delete attributes');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('defaultProductAttribute')) {
            if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                $product->deleteDefaultAttributes();
                $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute'));
                Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
            } else {
                $this->_errors[] = Tools::displayError('Cannot make default attribute');
            }
        } elseif (Tools::isSubmit('submitProductFeature')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    // delete all objects
                    $product->deleteFeatures();
                    // add new objects
                    $languages = Language::getLanguages(false);
                    foreach ($_POST as $key => $val) {
                        if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) {
                            if ($val) {
                                $product->addFeaturesToDB($match[1], $val);
                            } else {
                                if ($default_value = $this->checkFeatures($languages, $match[1])) {
                                    $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']);
                                    foreach ($languages as $language) {
                                        if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) {
                                            $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust);
                                        } else {
                                            $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding features.');
                }
            }
            $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
        } elseif (Tools::isSubmit('submitPricesModification')) {
            $_POST['tabs'] = 5;
            if ($this->tabAccess['edit'] === '1') {
                $id_specific_prices = Tools::getValue('spm_id_specific_price');
                $id_shops = Tools::getValue('spm_id_shop');
                $id_currencies = Tools::getValue('spm_id_currency');
                $id_countries = Tools::getValue('spm_id_country');
                $id_groups = Tools::getValue('spm_id_group');
                $prices = Tools::getValue('spm_price');
                $from_quantities = Tools::getValue('spm_from_quantity');
                $reductions = Tools::getValue('spm_reduction');
                $reduction_types = Tools::getValue('spm_reduction_type');
                $froms = Tools::getValue('spm_from');
                $tos = Tools::getValue('spm_to');
                foreach ($id_specific_prices as $key => $id_specific_price) {
                    if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) {
                        $specificPrice = new SpecificPrice((int) $id_specific_price);
                        $specificPrice->id_shop = (int) $id_shops[$key];
                        $specificPrice->id_currency = (int) $id_currencies[$key];
                        $specificPrice->id_country = (int) $id_countries[$key];
                        $specificPrice->id_group = (int) $id_groups[$key];
                        $specificPrice->price = (double) $prices[$key];
                        $specificPrice->from_quantity = (int) $from_quantities[$key];
                        $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]);
                        $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key];
                        $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key];
                        $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key];
                        if (!$specificPrice->update()) {
                            $this->_errors = Tools::displayError('An error occurred while updating the specific price.');
                        }
                    }
                }
                if (!sizeof($this->_errors)) {
                    Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token));
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('submitPriceAddition')) {
            if ($this->tabAccess['add'] === '1') {
                $id_product = (int) Tools::getValue('id_product');
                $id_shop = Tools::getValue('sp_id_shop');
                $id_currency = Tools::getValue('sp_id_currency');
                $id_country = Tools::getValue('sp_id_country');
                $id_group = Tools::getValue('sp_id_group');
                $price = Tools::getValue('sp_price');
                $from_quantity = Tools::getValue('sp_from_quantity');
                $reduction = (double) Tools::getValue('sp_reduction');
                $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type');
                $from = Tools::getValue('sp_from');
                $to = Tools::getValue('sp_to');
                if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) {
                    $specificPrice = new SpecificPrice();
                    $specificPrice->id_product = $id_product;
                    $specificPrice->id_shop = (int) $id_shop;
                    $specificPrice->id_currency = (int) $id_currency;
                    $specificPrice->id_country = (int) $id_country;
                    $specificPrice->id_group = (int) $id_group;
                    $specificPrice->price = (double) $price;
                    $specificPrice->from_quantity = (int) $from_quantity;
                    $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction);
                    $specificPrice->reduction_type = $reduction_type;
                    $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from;
                    $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to;
                    if (!$specificPrice->add()) {
                        $this->_errors = Tools::displayError('An error occurred while updating the specific price.');
                    } else {
                        Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token));
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('deleteSpecificPrice')) {
            if ($this->tabAccess['delete'] === '1') {
                if (!($obj = $this->loadObject())) {
                    return;
                }
                if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) {
                    $this->_errors[] = Tools::displayError('Invalid specific price ID');
                } else {
                    $specificPrice = new SpecificPrice((int) $id_specific_price);
                    if (!$specificPrice->delete()) {
                        $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price');
                    } else {
                        Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token));
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('submitSpecificPricePriorities')) {
            if (!($obj = $this->loadObject())) {
                return;
            }
            if (!($priorities = Tools::getValue('specificPricePriority'))) {
                $this->_errors[] = Tools::displayError('Please specify priorities');
            } elseif (Tools::isSubmit('specificPricePriorityToAll')) {
                if (!SpecificPrice::setPriorities($priorities)) {
                    $this->_errors[] = Tools::displayError('An error occurred while updating priorities.');
                } else {
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token));
                }
            } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) {
                $this->_errors[] = Tools::displayError('An error occurred while setting priorities.');
            } else {
                Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token));
            }
        } elseif (Tools::isSubmit('submitCustomizationConfiguration')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) {
                        $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.');
                    }
                    if (!sizeof($this->_errors) and !$product->updateLabels()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization.');
                    }
                    $product->uploadable_files = (int) $_POST['uploadable_files'];
                    $product->text_fields = (int) $_POST['text_fields'];
                    $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0;
                    if (!sizeof($this->_errors) and !$product->update()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.');
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitProductCustomization')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    foreach ($_POST as $field => $value) {
                        if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) {
                            $this->_errors[] = Tools::displayError('Label fields are invalid');
                        }
                    }
                    if (!sizeof($this->_errors) and !$product->updateLabels()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization.');
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (isset($_GET['position'])) {
            if ($this->tabAccess['edit'] !== '1') {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            } elseif (!Validate::isLoadedObject($object = $this->loadObject())) {
                $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
            }
            if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
                $this->_errors[] = Tools::displayError('Failed to update the position.');
            } else {
                Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog'));
            }
        } else {
            parent::postProcess(true);
        }
    }
    public function renderForm()
    {
        $back = Tools::safeOutput(Tools::getValue('back', ''));
        if (empty($back)) {
            $back = self::$currentIndex . '&token=' . $this->token;
        }
        $this->toolbar_btn['save-and-stay'] = array('href' => '#', 'desc' => $this->l('Save and Stay'));
        $current_object = $this->loadObject(true);
        // All the filter are prefilled with the correct information
        $customer_filter = '';
        if (Validate::isUnsignedId($current_object->id_customer) && ($customer = new Customer($current_object->id_customer)) && Validate::isLoadedObject($customer)) {
            $customer_filter = $customer->firstname . ' ' . $customer->lastname . ' (' . $customer->email . ')';
        }
        $gift_product_filter = '';
        if (Validate::isUnsignedId($current_object->gift_product) && ($product = new Product($current_object->gift_product, false, $this->context->language->id)) && Validate::isLoadedObject($product)) {
            $gift_product_filter = !empty($product->reference) ? $product->reference : $product->name;
        }
        $reduction_product_filter = '';
        if (Validate::isUnsignedId($current_object->reduction_product) && ($product = new Product($current_object->reduction_product, false, $this->context->language->id)) && Validate::isLoadedObject($product)) {
            $reduction_product_filter = !empty($product->reference) ? $product->reference : $product->name;
        }
        $product_rule_groups = $this->getProductRuleGroupsDisplay($current_object);
        $attribute_groups = AttributeGroup::getAttributesGroups($this->context->language->id);
        $currencies = Currency::getCurrencies();
        $languages = Language::getLanguages();
        $countries = $current_object->getAssociatedRestrictions('country', true, true);
        $groups = $current_object->getAssociatedRestrictions('group', false, true);
        $shops = $current_object->getAssociatedRestrictions('shop', false, false);
        $cart_rules = $current_object->getAssociatedRestrictions('cart_rule', false, true);
        $carriers = $current_object->getAssociatedRestrictions('carrier', true, false);
        foreach ($carriers as &$carriers2) {
            foreach ($carriers2 as &$carrier) {
                foreach ($carrier as $field => &$value) {
                    if ($field == 'name' && $value == '0') {
                        $value = Configuration::get('PS_SHOP_NAME');
                    }
                }
            }
        }
        $gift_product_select = '';
        $gift_product_attribute_select = '';
        if ((int) $current_object->gift_product) {
            $search_products = $this->searchProducts($gift_product_filter);
            foreach ($search_products['products'] as $product) {
                $gift_product_select .= '
				<option value="' . $product['id_product'] . '" ' . ($product['id_product'] == $current_object->gift_product ? 'selected="selected"' : '') . '>
					' . $product['name'] . (count($product['combinations']) == 0 ? ' - ' . $product['formatted_price'] : '') . '
				</option>';
                if (count($product['combinations'])) {
                    $gift_product_attribute_select .= '<select class="id_product_attribute" id="ipa_' . $product['id_product'] . '" name="ipa_' . $product['id_product'] . '">';
                    foreach ($product['combinations'] as $combination) {
                        $gift_product_attribute_select .= '
						<option ' . ($combination['id_product_attribute'] == $current_object->gift_product_attribute ? 'selected="selected"' : '') . ' value="' . $combination['id_product_attribute'] . '">
							' . $combination['attributes'] . ' - ' . $combination['formatted_price'] . '
						</option>';
                    }
                    $gift_product_attribute_select .= '</select>';
                }
            }
        }
        $product = new Product($current_object->gift_product);
        $this->context->smarty->assign(array('show_toolbar' => true, 'toolbar_btn' => $this->toolbar_btn, 'toolbar_scroll' => $this->toolbar_scroll, 'title' => array($this->l('Payment: '), $this->l('Cart Rules')), 'defaultDateFrom' => date('Y-m-d H:00:00'), 'defaultDateTo' => date('Y-m-d H:00:00', strtotime('+1 month')), 'customerFilter' => $customer_filter, 'giftProductFilter' => $gift_product_filter, 'gift_product_select' => $gift_product_select, 'gift_product_attribute_select' => $gift_product_attribute_select, 'reductionProductFilter' => $reduction_product_filter, 'defaultCurrency' => Configuration::get('PS_CURRENCY_DEFAULT'), 'id_lang_default' => Configuration::get('PS_LANG_DEFAULT'), 'languages' => $languages, 'currencies' => $currencies, 'countries' => $countries, 'carriers' => $carriers, 'groups' => $groups, 'shops' => $shops, 'cart_rules' => $cart_rules, 'product_rule_groups' => $product_rule_groups, 'product_rule_groups_counter' => count($product_rule_groups), 'attribute_groups' => $attribute_groups, 'currentIndex' => self::$currentIndex, 'currentToken' => $this->token, 'currentObject' => $current_object, 'currentTab' => $this, 'hasAttribute' => $product->hasAttributes()));
        $this->content .= $this->createTemplate('form.tpl')->fetch();
        $this->addJqueryUI('ui.datepicker');
        return parent::renderForm();
    }
 public function preProcess()
 {
     parent::preProcess();
     $orderTotal = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
     $this->cartDiscounts = self::$cart->getDiscounts();
     foreach ($this->cartDiscounts as $k => $this->cartDiscount) {
         if ($error = self::$cart->checkDiscountValidity(new Discount((int) $this->cartDiscount['id_discount']), $this->cartDiscounts, $orderTotal, self::$cart->getProducts())) {
             self::$cart->deleteDiscount((int) $this->cartDiscount['id_discount']);
         }
     }
     $add = Tools::getIsset('add') ? 1 : 0;
     $delete = Tools::getIsset('delete') ? 1 : 0;
     if (Configuration::get('PS_TOKEN_ENABLE') == 1 && strcasecmp(Tools::getToken(false), strval(Tools::getValue('token'))) && self::$cookie->isLogged() === true) {
         $this->errors[] = Tools::displayError('Invalid token');
     }
     // Update the cart ONLY if $this->cookies are available, in order to avoid ghost carts created by bots
     if (($add or Tools::getIsset('update') or $delete) and isset(self::$cookie->date_add)) {
         //get the values
         $idProduct = (int) Tools::getValue('id_product', NULL);
         $idProductAttribute = (int) Tools::getValue('id_product_attribute', Tools::getValue('ipa'));
         $customizationId = (int) Tools::getValue('id_customization', 0);
         $qty = (int) abs(Tools::getValue('qty', 1));
         if ($qty == 0) {
             $this->errors[] = Tools::displayError('Null quantity');
         } elseif (!$idProduct) {
             $this->errors[] = Tools::displayError('Product not found');
         } else {
             $producToAdd = new Product((int) $idProduct, true, (int) self::$cookie->id_lang);
             if ((!$producToAdd->id or !$producToAdd->active) and !$delete) {
                 if (Tools::getValue('ajax') == 'true') {
                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('Pproduct is no longer available.', false) . '"]}');
                 } else {
                     $this->errors[] = Tools::displayError('Pproduct is no longer available.', false);
                 }
             } else {
                 /* Check the quantity availability */
                 if ($idProductAttribute and is_numeric($idProductAttribute)) {
                     if (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) {
                         if (Tools::getValue('ajax') == 'true') {
                             die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}');
                         } else {
                             $this->errors[] = Tools::displayError('There is not enough product in stock.');
                         }
                     }
                 } elseif ($producToAdd->hasAttributes() and !$delete) {
                     $idProductAttribute = Product::getDefaultAttribute((int) $producToAdd->id, (int) $producToAdd->out_of_stock == 2 ? !(int) Configuration::get('PS_ORDER_OUT_OF_STOCK') : !(int) $producToAdd->out_of_stock);
                     if (!$idProductAttribute) {
                         Tools::redirectAdmin($link->getProductLink($producToAdd));
                     } elseif (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) {
                         if (Tools::getValue('ajax') == 'true') {
                             die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}');
                         } else {
                             $this->errors[] = Tools::displayError('There is not enough product in stock.');
                         }
                     }
                 } elseif (!$delete and !$producToAdd->checkQty((int) $qty)) {
                     if (Tools::getValue('ajax') == 'true') {
                         die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.') . '"]}');
                     } else {
                         $this->errors[] = Tools::displayError('There is not enough product in stock.');
                     }
                 }
                 /* Check vouchers compatibility */
                 if ($add and ($producToAdd->specificPrice and (double) $producToAdd->specificPrice['reduction'] or $producToAdd->on_sale)) {
                     $discounts = self::$cart->getDiscounts();
                     foreach ($discounts as $discount) {
                         if (!$discount['cumulable_reduction']) {
                             $this->errors[] = Tools::displayError('Cannot add this product because current voucher does not allow additional discounts.');
                         }
                     }
                 }
                 if (!sizeof($this->errors)) {
                     if ($add and $qty >= 0) {
                         /* Product addition to the cart */
                         if (!isset(self::$cart->id) or !self::$cart->id) {
                             self::$cart->add();
                             if (self::$cart->id) {
                                 self::$cookie->id_cart = (int) self::$cart->id;
                             }
                         }
                         if ($add and !$producToAdd->hasAllRequiredCustomizableFields() and !$customizationId) {
                             $this->errors[] = Tools::displayError('Please fill in all required fields, then save the customization.');
                         }
                         if (!sizeof($this->errors)) {
                             $updateQuantity = self::$cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, $customizationId, Tools::getValue('op', 'up'));
                             if ($updateQuantity < 0) {
                                 /* if product has attribute, minimal quantity is set with minimal quantity of attribute*/
                                 if ((int) $idProductAttribute) {
                                     $minimal_quantity = Attribute::getAttributeMinimalQty((int) $idProductAttribute);
                                 } else {
                                     $minimal_quantity = $producToAdd->minimal_quantity;
                                 }
                                 if (Tools::getValue('ajax') == 'true') {
                                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('You must add', false) . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity', false) . '"]}');
                                 } else {
                                     $this->errors[] = Tools::displayError('You must add') . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : '');
                                 }
                             } elseif (!$updateQuantity) {
                                 if (Tools::getValue('ajax') == 'true') {
                                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('You already have the maximum quantity available for this product.', false) . '"]}');
                                 } else {
                                     $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : '');
                                 }
                             }
                         }
                     } elseif ($delete) {
                         if (self::$cart->deleteProduct((int) $idProduct, (int) $idProductAttribute, (int) $customizationId)) {
                             if (!Cart::getNbProducts((int) self::$cart->id)) {
                                 self::$cart->id_carrier = 0;
                                 self::$cart->gift = 0;
                                 self::$cart->gift_message = '';
                                 self::$cart->update();
                             }
                         }
                     }
                 }
                 $discounts = self::$cart->getDiscounts();
                 foreach ($discounts as $discount) {
                     $discountObj = new Discount((int) $discount['id_discount'], (int) self::$cookie->id_lang);
                     if ($error = self::$cart->checkDiscountValidity($discountObj, $discounts, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), self::$cart->getProducts())) {
                         self::$cart->deleteDiscount((int) $discount['id_discount']);
                         self::$cart->update();
                         $errors[] = $error;
                     }
                 }
                 if (!sizeof($this->errors)) {
                     $queryString = Tools::safeOutput(Tools::getValue('query', NULL));
                     if ($queryString and !Configuration::get('PS_CART_REDIRECT')) {
                         Tools::redirect('search.php?search=' . $queryString);
                     }
                     if (isset($_SERVER['HTTP_REFERER'])) {
                         // Redirect to previous page
                         preg_match('!http(s?)://(.*)/(.*)!', $_SERVER['HTTP_REFERER'], $regs);
                         if (isset($regs[3]) and !Configuration::get('PS_CART_REDIRECT') and Tools::getValue('ajax') != 'true') {
                             Tools::redirect($regs[3]);
                         }
                     }
                 }
             }
             if (Tools::getValue('ajax') != 'true' and !sizeof($this->errors)) {
                 Tools::redirect('order.php?' . (isset($idProduct) ? 'ipa=' . (int) $idProduct : ''));
             }
         }
     }
 }