Pereiti prie turinio

Opencart stock auto update (reikia pagalbos)


Rekomenduojami pranešimai

Turiu failiuką, kuris iš tiekėjų atnaujina automatiškai prekių likučius (yra dar dydžiams ar spalvoms, tačiau atskiras failas), tačiau kiek pastebėjau su 1.5.5.1 versija veikia, o su naujasnia 2.0.3.1 nebeveikia, meta klaidą, gal kas galėtų pažiūrėti ir pakoreguoti ? Prašiau kažkada dėl importerio pagalbos, tačiau eilinį kartą nesulaukiau :)) tai gal čia sulauksiu.

 

Klaidą meta šioje eilutėje - jog stock nerastas:

 $stock = $stock + (float)$stock->attributes()['quantity'];

 

Failas cronjob_updateStock.php:

<?php
set_time_limit(0);

class UpdateStock {
   /**
    * Array of dealer given URL's
    *
    * @var array
    */
   private $xmlFiles = array(
       'full' => 'http://www.',
       'light' => 'http://www.',
       'categories' => 'http://www.',
       'sizes' => 'http://www.',
       'producers' => 'http://www.',
       'parameters' => 'http://www.',
       'stocks' => 'http://www.',
       'series' => 'http://www.',
       'warranties' => 'http://www.'
   );

   /**
    * Sizes map when we have size ID we have to convert it to real size used in shop
    *
    * @var array
    */
   private $sizesMap = array();

   /**
    * Counts total updated products (changed stocks).
    *
    * @var int
    */
   private $totalUpdated = 0;

   /**
    * Initial constructor
    *
    * @param DB $db
    * @param Log $log
    */
   public function __construct($db = null, $log = null) {
       $this->db = $db;
       $this->log = $log;
   }

   /**
    * Gets XML file
    *
    * @param string $file
    * @return SimpleXMLElement
    */
   private function getXml($file = 'full') {
       $content = file_get_contents($this->xmlFiles[$file]);
       $xml = simplexml_load_string($content);
       return $xml;
   }

   /**
    * Gets sizes from groups
    *
    * @param $xml
    * @return array
    */
   private function getGroupsWithSizes($xml) {
       $sizes = array();
       foreach ($xml->group as $group) {
           foreach ($group->size as $size) {
               $attributes = $size->attributes();
               foreach ($attributes as $key => $value) {
                   if ($key == 'id') {
                       $id = (string) $value;
                   }
               }
               if (isset($sizes[$id])) {
                   $this->log->write('---- Duplicate on size with ID: '.$id.'. Real size: '.$size->name.'. Now: '.$sizes[$id]);
               }
               if (is_array($size->name)) {
                   $sizes[$id] = (string) $size->name[0];
               } else {
                   $sizes[$id] = (string) $size->name;
               }
           }
       }
       return $sizes;
   }

   /**
    * Gets array of products that we have to update
    *
    * @param $xml
    * @return array
    */
   private function getUpdateProducts($xml) {
       $updateProducts = array();
       foreach ($xml->products->product as $product) {
           foreach ($product->sizes->size as $size) {
               $updateProduct = array();
               $productId = (string)$product->attributes()['code_producer'];
               $stock = 0;
               if (is_array($size->stock)) {
                   foreach ($size->stock as $stock) {
                       $stock = $stock + (float)$stock->attributes()['quantity'];
                   }
               } else {
                   $stock = (float)$size->stock->attributes()['quantity'];
               }
               $updateProduct['code'] = $productId;
               $updateProduct['size'] = (string)$this->sizesMap[(string)$size->attributes()['id']];
               $updateProduct['stock'] = $stock;
               $updateProducts[] = $updateProduct;
           }
       }
       return $updateProducts;
   }

   /**
    * Updates stocks of given products
    *
    * @param $updateProducts
    * @return bool
    */
   private function updateStocks($updateProducts) {
       foreach ($updateProducts as $updateProduct) {
           if ($updateProduct['size'] != 'one size') {
               $sql = "UPDATE " . DB_PREFIX . "product_option_value
                       LEFT JOIN " . DB_PREFIX . "product
                           ON " . DB_PREFIX . "product_option_value.product_id = " . DB_PREFIX . "product.product_id
                       LEFT JOIN " . DB_PREFIX . "option_value_description
                           ON " . DB_PREFIX . "product_option_value.option_value_id = " . DB_PREFIX . "option_value_description.option_value_id
                   SET " . DB_PREFIX . "product_option_value.quantity = '".$this->db->escape($updateProduct['stock'])."'
                   WHERE " . DB_PREFIX . "product.model = '".$this->db->escape($updateProduct['code'])."'
                           AND " . DB_PREFIX . "option_value_description.name = '".$this->db->escape($updateProduct['size'])."'";
           } else {
               $sql = "UPDATE " . DB_PREFIX . "product
                           SET quantity =  '".$this->db->escape($updateProduct['stock'])."'
                           WHERE model='".$this->db->escape($updateProduct['code'])."'";
           }
           $result = $this->db->query($sql);
           if (!$result) {
               $this->log->write('--- Error in SQL query');
               return false;
           }
           $affected = $this->db->countAffected();
           $this->totalUpdated = $this->totalUpdated + $affected;
           $this->log->write('Updated: '.$affected.'. Model: '.$updateProduct['code'].'. Size: '.$updateProduct['size'].'. Stock: '.$updateProduct['stock']);

           if ($updateProduct['size'] == 'one size') {
               continue; // jei vieno dydzio nieko nebedarom toliau.
           }

           if ($affected > 0) {
               $sql = "SELECT DISTINCT " . DB_PREFIX . "product_option_value.product_id FROM " . DB_PREFIX . "product_option_value LEFT JOIN " . DB_PREFIX . "product
                           ON " . DB_PREFIX . "product_option_value.product_id = " . DB_PREFIX . "product.product_id
                       LEFT JOIN " . DB_PREFIX . "option_value_description
                           ON " . DB_PREFIX . "product_option_value.option_value_id = " . DB_PREFIX . "option_value_description.option_value_id
                    WHERE " . DB_PREFIX . "product.model = '".$this->db->escape($updateProduct['code'])."'
                           AND " . DB_PREFIX . "option_value_description.name = '".$this->db->escape($updateProduct['size'])."'";
               $result = $this->db->query($sql);
               foreach ($result->rows as $product) {
                   $this->brainyFilter->addProductProperties($product['product_id']);
               }
           }
       }
       return true;
   }

