samedi 6 juin 2015

Prestashop webservice: update product and combination quantity

In prestashop, you can have products with combinations, in this case, the product quantity will get the combinations quantities sum. This is a function that uses the prestashop webservice to update the product/combination quantity, the difference here between product and combination, with product quantity, you have the product_attribute_id equal to 0 and for combination it's the id_product_attribute (the combination id)

function set_product_quantity($ProductId, $StokId, $AttributeId,$quantity){
 global $webService;
 $xml = $webService -> get(array('url' => PS_SHOP_PATH . '/api/stock_availables?schema=blank'));
 $resources = $xml -> children() -> children();
 $resources->id = $StokId;
 $resources->id_product  = $ProductId;
 $resources->quantity = $quantity;
 $resources->id_shop = 1;
 $resources->depends_on_stock = 0;
 try {
  $opt = array('resource' => 'stock_availables');
  $opt['putXml'] = $xml->asXML();
  $opt['id'] = $StokId ;
  $xml = $webService->edit($opt);
  $monfichier = fopen('log_stock.txt', 'a');
  fputs($monfichier, 'Date: '.date('d m y: hh:mm').PHP_EOL);
  fputs($monfichier, 'Exécution du script de mise à jour de stock'.PHP_EOL);
  fputs($monfichier, 'Quantity updated for product '.$ProductId.' product_attribute_id '. $AttributeId.PHP_EOL);
  echo 'Quantity updated for product '.$ProductId.' product_attribute_id '. $AttributeId.' id shop: '.$resources->id_shop.'
 }catch (PrestaShopWebserviceException $ex) {
  echo "Error con la cantidad  ->Error : ".$ex->getMessage().'
You should declare this includes,
You can find the file PSWebServiceLibrary.php in github And defines this constants
define('DEBUG', true);
define('PS_SHOP_PATH', 'yourShopPath');
define('PS_WS_AUTH_KEY', 'Your_Auth_Key');
You should generate your key in prestashop webservice back office tab To call this function
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
set_product_quantity($ProductId, $StokId, $AttributeId,$quantity);
$AttributeId should be 0 to change product quantity (parent) and combination id to change combination quantity

  Finally this is a function to get combination by product id and ean
function getIdProductAttribute($id_product, $ean){
$sql = 'SELECT `id_product_attribute` FROM `'._DB_PREFIX_.'product_attribute` pa

WHERE ean13 like \''.$ean.'\'  ';

$id_product_attribute = Db::getInstance()->getValue($sql);

$sql_stock = 'SELECT `id_stock_available` FROM `'._DB_PREFIX_.'stock_available` WHERE `id_product`='.$id_product.' and `id_product_attribute`='.$id_product_attribute;
$id_stock = Db::getInstance()->getValue($sql_stock);

return array('id_product_attribute'=>$id_product_attribute,'id_stock'=>$id_stock);
Hope this helps! Any suggestions or questions are welcome :)

0 commentaires :

Enregistrer un commentaire