public function processGenerate()
 {
     if (!is_array(Tools::getValue('options'))) {
         $this->errors[] = Tools::displayError('Please select at least one attribute.');
     } else {
         $tab = array_values(Tools::getValue('options'));
         if (count($tab) && Validate::isLoadedObject($this->product)) {
             AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab);
             $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab));
             $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations));
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 foreach ($attributes as $attribute) {
                     StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop);
                 }
             }
             SpecificPriceRule::disableAnyApplication();
             $this->product->deleteProductAttributes();
             $this->product->generateMultipleCombinations($values, $this->combinations);
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 $quantity = str_replace(',', '.', Tools::getValue('quantity'));
                 foreach ($attributes as $attribute) {
                     StockAvailable::setQuantity($this->product->id, $attribute['id_product_attribute'], $quantity);
                 }
             } else {
                 StockAvailable::synchronize($this->product->id);
             }
             SpecificPriceRule::enableAnyApplication();
             SpecificPriceRule::applyAllRules(array((int) $this->product->id));
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4');
         } else {
             $this->errors[] = Tools::displayError('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.');
         }
     }
 }
Example #2
0
 /**
  * For a given id_product, synchronizes StockAvailable::quantity with Stock::usable_quantity
  *
  * @param int $id_product
  */
 public static function synchronize($id_product, $order_id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     // gets warehouse ids grouped by shops
     $ids_warehouse = Warehouse::getWarehousesGroupedByShops();
     if ($order_id_shop !== null) {
         $order_warehouses = array();
         $wh = Warehouse::getWarehouses(false, (int) $order_id_shop);
         foreach ($wh as $warehouse) {
             $order_warehouses[] = $warehouse['id_warehouse'];
         }
     }
     // gets all product attributes ids
     $ids_product_attribute = array();
     foreach (Product::getProductAttributesIds($id_product) as $id_product_attribute) {
         $ids_product_attribute[] = $id_product_attribute['id_product_attribute'];
     }
     // Allow to order the product when out of stock?
     $out_of_stock = StockAvailable::outOfStock($id_product);
     $manager = StockManagerFactory::getManager();
     // loops on $ids_warehouse to synchronize quantities
     foreach ($ids_warehouse as $id_shop => $warehouses) {
         // first, checks if the product depends on stock for the given shop $id_shop
         if (StockAvailable::dependsOnStock($id_product, $id_shop)) {
             // init quantity
             $product_quantity = 0;
             // if it's a simple product
             if (empty($ids_product_attribute)) {
                 $allowed_warehouse_for_product = WareHouse::getProductWarehouseList((int) $id_product, 0, (int) $id_shop);
                 $allowed_warehouse_for_product_clean = array();
                 foreach ($allowed_warehouse_for_product as $warehouse) {
                     $allowed_warehouse_for_product_clean[] = (int) $warehouse['id_warehouse'];
                 }
                 $allowed_warehouse_for_product_clean = array_intersect($allowed_warehouse_for_product_clean, $warehouses);
                 if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_product_clean, $order_warehouses))) {
                     continue;
                 }
                 $product_quantity = $manager->getProductRealQuantities($id_product, null, $allowed_warehouse_for_product_clean, true);
             } else {
                 foreach ($ids_product_attribute as $id_product_attribute) {
                     $allowed_warehouse_for_combination = WareHouse::getProductWarehouseList((int) $id_product, (int) $id_product_attribute, (int) $id_shop);
                     $allowed_warehouse_for_combination_clean = array();
                     foreach ($allowed_warehouse_for_combination as $warehouse) {
                         $allowed_warehouse_for_combination_clean[] = (int) $warehouse['id_warehouse'];
                     }
                     $allowed_warehouse_for_combination_clean = array_intersect($allowed_warehouse_for_combination_clean, $warehouses);
                     if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_combination_clean, $order_warehouses))) {
                         continue;
                     }
                     $quantity = $manager->getProductRealQuantities($id_product, $id_product_attribute, $allowed_warehouse_for_combination_clean, true);
                     $query = new DbQuery();
                     $query->select('COUNT(*)');
                     $query->from('stock_available');
                     $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                     if ((int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query)) {
                         $query = array('table' => 'stock_available', 'data' => array('quantity' => $quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                         Db::getInstance()->update($query['table'], $query['data'], $query['where']);
                     } else {
                         $query = array('table' => 'stock_available', 'data' => array('quantity' => $quantity, 'depends_on_stock' => 1, 'out_of_stock' => $out_of_stock, 'id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute));
                         StockAvailable::addSqlShopParams($query['data']);
                         Db::getInstance()->insert($query['table'], $query['data']);
                     }
                     $product_quantity += $quantity;
                     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $quantity));
                 }
             }
             // updates
             // if $id_product has attributes, it also updates the sum for all attributes
             $query = array('table' => 'stock_available', 'data' => array('quantity' => $product_quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = 0' . StockAvailable::addSqlShopRestriction(null, $id_shop));
             Db::getInstance()->update($query['table'], $query['data'], $query['where']);
         }
     }
     // In case there are no warehouses, removes product from StockAvailable
     if (count($ids_warehouse) == 0) {
         Db::getInstance()->update('stock_available', array('quantity' => 0), 'id_product = ' . (int) $id_product);
     }
 }
 public function processGenerate()
 {
     if (!is_array(Tools::getValue('options'))) {
         $this->errors[] = $this->trans('Please select at least one attribute.', array(), 'Admin.Catalog.Notification');
     } else {
         $tab = array_values(Tools::getValue('options'));
         if (count($tab) && Validate::isLoadedObject($this->product)) {
             AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab);
             $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab));
             $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations));
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 foreach ($attributes as $attribute) {
                     StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop);
                 }
             }
             SpecificPriceRule::disableAnyApplication();
             $this->product->deleteProductAttributes();
             $this->product->generateMultipleCombinations($values, $this->combinations);
             // Reset cached default attribute for the product and get a new one
             Product::getDefaultAttribute($this->product->id, 0, true);
             Product::updateDefaultAttribute($this->product->id);
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 $quantity = (int) Tools::getValue('quantity');
                 foreach ($attributes as $attribute) {
                     if (Shop::getContext() == Shop::CONTEXT_ALL) {
                         $shops_list = Shop::getShops();
                         if (is_array($shops_list)) {
                             foreach ($shops_list as $current_shop) {
                                 if (isset($current_shop['id_shop']) && (int) $current_shop['id_shop'] > 0) {
                                     StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity, (int) $current_shop['id_shop']);
                                 }
                             }
                         }
                     } else {
                         StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity);
                     }
                 }
             } else {
                 StockAvailable::synchronize($this->product->id);
             }
             SpecificPriceRule::enableAnyApplication();
             SpecificPriceRule::applyAllRules(array((int) $this->product->id));
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4');
         } else {
             $this->errors[] = $this->trans('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.');
         }
     }
 }