   /**
    * Does all the dirty work
    *
    * @return bool
    */
   public function process() {
       $this->log->write('-- Stock import started');
       // populate sizes map
       $sizesXml = $this->getXml('sizes');
       if (!$sizesXml) {
           $this->log->write('--- Error with sizes XML');
           return false;
       }
       $this->sizesMap = $this->getGroupsWithSizes($sizesXml);
       if (empty($this->sizesMap)) {
           $this->log->write('--- Empty sizes map returned');
           return false;
       }
       // get and update stocks
       $stocksXml = $this->getXml('full');
       if (!$stocksXml) {
           $this->log->write('--- Error with stocks XML');
           return false;
       }

       $updateProducts = $this->getUpdateProducts($stocksXml);
       if (empty($updateProducts)) {
           $this->log->write('--- Empty updatable products array returned');
           return false;
       }

       if (!$this->updateStocks($updateProducts)) {
           return false;
       }

       $this->log->write('-- Stock import ended successfully. Updated: '.count($updateProducts).'. Affected: '.$this->totalUpdated);
       return true;

   }
}

// Version
define('VERSION', '1.5.5.1');

// Configuration
if (file_exists('config.php')) {
   require_once('config.php');
}

// Install
if (!defined('DIR_APPLICATION')) {
   header('Location: install/index.php');
   exit;
}

// VirtualQMOD
require_once('./vqmod/vqmod.php');
VQMod::bootup();

// VQMODDED Startup
require_once(VQMod::modCheck(DIR_SYSTEM . 'startup.php'));

// Registry
$registry = new Registry();

// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);

// Config
$config = new Config();
$registry->set('config', $config);

// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);

// Log
$log_file = '/import_stock/'.date('Y-m-d_G-i-s').'.txt';
$log = new Log($log_file);
$registry->set('log', $log);

include_once('admin/model/module/brainyfilter.php');
$brainyFilter = new ModelModuleBrainyFilter($registry);


$updateStock = new UpdateStock($db, $log, $brainyFilter);
if (!$updateStock->process()) {
   echo 'Error occured. Check '.$log_file;
} else {
   echo 'Done';
}

function error_handler($errno, $errstr, $errfile, $errline) {
   global $log, $config;

   switch ($errno) {
       case E_NOTICE:
       case E_USER_NOTICE:
           $error = 'Notice';
           break;
       case E_WARNING:
       case E_USER_WARNING:
           $error = 'Warning';
           break;
       case E_ERROR:
       case E_USER_ERROR:
           $error = 'Fatal Error';
           break;
       default:
           $error = 'Unknown';
           break;
   }

   if ($config->get('config_error_display')) {
       echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
   }

   if ($config->get('config_error_log')) {
       $log->write('PHP ' . $error . ':  ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
   }

   return true;
}

// Error Handler
set_error_handler('error_handler');
?>

Nuoroda į pranešimą
Dalintis kituose puslapiuose

Prisijunkite prie diskusijos

Jūs galite rašyti dabar, o registruotis vėliau. Jeigu turite paskyrą, prisijunkite dabar, kad rašytumėte iš savo paskyros.

Svečias
Parašykite atsakymą...

×   Įdėta kaip raiškusis tekstas.   Atkurti formatavimą

  Only 75 emoji are allowed.

×   Nuorodos turinys įdėtas automatiškai.   Rodyti kaip įprastą nuorodą

×   Jūsų anksčiau įrašytas turinys buvo atkurtas.   Išvalyti redaktorių

×   You cannot paste images directly. Upload or insert images from URL.

Įkraunama...
  • Dabar naršo   0 narių

    Nei vienas registruotas narys šiuo metu nežiūri šio puslapio.

  • Prisijunk prie bendruomenės dabar!

    Uždarbis.lt nariai domisi verslo, IT ir asmeninio tobulėjimo temomis, kartu sprendžia problemas, dalinasi žiniomis ir idėjomis, sutinka būsimus verslo partnerius ir dalyvauja gyvuose susitikimuose.

    Užsiregistruok dabar ir galėsi:

    ✔️ Dalyvauti diskusijose;

    ✔️ Kurti naujas temas;

    ✔️ Rašyti atsakymus;

    ✔️ Vertinti kitų žmonių pranešimus;

    ✔️ Susisiekti su bet kuriuo nariu asmeniškai;

    ✔️ Naudotis tamsia dizaino versija;

    ir dar daugiau.

    Registracija trunka ~30 sek. ir yra visiškai nemokama.

  • Naujausios temos

  • Karštos temos

×
×
  • Pasirinkite naujai kuriamo turinio tipą...