Example #4
0
 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']] = StockAvailable::getQuantityAvailableByProduct((int) $obj->id, $attribute['id_product_attribute']);
                 // 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) {
                     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 (!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'), '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 initContentForQuantities()
 {
     if ($this->object->id) {
         $tfowlgstly = "show_quantities";
         ${"GLOBALS"}["ygzeqkb"] = "show_quantities";
         $gmgclvkrjy = "attributes";
         ${"GLOBALS"}["jhngqfjufp"] = "attributes";
         $cggvbxsk = "attributes";
         ${${"GLOBALS"}["jhngqfjufp"]} = $this->object->getAttributesResume($this->context->language->id);
         ${"GLOBALS"}["aofqmvff"] = "attribute";
         ${"GLOBALS"}["vyyogyvfbtx"] = "attributes";
         $nfdcluhk = "attributes";
         $khzorwi = "shop_context";
         if (empty(${$nfdcluhk})) {
             ${$cggvbxsk}[] = array("id_product_attribute" => 0, "attribute_designation" => "");
         }
         ${"GLOBALS"}["klqbahrije"] = "shop_context";
         ${${"GLOBALS"}["ldfuknydnzr"]} = array();
         ${${"GLOBALS"}["ymshseez"]} = array();
         ${"GLOBALS"}["lztnksxrb"] = "group_shop";
         foreach (${${"GLOBALS"}["vyyogyvfbtx"]} as ${${"GLOBALS"}["aofqmvff"]}) {
             $rvrxkz = "product_designation";
             $ycvvjwmxtnm = "attribute";
             $dxuqsu = "available_quantity";
             ${$dxuqsu}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = StockAvailable::getQuantityAvailableByProduct((int) $this->object->id, ${$ycvvjwmxtnm}["id_product_attribute"]);
             ${$rvrxkz}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = rtrim($this->object->name[$this->context->language->id] . " - " . ${${"GLOBALS"}["iixdipeiyldv"]}["attribute_designation"], " - ");
         }
         ${${"GLOBALS"}["ueicxl"]} = true;
         ${$khzorwi} = Shop::getContext();
         ${${"GLOBALS"}["lztnksxrb"]} = $this->context->shop->getGroup();
         $wktpughd = "pack_quantity";
         ${"GLOBALS"}["eukvwdf"] = "advanced_stock_management_warning";
         if (${${"GLOBALS"}["klqbahrije"]} == Shop::CONTEXT_ALL) {
             ${$tfowlgstly} = false;
         } elseif (${${"GLOBALS"}["ohyfjtkcy"]} == Shop::CONTEXT_GROUP) {
             if (!$group_shop->share_stock) {
                 ${${"GLOBALS"}["ueicxl"]} = false;
             }
         } else {
             $eksumjgu = "show_quantities";
             if ($group_shop->share_stock) {
                 ${$eksumjgu} = false;
             }
         }
         self::$smarty->assign("ps_stock_management", Configuration::get("PS_STOCK_MANAGEMENT"));
         self::$smarty->assign("has_attribute", $this->object->hasAttributes());
         if (Combination::isFeatureActive()) {
             self::$smarty->assign("countAttributes", (int) Db::getInstance()->getValue("SELECT COUNT(id_product) FROM " . _DB_PREFIX_ . "product_attribute WHERE id_product = " . (int) $this->object->id));
         }
         ${${"GLOBALS"}["eukvwdf"]} = false;
         if (Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && $this->object->advanced_stock_management) {
             ${"GLOBALS"}["awunkp"] = "p_attributes";
             ${"GLOBALS"}["qxobmbos"] = "warehouses";
             ${"GLOBALS"}["cjtetqei"] = "warehouses";
             $ukjfpwyojlf = "p_attribute";
             ${${"GLOBALS"}["iczelyves"]} = Product::getProductAttributesIds($this->object->id);
             ${"GLOBALS"}["kcjlbgqb"] = "advanced_stock_management_warning";
             ${"GLOBALS"}["dlsnuhn"] = "warehouses";
             ${${"GLOBALS"}["qxobmbos"]} = array();
             ${"GLOBALS"}["ojmjigmfve"] = "p_attributes";
             if (!${${"GLOBALS"}["awunkp"]}) {
                 ${${"GLOBALS"}["mdrvdmghqrtc"]}[] = Warehouse::getProductWarehouseList($this->object->id, 0);
             }
             foreach (${${"GLOBALS"}["ojmjigmfve"]} as ${$ukjfpwyojlf}) {
                 ${"GLOBALS"}["uevlubu"] = "ws";
                 ${"GLOBALS"}["fpbyfow"] = "warehouses";
                 ${"GLOBALS"}["inddsyj"] = "ws";
                 ${${"GLOBALS"}["yrbmurnh"]} = Warehouse::getProductWarehouseList($this->object->id, ${${"GLOBALS"}["bhprusfblhn"]}["id_product_attribute"]);
                 if (${${"GLOBALS"}["uevlubu"]}) {
                     ${${"GLOBALS"}["fpbyfow"]}[] = ${${"GLOBALS"}["inddsyj"]};
                 }
             }
             ${${"GLOBALS"}["dlsnuhn"]} = array_unique(${${"GLOBALS"}["cjtetqei"]});
             if (empty(${${"GLOBALS"}["mdrvdmghqrtc"]})) {
                 ${${"GLOBALS"}["kcjlbgqb"]} = true;
             }
         }
         if (${${"GLOBALS"}["uucoxnutvd"]}) {
             $this->displayWarning($this->getMessage("If you wish to use the advanced stock management, you have to:"));
             $this->displayWarning("- " . $this->getMessage("associate your products with warehouses"));
             $this->displayWarning("- " . $this->getMessage("associate your warehouses with carriers"));
             $this->displayWarning("- " . $this->getMessage("associate your warehouses with the appropriate shops"));
         }
         ${${"GLOBALS"}["qbmqjuoutyh"]} = null;
         if (Pack::isPack($this->object->id)) {
             ${"GLOBALS"}["wdcmwsfvsft"] = "pack_quantity";
             $mdjqucflf = "items";
             ${${"GLOBALS"}["wfbswtei"]} = Pack::getItems((int) $this->object->id, Configuration::get("PS_LANG_DEFAULT"));
             $mhikkwxp = "pack_quantities";
             ${"GLOBALS"}["kamnnzyptd"] = "pack_quantities";
             ${${"GLOBALS"}["kamnnzyptd"]} = array();
             foreach (${$mdjqucflf} as ${${"GLOBALS"}["gpnqjgaosuld"]}) {
                 if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) {
                     $gkwutr = "pack_id_product_attribute";
                     ${${"GLOBALS"}["wkyidmmlbbc"]} = Product::getDefaultAttribute($item->id, 1);
                     ${${"GLOBALS"}["pnfrmcr"]}[] = Product::getQuantity($item->id, ${$gkwutr}) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1);
                 }
             }
             $oissvbm = "pack_quantities";
             ${${"GLOBALS"}["wdcmwsfvsft"]} = ${$oissvbm}[0];
             foreach (${$mhikkwxp} as ${${"GLOBALS"}["kzwkbwmzgtl"]}) {
                 ${"GLOBALS"}["iwrwjuvdmi"] = "value";
                 if (${${"GLOBALS"}["qbmqjuoutyh"]} > ${${"GLOBALS"}["iwrwjuvdmi"]}) {
                     ${${"GLOBALS"}["qbmqjuoutyh"]} = ${${"GLOBALS"}["kzwkbwmzgtl"]};
                 }
             }
             if (!Warehouse::getPackWarehouses((int) $this->object->id)) {
                 $this->displayWarning($this->getMessage("You must have a common warehouse between this pack and its product."));
             }
         }
         ${${"GLOBALS"}["lixyhrpqnh"]} = new Language($this->id_language);
         self::$smarty->assign("iso_code", $lang->iso_code ? $lang->iso_code : "en");
         self::$smarty->assign(array("attributes" => ${$gmgclvkrjy}, "available_quantity" => ${${"GLOBALS"}["ldfuknydnzr"]}, "pack_quantity" => ${$wktpughd}, "stock_management_active" => Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT"), "product_designation" => ${${"GLOBALS"}["ymshseez"]}, "show_quantities" => ${${"GLOBALS"}["ygzeqkb"]}, "order_out_of_stock" => Configuration::get("PS_ORDER_OUT_OF_STOCK")));
     } else {
         $this->displayWarning($this->getMessage("You must save this product before managing quantities."));
     }
 }
 /**
  * @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 #7
0
 public static function synchronize($id_product, $order_id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     if (Pack::isPack($id_product)) {
         if (Validate::isLoadedObject($product = new Product((int) $id_product))) {
             if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                 $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                 foreach ($products_pack as $product_pack) {
                     StockAvailable::synchronize($product_pack->id, $order_id_shop);
                 }
             }
         } else {
             return false;
         }
     }
     $ids_warehouse = Warehouse::getWarehousesGroupedByShops();
     if ($order_id_shop !== null) {
         $order_warehouses = array();
         $wh = Warehouse::getWarehouses(false, (int) $order_id_shop);
         foreach ($wh as $warehouse) {
             $order_warehouses[] = $warehouse['id_warehouse'];
         }
     }
     $ids_product_attribute = array();
     foreach (Product::getProductAttributesIds($id_product) as $id_product_attribute) {
         $ids_product_attribute[] = $id_product_attribute['id_product_attribute'];
     }
     $out_of_stock = StockAvailable::outOfStock($id_product);
     $manager = StockManagerFactory::getManager();
     foreach ($ids_warehouse as $id_shop => $warehouses) {
         if (StockAvailable::dependsOnStock($id_product, $id_shop)) {
             $product_quantity = 0;
             if (empty($ids_product_attribute)) {
                 $allowed_warehouse_for_product = WareHouse::getProductWarehouseList((int) $id_product, 0, (int) $id_shop);
                 $allowed_warehouse_for_product_clean = array();
                 foreach ($allowed_warehouse_for_product as $warehouse) {
                     $allowed_warehouse_for_product_clean[] = (int) $warehouse['id_warehouse'];
                 }
                 $allowed_warehouse_for_product_clean = array_intersect($allowed_warehouse_for_product_clean, $warehouses);
                 if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_product_clean, $order_warehouses))) {
                     continue;
                 }
                 $product_quantity = $manager->getProductRealQuantities($id_product, null, $allowed_warehouse_for_product_clean, true);
                 Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => 0, 'quantity' => $product_quantity));
             } else {
                 foreach ($ids_product_attribute as $id_product_attribute) {
                     $allowed_warehouse_for_combination = WareHouse::getProductWarehouseList((int) $id_product, (int) $id_product_attribute, (int) $id_shop);
                     $allowed_warehouse_for_combination_clean = array();
                     foreach ($allowed_warehouse_for_combination as $warehouse) {
                         $allowed_warehouse_for_combination_clean[] = (int) $warehouse['id_warehouse'];
                     }
                     $allowed_warehouse_for_combination_clean = array_intersect($allowed_warehouse_for_combination_clean, $warehouses);
                     if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_combination_clean, $order_warehouses))) {
                         continue;
                     }
                     $quantity = $manager->getProductRealQuantities($id_product, $id_product_attribute, $allowed_warehouse_for_combination_clean, true);
                     $query = new DbQuery();
                     $query->select('COUNT(*)');
                     $query->from('stock_available');
                     $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                     if ((int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query)) {
                         $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array(), 'quantity', $quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                         Db::getInstance()->update($query['table'], $query['data'], $query['where']);
                     } else {
                         $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array('depends_on_stock' => 1, 'out_of_stock' => $out_of_stock, 'id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute), 'quantity', $quantity));
                         StockAvailable::addSqlShopParams($query['data']);
                         Db::getInstance()->insert($query['table'], $query['data']);
                     }
                     $product_quantity += $quantity;
                     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $quantity));
                 }
             }
             $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array(), 'quantity', $product_quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = 0' . StockAvailable::addSqlShopRestriction(null, $id_shop));
             Db::getInstance()->update($query['table'], $query['data'], $query['where']);
         }
     }
     if (count($ids_warehouse) == 0 && StockAvailable::dependsOnStock((int) $id_product)) {
         Db::getInstance()->update('stock_available', array('quantity' => 0, 'quantity_remainder' => 0), 'id_product = ' . (int) $id_product);
     }
     Cache::clean('StockAvailable::getQuantityAvailableByProduct_' . (int) $id_product . '*');
 }
Example #8
0
 public static function indexation($id_product = false, $update = false)
 {
     $id_lang = Cmsearch::getLangId();
     $convermax = new ConvermaxAPI();
     if (!$id_product) {
         if (!$convermax->batchStart()) {
             return false;
         }
     }
     $start = 0;
     while ($products = Cmsearch::getProductsToIndex($id_lang, $start, 200, $id_product)) {
         $start = $start + 200;
         if (count($products) == 0) {
             break;
         }
         $products_array = array();
         $products_count = count($products);
         for ($i = 0; $i < $products_count; $i++) {
             if ($products[$i]['features']) {
                 foreach ($products[$i]['features'] as $feature) {
                     $f_name = 'f_' . $convermax->sanitize($feature['name']);
                     $products[$i][$f_name][] = $feature['value'];
                 }
                 unset($products[$i]['features']);
             }
             foreach ($products[$i] as $key => $val) {
                 if (is_array($val)) {
                     foreach ($val as $k => $v) {
                         if (is_array($v)) {
                             unset($products[$i][$key]);
                         }
                     }
                 }
             }
             $img_id = Product::getCover($products[$i]['id_product']);
             $link = new Link();
             $img_link = $link->getImageLink($products[$i]['link_rewrite'], $img_id['id_image'], ImageType::getFormatedName('small'));
             $products[$i]['img_link'] = str_replace(Tools::getHttpHost(), '', $img_link);
             $products[$i]['link'] = str_replace(Tools::getHttpHost(true), '', $products[$i]['link']);
             $cat_full = Product::getProductCategoriesFull($products[$i]['id_product']);
             $category_full = array();
             $home_category = Configuration::get('PS_HOME_CATEGORY');
             foreach ($cat_full as $cat) {
                 $category = new Category($cat['id_category']);
                 $categories = $category->getParentsCategories();
                 $c_full = array();
                 foreach ($categories as $cats) {
                     if ($cats['id_category'] != $home_category) {
                         $c_full[] = $cats['name'];
                     }
                 }
                 if (!empty($c_full)) {
                     $category_full[] = implode('>', array_reverse($c_full));
                 }
             }
             $products[$i]['category_full'] = $category_full;
             $products[$i]['ean13'] = array($products[$i]['ean13']);
             $products[$i]['upc'] = array($products[$i]['upc']);
             $products[$i]['reference'] = array($products[$i]['reference']);
             $products[$i]['supplier_reference'] = array($products[$i]['supplier_reference']);
             $product = new Product($products[$i]['id_product']);
             $combinations = Product::getProductAttributesIds($products[$i]['id_product']);
             $attribs = array();
             $ean13 = array();
             $upc = array();
             $reference = array();
             $supplier_reference = array();
             foreach ($combinations as $combination) {
                 $comb = $product->getAttributeCombinationsById($combination['id_product_attribute'], $id_lang);
                 foreach ($comb as $com) {
                     $a_name = 'a_' . $convermax->sanitize($com['group_name']);
                     if ($com['is_color_group'] == 1) {
                         $attribs[$a_name][] = $com['id_attribute'];
                     } else {
                         $attribs[$a_name][] = $com['attribute_name'];
                     }
                     if (!empty($com['ean13'])) {
                         $ean13[] = $com['ean13'];
                     }
                     if (!empty($com['upc'])) {
                         $upc[] = $com['upc'];
                     }
                     if (!empty($com['reference'])) {
                         $reference[] = $com['reference'];
                     }
                     if (!empty($com['supplier_reference'])) {
                         $supplier_reference[] = $com['supplier_reference'];
                     }
                 }
             }
             foreach ($attribs as $k => $v) {
                 $products[$i][$k] = array_values(array_unique($v));
             }
             if (!empty($ean13)) {
                 $products[$i]['ean13'] = array_merge((array) $products[$i]['ean13'], array_unique($ean13));
             }
             if (!empty($upc)) {
                 $products[$i]['upc'] = array_merge((array) $products[$i]['upc'], array_unique($upc));
             }
             if (!empty($reference)) {
                 $products[$i]['reference'] = array_merge((array) $products[$i]['reference'], array_unique($reference));
             }
             if (!empty($supplier_reference)) {
                 $products[$i]['supplier_reference'] = array_merge((array) $products[$i]['supplier_reference'], array_unique($supplier_reference));
             }
             if (!in_array($products[$i]['id_product'], $products_array)) {
                 $products_array[] = (int) $products[$i]['id_product'];
             }
         }
         if ($update) {
             if (!$convermax->update($products)) {
                 return false;
             }
         } elseif ($id_product) {
             if (!$convermax->add($products)) {
                 return false;
             }
         } elseif (!$convermax->batchAdd($products)) {
             return false;
         }
         if ($id_product) {
             break;
         }
     }
     if (!$id_product) {
         if (!$convermax->batchEnd()) {
             return false;
         }
     }
     return true;
 }
 public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
 {
     if (Tools::isSubmit('csv') && (int) Tools::getValue('id_warehouse') != -1) {
         $limit = false;
     }
     $stckmgtfr = ERP_STCKMGTFR;
     if ($this->controller_status == STATUS1) {
         $limit = $stckmgtfr;
         $this->informations[] = sprintf($this->l('You are using the free version of 1-Click ERP which limits document editing to %d products'), $limit);
     }
     $order_by_valuation = false;
     $order_by_real_quantity = false;
     if ($this->context->cookie->{$this->table . 'Orderby'} == 'valuation') {
         unset($this->context->cookie->{$this->table . 'Orderby'});
         $order_by_valuation = true;
     } else {
         if ($this->context->cookie->{$this->table . 'Orderby'} == 'real_quantity') {
             echo '$order_by_real_quantity';
             unset($this->context->cookie->{$this->table . 'Orderby'});
             $order_by_real_quantity = true;
         } else {
             if (Tools::isSubmit('configurationOrderby') && Tools::getValue('configurationOrderby') == 'real_quantity') {
                 unset($this->context->cookie->{$this->table . 'Orderby'});
                 $order_by_real_quantity = true;
             }
         }
     }
     parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
     // Add columns only for the product in stock list
     if (isset($this->_list[0]['id_product'])) {
         $nb_items = count($this->_list);
         for ($i = 0; $i < $nb_items; ++$i) {
             $item =& $this->_list[$i];
             $item[$this->identifier] = $item['id_product'];
             // gets stock manager
             $manager = StockManagerFactory::getManager();
             $id_warehouse = (int) $this->getCurrentCoverageWarehouse();
             // gets quantities and valuation
             $query = new DbQuery();
             $query->select('SUM(physical_quantity) as physical_quantity');
             $query->select('SUM(usable_quantity) as usable_quantity');
             $query->select('SUM(price_te * physical_quantity) as valuation');
             $query->from('stock');
             $query->where('id_product =' . (int) $item['id_product'] . ' AND id_product_attribute = ' . (int) $item['id_product_attribute']);
             // If id = -1, all warehouses
             if ($id_warehouse != -1) {
                 $query->where('id_warehouse = ' . $id_warehouse);
             }
             $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
             $item['physical_quantity'] = $res['physical_quantity'] == '' ? 0 : $res['physical_quantity'];
             $item['usable_quantity'] = $res['usable_quantity'] == '' ? 0 : $res['usable_quantity'];
             // gets real_quantity depending on the warehouse
             $item['real_quantity'] = $manager->getProductRealQuantities($item['id_product'], $item['id_product_attribute'], $this->getCurrentCoverageWarehouse() == -1 ? null : array($this->getCurrentCoverageWarehouse()), true);
             // removes the valuation if the filter corresponds to 'all warehouses'
             if ($this->getCurrentCoverageWarehouse() == -1) {
                 $item['valuation'] = 'N/A';
             } else {
                 $item['valuation'] = $res['valuation'];
             }
         }
         if ($this->getCurrentCoverageWarehouse() != -1 && $order_by_valuation) {
             usort($this->_list, array($this, 'valuationCmp'));
         } else {
             if ($order_by_real_quantity) {
                 usort($this->_list, array($this, 'realQuantityCmp'));
             }
         }
     }
     if (isset($this->_list[0]['id_stock_available'])) {
         $nb_items = count($this->_list);
         for ($i = 0; $i < $nb_items; ++$i) {
             $item =& $this->_list[$i];
             if ((int) $item['id_product_attribute'] == 0) {
                 if (count(Product::getProductAttributesIds((int) $item['id_product'])) > 0) {
                     $item['quantity'] = '--';
                 }
             }
         }
     }
     // Add TTC price column for  stock, stock available & illicotimemachine
     if (isset($this->_list[0]['id_product']) || isset($this->_list[0]['id_stock_available']) || isset($this->_list[0]['id_stock_image_content'])) {
         $nb_items = count($this->_list);
         for ($i = 0; $i < $nb_items; ++$i) {
             $item =& $this->_list[$i];
             $query = new DbQuery();
             $query->select('rate');
             $query->from('tax', 't');
             $query->innerjoin('tax_rule', 'tr', 'tr.id_tax = t.id_tax');
             $query->where('t.id_tax = ' . (int) $item['id_tax_rules_group']);
             $query->where('tr.id_country = ' . (int) $this->context->country->id);
             $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
             // If we are on a product
             if ($item['price_attribute'] == null) {
                 $item['price'] = $item['price_product'];
                 $item['price_ttc'] = $item['price_product'] * ($res['rate'] / 100) + $item['price_product'];
             } else {
                 $item['price'] = $price = $item['price_product'] + $item['price_attribute'];
                 $item['price_ttc'] = $price * ($res['rate'] / 100) + $price;
             }
         }
     }
     // totals
     $this->getTotalPrices();
 }
 public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
 {
     if ($this->controller_status == STATUS1) {
         $limit = ERP_IVTFR;
         $this->informations[] = sprintf($this->l('You are using the free version of 1-Click ERP which limits the display to %d products'), $limit);
     }
     parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
     // Get the render type
     $id_display = $this->getCurrentValue('id_display');
     // Get the current warehouse
     $id_warehouse = $this->getCurrentValue('id_warehouse');
     if ($id_warehouse == '') {
         $id_warehouse = $this->getCookie('id_warehouse');
     }
     // Send number products to template to show/hide div-popup
     $nb_items = count($this->_list);
     $this->tpl_list_vars['nb_items'] = $nb_items;
     for ($i = 0; $i < $nb_items; ++$i) {
         $item =& $this->_list[$i];
         if (!isset($item['product_name']) && isset($item['name'])) {
             $item['product_name'] = $item['name'];
         }
         // set Ids depends of the current render
         if (strrpos($item['id_product'], ';') > 0) {
             $ids = explode(";", $item['id_product']);
             $id_product = $ids[0];
             $id_product_attribute = $ids[1];
         } else {
             $id_product = $item['id_product'];
             $id_product_attribute = 0;
         }
         $query = new DbQuery();
         // Products declensions (if render is mixed, force on an empty array)
         $attributes_ids = $id_display == 1 ? array() : Product::getProductAttributesIds((int) $id_product);
         $item['have_attribute'] = false;
         // add additional column only if we re on a product without declension
         // else they will be shown on declension
         if (count($attributes_ids) == 0) {
             // add quantity noted
             // If advanced stock manager is inactif, only show quantity
             if (!$this->advanced_stock_management) {
                 // get the quantity
                 $query->select('quantity');
                 $query->from('stock_available');
                 $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute);
                 $query->orderBy('id_stock_available DESC');
                 // execute query
                 $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
                 // Add column to array
                 $item['quantity'] = $res['quantity'];
             } else {
                 // get the physical and usable quantity
                 $query->select('physical_quantity');
                 $query->select('usable_quantity');
                 $query->from('stock');
                 $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . ' AND id_warehouse =' . (int) $id_warehouse);
                 // Execute query
                 $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
                 // Add column to array
                 $item['physical_quantity'] = $res['physical_quantity'];
                 $item['usable_quantity'] = $res['usable_quantity'];
                 // the real quantity depends of the warehouse
                 $manager = StockManagerFactory::getManager();
                 $item['real_quantity'] = $manager->getProductRealQuantities($id_product, $id_product_attribute, $this->getCookie('id_warehouse') == -1 ? null : array($this->getCookie('id_warehouse')), true);
                 // add location
                 $location = ErpWarehouseProductLocationClass::getCompleteLocation($id_product, $id_product_attribute, $this->getCookie('id_warehouse') == -1 ? 1 : $this->getCookie('id_warehouse'));
                 $item['location'] = $location;
             }
         } else {
             $item['have_attribute'] = true;
         }
     }
     // display 0: add detail column +-
     if ($id_display == 0) {
         $this->addRowAction('details');
     }
     // display 1 : sort products by location
     /*else
       usort($this->_list, array('AdminInventoryController', 'cmp'));*/
 }