From dedd9b7b02b1162e38e46633efaaa857189744c7 Mon Sep 17 00:00:00 2001 From: Kamel Khelifa Date: Tue, 20 Aug 2024 17:33:56 +0200 Subject: [PATCH] =?UTF-8?q?Correction=20du=20support=20WPML=20pour=20les?= =?UTF-8?q?=20produits=20traduits=20synchronis=C3=A9s=20via=20les=20croche?= =?UTF-8?q?ts=20WEB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ChangeLog.md | 6 +- VERSION | 2 +- .../eCommercePendingWebHook.class.php | 54 +- class/business/eCommerceSynchro.class.php | 3733 ++++++++--------- class/business/eCommerceUtils.class.php | 218 +- class/data/eCommerceCategory.class.php | 1220 +++--- class/data/eCommerceCommande.class.php | 665 ++- class/data/eCommerceFacture.class.php | 691 ++- class/data/eCommercePaymentGateways.class.php | 314 +- class/data/eCommerceProduct.class.php | 663 ++- class/data/eCommerceRemoteAccess.class.php | 646 +-- ...ommerceRemoteShippingZoneMethods.class.php | 2 +- .../eCommerceRemoteShippingZones.class.php | 2 +- .../data/eCommerceRemoteWarehouses.class.php | 232 +- class/data/eCommerceSite.class.php | 870 ++-- class/data/eCommerceSociete.class.php | 627 ++- class/data/eCommerceSocpeople.class.php | 703 ++-- ...eCommerceRemoteAccessWoocommerce.class.php | 3393 +++++++-------- sql/llx_ecommerce_category.sql | 5 +- sql/llx_ecommerce_product.sql | 1 + sql/update.sql | 4 + 21 files changed, 6879 insertions(+), 7172 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 37b3624..ef040a8 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,5 +1,8 @@ # ChangeLog +## [14.0.9] - 20-08-2024 +- Correction du support WPML pour les produits traduits synchronisés via les crochets WEB + ## [14.0.8] - 14-08-2024 - Correction du nettoyage des id distants en doublons par site - Precision lors d'un message d'erreur lors de la synchro des categories @@ -921,7 +924,8 @@ - Initial version. -[Non Distribué]: https://github.com/OPEN-DSI/ecommerceng_woosync/compare/14.0.8...HEAD +[Non Distribué]: https://github.com/OPEN-DSI/ecommerceng_woosync/compare/14.0.9...HEAD +[14.0.9]: https://github.com/OPEN-DSI/ecommerceng_woosync/commits/14.0.9 [14.0.8]: https://github.com/OPEN-DSI/ecommerceng_woosync/commits/14.0.8 [14.0.7]: https://github.com/OPEN-DSI/ecommerceng_woosync/commits/14.0.7 [14.0.6]: https://github.com/OPEN-DSI/ecommerceng_woosync/commits/14.0.6 diff --git a/VERSION b/VERSION index 979f1e3..a03a651 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -14.0.8 \ No newline at end of file +14.0.9 \ No newline at end of file diff --git a/class/business/eCommercePendingWebHook.class.php b/class/business/eCommercePendingWebHook.class.php index 65992ac..2f85231 100755 --- a/class/business/eCommercePendingWebHook.class.php +++ b/class/business/eCommercePendingWebHook.class.php @@ -36,17 +36,17 @@ class eCommercePendingWebHook public $element = 'ecommercependingwebhook'; /** - * @var DoliDB Database handler. - */ - public $db; - /** - * @var string Error - */ - public $error = ''; - /** - * @var array Errors - */ - public $errors = array(); + * @var DoliDB Database handler. + */ + public $db; + /** + * @var string Error + */ + public $error = ''; + /** + * @var array Errors + */ + public $errors = array(); /** * @var array Warnings */ @@ -131,13 +131,13 @@ class eCommercePendingWebHook const STATUS_WARNING = 3; /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; // List of long language codes for bank record status $this->labelStatus = array( @@ -154,7 +154,7 @@ public function __construct($db) self::STATUS_ERROR => 'ECommerceWebHooksStatusShortError', self::STATUS_WARNING => 'ECommerceWebHooksStatusShortWarning', ); - } + } /** * Check if the data is OK @@ -264,7 +264,7 @@ public function create() * @param int $row_id WebHook line ID * @return int <0 if KO, >0 if OK */ - public function delete($row_id = 0) + public function delete($row_id = 0) { dol_syslog(__METHOD__ . " row_id=$row_id", LOG_DEBUG); @@ -354,7 +354,7 @@ public function setStatusProcessed($row_id) ", datep = '" . $this->db->idate($now) . "'" . ", error_msg = NULL" . " WHERE rowid = " . $row_id . - " AND status IN (" . self::STATUS_ERROR . "," .self::STATUS_NOT_PROCESSED . "," . self::STATUS_WARNING . ")"; + " AND status IN (" . self::STATUS_ERROR . "," . self::STATUS_NOT_PROCESSED . "," . self::STATUS_WARNING . ")"; $this->db->begin(); @@ -519,9 +519,7 @@ public function synchronize($site_id = 0, $webhook_topic = '', $webhook_resource return -2; } } - } - - // Order + } // Order elseif ($webhook_resource == 'order') { if ($webhook_event == 'created' || $webhook_event == 'updated') { $result = $synchro->synchronizeOrderFromData($data); @@ -846,7 +844,7 @@ private function _formatEmail($name, $email) * @param string $sendcontext 'standard', 'emailing', ... * @return int|string <0 if KO, result message if OK */ - public function _sendEmail($subject, $sendto, $from, $body, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $sendtocc="", $sendtobcc="", $deliveryreceipt=0, $msgishtml=1, $errors_to='', $css='', $moreinheader='', $sendcontext='standard') + public function _sendEmail($subject, $sendto, $from, $body, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $sendtocc = "", $sendtobcc = "", $deliveryreceipt = 0, $msgishtml = 1, $errors_to = '', $css = '', $moreinheader = '', $sendcontext = 'standard') { global $langs, $dolibarr_main_url_root; dol_syslog(__METHOD__ . " subject=$subject, sendto=$sendto, from=$from, body=$body, filename_list=".json_encode($filename_list).", mimetype_list=".json_encode($mimetype_list).", mimefilename_list=".json_encode($mimefilename_list).", sendtocc=$sendtocc, sendtobcc=$sendtobcc, deliveryreceipt=$deliveryreceipt, msgishtml=$msgishtml, errors_to=$errors_to, css=$css, moreinheader=$moreinheader, sendcontext=$sendcontext", LOG_DEBUG); @@ -1058,9 +1056,9 @@ public function archive() * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto * @return string Libelle du statut */ - function getLibStatut($mode=0) + function getLibStatut($mode = 0) { - return $this->LibStatut($this->statut,$mode); + return $this->LibStatut($this->statut, $mode); } /** @@ -1070,7 +1068,7 @@ function getLibStatut($mode=0) * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto * @return string Libelle du statut */ - public function LibStatut($statut, $mode=0) + public function LibStatut($statut, $mode = 0) { global $langs; diff --git a/class/business/eCommerceSynchro.class.php b/class/business/eCommerceSynchro.class.php index b2f0b35..ea54ffc 100755 --- a/class/business/eCommerceSynchro.class.php +++ b/class/business/eCommerceSynchro.class.php @@ -47,72 +47,71 @@ require_once(DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'); - class eCommerceSynchro { - public $error; - public $errors=array(); - public $success=array(); + public $error; + public $errors=array(); + public $success=array(); public $warnings=array(); - public $langs; - public $user; + public $langs; + public $user; - //Data access - /** - * @var DoliDB - */ - private $db; - public $eCommerceRemoteAccess; + //Data access + /** + * @var DoliDB + */ + private $db; + public $eCommerceRemoteAccess; - /** - * @var eCommerceSite - */ - private $eCommerceSite; - /** - * @var eCommerceSociete - */ - private $eCommerceSociete; - /** - * @var eCommerceSocpeople - */ - private $eCommerceSocpeople; - /** - * @var eCommerceProduct - */ - private $eCommerceProduct; - /** - * @var eCommerceCategory - */ - private $eCommerceCategory; - /** - * @var eCommerceCategory - */ - private $eCommerceMotherCategory; - /** - * @var eCommerceCommande - */ - private $eCommerceCommande; - /** - * @var eCommerceFacture - */ - private $eCommerceFacture; - //class members + /** + * @var eCommerceSite + */ + private $eCommerceSite; + /** + * @var eCommerceSociete + */ + private $eCommerceSociete; + /** + * @var eCommerceSocpeople + */ + private $eCommerceSocpeople; + /** + * @var eCommerceProduct + */ + private $eCommerceProduct; + /** + * @var eCommerceCategory + */ + private $eCommerceCategory; + /** + * @var eCommerceCategory + */ + private $eCommerceMotherCategory; + /** + * @var eCommerceCommande + */ + private $eCommerceCommande; + /** + * @var eCommerceFacture + */ + private $eCommerceFacture; + //class members public $fromDate; public $toDate; - public $toNb; + public $toNb; - private $societeLastUpdateDate; - private $sopeopleLastUpdateDate; - private $productLastUpdateDate; - private $commandeLastUpdateDate; - private $factureLastUpdateDate; + private $societeLastUpdateDate; + private $sopeopleLastUpdateDate; + private $productLastUpdateDate; + private $commandeLastUpdateDate; + private $factureLastUpdateDate; - private $societeToUpdate; - private $socpeopleToUpdate; - private $productToUpdate; - private $categoryToUpdate; - private $commandeToUpdate; - private $factureToUpdate; + private $societeToUpdate; + private $socpeopleToUpdate; + private $productToUpdate; + private $categoryToUpdate; + private $commandeToUpdate; + private $factureToUpdate; public $cache_categories; public static $default_extra_fields_cached; @@ -122,69 +121,61 @@ class eCommerceSynchro /** - * Constructor - * - * @param Database $db Database handler - * @param eCommerceSite $site Object eCommerceSite - * @param datetime $fromDate Beginning date to synch all data modified before this date + * Constructor + * + * @param Database $db Database handler + * @param eCommerceSite $site Object eCommerceSite + * @param datetime $fromDate Beginning date to synch all data modified before this date * @param datetime $toDate Ending date to synch all data modified before this date (null by default = until now) - * @param int $toNb Max nb of record to count or synch (Used only for synch, not for count for the moment !) - */ - function __construct($db, $site, $fromDate=null, $toDate=null, $toNb=0) - { - global $langs, $user; + * @param int $toNb Max nb of record to count or synch (Used only for synch, not for count for the moment !) + */ + public function __construct($db, $site, $fromDate=null, $toDate=null, $toNb=0) + { + global $langs, $user; - try { - $this->langs = $langs; - $this->user = $user; - $this->db = $db; - $this->eCommerceSite = $site; + try { + $this->langs = $langs; + $this->user = $user; + $this->db = $db; + $this->eCommerceSite = $site; $this->langs->load('ecommerceng@ecommerceng'); - $this->eCommerceRemoteAccess = new eCommerceRemoteAccess($this->db, $this->eCommerceSite); + $this->eCommerceRemoteAccess = new eCommerceRemoteAccess($this->db, $this->eCommerceSite); $this->fromDate = is_numeric($fromDate) ? $fromDate : null; - $this->toDate = is_numeric($toDate) ? $toDate : null; + $this->toDate = is_numeric($toDate) ? $toDate : null; // if (empty($toDate)) $this->toDate = (dol_now() - 10); // Set date to use as last update date (we remove 10 second to be sure we don't have pb with not sync date) // else $this->toDate = $toDate; - } - catch (Exception $e) - { - $this->errors[] = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); - } - } + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); + } + } - /** - * Connect to remote - */ - function connect() - { - dol_syslog("eCommerceSynchro Connect to remote", LOG_DEBUG); + /** + * Connect to remote + */ + function connect() + { + dol_syslog("eCommerceSynchro Connect to remote", LOG_DEBUG); - try - { - if (! $this->eCommerceRemoteAccess->connect()) - { - $this->error = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); - $this->errors[] = $this->error; - $this->errors= array_merge($this->errors, $this->eCommerceRemoteAccess->errors); - dol_syslog("eCommerceSynchro Connect error ".$this->error, LOG_DEBUG); - return -1; - } - else - { - dol_syslog("eCommerceSynchro Connected", LOG_DEBUG); - } + try { + if (!$this->eCommerceRemoteAccess->connect()) { + $this->error = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); + $this->errors[] = $this->error; + $this->errors = array_merge($this->errors, $this->eCommerceRemoteAccess->errors); + dol_syslog("eCommerceSynchro Connect error " . $this->error, LOG_DEBUG); + return -1; + } else { + dol_syslog("eCommerceSynchro Connected", LOG_DEBUG); + } - return 1; - } - catch (Exception $e) - { - $this->errors[] = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); - } + return 1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceConnectErrorCheckUsernamePasswordAndAdress'); + } - return -1; - } + return -1; + } /** * Get default extrafields @@ -201,18 +192,18 @@ public function getDefaultExtraFields($table_element, $site) $extra_fields->fetch_name_optionals_label($table_element); $values = []; - if (is_array($extra_fields->attributes[$table_element]['label'])) { - foreach ($extra_fields->attributes[$table_element]['label'] as $key => $value) { - if (preg_match('/^ecommerceng_/', $key)) continue; - - $value = null; - if (!empty($site->parameters['extra_fields'][$table_element]['activated']['dft'][$key])) { - $value = $site->parameters['extra_fields'][$table_element]['values']['dft'][$key]; - } - if (!isset($value)) $value = $extra_fields->attributes[$table_element]['default'][$key]; - $values['options_' . $key] = $value; - } - } + if (is_array($extra_fields->attributes[$table_element]['label'])) { + foreach ($extra_fields->attributes[$table_element]['label'] as $key => $value) { + if (preg_match('/^ecommerceng_/', $key)) continue; + + $value = null; + if (!empty($site->parameters['extra_fields'][$table_element]['activated']['dft'][$key])) { + $value = $site->parameters['extra_fields'][$table_element]['values']['dft'][$key]; + } + if (!isset($value)) $value = $extra_fields->attributes[$table_element]['default'][$key]; + $values['options_' . $key] = $value; + } + } self::$default_extra_fields_cached[$table_element] = $values; } @@ -220,403 +211,360 @@ public function getDefaultExtraFields($table_element, $site) return self::$default_extra_fields_cached[$table_element]; } - /** - * Getter for toDate - */ - public function getToDate() - { - return $this->toDate; - } - - /** - * Instanciate eCommerceSociete data class access - */ - private function initECommerceSociete() - { - $this->eCommerceSociete = new eCommerceSociete($this->db); - } - - /** - * Instanciate eCommerceSocpeople data class access - */ - private function initECommerceSocpeople() - { - $this->eCommerceSocpeople = new eCommerceSocpeople($this->db); - } + /** + * Getter for toDate + */ + public function getToDate() + { + return $this->toDate; + } - /** - * Instanciate eCommerceProduct data class access - */ - private function initECommerceProduct() - { - $this->eCommerceProduct = new eCommerceProduct($this->db); - } + /** + * Instanciate eCommerceSociete data class access + */ + private function initECommerceSociete() + { + $this->eCommerceSociete = new eCommerceSociete($this->db); + } - /** - * Instanciate eCommerceCategory data class access - */ - private function initECommerceCategory() - { - $this->eCommerceCategory = new eCommerceCategory($this->db); - $this->eCommerceMotherCategory = new eCommerceCategory($this->db); - } + /** + * Instanciate eCommerceSocpeople data class access + */ + private function initECommerceSocpeople() + { + $this->eCommerceSocpeople = new eCommerceSocpeople($this->db); + } - /** - * Instanciate eCommerceCommande data class access - */ - private function initECommerceCommande() - { - $this->eCommerceCommande = new eCommerceCommande($this->db); - } + /** + * Instanciate eCommerceProduct data class access + */ + private function initECommerceProduct() + { + $this->eCommerceProduct = new eCommerceProduct($this->db); + } - /** - * Instanciate eCommerceFacture data class access - */ - private function initECommerceFacture() - { - $this->eCommerceFacture = new eCommerceFacture($this->db); - } + /** + * Instanciate eCommerceCategory data class access + */ + private function initECommerceCategory() + { + $this->eCommerceCategory = new eCommerceCategory($this->db); + $this->eCommerceMotherCategory = new eCommerceCategory($this->db); + } + /** + * Instanciate eCommerceCommande data class access + */ + private function initECommerceCommande() + { + $this->eCommerceCommande = new eCommerceCommande($this->db); + } + /** + * Instanciate eCommerceFacture data class access + */ + private function initECommerceFacture() + { + $this->eCommerceFacture = new eCommerceFacture($this->db); + } - /** - * Get the last date of product update - * - * @param Boolean $force Bool to force update - * @return datetime Datetime - */ - public function getProductLastUpdateDate($force = false) - { + /** + * Get the last date of product update + * + * @param Boolean $force Bool to force update + * @return datetime Datetime + */ + public function getProductLastUpdateDate($force = false) + { global $conf; try { - if (!isset($this->productLastUpdateDate) || $force == true) - { + if (!isset($this->productLastUpdateDate) || $force == true) { // if (!isset($this->eCommerceProduct)) // $this->initECommerceProduct(); // $this->productLastUpdateDate = $this->eCommerceProduct->getLastUpdate($this->eCommerceSite->id); $last_sync_date = 'ECOMMERCE_LAST_SYNC_DATE_PRODUCT_' . $this->eCommerceSite->id; $this->productLastUpdateDate = isset($conf->global->$last_sync_date) ? $conf->global->$last_sync_date : null; } - return $this->productLastUpdateDate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetProductLastUpdateDate'); - } - } + return $this->productLastUpdateDate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetProductLastUpdateDate'); + } + } - /** - * Get the last date of societe update - * - * @param boolean $force Bool to force update - * @return datetime Date time - */ - public function getSocieteLastUpdateDate($force = false) - { - global $conf; - try { - if (!isset($this->societeLastUpdateDate) || $force == true) - { + /** + * Get the last date of societe update + * + * @param boolean $force Bool to force update + * @return datetime Date time + */ + public function getSocieteLastUpdateDate($force = false) + { + global $conf; + try { + if (!isset($this->societeLastUpdateDate) || $force == true) { // if (!isset($this->eCommerceSociete)) // $this->initECommerceSociete(); // Init $this->eCommerceSociete // $this->societeLastUpdateDate = $this->eCommerceSociete->getLastUpdate($this->eCommerceSite->id); $last_sync_date = 'ECOMMERCE_LAST_SYNC_DATE_CUSTOMER_' . $this->eCommerceSite->id; $this->societeLastUpdateDate = isset($conf->global->$last_sync_date) ? $conf->global->$last_sync_date : null; } - return $this->societeLastUpdateDate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetSocieteLastUpdateDate'); - } - } + return $this->societeLastUpdateDate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetSocieteLastUpdateDate'); + } + } - /** - * Get the last date of commande update - * - * @param boolean $force Bool to force update - * @return datetime Date time - */ - public function getCommandeLastUpdateDate($force = false) - { + /** + * Get the last date of commande update + * + * @param boolean $force Bool to force update + * @return datetime Date time + */ + public function getCommandeLastUpdateDate($force = false) + { global $conf; try { - if (!isset($this->commandeLastUpdateDate) || $force == true) - { + if (!isset($this->commandeLastUpdateDate) || $force == true) { // if (!isset($this->eCommerceCommande)) // $this->initECommerceCommande(); // $this->commandeLastUpdateDate = $this->eCommerceCommande->getLastUpdate($this->eCommerceSite->id); $last_sync_date = 'ECOMMERCE_LAST_SYNC_DATE_ORDER_' . $this->eCommerceSite->id; $this->commandeLastUpdateDate = isset($conf->global->$last_sync_date) ? $conf->global->$last_sync_date : null; } - return $this->commandeLastUpdateDate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeLastUpdateDate'); - } - } - - /** - * Get the last date of facture update - * - * @param boolean $force Bool to force update - * @return datetime Date time - */ - public function getFactureLastUpdateDate($force = false) - { - try { - if (!isset($this->eCommerceFactureLastUpdateDate) || $force == true) - { - if (!isset($this->eCommerceFacture)) - $this->initECommerceFacture(); - $this->factureLastUpdateDate = $this->eCommerceFacture->getLastUpdate($this->eCommerceSite->id); - } - return $this->factureLastUpdateDate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetFactureLastUpdateDate'); - } - } - + return $this->commandeLastUpdateDate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeLastUpdateDate'); + } + } + /** + * Get the last date of facture update + * + * @param boolean $force Bool to force update + * @return datetime Date time + */ + public function getFactureLastUpdateDate($force = false) + { + try { + if (!isset($this->eCommerceFactureLastUpdateDate) || $force == true) { + if (!isset($this->eCommerceFacture)) + $this->initECommerceFacture(); + $this->factureLastUpdateDate = $this->eCommerceFacture->getLastUpdate($this->eCommerceSite->id); + } + return $this->factureLastUpdateDate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetFactureLastUpdateDate'); + } + } public function getNbCategoriesInDolibarr() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."categorie WHERE type = 0"; + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "categorie WHERE type = 0"; $sql .= " AND entity IN (" . getEntity('category') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbCategoriesInDolibarrLinkedToE($excludeid = 0) - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_category WHERE type = 0 AND fk_site=".$this->eCommerceSite->id; - $sql.=" AND fk_category <> ".$excludeid; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_category WHERE type = 0 AND fk_site=" . $this->eCommerceSite->id; + $sql .= " AND fk_category <> " . $excludeid; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } - /** - * Rebuilding the category tree as an array - * Return an array of table('id','id_mere',...) trie selon arbre et avec: - * id = id de la categorie - * id_mere = id de la categorie mere - * id_children = tableau des id enfant - * label = nom de la categorie - * fulllabel = nom avec chemin complet de la categorie - * fullpath = chemin complet compose des id - * - * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member'). - * Old mode (0, 1, 2, ...) is deprecated. - * @param int $parent_id Id of parent category (0 for root). - * - * @return array Array of categories. this->cats and this->motherof are set. - */ - public function fetch_categories($type, $parent_id=0) { - if (!isset($this->cache_categories[$type])) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $cat = new Categorie($this->db); - $all_cat = $cat->get_full_arbo($type); - - $parent_id = $parent_id > 0 ? $parent_id : ''; - $cat_arbo = array(); - foreach ($all_cat as $category) { - if (preg_match('/_'.$parent_id.'(_|$)/', $category['fullpath'])) { - $cat_arbo[$category['id']] = $category; - } - } + /** + * Rebuilding the category tree as an array + * Return an array of table('id','id_mere',...) trie selon arbre et avec: + * id = id de la categorie + * id_mere = id de la categorie mere + * id_children = tableau des id enfant + * label = nom de la categorie + * fulllabel = nom avec chemin complet de la categorie + * fullpath = chemin complet compose des id + * + * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member'). + * Old mode (0, 1, 2, ...) is deprecated. + * @param int $parent_id Id of parent category (0 for root). + * + * @return array Array of categories. this->cats and this->motherof are set. + */ + public function fetch_categories($type, $parent_id=0) + { + if (!isset($this->cache_categories[$type])) { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $cat = new Categorie($this->db); + $all_cat = $cat->get_full_arbo($type); - $this->cache_categories[$type] = $cat_arbo; - } - } + $parent_id = $parent_id > 0 ? $parent_id : ''; + $cat_arbo = array(); + foreach ($all_cat as $category) { + if (preg_match('/_' . $parent_id . '(_|$)/', $category['fullpath'])) { + $cat_arbo[$category['id']] = $category; + } + } + + $this->cache_categories[$type] = $cat_arbo; + } + } public function getNbCategoriesInDolibarrNotLinkedToE($excludeid = 0) - { - $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); - $cats_id = array_keys($this->cache_categories['product']); - $nb_cat = count($this->cache_categories['product']) - 1; - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_category" . - " WHERE type = 0 AND fk_site=".$this->eCommerceSite->id." AND fk_category IN (".implode(',', $cats_id).")". - " AND fk_category <> ".$excludeid; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $nb_cat - $obj->nb; - } - else - { - return -1; - } - } + { + $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); + $cats_id = array_keys($this->cache_categories['product']); + $nb_cat = count($this->cache_categories['product']) - 1; + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_category" . + " WHERE type = 0 AND fk_site=" . $this->eCommerceSite->id . " AND fk_category IN (" . implode(',', $cats_id) . ")" . + " AND fk_category <> " . $excludeid; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $nb_cat - $obj->nb; + } else { + return -1; + } + } public function getNbProductInDolibarr() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."product"; + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "product"; $sql .= " WHERE entity IN (" . getEntity('product') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbProductInDolibarrLinkedToE() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_product WHERE fk_site=".$this->eCommerceSite->id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_product WHERE fk_site=" . $this->eCommerceSite->id; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbProductInDolibarrNotLinkedToE() - { - $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); - $cats_id = array_keys($this->cache_categories['product']); - $sql="SELECT COUNT(DISTINCT p.rowid) as nb FROM ".MAIN_DB_PREFIX."product as p" . - " INNER JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product AND cp.fk_categorie IN (".implode(',', $cats_id).")" . - " LEFT JOIN ".MAIN_DB_PREFIX."ecommerce_product as ep ON p.rowid = ep.fk_product AND ep.fk_site=".$this->eCommerceSite->id . - " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as pf ON pf.fk_object = p.rowid" . + { + $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); + $cats_id = array_keys($this->cache_categories['product']); + $sql = "SELECT COUNT(DISTINCT p.rowid) as nb FROM " . MAIN_DB_PREFIX . "product as p" . + " INNER JOIN " . MAIN_DB_PREFIX . "categorie_product as cp ON p.rowid = cp.fk_product AND cp.fk_categorie IN (" . implode(',', $cats_id) . ")" . + " LEFT JOIN " . MAIN_DB_PREFIX . "ecommerce_product as ep ON p.rowid = ep.fk_product AND ep.fk_site=" . $this->eCommerceSite->id . + " LEFT JOIN " . MAIN_DB_PREFIX . "product_extrafields as pf ON pf.fk_object = p.rowid" . " WHERE (ep.rowid IS NULL OR ep.last_update < p.tms OR (pf.tms IS NOT NULL AND ep.last_update < pf.tms))" . " AND p.entity IN (" . getEntity('product') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbSocieteInDolibarr() - { - /*$sql="SELECT COUNT(s.rowid) as nb FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."categorie_societe as cs"; - $sql.=" WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = ".$this->eCommerceSite->fk_cat_societe; + { + /*$sql="SELECT COUNT(s.rowid) as nb FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."categorie_societe as cs"; + $sql.=" WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = ".$this->eCommerceSite->fk_cat_societe; */ - $sql="SELECT COUNT(s.rowid) as nb FROM ".MAIN_DB_PREFIX."societe as s"; + $sql = "SELECT COUNT(s.rowid) as nb FROM " . MAIN_DB_PREFIX . "societe as s"; $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbSocieteInDolibarrLinkedToE() - { - $sql="SELECT COUNT(s.rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_societe as s WHERE fk_site=".$this->eCommerceSite->id; + { + $sql = "SELECT COUNT(s.rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_societe as s WHERE fk_site=" . $this->eCommerceSite->id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbCommandeInDolibarr() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."commande"; + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "commande"; $sql .= " WHERE entity IN (" . getEntity('commande') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbCommandeInDolibarrLinkedToE() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_commande WHERE fk_site=".$this->eCommerceSite->id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_commande WHERE fk_site=" . $this->eCommerceSite->id; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbFactureInDolibarr() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."facture"; + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "facture"; $sql .= " WHERE entity IN (" . getEntity('facture') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } public function getNbFactureInDolibarrLinkedToE() - { - $sql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."ecommerce_facture WHERE fk_site=".$this->eCommerceSite->id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - return $obj->nb; - } - else - { - return -1; - } - } + { + $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "ecommerce_facture WHERE fk_site=" . $this->eCommerceSite->id; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + return $obj->nb; + } else { + return -1; + } + } - /** - * Return list o categories to update - * - * @param boolean $force Force analysis of list, even if array list $this->categoryToUpdate is already defined - */ - public function getCategoriesToUpdate($force = false) + /** + * Return list o categories to update + * + * @param boolean $force Force analysis of list, even if array list $this->categoryToUpdate is already defined + */ + public function getCategoriesToUpdate($force = false) { if (!isset($this->categoryToUpdate) || $force == true) { $this->categoryToUpdate = array(); @@ -673,461 +621,428 @@ public function getCategoriesToUpdate($force = false) return false; } - /** - * Get modified product since the last update - * - * @param int $force Bool to force to reload cache list $this->productToUpdate - * @return array Array of remote product (also stored into this->productToUpdate) - */ - public function getProductToUpdate($force = false) - { - try { - if (!isset($this->productToUpdate) || $force == true) - { - $lastupdatedate = $this->getProductLastUpdateDate($force); - $this->productToUpdate = $this->eCommerceRemoteAccess->getProductToUpdate($lastupdatedate, $this->toDate); - } - if (empty($this->productToUpdate) && (! empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) - { - if (! empty($this->eCommerceRemoteAccess->error)) $this->error=$this->eCommerceRemoteAccess->error; - if (! empty($this->eCommerceRemoteAccess->errors)) $this->errors=array_merge($this->errors, $this->eCommerceRemoteAccess->errors); - return -1; - } - return $this->productToUpdate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetProductToUpdate'); - } - } + /** + * Get modified product since the last update + * + * @param int $force Bool to force to reload cache list $this->productToUpdate + * @return array Array of remote product (also stored into this->productToUpdate) + */ + public function getProductToUpdate($force = false) + { + try { + if (!isset($this->productToUpdate) || $force == true) { + $lastupdatedate = $this->getProductLastUpdateDate($force); + $this->productToUpdate = $this->eCommerceRemoteAccess->getProductToUpdate($lastupdatedate, $this->toDate); + } + if (empty($this->productToUpdate) && (!empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) { + if (!empty($this->eCommerceRemoteAccess->error)) $this->error = $this->eCommerceRemoteAccess->error; + if (!empty($this->eCommerceRemoteAccess->errors)) $this->errors = array_merge($this->errors, $this->eCommerceRemoteAccess->errors); + return -1; + } + return $this->productToUpdate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetProductToUpdate'); + } + } - /** - * Get modified societe since the last update - * - * @param int $force Bool to force to reload cache list $this->societeToUpdate - * @return array Array of remote societe (also stored into this->societeToUpdate) - */ - public function getSocieteToUpdate($force = false) - { - try { - if (!isset($this->societeToUpdate) || $force == true) - { - $lastupdatedate=$this->getSocieteLastUpdateDate($force); - $this->societeToUpdate = $this->eCommerceRemoteAccess->getSocieteToUpdate($lastupdatedate, $this->toDate); - } - if (empty($this->societeToUpdate) && (! empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) - { - if (! empty($this->eCommerceRemoteAccess->error)) $this->error=$this->eCommerceRemoteAccess->error; - if (! empty($this->eCommerceRemoteAccess->errors)) $this->errors=array_merge($this->errors, $this->eCommerceRemoteAccess->errors); - return -1; - } - return $this->societeToUpdate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetSocieteToUpdate'); - } - } + /** + * Get modified societe since the last update + * + * @param int $force Bool to force to reload cache list $this->societeToUpdate + * @return array Array of remote societe (also stored into this->societeToUpdate) + */ + public function getSocieteToUpdate($force = false) + { + try { + if (!isset($this->societeToUpdate) || $force == true) { + $lastupdatedate = $this->getSocieteLastUpdateDate($force); + $this->societeToUpdate = $this->eCommerceRemoteAccess->getSocieteToUpdate($lastupdatedate, $this->toDate); + } + if (empty($this->societeToUpdate) && (!empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) { + if (!empty($this->eCommerceRemoteAccess->error)) $this->error = $this->eCommerceRemoteAccess->error; + if (!empty($this->eCommerceRemoteAccess->errors)) $this->errors = array_merge($this->errors, $this->eCommerceRemoteAccess->errors); + return -1; + } + return $this->societeToUpdate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetSocieteToUpdate'); + } + } - /** - * Get modified commande since the last update - * - * @param int $force Bool to force to reload cache list $this->commandeToUpdate - * @return array Array of remote order (also stored into this->commandeToUpdate) - */ - public function getCommandeToUpdate($force = false) - { - try { - if (!isset($this->commandeToUpdate) || $force == true) - { - $lastupdatedate=$this->getCommandeLastUpdateDate($force); - $this->commandeToUpdate = $this->eCommerceRemoteAccess->getCommandeToUpdate($lastupdatedate, $this->toDate); - } - if (empty($this->commandeToUpdate) && (! empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) - { - $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeToUpdate'); - if (! empty($this->eCommerceRemoteAccess->error)) $this->error=$this->eCommerceRemoteAccess->error; - if (! empty($this->eCommerceRemoteAccess->errors)) $this->errors=array_merge($this->errors, $this->eCommerceRemoteAccess->errors); - return -1; - } - return $this->commandeToUpdate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeToUpdate'); - } - } + /** + * Get modified commande since the last update + * + * @param int $force Bool to force to reload cache list $this->commandeToUpdate + * @return array Array of remote order (also stored into this->commandeToUpdate) + */ + public function getCommandeToUpdate($force = false) + { + try { + if (!isset($this->commandeToUpdate) || $force == true) { + $lastupdatedate = $this->getCommandeLastUpdateDate($force); + $this->commandeToUpdate = $this->eCommerceRemoteAccess->getCommandeToUpdate($lastupdatedate, $this->toDate); + } + if (empty($this->commandeToUpdate) && (!empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeToUpdate'); + if (!empty($this->eCommerceRemoteAccess->error)) $this->error = $this->eCommerceRemoteAccess->error; + if (!empty($this->eCommerceRemoteAccess->errors)) $this->errors = array_merge($this->errors, $this->eCommerceRemoteAccess->errors); + return -1; + } + return $this->commandeToUpdate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetCommandeToUpdate'); + } + } - /** - * Get modified facture since the last update - * - * @param int $force Bool to force to reload cache list $this->factureToUpdate - * @return array Array of remote invoice (also stored into this->factureToUpdate) - */ - public function getFactureToUpdate($force = false) - { - try { - if (!isset($this->factureToUpdate) || $force == true) - { - $lastupdatedate=$this->getFactureLastUpdateDate($force); - $this->factureToUpdate = $this->eCommerceRemoteAccess->getFactureToUpdate($lastupdatedate, $this->toDate); - } - if (empty($this->factureToUpdate) && (! empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) - { - if (! empty($this->eCommerceRemoteAccess->error)) $this->error=$this->eCommerceRemoteAccess->error; - if (! empty($this->eCommerceRemoteAccess->errors)) $this->errors=array_merge($this->errors, $this->eCommerceRemoteAccess->errors); - return -1; - } - return $this->factureToUpdate; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetFactureToUpdate'); - } - } + /** + * Get modified facture since the last update + * + * @param int $force Bool to force to reload cache list $this->factureToUpdate + * @return array Array of remote invoice (also stored into this->factureToUpdate) + */ + public function getFactureToUpdate($force = false) + { + try { + if (!isset($this->factureToUpdate) || $force == true) { + $lastupdatedate = $this->getFactureLastUpdateDate($force); + $this->factureToUpdate = $this->eCommerceRemoteAccess->getFactureToUpdate($lastupdatedate, $this->toDate); + } + if (empty($this->factureToUpdate) && (!empty($this->error) || !empty($this->errors) || !empty($this->eCommerceRemoteAccess->error) || !empty($this->eCommerceRemoteAccess->errors))) { + if (!empty($this->eCommerceRemoteAccess->error)) $this->error = $this->eCommerceRemoteAccess->error; + if (!empty($this->eCommerceRemoteAccess->errors)) $this->errors = array_merge($this->errors, $this->eCommerceRemoteAccess->errors); + return -1; + } + return $this->factureToUpdate; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetFactureToUpdate'); + } + } + /* getNbXXXToUpdate */ - /* getNbXXXToUpdate */ + /** + * Get count of modified product since the last update + * + * @param boolean $force Bool to force update + * @return int <0 if KO, >=0 if OK + */ + public function getNbProductToUpdate($force = false) + { + try { + $result = $this->getProductToUpdate($force); + if (is_array($result)) return count($result); + else return -1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); + return -2; + } + } + /** + * Get count of modified categories since the last update + * + * @param boolean $force Bool to force update + * @return int <0 if KO, >=0 if OK + */ + public function getNbCategoriesToUpdate($force = false) + { + try { + $result = $this->getCategoriesToUpdate($force); + if (is_array($result)) return count($result); + else return -1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetNbCategoriesToUpdate'); + return -2; + } + } - /** - * Get count of modified product since the last update - * - * @param boolean $force Bool to force update - * @return int <0 if KO, >=0 if OK - */ - public function getNbProductToUpdate($force = false) - { - try { - $result = $this->getProductToUpdate($force); - if (is_array($result)) return count($result); - else return -1; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); - return -2; - } - } + /** + * Get count of modified societe since the last update + * + * @param boolean $force Bool to force update + * @return int <0 if KO, >=0 if OK + */ + public function getNbSocieteToUpdate($force = false) + { + try { + $result = $this->getSocieteToUpdate($force); + if (is_array($result)) return count($result); + else return -1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); + return -2; + } + } - /** - * Get count of modified categories since the last update - * - * @param boolean $force Bool to force update - * @return int <0 if KO, >=0 if OK - */ - public function getNbCategoriesToUpdate($force = false) - { - try { - $result = $this->getCategoriesToUpdate($force); - if (is_array($result)) return count($result); - else return -1; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetNbCategoriesToUpdate'); - return -2; - } - } + /** + * Get count of modified commande since the last update + * + * @param boolean $force Bool to force update + * @return int <0 if KO, >=0 if OK + */ + public function getNbCommandeToUpdate($force = false) + { + try { + $result = $this->getCommandeToUpdate($force); + if (is_array($result)) return count($result); + else return -1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); + return -2; + } + } - /** - * Get count of modified societe since the last update - * - * @param boolean $force Bool to force update - * @return int <0 if KO, >=0 if OK - */ - public function getNbSocieteToUpdate($force = false) - { - try { - $result = $this->getSocieteToUpdate($force); - if (is_array($result)) return count($result); - else return -1; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); - return -2; - } - } + /** + * Get count of modified facture since the last update + * + * @param boolean $force Bool to force update + * @return int <0 if KO, >=0 if OK + */ + public function getNbFactureToUpdate($force = false) + { + try { + $result = $this->getFactureToUpdate($force); + if (is_array($result)) return count($result); + else return -1; + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); + return -2; + } + } - /** - * Get count of modified commande since the last update - * - * @param boolean $force Bool to force update - * @return int <0 if KO, >=0 if OK - */ - public function getNbCommandeToUpdate($force = false) - { - try { - $result = $this->getCommandeToUpdate($force); - if (is_array($result)) return count($result); - else return -1; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); - return -2; - } - } + /** + * Sync categories + * + * @param int $toNb Max nb to synch + * @return int <0 if KO, >= 0 if ok + */ + public function synchCategory($toNb=0) + { + $error = 0; - /** - * Get count of modified facture since the last update - * - * @param boolean $force Bool to force update - * @return int <0 if KO, >=0 if OK - */ - public function getNbFactureToUpdate($force = false) - { - try { - $result = $this->getFactureToUpdate($force); - if (is_array($result)) return count($result); - else return -1; - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorGetNbSocieteToUpdate'); - return -2; - } - } + $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__ . " - toNb: {$toNb}"); + try { + $nbrecorderror = 0; + $nbgoodsunchronize = 0; + $categories = array(); - /** - * Sync categories - * - * @param int $toNb Max nb to synch - * @return int <0 if KO, >= 0 if ok - */ - public function synchCategory($toNb=0) - { - $error=0; + dol_syslog("***** eCommerceSynchro synchCategory"); + + // Safety check : importRootCategory exists + $dBRootCategorie = new Categorie($this->db); + $importRootExists = ($dBRootCategorie->fetch($this->eCommerceSite->fk_cat_product) > 0) ? 1 : 0; + + if ($importRootExists) { + dol_syslog("synchCategory importRootExists=" . $importRootExists); + + $resulttoupdate = $this->getCategoriesToUpdate(); // Return list of categories that were modified on ecommerce side + /* Do not sort run this, we want to keep sort on parent categori first and not by updated_at date. + if (is_array($resulttoupdate)) + { + if (count($resulttoupdate) > 0) $categories = $this->eCommerceRemoteAccess->convertRemoteObjectIntoDolibarrCategory($resulttoupdate,$toNb); + } + else + { + $error++; + }*/ + $categories = $resulttoupdate; + + // Check return of remote... + if (is_array($resulttoupdate) && count($resulttoupdate) > 0 && (!is_array($categories) || count($categories) == 0)) // return of remote is bad or empty when input was not empty + { + $error++; + } + if (!$error && is_array($categories)) { + $counter = 0; + foreach ($categories as $categoryArray) // Loop on each categories found on ecommerce side. Cursor is $categoryArray + { + $counter++; + if ($toNb > 0 && $counter > $toNb) break; + + dol_syslog("synchCategory Process sync of ecommerce category remote_id=" . $categoryArray['category_id'] . " name=" . $categoryArray['name'] . " remote parent_id=" . $categoryArray['parent_id']); + + $this->db->begin(); + + $this->initECommerceCategory(); // Initialise new objects eCommerceMotherCategory and eCommerceCategory + + $dBCategorie = new Categorie($this->db); + + // Check if the ecommerce category has an ecommerce parent category, if not, that implies it is root + $motherExists = $this->eCommerceMotherCategory->fetchByRemoteId($categoryArray['parent_id'], $this->eCommerceSite->id); + // Now $this->eCommerceMotherCategory contains the mother category or null + + // if fetch on eCommerceMotherCategory has failed, it is root + if ($motherExists < 1 && ($this->eCommerceMotherCategory->fetchByFKCategory($this->eCommerceSite->fk_cat_product, $this->eCommerceSite->id) < 0)) { + // get the importRootCategory of Dolibarr set for the eCommerceSite + $dBCategorie->fetch($this->eCommerceSite->fk_cat_product); + + $this->eCommerceMotherCategory->label = $dBCategorie->label; + $this->eCommerceMotherCategory->type = $dBCategorie->type; + $this->eCommerceMotherCategory->description = $dBCategorie->description; + $this->eCommerceMotherCategory->fk_category = $dBCategorie->id; + $this->eCommerceMotherCategory->fk_site = $this->eCommerceSite->id; + $this->eCommerceMotherCategory->remote_id = $categoryArray['parent_id']; + $this->eCommerceMotherCategory->last_update = ''; + $this->eCommerceMotherCategory->other_data = $categoryArray['other_data']; + + // Create an entry to map importRootCategory in eCommerceCategory + $result = $this->eCommerceMotherCategory->create($this->user); + if ($result < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceMotherCategoryCreateError', $categoryArray['label'], $categoryArray['category_id'], $this->eCommerceSite->id); + $this->errors = array_merge($this->errors, $this->eCommerceMotherCategory->errors); + break; + } + + // reset $dBCategorie + $dBCategorie = new Categorie($this->db); + } - $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__ . " - toNb: {$toNb}"); + // If we did not find mother yet (creation was not done in hierarchy order), we create category in root for magento + if (empty($this->eCommerceMotherCategory->fk_category)) { + dol_syslog("We did not found parent category in dolibarr, for parent remote_id=" . $categoryArray['parent_id'] . ", so we create " . $categoryArray['name'] . " with remote_id=" . $categoryArray['category_id'] . " on root."); + $fk_parent = $this->eCommerceSite->fk_cat_product; + } else { + dol_syslog("We found parent category dolibarr id=" . $this->eCommerceMotherCategory->fk_category); + $fk_parent = $this->eCommerceMotherCategory->fk_category; + } - try { - $nbgoodsunchronize = 0; - $categories=array(); + // Search if category link already exist + $synchExists = $this->eCommerceCategory->fetchByRemoteId($categoryArray['category_id'], $this->eCommerceSite->id); + if ($synchExists > 0) { + $eCommerceCatExists = $dBCategorie->fetch($this->eCommerceCategory->fk_category); + } else { + $eCommerceCatExists = -1; + // Search if already exist + $sql = "SELECT c.rowid"; + $sql .= " FROM " . MAIN_DB_PREFIX . "categorie as c "; + $sql .= " WHERE c.entity IN (" . getEntity('category', 1) . ")"; + $sql .= " AND c.type = 0"; + $sql .= " AND c.fk_parent = " . $fk_parent; + $sql .= " AND c.label = '" . $this->db->escape($categoryArray['name']) . "'"; - dol_syslog("***** eCommerceSynchro synchCategory"); + $resql = $this->db->query($sql); + if ($resql) { + if ($obj = $this->db->fetch_object($resql)) { + $eCommerceCatExists = $dBCategorie->fetch($obj->rowid); + // Search if category link exist + $synchExists = $this->eCommerceCategory->fetchByFKCategory($obj->rowid, $this->eCommerceSite->id); + } + } + } - // Safety check : importRootCategory exists - $dBRootCategorie = new Categorie($this->db); - $importRootExists = ($dBRootCategorie->fetch($this->eCommerceSite->fk_cat_product) > 0) ? 1 : 0; + if ($dBCategorie->id > 0) $dBCategorie->oldcopy = clone $dBCategorie; - if ($importRootExists) - { - dol_syslog("synchCategory importRootExists=".$importRootExists); + // Affect attributes of $categoryArray to $dBCategorie + $dBCategorie->type = 0; // for product category type + $dBCategorie->label = $categoryArray['name']; + $dBCategorie->description = $categoryArray['description']; + $dBCategorie->fk_parent = ($fk_parent != $dBCategorie->id) ? $fk_parent : 0; + $dBCategorie->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; - $resulttoupdate = $this->getCategoriesToUpdate(); // Return list of categories that were modified on ecommerce side - /* Do not sort run this, we want to keep sort on parent categori first and not by updated_at date. - if (is_array($resulttoupdate)) - { - if (count($resulttoupdate) > 0) $categories = $this->eCommerceRemoteAccess->convertRemoteObjectIntoDolibarrCategory($resulttoupdate,$toNb); - } - else - { - $error++; - }*/ - $categories=$resulttoupdate; + if (!($eCommerceCatExists > 0)) $dBCategorie->array_options = $this->getDefaultExtraFields($dBCategorie->table_element, $this->eCommerceSite); - // Check return of remote... - if (is_array($resulttoupdate) && count($resulttoupdate) > 0 && (! is_array($categories) || count($categories) == 0)) // return of remote is bad or empty when input was not empty - { - $error++; - } - if (! $error && is_array($categories)) - { - $counter = 0; - foreach ($categories as $categoryArray) // Loop on each categories found on ecommerce side. Cursor is $categoryArray - { - $counter++; - if ($toNb > 0 && $counter > $toNb) break; - - dol_syslog("synchCategory Process sync of ecommerce category remote_id=".$categoryArray['category_id']." name=".$categoryArray['name']." remote parent_id=".$categoryArray['parent_id']); - - $this->db->begin(); - - $this->initECommerceCategory(); // Initialise new objects eCommerceMotherCategory and eCommerceCategory - - $dBCategorie = new Categorie($this->db); - - // Check if the ecommerce category has an ecommerce parent category, if not, that implies it is root - $motherExists = $this->eCommerceMotherCategory->fetchByRemoteId($categoryArray['parent_id'], $this->eCommerceSite->id); - // Now $this->eCommerceMotherCategory contains the mother category or null - - // if fetch on eCommerceMotherCategory has failed, it is root - if ($motherExists < 1 && ($this->eCommerceMotherCategory->fetchByFKCategory($this->eCommerceSite->fk_cat_product, $this->eCommerceSite->id) < 0)) - { - // get the importRootCategory of Dolibarr set for the eCommerceSite - $dBCategorie->fetch($this->eCommerceSite->fk_cat_product); - - $this->eCommerceMotherCategory->label = $dBCategorie->label; - $this->eCommerceMotherCategory->type = $dBCategorie->type; - $this->eCommerceMotherCategory->description = $dBCategorie->description; - $this->eCommerceMotherCategory->fk_category = $dBCategorie->id; - $this->eCommerceMotherCategory->fk_site = $this->eCommerceSite->id; - $this->eCommerceMotherCategory->remote_id = $categoryArray['parent_id']; - $this->eCommerceMotherCategory->last_update = ''; - - // Create an entry to map importRootCategory in eCommerceCategory - $result = $this->eCommerceMotherCategory->create($this->user); - if ($result < 0) { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceMotherCategoryCreateError', $categoryArray['label'], $categoryArray['category_id'], $this->eCommerceSite->id); - $this->errors = array_merge($this->errors, $this->eCommerceMotherCategory->errors); - break; - } - - // reset $dBCategorie - $dBCategorie = new Categorie($this->db); - } - - // If we did not find mother yet (creation was not done in hierarchy order), we create category in root for magento - if (empty($this->eCommerceMotherCategory->fk_category)) - { - dol_syslog("We did not found parent category in dolibarr, for parent remote_id=".$categoryArray['parent_id'].", so we create ".$categoryArray['name']." with remote_id=".$categoryArray['category_id']." on root."); - $fk_parent = $this->eCommerceSite->fk_cat_product; - } - else - { - dol_syslog("We found parent category dolibarr id=".$this->eCommerceMotherCategory->fk_category); - $fk_parent = $this->eCommerceMotherCategory->fk_category; - } - - // Search if category link already exist - $synchExists = $this->eCommerceCategory->fetchByRemoteId($categoryArray['category_id'], $this->eCommerceSite->id); - if ($synchExists > 0) { - $eCommerceCatExists = $dBCategorie->fetch($this->eCommerceCategory->fk_category); - } else { - $eCommerceCatExists = -1; - // Search if already exist - $sql = "SELECT c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c "; - $sql.= " WHERE c.entity IN (".getEntity('category',1).")"; - $sql.= " AND c.type = 0"; - $sql.= " AND c.fk_parent = ".$fk_parent; - $sql.= " AND c.label = '".$this->db->escape($categoryArray['name'])."'"; - - $resql = $this->db->query($sql); - if ($resql) { - if ($obj = $this->db->fetch_object($resql)) { - $eCommerceCatExists = $dBCategorie->fetch($obj->rowid); - // Search if category link exist - $synchExists = $this->eCommerceCategory->fetchByFKCategory($obj->rowid, $this->eCommerceSite->id); - } - } - } + if ($eCommerceCatExists > 0) { + $result = $dBCategorie->update($this->user); + } else { + $result = $dBCategorie->create($this->user); + } - if ($dBCategorie->id > 0) $dBCategorie->oldcopy = clone $dBCategorie; + // if synchro category ok + if ($result >= 0) { + $this->eCommerceCategory->fk_site = $this->eCommerceSite->id; + $this->eCommerceCategory->type = $dBCategorie->type; + $this->eCommerceCategory->fk_category = $dBCategorie->id; + $this->eCommerceCategory->label = $dBCategorie->label; + $this->eCommerceCategory->description = $dBCategorie->description; + $this->eCommerceCategory->remote_id = $categoryArray['category_id']; + $this->eCommerceCategory->remote_parent_id = $categoryArray['parent_id']; + $this->eCommerceCategory->other_data = $categoryArray['other_data']; + if (!empty($categoryArray['updated_at'])) $this->eCommerceCategory->last_update = strtotime($categoryArray['updated_at']); + + if ($synchExists > 0) // update it remotely + { + if ($this->eCommerceCategory->update($this->user) < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceCategoryUpdateError'); + $this->errors = array_merge($this->errors, $this->eCommerceCategory->errors); + break; + } + } else // create it remotely + { + if ($this->eCommerceCategory->create($this->user) < 0) // insert into table lxx_ecommerce_category + { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceCategoryCreateError') . ' ' . $categoryArray['label']; + $this->errors = array_merge($this->errors, $this->eCommerceCategory->errors); + break; + } + } + } else { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSynchCategoryError') . ' ' . $dBCategorie->error; + break; + } - // Affect attributes of $categoryArray to $dBCategorie - $dBCategorie->type = 0; // for product category type - $dBCategorie->label = $categoryArray['name']; - $dBCategorie->description = $categoryArray['description']; - $dBCategorie->fk_parent = ($fk_parent != $dBCategorie->id) ? $fk_parent : 0; - $dBCategorie->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; + //var_dump($nbgoodsunchronize);exit; + unset($dBCategorie); - if (!($eCommerceCatExists > 0)) $dBCategorie->array_options = $this->getDefaultExtraFields($dBCategorie->table_element, $this->eCommerceSite); + if ($error || !empty($this->errors)) { + $this->db->rollback(); + $nbrecorderror++; + break; // We decide to stop on first error + } else { + $this->db->commit(); + $nbgoodsunchronize = $nbgoodsunchronize + 1; + } + } // end foreach - if ($eCommerceCatExists > 0) - { - $result = $dBCategorie->update($this->user); - } - else - { - $result = $dBCategorie->create($this->user); - } - - // if synchro category ok - if ($result >= 0) - { - $this->eCommerceCategory->fk_site = $this->eCommerceSite->id; - $this->eCommerceCategory->type = $dBCategorie->type; - $this->eCommerceCategory->fk_category = $dBCategorie->id; - $this->eCommerceCategory->label = $dBCategorie->label; - $this->eCommerceCategory->description = $dBCategorie->description; - $this->eCommerceCategory->remote_id = $categoryArray['category_id']; - $this->eCommerceCategory->remote_parent_id = $categoryArray['parent_id']; - if (!empty($categoryArray['updated_at'])) $this->eCommerceCategory->last_update = strtotime($categoryArray['updated_at']); - - if ($synchExists > 0) // update it remotely - { - if ($this->eCommerceCategory->update($this->user) < 0) - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceCategoryUpdateError'); - $this->errors = array_merge($this->errors, $this->eCommerceCategory->errors); - break; - } - } - else // create it remotely - { - if ($this->eCommerceCategory->create($this->user) < 0) // insert into table lxx_ecommerce_category - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceCategoryCreateError') . ' ' . $categoryArray['label']; - $this->errors = array_merge($this->errors, $this->eCommerceCategory->errors); - break; - } - } - } - else - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSynchCategoryError') . ' ' . $dBCategorie->error; - break; - } - - //var_dump($nbgoodsunchronize);exit; - unset($dBCategorie); - - if ($error || ! empty($this->errors)) - { - $this->db->rollback(); - $nbrecorderror++; - break; // We decide to stop on first error - } - else - { - $this->db->commit(); - $nbgoodsunchronize = $nbgoodsunchronize + 1; - } - } // end foreach - - if (empty($this->errors) && ! $error) - { - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); - - // TODO If we commit even if there was an error (to validate previous record ok), we must also remove 1 second the the higher - // date into table of links to be sure we will retry (during next synch) also record with same update_at than the last record ok. + if (empty($this->errors) && !$error) { + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); + + // TODO If we commit even if there was an error (to validate previous record ok), we must also remove 1 second the the higher + // date into table of links to be sure we will retry (during next synch) also record with same update_at than the last record ok. eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return $nbgoodsunchronize; - } - else - { - dol_syslog(__METHOD__ . " - Error synchro categories for parent remote_id=".$categoryArray['parent_id'].", name=".$categoryArray['name'].", remote_id=".$categoryArray['category_id']." : " . $this->errorsToString()); - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); - if (isset($categoryArray['name'])) $this->errors[] = "Category parent remote_id=".$categoryArray['parent_id'].", name=".$categoryArray['name'].", remote_id=".$categoryArray['category_id']; + } else { + dol_syslog(__METHOD__ . " - Error synchro categories for parent remote_id=" . $categoryArray['parent_id'] . ", name=" . $categoryArray['name'] . ", remote_id=" . $categoryArray['category_id'] . " : " . $this->errorsToString()); + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); + if (isset($categoryArray['name'])) $this->errors[] = "Category parent remote_id=" . $categoryArray['parent_id'] . ", name=" . $categoryArray['name'] . ", remote_id=" . $categoryArray['category_id']; eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return -1; - } - } - else - { - $this->error=$this->langs->trans('ECommerceErrorsynchCategory').' (Code FailToGetDetailsOfRecord)'; - $this->errors[] = $this->error; - } - } - else - { - $this->error = $this->langs->trans('ECommerceSynchCategoryNoImportRoot'); - $this->errors[] = $this->error; + } + } else { + $this->error = $this->langs->trans('ECommerceErrorsynchCategory') . ' (Code FailToGetDetailsOfRecord)'; + $this->errors[] = $this->error; + } + } else { + $this->error = $this->langs->trans('ECommerceSynchCategoryNoImportRoot'); + $this->errors[] = $this->error; eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return -1; - } - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceSynchCategoryConnectError').': '.$e->getMessage(); + } + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceSynchCategoryConnectError') . ': ' . $e->getMessage(); eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return -1; - } + } eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return -1; - } - + } - /** - * Synchronize societe to update - * + /** + * Synchronize societe to update + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date * @param array $remote_ids Force to synchronize the specified remote_ids * @param int $toNb Max nb to synch * @return int >0 if OK, <0 if KO - */ - public function synchSociete($remote_ids = array(), $toNb = 0) + */ + public function synchSociete($remote_ids = array(), $toNb = 0) { dol_syslog(__METHOD__ . ' remote_ids=' . json_encode($remote_ids) . ', toNb=' . $toNb, LOG_DEBUG); @@ -1154,160 +1069,147 @@ public function synchSociete($remote_ids = array(), $toNb = 0) return -1; } + /** + * Synchronize socpeople to update for a society: Create or update it into dolibarr, then update the ecommerce_socpeople table. + * + * @param array $socpeopleArray Array with all params to synchronize + * @return int Id of socpeople into Dolibarr if OK and false if KO + */ + public function synchSocpeople($socpeopleArray) + { + global $conf; - /** - * Synchronize socpeople to update for a society: Create or update it into dolibarr, then update the ecommerce_socpeople table. - * - * @param array $socpeopleArray Array with all params to synchronize - * @return int Id of socpeople into Dolibarr if OK and false if KO - */ - public function synchSocpeople($socpeopleArray) - { - global $conf; - - $error=0; - $synchExists = 0; - $contactExists = 0; + $error = 0; + $synchExists = 0; + $contactExists = 0; - $dBContact = new Contact($this->db); + $dBContact = new Contact($this->db); - try { - dol_syslog("***** eCommerceSynchro synchSocPeople remote_id=".$socpeopleArray['remote_id']." site=".$this->eCommerceSite->id); + try { + dol_syslog("***** eCommerceSynchro synchSocPeople remote_id=" . $socpeopleArray['remote_id'] . " site=" . $this->eCommerceSite->id); - if (!isset($this->eCommerceSocpeople)) - $this->initECommerceSocpeople(); + if (!isset($this->eCommerceSocpeople)) + $this->initECommerceSocpeople(); - //print "Work on remote_id = " .$socpeopleArray['remote_id']." type = ".$socpeopleArray['type']."\n"; + //print "Work on remote_id = " .$socpeopleArray['remote_id']." type = ".$socpeopleArray['type']."\n"; - //check if contact exists in eCommerceSocpeople table - if (!empty($socpeopleArray['remote_id'])) { - // $socpeopleArray['type'] = 1 = Contact de tiers - // $socpeopleArray['type'] = 2 = Contact de commande - // $socpeopleArray['type'] = 3 = Contact de facture - // $socpeopleArray['type'] = 4 = Contact de livraison - $synchExists = $this->eCommerceSocpeople->fetchByRemoteId($socpeopleArray['remote_id'], $socpeopleArray['type'], $this->eCommerceSite->id); + //check if contact exists in eCommerceSocpeople table + if (!empty($socpeopleArray['remote_id'])) { + // $socpeopleArray['type'] = 1 = Contact de tiers + // $socpeopleArray['type'] = 2 = Contact de commande + // $socpeopleArray['type'] = 3 = Contact de facture + // $socpeopleArray['type'] = 4 = Contact de livraison + $synchExists = $this->eCommerceSocpeople->fetchByRemoteId($socpeopleArray['remote_id'], $socpeopleArray['type'], $this->eCommerceSite->id); - if ($synchExists > 0) { - $contactExists = $dBContact->fetch($this->eCommerceSocpeople->fk_socpeople); - } - } + if ($synchExists > 0) { + $contactExists = $dBContact->fetch($this->eCommerceSocpeople->fk_socpeople); + } + } if ($contactExists > 0) $dBContact->oldcopy = clone $dBContact; - //set data into contact - $dBContact->socid = $socpeopleArray['fk_soc']; - $dBContact->fk_soc = $socpeopleArray['fk_soc']; - $dBContact->firstname = $socpeopleArray['firstname']; - $dBContact->lastname = $socpeopleArray['lastname']; - $dBContact->address = $socpeopleArray['address']; - $dBContact->cp = $socpeopleArray['zip']; - if ((float) DOL_VERSION >= 6.0) - { - $dBContact->zip = dol_trunc($socpeopleArray['zip'], 25, 'right', 'UTF-8', 1); - } - else - { - $dBContact->zip = dol_trunc($socpeopleArray['zip'], 10, 'right', 'UTF-8', 1); - } - $dBContact->town = dol_trunc($socpeopleArray['town'], 30, 'right', 'UTF-8', 1); - $dBContact->ville = $dBContact->town; - $dBContact->country_id = $socpeopleArray['country_id']; - $dBContact->email = $socpeopleArray['email']; - $dBContact->phone_pro = dol_trunc($socpeopleArray['phone'], 30, 'right', 'UTF-8', 1); - $dBContact->fax = dol_trunc($socpeopleArray['fax'], 30, 'right', 'UTF-8', 1); - $dBContact->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; - - if (!$contactExists) { - $contactExists = $this->getContactIdFromInfos($dBContact); - if ($contactExists > 0) { - $contactExists = $dBContact->fetch($contactExists); + //set data into contact + $dBContact->socid = $socpeopleArray['fk_soc']; + $dBContact->fk_soc = $socpeopleArray['fk_soc']; + $dBContact->firstname = $socpeopleArray['firstname']; + $dBContact->lastname = $socpeopleArray['lastname']; + $dBContact->address = $socpeopleArray['address']; + $dBContact->cp = $socpeopleArray['zip']; + if ((float) DOL_VERSION >= 6.0) { + $dBContact->zip = dol_trunc($socpeopleArray['zip'], 25, 'right', 'UTF-8', 1); + } else { + $dBContact->zip = dol_trunc($socpeopleArray['zip'], 10, 'right', 'UTF-8', 1); + } + $dBContact->town = dol_trunc($socpeopleArray['town'], 30, 'right', 'UTF-8', 1); + $dBContact->ville = $dBContact->town; + $dBContact->country_id = $socpeopleArray['country_id']; + $dBContact->email = $socpeopleArray['email']; + $dBContact->phone_pro = dol_trunc($socpeopleArray['phone'], 30, 'right', 'UTF-8', 1); + $dBContact->fax = dol_trunc($socpeopleArray['fax'], 30, 'right', 'UTF-8', 1); + $dBContact->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; + + if (!$contactExists) { + $contactExists = $this->getContactIdFromInfos($dBContact); + if ($contactExists > 0) { + $contactExists = $dBContact->fetch($contactExists); $dBContact->oldcopy = clone $dBContact; - if (isset($socpeopleArray['country_id'])) $dBContact->country_id = $socpeopleArray['country_id']; - if (isset($socpeopleArray['email'])) $dBContact->email = $socpeopleArray['email']; - if (isset($socpeopleArray['phone'])) $dBContact->phone_pro = dol_trunc($socpeopleArray['phone'], 30, 'right', 'UTF-8', 1); - if (isset($socpeopleArray['fax'])) $dBContact->fax = dol_trunc($socpeopleArray['fax'], 30, 'right', 'UTF-8', 1); - $dBContact->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; - $synchExists = $this->eCommerceSocpeople->fetchByFkSocpeople($dBContact->id, $this->eCommerceSite->id); - } - } + if (isset($socpeopleArray['country_id'])) $dBContact->country_id = $socpeopleArray['country_id']; + if (isset($socpeopleArray['email'])) $dBContact->email = $socpeopleArray['email']; + if (isset($socpeopleArray['phone'])) $dBContact->phone_pro = dol_trunc($socpeopleArray['phone'], 30, 'right', 'UTF-8', 1); + if (isset($socpeopleArray['fax'])) $dBContact->fax = dol_trunc($socpeopleArray['fax'], 30, 'right', 'UTF-8', 1); + $dBContact->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; + $synchExists = $this->eCommerceSocpeople->fetchByFkSocpeople($dBContact->id, $this->eCommerceSite->id); + } + } if ($contactExists == 0) $dBContact->array_options = $this->getDefaultExtraFields($dBContact->table_element, $this->eCommerceSite); - if ($contactExists > 0) { - $result = $dBContact->update($dBContact->id, $this->user); - if ($result < 0) { - $error++; - $this->error = $this->langs->trans('ECommerceSynchContactUpdateError') . ' ' . $dBContact->error; - $this->errors[] = $this->error; - } - } else if ($contactExists == 0) { - $result = $dBContact->create($this->user); - if ($result < 0) { - $error++; - $this->error = $this->langs->trans('ECommerceSynchContactCreateError') . ' ' . $dBContact->error; - $this->errors[] = $this->error; - } - } else if ($synchExists > 0 && $contactExists < 0) { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSynchSocieteErrorBetweenECommerceSocpeopleAndContact'); - } else if ($contactExists < 0) { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSynchContactFetchError') . ' ' . $dBContact->error; - } - - //if create/update of contact table is ok - if (! $error && $result >= 0) - { - $this->eCommerceSocpeople->last_update = $socpeopleArray['last_update']; - $this->eCommerceSocpeople->fk_socpeople = $dBContact->id; - //if a previous synchro exists - if ($synchExists > 0) - { - //eCommerce update - if ($this->eCommerceSocpeople->update($this->user) < 0) - { - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceSocpeopleUpdateError'); - $this->errors = array_merge($this->errors, $this->eCommerceSocpeople->errors); - return false; - } - } - //if not previous synchro exists - else - { - //eCommerce create - $this->eCommerceSocpeople->fk_site = $this->eCommerceSite->id; - $this->eCommerceSocpeople->remote_id = !empty($socpeopleArray['remote_id']) ? $socpeopleArray['remote_id'] : 'none-'.$dBContact->id; - $this->eCommerceSocpeople->type = $socpeopleArray['type']; - if ($this->eCommerceSocpeople->create($this->user) < 0) - { - $this->errors[] = $this->langs->trans('ECommerceSynchECommerceSocpeopleCreateError', $socpeopleArray['fk_soc'], $socpeopleArray['firstname'], $socpeopleArray['lastname']) . ' : ' . $this->eCommerceSocpeople->error; - $this->errors = array_merge($this->errors, $this->eCommerceSocpeople->errors); - return false; - } - } - return $dBContact->id; - } - else - { - $this->errors[] = $this->langs->trans('ECommerceSynchSocpeopleErrorCreateUpdateSocpeople'); - return false; - } - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorsynchSocpeople').': '.$e->getMessage(); - } - return false; - } + if ($contactExists > 0) { + $result = $dBContact->update($dBContact->id, $this->user); + if ($result < 0) { + $error++; + $this->error = $this->langs->trans('ECommerceSynchContactUpdateError') . ' ' . $dBContact->error; + $this->errors[] = $this->error; + } + } elseif ($contactExists == 0) { + $result = $dBContact->create($this->user); + if ($result < 0) { + $error++; + $this->error = $this->langs->trans('ECommerceSynchContactCreateError') . ' ' . $dBContact->error; + $this->errors[] = $this->error; + } + } elseif ($synchExists > 0 && $contactExists < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSynchSocieteErrorBetweenECommerceSocpeopleAndContact'); + } elseif ($contactExists < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSynchContactFetchError') . ' ' . $dBContact->error; + } + //if create/update of contact table is ok + if (!$error && $result >= 0) { + $this->eCommerceSocpeople->last_update = $socpeopleArray['last_update']; + $this->eCommerceSocpeople->fk_socpeople = $dBContact->id; + //if a previous synchro exists + if ($synchExists > 0) { + //eCommerce update + if ($this->eCommerceSocpeople->update($this->user) < 0) { + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceSocpeopleUpdateError'); + $this->errors = array_merge($this->errors, $this->eCommerceSocpeople->errors); + return false; + } + } //if not previous synchro exists + else { + //eCommerce create + $this->eCommerceSocpeople->fk_site = $this->eCommerceSite->id; + $this->eCommerceSocpeople->remote_id = !empty($socpeopleArray['remote_id']) ? $socpeopleArray['remote_id'] : 'none-' . $dBContact->id; + $this->eCommerceSocpeople->type = $socpeopleArray['type']; + if ($this->eCommerceSocpeople->create($this->user) < 0) { + $this->errors[] = $this->langs->trans('ECommerceSynchECommerceSocpeopleCreateError', $socpeopleArray['fk_soc'], $socpeopleArray['firstname'], $socpeopleArray['lastname']) . ' : ' . $this->eCommerceSocpeople->error; + $this->errors = array_merge($this->errors, $this->eCommerceSocpeople->errors); + return false; + } + } + return $dBContact->id; + } else { + $this->errors[] = $this->langs->trans('ECommerceSynchSocpeopleErrorCreateUpdateSocpeople'); + return false; + } + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorsynchSocpeople') . ': ' . $e->getMessage(); + } + return false; + } - /** - * Synchronize product to update - * - * @param array $remote_ids Force to synchronize the specified remote_ids + /** + * Synchronize product to update + * + * @param array $remote_ids Force to synchronize the specified remote_ids * @param int $toNb Max nb to synch - * @return int >0 if OK, <0 if KO - */ - public function synchProduct($remote_ids=array(), $toNb=0) - { + * @return int >0 if OK, <0 if KO + */ + public function synchProduct($remote_ids = array(), $toNb = 0) + { dol_syslog(__METHOD__ . ' remote_ids=' . json_encode($remote_ids) . ', toNb=' . $toNb, LOG_DEBUG); $this->error = ''; @@ -1332,18 +1234,17 @@ public function synchProduct($remote_ids=array(), $toNb=0) return -1; } - - /** - * Synchronize commande to update - * Inclut synchProduct et synchSociete - * + /** + * Synchronize commande to update + * Inclut synchProduct et synchSociete + * * @param array $remote_ids Force to synchronize the specified remote_ids - * @param int $toNb Max nb to synch + * @param int $toNb Max nb to synch * @param bool $dont_synchronize_products Bypass the synchronization of the product of the order * @return int >0 if OK, <0 if KO - */ - public function synchCommande($remote_ids=array(), $toNb=0, $dont_synchronize_products = false) - { + */ + public function synchCommande($remote_ids = array(), $toNb = 0, $dont_synchronize_products = false) + { dol_syslog(__METHOD__ . ' remote_ids=' . json_encode($remote_ids) . ', toNb=' . $toNb, LOG_DEBUG); $this->error = ''; @@ -1368,638 +1269,574 @@ public function synchCommande($remote_ids=array(), $toNb=0, $dont_synchronize_pr return -1; } - /** - * Synchronize facture to update - * - * @param int $toNb Max nb to synch - * @return int Id of product synchronized if OK, -1 if KO - */ - public function synchFacture($toNb=0) - { - global $conf, $user; + /** + * Synchronize facture to update + * + * @param int $toNb Max nb to synch + * @return int Id of product synchronized if OK, -1 if KO + */ + public function synchFacture($toNb=0) + { + global $conf, $user; - $error = 0; + $nbrecorderror = 0; + $nbgoodsunchronize = 0; + $error = 0; - try { - $factures = array(); + try { + $factures = array(); - dol_syslog("***** eCommerceSynchro synchFacture"); + dol_syslog("***** eCommerceSynchro synchFacture"); - $resulttoupdate=$this->getFactureToUpdate(); - if (is_array($resulttoupdate)) - { - if (count($resulttoupdate) > 0) $factures = $this->eCommerceRemoteAccess->convertRemoteObjectIntoDolibarrFacture($resulttoupdate, $toNb); - } - else - { - $error++; - } + $resulttoupdate = $this->getFactureToUpdate(); + if (is_array($resulttoupdate)) { + if (count($resulttoupdate) > 0) $factures = $this->eCommerceRemoteAccess->convertRemoteObjectIntoDolibarrFacture($resulttoupdate, $toNb); + } else { + $error++; + } - // Check return of remote... - if (is_array($resulttoupdate) && count($resulttoupdate) > 0 && (! is_array($factures) || count($factures) == 0)) // return of remote is bad or empty when input was not empty - { - $error++; - } + // Check return of remote... + if (is_array($resulttoupdate) && count($resulttoupdate) > 0 && (!is_array($factures) || count($factures) == 0)) // return of remote is bad or empty when input was not empty + { + $error++; + } - if (! $error && is_array($factures)) - { - // Local filter to exclude bundles and other complex types + if (!$error && is_array($factures)) { + // Local filter to exclude bundles and other complex types // $productsTypesOk = array('simple', 'virtual', 'downloadable'); - $counter=0; - foreach ($factures as $factureArray) - { - dol_syslog("- Process synch of invoice with remote_order_id=".$factureArray['remote_order_id']); - - $counter++; - if ($toNb > 0 && $counter > $toNb) break; - - $this->db->begin(); - - $this->initECommerceCommande(); - $this->initECommerceFacture(); - $this->initECommerceSociete(); - - $dBFacture = new Facture($this->db); - $dBCommande = new Commande($this->db); - $dBExpedition = new Expedition($this->db); - - //check if commande exists in eCommerceCommande (with remote_order_id) - $synchCommandeExists = $this->eCommerceCommande->fetchByRemoteId($factureArray['remote_order_id'], $this->eCommerceSite->id); - - //check if ref exists in commande - $refCommandeExists = $dBCommande->fetch($this->eCommerceCommande->fk_commande); - - //check if societe exists in eCommerceSociete (with remote id). This init ->fk_societe. This is a sql request. - //$societeExists will be 1 (found) or -1 (not found) - if (! empty($factureArray['remote_id_societe'])) // May be empty if customer is a non logged user or was deleted on magento side. - { - $societeExists = $this->eCommerceSociete->fetchByRemoteId($factureArray['remote_id_societe'], $this->eCommerceSite->id); - } - else - { - // This is an unknown customer. May be a non logged customer. - if ($this->eCommerceSite->fk_anonymous_thirdparty > 0) - { - $societeExists = 1; - $this->eCommerceSociete->fk_societe = $this->eCommerceSite->fk_anonymous_thirdparty; - } - else - { - $societeExists = 0; - } - } - - //if societe and commande exists start - if ($societeExists > 0 && $synchCommandeExists > 0) - { - //check if facture exists in eCommerceFacture (with remote id) - $synchFactureExists = $this->eCommerceFacture->fetchByRemoteId($factureArray['remote_id'], $this->eCommerceSite->id); - if ($synchFactureExists > 0) - { - //check if facture exists in facture - $refFactureExists = $dBFacture->fetch($this->eCommerceFacture->fk_facture); - if ($refFactureExists > 0) - { - //update - if ($dBFacture->statut != $factureArray['status']) - { - dol_syslog("Status of invoice has changed, we update invoice from status ".$dBFacture->statut." to status ".$factureArray['status']); - - // Draft or not draft - if ($factureArray['status'] == Facture::STATUS_DRAFT) // status draft. Should not happen with magento - { - // Target status is status draft. Should not happen with magento. - // Nothing to do - } - else - { - // Target status is not draft. We validate if current status is still draft to get correct ref. - if ($dBFacture->statut == Facture::STATUS_DRAFT) - { - $idWareHouse = 0; - // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync - //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; - $dBFacture->validate($this->user, '', $idWareHouse); - } - } - - // Which target status ? - if ($factureArray['status'] == Facture::STATUS_VALIDATED) - { - if ($dBFacture->statut != Facture::STATUS_VALIDATED) - { - $dBFacture->setStatut(Facture::STATUS_VALIDATED, $dBFacture->id, $dBFacture->table_element); - } - } - if ($factureArray['status'] == Facture::STATUS_ABANDONED) - { - if ($dBFacture->statut != Facture::STATUS_ABANDONED) - { - $dBFacture->set_canceled($this->user, $factureArray['close_code'], $factureArray['close_note']); - } - } - if ($factureArray['status'] == Facture::STATUS_CLOSED) - { - if ($dBFacture->statut != Facture::STATUS_CLOSED) - { - // Enter payments - //$dBFacture->cloture($this->user); - $payment = new Paiement($this->db); - /* - $payment->datepaye = 'ee'; - $payment->paiementid = 0; - $payment->num_paiement = 0; - $payment->amounts=array(); - $resultpayment = $payment->create($user); - if ($resultpayment < 0) - { - $error++; - $this->errors[] = "Failed to create payment"; - } - */ - - $dBFacture->set_paid($this->user, '', ''); - } - } - - } - - } - else - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorFactureSynchExistsButNotFacture'); - break; - } - } - else - { - //create invoice - - // If we create invoice, we can force status of order in some cases - if ($refCommandeExists > 0 && $dBCommande->statut == Commande::STATUS_DRAFT) - { - $idWareHouse = 0; - // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync - //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; - $dBCommande->valid($this->user, $idWareHouse); - } - if ($refCommandeExists > 0 && $dBCommande->statut == Commande::STATUS_VALIDATED) - { - $dBCommande->cloture($this->user); - } - //var_dump($factureArray);exit; - - - $settlementTermsId = $this->getSettlementTermsId($factureArray['code_cond_reglement']); - - // First, we check object does not alreay exists. If not, we create it, if it exists, do nothing. - $result = $dBFacture->fetch(0, '', $this->eCommerceSite->name.'-'.$factureArray['remote_id']); - if ($result == 0) - { - $origin = 'commande'; - $originid = $dBCommande->id; - - $dBFacture->ref_client = $factureArray['ref_client']; - $dBFacture->ref_ext = $this->eCommerceSite->name.'-'.$factureArray['remote_id']; - $dBFacture->date = strtotime($factureArray['date']); - $dBFacture->socid = $this->eCommerceSociete->fk_societe; - $dBFacture->cond_reglement_id = $settlementTermsId; - $dBFacture->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; - $dBFacture->note_private=""; - if (! empty($conf->global->ECOMMERCENG_ENABLE_LOG_IN_NOTE)) - { - $dBFacture->note_private .= "Last eCommerce invoice received:\n".dol_trunc(serialize(var_export($factureArray['remote_invoice'], true)), 65000); - $dBFacture->note_private .= "\n\n"; - $dBFacture->note_private .= "Last eCommerce order received:\n".dol_trunc(serialize(var_export($factureArray['remote_order'], true)), 65000); - } - - // Add link to order (cut takenf from facture card page) - $dBFacture->origin = $origin; - $dBFacture->origin_id = $originid; - $dBFacture->linked_objects[$dBFacture->origin] = $dBFacture->origin_id; + $counter = 0; + foreach ($factures as $factureArray) { + dol_syslog("- Process synch of invoice with remote_order_id=" . $factureArray['remote_order_id']); + + $counter++; + if ($toNb > 0 && $counter > $toNb) break; + + $this->db->begin(); + + $this->initECommerceCommande(); + $this->initECommerceFacture(); + $this->initECommerceSociete(); + + $dBFacture = new Facture($this->db); + $dBCommande = new Commande($this->db); + $dBExpedition = new Expedition($this->db); + + //check if commande exists in eCommerceCommande (with remote_order_id) + $synchCommandeExists = $this->eCommerceCommande->fetchByRemoteId($factureArray['remote_order_id'], $this->eCommerceSite->id); + + //check if ref exists in commande + $refCommandeExists = $dBCommande->fetch($this->eCommerceCommande->fk_commande); + + //check if societe exists in eCommerceSociete (with remote id). This init ->fk_societe. This is a sql request. + //$societeExists will be 1 (found) or -1 (not found) + if (!empty($factureArray['remote_id_societe'])) // May be empty if customer is a non logged user or was deleted on magento side. + { + $societeExists = $this->eCommerceSociete->fetchByRemoteId($factureArray['remote_id_societe'], $this->eCommerceSite->id); + } else { + // This is an unknown customer. May be a non logged customer. + if ($this->eCommerceSite->fk_anonymous_thirdparty > 0) { + $societeExists = 1; + $this->eCommerceSociete->fk_societe = $this->eCommerceSite->fk_anonymous_thirdparty; + } else { + $societeExists = 0; + } + } + + //if societe and commande exists start + if ($societeExists > 0 && $synchCommandeExists > 0) { + //check if facture exists in eCommerceFacture (with remote id) + $synchFactureExists = $this->eCommerceFacture->fetchByRemoteId($factureArray['remote_id'], $this->eCommerceSite->id); + if ($synchFactureExists > 0) { + //check if facture exists in facture + $refFactureExists = $dBFacture->fetch($this->eCommerceFacture->fk_facture); + if ($refFactureExists > 0) { + //update + if ($dBFacture->statut != $factureArray['status']) { + dol_syslog("Status of invoice has changed, we update invoice from status " . $dBFacture->statut . " to status " . $factureArray['status']); + + // Draft or not draft + if ($factureArray['status'] == Facture::STATUS_DRAFT) // status draft. Should not happen with magento + { + // Target status is status draft. Should not happen with magento. + // Nothing to do + } else { + // Target status is not draft. We validate if current status is still draft to get correct ref. + if ($dBFacture->statut == Facture::STATUS_DRAFT) { + $idWareHouse = 0; + // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync + //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; + $dBFacture->validate($this->user, '', $idWareHouse); + } + } + + // Which target status ? + if ($factureArray['status'] == Facture::STATUS_VALIDATED) { + if ($dBFacture->statut != Facture::STATUS_VALIDATED) { + $dBFacture->setStatut(Facture::STATUS_VALIDATED, $dBFacture->id, $dBFacture->table_element); + } + } + if ($factureArray['status'] == Facture::STATUS_ABANDONED) { + if ($dBFacture->statut != Facture::STATUS_ABANDONED) { + $dBFacture->set_canceled($this->user, $factureArray['close_code'], $factureArray['close_note']); + } + } + if ($factureArray['status'] == Facture::STATUS_CLOSED) { + if ($dBFacture->statut != Facture::STATUS_CLOSED) { + // Enter payments + //$dBFacture->cloture($this->user); + $payment = new Paiement($this->db); + /* + $payment->datepaye = 'ee'; + $payment->paiementid = 0; + $payment->num_paiement = 0; + $payment->amounts=array(); + $resultpayment = $payment->create($user); + if ($resultpayment < 0) + { + $error++; + $this->errors[] = "Failed to create payment"; + } + */ + + $dBFacture->set_paid($this->user, '', ''); + } + } + + } + + } else { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorFactureSynchExistsButNotFacture'); + break; + } + } else { + //create invoice + + // If we create invoice, we can force status of order in some cases + if ($refCommandeExists > 0 && $dBCommande->statut == Commande::STATUS_DRAFT) { + $idWareHouse = 0; + // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync + //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; + $dBCommande->valid($this->user, $idWareHouse); + } + if ($refCommandeExists > 0 && $dBCommande->statut == Commande::STATUS_VALIDATED) { + $dBCommande->cloture($this->user); + } + //var_dump($factureArray);exit; + + + $settlementTermsId = $this->getSettlementTermsId($factureArray['code_cond_reglement']); + + // First, we check object does not alreay exists. If not, we create it, if it exists, do nothing. + $result = $dBFacture->fetch(0, '', $this->eCommerceSite->name . '-' . $factureArray['remote_id']); + if ($result == 0) { + $origin = 'commande'; + $originid = $dBCommande->id; + + $dBFacture->ref_client = $factureArray['ref_client']; + $dBFacture->ref_ext = $this->eCommerceSite->name . '-' . $factureArray['remote_id']; + $dBFacture->date = strtotime($factureArray['date']); + $dBFacture->socid = $this->eCommerceSociete->fk_societe; + $dBFacture->cond_reglement_id = $settlementTermsId; + $dBFacture->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; + $dBFacture->note_private = ""; + if (!empty($conf->global->ECOMMERCENG_ENABLE_LOG_IN_NOTE)) { + $dBFacture->note_private .= "Last eCommerce invoice received:\n" . dol_trunc(serialize(var_export($factureArray['remote_invoice'], true)), 65000); + $dBFacture->note_private .= "\n\n"; + $dBFacture->note_private .= "Last eCommerce order received:\n" . dol_trunc(serialize(var_export($factureArray['remote_order'], true)), 65000); + } + + // Add link to order (cut takenf from facture card page) + $dBFacture->origin = $origin; + $dBFacture->origin_id = $originid; + $dBFacture->linked_objects[$dBFacture->origin] = $dBFacture->origin_id; $dBFacture->array_options = $this->getDefaultExtraFields($dBFacture->table_element, $this->eCommerceSite); - // Now we create invoice - $result = $dBFacture->create($this->user); - - //add or update contacts of invoice - $factureArray['socpeopleLivraison']['fk_soc'] = $this->eCommerceSociete->fk_societe; - $factureArray['socpeopleFacture']['fk_soc'] = $this->eCommerceSociete->fk_societe; - - $socpeopleLivraisonId = $this->synchSocpeople($factureArray['socpeopleLivraison']); - $socpeopleFactureId = $this->synchSocpeople($factureArray['socpeopleFacture']); - - if ($socpeopleLivraisonId > 0) - $dBFacture->add_contact($socpeopleLivraisonId, 'SHIPPING'); - if ($socpeopleFactureId > 0) - $dBFacture->add_contact($socpeopleFactureId, 'BILLING'); - - //add items - if (count($factureArray['items'])) - foreach ($factureArray['items'] as $item) - { - $this->initECommerceProduct(); - $this->eCommerceProduct->fetchByRemoteId($item['id_remote_product'], $this->eCommerceSite->id); - - // Define the buy price for margin calculation - $buyprice=0; - $fk_product = $this->eCommerceProduct->fk_product; - if (($result = $dBFacture->defineBuyPrice($item['price'], 0, $fk_product)) < 0) - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureUpdateError').' '.$dbFacture->error; - $this->errors = array_merge($this->errors, $dbFacture->errors); - break; // break items - } - else - { - $buyprice = $result; - } - $dBFacture->addline( - $item['description'], - $item['price'], - $item['qty'], - $item['tva_tx'], - 0, - 0, - $this->eCommerceProduct->fk_product, - 0, - '', //date_start - '', //date_end - 0, //ventil - 0, //info_bits - 0, //fk_remise_except - 'HT', - 0, //pu_ttc - 0, // FIXME Use type of article 0:product 1:service - 0, //rang - 0, //special code - '', // This field seems not used - 0, // This field seems not used - 0, //fk_parent_line - 0, //fk_fourn_price - $buyprice - ); - unset($this->eCommerceProduct); - } - - //add delivery - if (! $error && $factureArray['delivery']['qty'] > 0) - { - $delivery = $factureArray['delivery']; - - // TODO Get buy price depending on margin option. No margin on delivery line ? - $buyprice=0; - - $dBFacture->addline($delivery['description'], $delivery['price'], $delivery['qty'], $delivery['tva_tx'], 0, 0, 0, //fk_product - 0, //remise_percent - '', //date_start - '', //date_end - 0, //ventil - 0, //info_bits - 0, //fk_remise_except - 'HT', //price_base_type - 0, //pu_ttc - 1, //type 0:product 1:service - 0, //rang - 0, //special code - '', // origin - 0, // origin_id - 0, //fk_parent_line - 0, //fk_fourn_price - $buyprice - ); - } - } - - // Now update status - if (! $error) - { - //if ($dBFacture->statut != $factureArray['status']) // Always when creating - //{ - dol_syslog("synchFacture Status of invoice must be now set: we update invoice id=".$dBFacture->id." ref_client=".$dBFacture->ref_client." from status ".$dBFacture->statut." to status ".$factureArray['status']); - - // Draft or not draft - if ($factureArray['status'] == Facture::STATUS_DRAFT) // status draft. Should not happen with magento - { - // Target status is status draft. Should not happen with magento. - // Nothing to do - } - else - { - // Target status is not draft. We validate if current status is still draft to get correct ref. - if ($dBFacture->statut == Facture::STATUS_DRAFT) - { - $idWareHouse = 0; - // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync - //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; - $dBFacture->validate($this->user, '', $idWareHouse); - } - } - - // Which target status ? - if ($factureArray['status'] == Facture::STATUS_VALIDATED) - { - if ($dBFacture->statut != Facture::STATUS_VALIDATED) - { - $dBFacture->setStatut(Facture::STATUS_VALIDATED, $dBFacture->id, $dBFacture->table_element); - } - } - if ($factureArray['status'] == Facture::STATUS_ABANDONED) - { - if ($dBFacture->statut != Facture::STATUS_ABANDONED) - { - $dBFacture->set_canceled($this->user, $factureArray['close_code'], $factureArray['close_note']); - } - } - if ($factureArray['status'] == Facture::STATUS_CLOSED) - { - if ($dBFacture->statut != Facture::STATUS_CLOSED) - { - // Enter payment - // Magento seems to do one payment for one invoice - - $payment = new Paiement($this->db); - /* - $payment->datepaye = 'ee'; - $payment->paiementid = 0; - $payment->num_paiement = 0; - $payment->amounts=array(); - $resultpayment = $payment->create($user); - if ($resultpayment < 0) - { - $error++; - $this->errors[] = "Failed to create payment"; - $this->errors = array_merge($this->errors, $payment->errors); - } - */ - - //$factureArray['remote_order']["payment"] is one record with summ of different payments/invoices. - - //exit; - - $dBFacture->set_paid($this->user, '', ''); - } - } - - } - - } - - /* ************************************************************** - * - * register into eCommerceFacture - * - * ************************************************************** */ - //if synchro invoice ok - if (! $error) - { - $this->eCommerceFacture->last_update = $factureArray['last_update']; - $this->eCommerceFacture->fk_facture = $dBFacture->id; - //if a previous synchro exists - if ($synchFactureExists > 0) - { - //eCommerce update - if ($this->eCommerceFacture->update($this->user) < 0) - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureUpdateError').' '.$this->eCommerceFacture->error; - $this->errors = array_merge($this->errors, $this->eCommerceFacture->errors); - } - } - //if not previous synchro exists - else - { - // May be an old record with an old product removed on eCommerce still exists, we delete it before insert. - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_facture WHERE fk_facture=".$this->eCommerceFacture->fk_facture; - $resql = $this->db->query($sql); - - //eCommerce create - $this->eCommerceFacture->fk_site = $this->eCommerceSite->id; - $this->eCommerceFacture->remote_id = $factureArray['remote_id']; - if ($this->eCommerceFacture->create($this->user) < 0) - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureCreateError').' '.$dBFacture->id.', '.$this->eCommerceFacture->error; - $this->errors = array_merge($this->errors, $this->eCommerceFacture->errors); - dol_syslog($this->langs->trans('ECommerceSyncheCommerceFactureCreateError') . ' ' . $dBFacture->id.', '.$this->eCommerceFacture->error, LOG_WARNING); - } - } - } - else - { - $error++; - $this->errors[] = $this->langs->trans('ECommerceSynchCommandeError'); - } - } - else - { - $error++; - if ($societeExists <= 0) - { - $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorSocieteNotExists', $factureArray['remote_id_societe']); - } - if ($synchCommandeExists <= 0) - { - $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorCommandeNotExists', $factureArray['remote_order_id']); - } - } - - unset($dBFacture); - unset($dBCommande); - unset($dBExpedition); - unset($this->eCommerceSociete); - unset($this->eCommerceFacture); - unset($this->eCommerceCommande); - - if ($error || ! empty($this->errors)) - { - $this->db->rollback(); - $nbrecorderror++; - break; // We decide to stop on first error - } - else - { - $this->db->commit(); - $nbgoodsunchronize = $nbgoodsunchronize + 1; - } - } + // Now we create invoice + $result = $dBFacture->create($this->user); + + //add or update contacts of invoice + $factureArray['socpeopleLivraison']['fk_soc'] = $this->eCommerceSociete->fk_societe; + $factureArray['socpeopleFacture']['fk_soc'] = $this->eCommerceSociete->fk_societe; + + $socpeopleLivraisonId = $this->synchSocpeople($factureArray['socpeopleLivraison']); + $socpeopleFactureId = $this->synchSocpeople($factureArray['socpeopleFacture']); + + if ($socpeopleLivraisonId > 0) + $dBFacture->add_contact($socpeopleLivraisonId, 'SHIPPING'); + if ($socpeopleFactureId > 0) + $dBFacture->add_contact($socpeopleFactureId, 'BILLING'); + + //add items + if (count($factureArray['items'])) + foreach ($factureArray['items'] as $item) { + $this->initECommerceProduct(); + $this->eCommerceProduct->fetchByRemoteId($item['id_remote_product'], $this->eCommerceSite->id); + + // Define the buy price for margin calculation + $buyprice = 0; + $fk_product = $this->eCommerceProduct->fk_product; + if (($result = $dBFacture->defineBuyPrice($item['price'], 0, $fk_product)) < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureUpdateError') . ' ' . $dBFacture->error; + $this->errors = array_merge($this->errors, $dBFacture->errors); + break; // break items + } else { + $buyprice = $result; + } + $dBFacture->addline( + $item['description'], + $item['price'], + $item['qty'], + $item['tva_tx'], + 0, + 0, + $this->eCommerceProduct->fk_product, + 0, + '', //date_start + '', //date_end + 0, //ventil + 0, //info_bits + 0, //fk_remise_except + 'HT', + 0, //pu_ttc + 0, // FIXME Use type of article 0:product 1:service + 0, //rang + 0, //special code + '', // This field seems not used + 0, // This field seems not used + 0, //fk_parent_line + 0, //fk_fourn_price + $buyprice + ); + unset($this->eCommerceProduct); + } + + //add delivery + if (!$error && $factureArray['delivery']['qty'] > 0) { + $delivery = $factureArray['delivery']; + + // TODO Get buy price depending on margin option. No margin on delivery line ? + $buyprice = 0; + + $dBFacture->addline($delivery['description'], $delivery['price'], $delivery['qty'], $delivery['tva_tx'], 0, 0, 0, //fk_product + 0, //remise_percent + '', //date_start + '', //date_end + 0, //ventil + 0, //info_bits + 0, //fk_remise_except + 'HT', //price_base_type + 0, //pu_ttc + 1, //type 0:product 1:service + 0, //rang + 0, //special code + '', // origin + 0, // origin_id + 0, //fk_parent_line + 0, //fk_fourn_price + $buyprice + ); + } + } + + // Now update status + if (!$error) { + //if ($dBFacture->statut != $factureArray['status']) // Always when creating + //{ + dol_syslog("synchFacture Status of invoice must be now set: we update invoice id=" . $dBFacture->id . " ref_client=" . $dBFacture->ref_client . " from status " . $dBFacture->statut . " to status " . $factureArray['status']); + + // Draft or not draft + if ($factureArray['status'] == Facture::STATUS_DRAFT) // status draft. Should not happen with magento + { + // Target status is status draft. Should not happen with magento. + // Nothing to do + } else { + // Target status is not draft. We validate if current status is still draft to get correct ref. + if ($dBFacture->statut == Facture::STATUS_DRAFT) { + $idWareHouse = 0; + // We don't change stock here, even if dolibarr option is on because, this should be already done by product sync + //if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $idWareHouse=$this->eCommerceSite->fk_warehouse; + $dBFacture->validate($this->user, '', $idWareHouse); + } + } + + // Which target status ? + if ($factureArray['status'] == Facture::STATUS_VALIDATED) { + if ($dBFacture->statut != Facture::STATUS_VALIDATED) { + $dBFacture->setStatut(Facture::STATUS_VALIDATED, $dBFacture->id, $dBFacture->table_element); + } + } + if ($factureArray['status'] == Facture::STATUS_ABANDONED) { + if ($dBFacture->statut != Facture::STATUS_ABANDONED) { + $dBFacture->set_canceled($this->user, $factureArray['close_code'], $factureArray['close_note']); + } + } + if ($factureArray['status'] == Facture::STATUS_CLOSED) { + if ($dBFacture->statut != Facture::STATUS_CLOSED) { + // Enter payment + // Magento seems to do one payment for one invoice + + $payment = new Paiement($this->db); + /* + $payment->datepaye = 'ee'; + $payment->paiementid = 0; + $payment->num_paiement = 0; + $payment->amounts=array(); + $resultpayment = $payment->create($user); + if ($resultpayment < 0) + { + $error++; + $this->errors[] = "Failed to create payment"; + $this->errors = array_merge($this->errors, $payment->errors); + } + */ + + //$factureArray['remote_order']["payment"] is one record with summ of different payments/invoices. + + //exit; + + $dBFacture->set_paid($this->user, '', ''); + } + } + + } + + } + + /* ************************************************************** + * + * register into eCommerceFacture + * + * ************************************************************** */ + //if synchro invoice ok + if (!$error) { + $this->eCommerceFacture->last_update = $factureArray['last_update']; + $this->eCommerceFacture->fk_facture = $dBFacture->id; + //if a previous synchro exists + if ($synchFactureExists > 0) { + //eCommerce update + if ($this->eCommerceFacture->update($this->user) < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureUpdateError') . ' ' . $this->eCommerceFacture->error; + $this->errors = array_merge($this->errors, $this->eCommerceFacture->errors); + } + } //if not previous synchro exists + else { + // May be an old record with an old product removed on eCommerce still exists, we delete it before insert. + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_facture WHERE fk_facture=" . $this->eCommerceFacture->fk_facture; + $resql = $this->db->query($sql); + + //eCommerce create + $this->eCommerceFacture->fk_site = $this->eCommerceSite->id; + $this->eCommerceFacture->remote_id = $factureArray['remote_id']; + if ($this->eCommerceFacture->create($this->user) < 0) { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSyncheCommerceFactureCreateError') . ' ' . $dBFacture->id . ', ' . $this->eCommerceFacture->error; + $this->errors = array_merge($this->errors, $this->eCommerceFacture->errors); + dol_syslog($this->langs->trans('ECommerceSyncheCommerceFactureCreateError') . ' ' . $dBFacture->id . ', ' . $this->eCommerceFacture->error, LOG_WARNING); + } + } + } else { + $error++; + $this->errors[] = $this->langs->trans('ECommerceSynchCommandeError'); + } + } else { + $error++; + if ($societeExists <= 0) { + $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorSocieteNotExists', $factureArray['remote_id_societe']); + } + if ($synchCommandeExists <= 0) { + $this->errors[] = $this->langs->trans('ECommerceSynchFactureErrorCommandeNotExists', $factureArray['remote_order_id']); + } + } + + unset($dBFacture); + unset($dBCommande); + unset($dBExpedition); + unset($this->eCommerceSociete); + unset($this->eCommerceFacture); + unset($this->eCommerceCommande); + + if ($error || !empty($this->errors)) { + $this->db->rollback(); + $nbrecorderror++; + break; // We decide to stop on first error + } else { + $this->db->commit(); + $nbgoodsunchronize = $nbgoodsunchronize + 1; + } + } - if (! $error) - { - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchFactureSuccess'); + if (!$error) { + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchFactureSuccess'); - // TODO If we commit even if there was an error (to validate previous record ok), we must also remove 1 second the the higher - // date into table of links to be sure we will retry also record with same update_at than the last record ok + // TODO If we commit even if there was an error (to validate previous record ok), we must also remove 1 second the the higher + // date into table of links to be sure we will retry also record with same update_at than the last record ok - return $nbgoodsunchronize; - } - else - { - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchFactureSuccess'); + return $nbgoodsunchronize; + } else { + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchFactureSuccess'); - return -1; - } - } - else - { - $this->error=$this->langs->trans('ECommerceErrorsynchFacture').' (Code FailToGetDetailsOfRecord)'; - $this->errors[] = $this->error; - } - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorsynchFacture').': '.$e->getMessage(); - } + return -1; + } + } else { + $this->error = $this->langs->trans('ECommerceErrorsynchFacture') . ' (Code FailToGetDetailsOfRecord)'; + $this->errors[] = $this->error; + } + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorsynchFacture') . ': ' . $e->getMessage(); + } - return -1; - } + return -1; + } - /** - * Synchronize shipment - * - * @param Shipment $livraison Shipment object - * @param int $remote_order_id Remote id of order - * @return bool true or false - */ - public function synchLivraison($livraison, $remote_order_id) - { - $error = 0; + /** + * Synchronize shipment + * + * @param Shipment $livraison Shipment object + * @param int $remote_order_id Remote id of order + * @return bool true or false + */ + public function synchLivraison($livraison, $remote_order_id) + { + $error = 0; - try { - dol_syslog("***** eCommerceSynchro syncLivraison"); + try { + dol_syslog("***** eCommerceSynchro syncLivraison"); - return $this->eCommerceRemoteAccess->createRemoteLivraison($livraison, $remote_order_id); - } catch (Exception $e) { - $this->errors[] = $this->langs->trans('ECommerceErrorrCeateRemoteLivraison').': '.$e->getMessage(); - } - return false; - } + return $this->eCommerceRemoteAccess->createRemoteLivraison($livraison, $remote_order_id); + } catch (Exception $e) { + $this->errors[] = $this->langs->trans('ECommerceErrorrCeateRemoteLivraison') . ': ' . $e->getMessage(); + } + return false; + } - /** - * Sync categories from Dolibarr to ECommerce - * - * @param int $toNb Max nb to synch - * @return int <0 if KO, >= 0 if ok - */ - public function synchDtoECategory($toNb=0) - { - global $user; + /** + * Sync categories from Dolibarr to ECommerce + * + * @param int $toNb Max nb to synch + * @return int <0 if KO, >= 0 if ok + */ + public function synchDtoECategory($toNb=0) + { + global $user; - $error = 0; - $nbgoodsunchronize = 0; + $error = 0; + $nbgoodsunchronize = 0; - dol_syslog("***** eCommerceSynchro synchDtoECategory"); + dol_syslog("***** eCommerceSynchro synchDtoECategory"); $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__ . " - toNb: {$toNb}"); - $this->initECommerceCategory(); // Initialise 2 properties eCommerceCategory and eCommerceMotherCategory + $this->initECommerceCategory(); // Initialise 2 properties eCommerceCategory and eCommerceMotherCategory - $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); - $categories = $this->cache_categories['product']; + $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); + $categories = $this->cache_categories['product']; - $already_synch = array(); - $sql="SELECT fk_category FROM ".MAIN_DB_PREFIX."ecommerce_category WHERE type = 0 AND fk_site=".$this->eCommerceSite->id; - $resql=$this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $already_synch[] = $obj->fk_category; - } - } else { - $error_msg = $this->langs->trans('ECommerceErrorGetCategoryIdsAlreadyLinked', $this->eCommerceSite->name, $this->db->lasterror()); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_WARNING); + $already_synch = array(); + $sql = "SELECT fk_category FROM " . MAIN_DB_PREFIX . "ecommerce_category WHERE type = 0 AND fk_site=" . $this->eCommerceSite->id; + $resql = $this->db->query($sql); + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + $already_synch[] = $obj->fk_category; + } + } else { + $error_msg = $this->langs->trans('ECommerceErrorGetCategoryIdsAlreadyLinked', $this->eCommerceSite->name, $this->db->lasterror()); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_WARNING); eCommerceUtils::stopAndLogStopwatch($stopwatch_id); return -1; - } + } - $index = 0; - $group = array(); - foreach ($categories as $cat_id => $category) { - if (in_array($cat_id, $already_synch)) continue; + $index = 0; + $group = array(); + foreach ($categories as $cat_id => $category) { + if (in_array($cat_id, $already_synch)) continue; - $index++; - $group[$cat_id] = $category; - if ($index == $toNb) { - break; - } - } + $index++; + $group[$cat_id] = $category; + if ($index == $toNb) { + break; + } + } - $cats_id_remote_id = $this->eCommerceRemoteAccess->createRemoteCategories($group); - $now = dol_now(); - if ($cats_id_remote_id === false || !empty($this->errors)) { - $error++; - } + $cats_id_remote_id = $this->eCommerceRemoteAccess->createRemoteCategories($group); + $now = dol_now(); + if ($cats_id_remote_id === false || !empty($this->errors)) { + $error++; + } - if (is_array($cats_id_remote_id) && count($cats_id_remote_id)) { - foreach ($cats_id_remote_id as $cat_id => $remote_ids) { - if ($this->eCommerceCategory->fetchByFKCategory($cat_id, $this->eCommerceSite->id) > 0) { - $this->eCommerceCategory->delete($user); - } + if (is_array($cats_id_remote_id) && count($cats_id_remote_id)) { + foreach ($cats_id_remote_id as $cat_id => $remote_ids) { + if ($this->eCommerceCategory->fetchByFKCategory($cat_id, $this->eCommerceSite->id) > 0) { + $this->eCommerceCategory->delete($user); + } - // Create remote link - $category = $categories[$cat_id]; - $this->eCommerceCategory->label = $category['label']; - $this->eCommerceCategory->type = 0; // product - $this->eCommerceCategory->description = $category['description']; - $this->eCommerceCategory->fk_category = $cat_id; - $this->eCommerceCategory->fk_site = $this->eCommerceSite->id; - $this->eCommerceCategory->remote_id = $remote_ids['remote_id']; - $this->eCommerceCategory->remote_parent_id = $remote_ids['remote_parent_id']; - $this->eCommerceCategory->last_update = dol_print_date($now, '%Y-%m-%d %H:%M:%S'); - $res = $this->eCommerceCategory->create($user); - if ($res < 0) { - $error++; - $error_msg = $this->langs->trans('ECommerceCreateRemoteCategoryLink', $cat_id, $this->eCommerceSite->name, $this->eCommerceCategory->error); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_WARNING); - } else { - $nbgoodsunchronize++; - } - } - } + // Create remote link + $category = $categories[$cat_id]; + $this->eCommerceCategory->label = $category['label']; + $this->eCommerceCategory->type = 0; // product + $this->eCommerceCategory->description = $category['description']; + $this->eCommerceCategory->fk_category = $cat_id; + $this->eCommerceCategory->fk_site = $this->eCommerceSite->id; + $this->eCommerceCategory->remote_id = $remote_ids['remote_id']; + $this->eCommerceCategory->remote_parent_id = $remote_ids['remote_parent_id']; + $this->eCommerceCategory->last_update = dol_print_date($now, '%Y-%m-%d %H:%M:%S'); + $res = $this->eCommerceCategory->create($user); + if ($res < 0) { + $error++; + $error_msg = $this->langs->trans('ECommerceCreateRemoteCategoryLink', $cat_id, $this->eCommerceSite->name, $this->eCommerceCategory->error); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_WARNING); + } else { + $nbgoodsunchronize++; + } + } + } - if ($nbgoodsunchronize > 0) { - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); - } + if ($nbgoodsunchronize > 0) { + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchCategorySuccess'); + } eCommerceUtils::stopAndLogStopwatch($stopwatch_id); if (!$error) { - return $nbgoodsunchronize; - } else { - return -1; - } - } + return $nbgoodsunchronize; + } else { + return -1; + } + } - /** - * Synchronize product from Dolibarr to ECommerce - * - * @param int $toNb Max nb to synch - * @return int <0 if KO, >= 0 if ok - */ - public function synchDtoEProduct($toNb=0) - { - global $conf, $langs, $user; + /** + * Synchronize product from Dolibarr to ECommerce + * + * @param int $toNb Max nb to synch + * @return int <0 if KO, >= 0 if ok + */ + public function synchDtoEProduct($toNb=0) + { + global $conf, $langs, $user; $langs->load('ecommerceng@ecommerceng'); - $error = 0; - $nbgoodsunchronize = 0; + $error = 0; + $nbgoodsunchronize = 0; - dol_syslog("***** eCommerceSynchro synchDtoEProduct"); + dol_syslog("***** eCommerceSynchro synchDtoEProduct"); $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__ . " - toNb: {$toNb}"); - $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); - $cats_id = array_keys($this->cache_categories['product']); + $this->fetch_categories('product', $this->eCommerceSite->fk_cat_product); + $cats_id = array_keys($this->cache_categories['product']); - $sql = "SELECT DISTINCT p.rowid, IFNULL(ep.remote_id, '') as remote_id FROM " . MAIN_DB_PREFIX . "product as p" . - " INNER JOIN " . MAIN_DB_PREFIX . "categorie_product as cp ON p.rowid = cp.fk_product AND cp.fk_categorie IN (" . implode(',', $cats_id) . ")" . - " LEFT JOIN " . MAIN_DB_PREFIX . "ecommerce_product as ep ON p.rowid = ep.fk_product AND ep.fk_site=" . $this->eCommerceSite->id . - " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as pf ON pf.fk_object = p.rowid" . + $sql = "SELECT DISTINCT p.rowid, IFNULL(ep.remote_id, '') as remote_id FROM " . MAIN_DB_PREFIX . "product as p" . + " INNER JOIN " . MAIN_DB_PREFIX . "categorie_product as cp ON p.rowid = cp.fk_product AND cp.fk_categorie IN (" . implode(',', $cats_id) . ")" . + " LEFT JOIN " . MAIN_DB_PREFIX . "ecommerce_product as ep ON p.rowid = ep.fk_product AND ep.fk_site=" . $this->eCommerceSite->id . + " LEFT JOIN " . MAIN_DB_PREFIX . "product_extrafields as pf ON pf.fk_object = p.rowid" . " WHERE (ep.rowid IS NULL OR ep.last_update < p.tms OR (pf.tms IS NOT NULL AND ep.last_update < pf.tms))" . " AND p.entity IN (" . getEntity('product') . ")"; $resql = $this->db->query($sql); - if ($resql) { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + if ($resql) { + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; $product_static = new Product($this->db); $ec_price_entities = explode(',', getEntity('productprice')); @@ -2020,8 +1857,8 @@ public function synchDtoEProduct($toNb=0) $this->error = $this->eCommerceRemoteAccess->error; $this->errors = $this->eCommerceRemoteAccess->errors; } else { - $remote_id = $result['remote_id']; - $remote_language = $result['language']; + $remote_id = $result['remote_id']; + $remote_language = $result['language']; $product_static->url = $result['remote_url']; $product_static->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; @@ -2038,8 +1875,8 @@ public function synchDtoEProduct($toNb=0) if (!$error) { $this->eCommerceProduct->remote_id = $remote_id; $this->eCommerceProduct->fk_site = $this->eCommerceSite->id; - $this->eCommerceProduct->fk_product = $product_static->id; - $this->eCommerceProduct->lang = $remote_language; + $this->eCommerceProduct->fk_product = $product_static->id; + $this->eCommerceProduct->lang = $remote_language; $this->eCommerceProduct->last_update = dol_print_date($now, '%Y-%m-%d %H:%M:%S'); if ($this->eCommerceSite->stock_sync_direction == 'dolibarr2ecommerce') $this->eCommerceProduct->last_update_stock = $this->eCommerceProduct->last_update; if ($this->eCommerceProduct->create($user) < 0) { @@ -2084,36 +1921,35 @@ public function synchDtoEProduct($toNb=0) } if ($nbgoodsunchronize > 0) { - $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchProductSuccess'); - } + $this->success[] = $nbgoodsunchronize . ' ' . $this->langs->trans('ECommerceSynchProductSuccess'); + } eCommerceUtils::stopAndLogStopwatch($stopwatch_id); - if (!$error) { - return $nbgoodsunchronize; - } else { - return -1; - } - } else { - $this->error = $this->db->lasterror(); + if (!$error) { + return $nbgoodsunchronize; + } else { + return -1; + } + } else { + $this->error = $this->db->lasterror(); eCommerceUtils::stopAndLogStopwatch($stopwatch_id); - return -1; - } - } - + return -1; + } + } - /** - * Return dictionnary entry for a code - * - * @param string $code Code of payment term - * @return mixed Record - */ + /** + * Return dictionnary entry for a code + * + * @param string $code Code of payment term + * @return mixed Record + */ public function getSettlementTermsId($code) - { - $table = MAIN_DB_PREFIX . "c_payment_term"; - $eCommerceDict = new eCommerceDict($this->db, $table); - $settlementTerms = $eCommerceDict->fetchByCode($code); - return $settlementTerms['rowid']; - } + { + $table = MAIN_DB_PREFIX . "c_payment_term"; + $eCommerceDict = new eCommerceDict($this->db, $table); + $settlementTerms = $eCommerceDict->fetchByCode($code); + return $settlementTerms['rowid']; + } /*private function getAnonymousConstValue() { @@ -2164,109 +2000,98 @@ public function getSettlementTermsId($code) } }*/ - /** - * Delete any data linked to synchronization, then delete synchro's datas to clean sync - * - * @param int $deletealsoindolibarr 0=Delete only link table, 1=Delete also record in dolibarr - * @param string $mode '' to delete all, 'categories', 'products', 'thirdparties', 'orders', 'invoices' - * @return void - */ - public function dropImportedAndSyncData($deletealsoindolibarr, $mode='') - { - global $conf; - dol_syslog("***** eCommerceSynchro dropImportedAndSyncData"); + /** + * Delete any data linked to synchronization, then delete synchro's datas to clean sync + * + * @param int $deletealsoindolibarr 0=Delete only link table, 1=Delete also record in dolibarr + * @param string $mode '' to delete all, 'categories', 'products', 'thirdparties', 'orders', 'invoices' + * @return void + */ + public function dropImportedAndSyncData($deletealsoindolibarr, $mode='') + { + global $conf; + dol_syslog("***** eCommerceSynchro dropImportedAndSyncData"); $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__ . " - mode: {$mode}"); - // Drop invoices - if (empty($mode) || preg_match('/^invoices/', $mode)) - { - $dolObjectsDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceFacture(); - $arrayECommerceFactureIds = $this->eCommerceFacture->getAllECommerceFactureIds($this->eCommerceSite->id); + // Drop invoices + if (empty($mode) || preg_match('/^invoices/', $mode)) { + $dolObjectsDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceFacture(); + $arrayECommerceFactureIds = $this->eCommerceFacture->getAllECommerceFactureIds($this->eCommerceSite->id); - $this->db->begin(); + $this->db->begin(); - foreach ($arrayECommerceFactureIds as $idFacture) - { - $this->initECommerceFacture(); - if ($this->eCommerceFacture->fetch($idFacture) > 0) - { - if ($deletealsoindolibarr) - { - $dbFacture = new Facture($this->db); - if ($dbFacture->fetch($this->eCommerceFacture->fk_facture) > 0) - { - $idWarehouse = 0; - // We don't change stock here, it's a clean of database that don't change stock - if ((float) DOL_VERSION < 5.0) $resultdelete = $dbFacture->delete($dbFacture->id, 0, $idWarehouse); - else $resultdelete = $dbFacture->delete($this->user, 0, $idWarehouse); - - if ($resultdelete > 0) - $dolObjectsDeleted++; - } - } - if ($this->eCommerceFacture->delete($this->user) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceFactureIds as $idFacture) { + $this->initECommerceFacture(); + if ($this->eCommerceFacture->fetch($idFacture) > 0) { + if ($deletealsoindolibarr) { + $dbFacture = new Facture($this->db); + if ($dbFacture->fetch($this->eCommerceFacture->fk_facture) > 0) { + $idWarehouse = 0; + // We don't change stock here, it's a clean of database that don't change stock + if ((float)DOL_VERSION < 5.0) $resultdelete = $dbFacture->delete($dbFacture->id, 0, $idWarehouse); + else $resultdelete = $dbFacture->delete($this->user, 0, $idWarehouse); + + if ($resultdelete > 0) + $dolObjectsDeleted++; + } + } + if ($this->eCommerceFacture->delete($this->user) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolFactureSuccess'); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchFactureSuccess'); - unset($this->eCommerceFacture); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolFactureSuccess'); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchFactureSuccess'); + unset($this->eCommerceFacture); - $this->db->commit(); - } + $this->db->commit(); + } - //Drop commands - if (empty($mode) || preg_match('/^orders/', $mode)) - { - $dolObjectsDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceCommande(); - $arrayECommerceCommandeIds = $this->eCommerceCommande->getAllECommerceCommandeIds($this->eCommerceSite->id); + //Drop commands + if (empty($mode) || preg_match('/^orders/', $mode)) { + $dolObjectsDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceCommande(); + $arrayECommerceCommandeIds = $this->eCommerceCommande->getAllECommerceCommandeIds($this->eCommerceSite->id); - $this->db->begin(); + $this->db->begin(); - foreach ($arrayECommerceCommandeIds as $idCommande) - { - $this->initECommerceCommande(); - if ($this->eCommerceCommande->fetch($idCommande) > 0) - { - if ($deletealsoindolibarr) - { - $dbCommande = new Commande($this->db); - if ($dbCommande->fetch($this->eCommerceCommande->fk_commande) > 0) - { - $resultdelete = $dbCommande->delete($this->user); - if ($resultdelete > 0) - $dolObjectsDeleted++; - } - } - if ($this->eCommerceCommande->delete($this->user) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceCommandeIds as $idCommande) { + $this->initECommerceCommande(); + if ($this->eCommerceCommande->fetch($idCommande) > 0) { + if ($deletealsoindolibarr) { + $dbCommande = new Commande($this->db); + if ($dbCommande->fetch($this->eCommerceCommande->fk_commande) > 0) { + $resultdelete = $dbCommande->delete($this->user); + if ($resultdelete > 0) + $dolObjectsDeleted++; + } + } + if ($this->eCommerceCommande->delete($this->user) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolCommandeSuccess'); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchCommandeSuccess'); - unset($this->eCommerceCommande); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolCommandeSuccess'); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchCommandeSuccess'); + unset($this->eCommerceCommande); - $this->db->commit(); - } + $this->db->commit(); + } - //Drop products - if (empty($mode) || preg_match('/^products/', $mode)) - { - $dolObjectsDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceProduct(); - $arrayECommerceProductIds = $this->eCommerceProduct->getAllECommerceProductIds($this->eCommerceSite->id); + //Drop products + if (empty($mode) || preg_match('/^products/', $mode)) { + $dolObjectsDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceProduct(); + $arrayECommerceProductIds = $this->eCommerceProduct->getAllECommerceProductIds($this->eCommerceSite->id); - $this->db->begin(); + $this->db->begin(); - // Remove all categories of the ecommerce on the products + // Remove all categories of the ecommerce on the products if (empty($conf->global->ECOMMERCE_DONT_UNSET_CATEGORIE_OF_PRODUCT_WHEN_DELINK)) { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; $c = new Categorie($this->db); @@ -2294,178 +2119,157 @@ public function dropImportedAndSyncData($deletealsoindolibarr, $mode='') } } - foreach ($arrayECommerceProductIds as $idProduct) - { - $this->initECommerceProduct(); - if ($this->eCommerceProduct->fetch($idProduct) > 0) - { - if ($deletealsoindolibarr) - { - $dbProduct = new Product($this->db); - if ($dbProduct->fetch($this->eCommerceProduct->fk_product) > 0) - { - if ((float)DOL_VERSION < 6.0) { - $resultdelete = $dbProduct->delete(); - } else { - $resultdelete = $dbProduct->delete($this->user); - } - if ($resultdelete > 0) - $dolObjectsDeleted++; - } - } - - if ($this->eCommerceProduct->delete($this->user, 0) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceProductIds as $idProduct) { + $this->initECommerceProduct(); + if ($this->eCommerceProduct->fetch($idProduct) > 0) { + if ($deletealsoindolibarr) { + $dbProduct = new Product($this->db); + if ($dbProduct->fetch($this->eCommerceProduct->fk_product) > 0) { + if ((float)DOL_VERSION < 6.0) { + $resultdelete = $dbProduct->delete(); + } else { + $resultdelete = $dbProduct->delete($this->user); + } + if ($resultdelete > 0) + $dolObjectsDeleted++; + } + } + + if ($this->eCommerceProduct->delete($this->user, 0) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolProductSuccess'); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchProductSuccess'); - if ($synchCategoriesDeleted) $this->success[] = $synchCategoriesDeleted . ' ' . $this->langs->trans('ECommerceResetCategoriesProductSuccess'); - unset($this->eCommerceProduct); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolProductSuccess'); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchProductSuccess'); + if ($synchCategoriesDeleted) $this->success[] = $synchCategoriesDeleted . ' ' . $this->langs->trans('ECommerceResetCategoriesProductSuccess'); + unset($this->eCommerceProduct); - if ($error) { - $this->db->rollback(); - } else { - $this->db->commit(); - } - } + if ($error) { + $this->db->rollback(); + } else { + $this->db->commit(); + } + } - //Drop socPeople - if (empty($mode) || preg_match('/^thirdparties/', $mode)) -// if (empty($mode) || preg_match('/^contacts/', $mode)) - { - $dolObjectsDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceSocpeople(); - $arrayECommerceSocpeopleIds = $this->eCommerceSocpeople->getAllECommerceSocpeopleIds($this->eCommerceSite->id); + //Drop socPeople + if (empty($mode) || preg_match('/^thirdparties/', $mode)) // if (empty($mode) || preg_match('/^contacts/', $mode)) + { + $dolObjectsDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceSocpeople(); + $arrayECommerceSocpeopleIds = $this->eCommerceSocpeople->getAllECommerceSocpeopleIds($this->eCommerceSite->id); - $this->db->begin(); + $this->db->begin(); - foreach ($arrayECommerceSocpeopleIds as $idSocpeople) - { - $this->initECommerceSocpeople(); - if ($this->eCommerceSocpeople->fetch($idSocpeople) > 0) - { - if ($deletealsoindolibarr) - { - $dbSocpeople = new Contact($this->db); - if ($dbSocpeople->fetch($this->eCommerceSocpeople->fk_socpeople) > 0) - { - $resultdelete = $dbSocpeople->delete(0); - if ($resultdelete > 0) - $dolObjectsDeleted++; - } - } - if ($this->eCommerceSocpeople->delete($this->user, 0) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceSocpeopleIds as $idSocpeople) { + $this->initECommerceSocpeople(); + if ($this->eCommerceSocpeople->fetch($idSocpeople) > 0) { + if ($deletealsoindolibarr) { + $dbSocpeople = new Contact($this->db); + if ($dbSocpeople->fetch($this->eCommerceSocpeople->fk_socpeople) > 0) { + $resultdelete = $dbSocpeople->delete(0); + if ($resultdelete > 0) + $dolObjectsDeleted++; + } + } + if ($this->eCommerceSocpeople->delete($this->user, 0) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolSocpeopleSuccess'); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchSocpeopleSuccess'); - unset($this->eCommerceSocpeople); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolSocpeopleSuccess'); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchSocpeopleSuccess'); + unset($this->eCommerceSocpeople); - $this->db->commit(); - } + $this->db->commit(); + } - //Drop societes - if (empty($mode) || preg_match('/^thirdparties/', $mode)) - { - $dolObjectsDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceSociete(); - $arrayECommerceSocieteIds = $this->eCommerceSociete->getAllECommerceSocieteIds($this->eCommerceSite->id); + //Drop societes + if (empty($mode) || preg_match('/^thirdparties/', $mode)) { + $dolObjectsDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceSociete(); + $arrayECommerceSocieteIds = $this->eCommerceSociete->getAllECommerceSocieteIds($this->eCommerceSite->id); - $this->db->begin(); + $this->db->begin(); - foreach ($arrayECommerceSocieteIds as $idSociete) - { - $this->initECommerceSociete(); - if ($this->eCommerceSociete->fetch($idSociete) > 0) - { - // Skip anonymous thirdparty - if ($this->eCommerceSociete->remote_id == 0) continue; - - if ($deletealsoindolibarr) - { - $dbSociete = new Societe($this->db); - if ($dbSociete->fetch($this->eCommerceSociete->fk_societe) > 0) - { - $resultdelete = $dbSociete->delete($dbSociete->id, $this->user, 1); - if ($resultdelete > 0) - $dolObjectsDeleted++; - } - } - if ($this->eCommerceSociete->delete($this->user, 0, $this->eCommerceSite->name) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceSocieteIds as $idSociete) { + $this->initECommerceSociete(); + if ($this->eCommerceSociete->fetch($idSociete) > 0) { + // Skip anonymous thirdparty + if ($this->eCommerceSociete->remote_id == 0) continue; + + if ($deletealsoindolibarr) { + $dbSociete = new Societe($this->db); + if ($dbSociete->fetch($this->eCommerceSociete->fk_societe) > 0) { + $resultdelete = $dbSociete->delete($dbSociete->id, $this->user, 1); + if ($resultdelete > 0) + $dolObjectsDeleted++; + } + } + if ($this->eCommerceSociete->delete($this->user, 0, $this->eCommerceSite->name) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolSocieteSuccess'); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchSocieteSuccess'); - unset($this->eCommerceSociete); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolSocieteSuccess'); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchSocieteSuccess'); + unset($this->eCommerceSociete); - $this->db->commit(); - } + $this->db->commit(); + } - //Drop categories - if (empty($mode) || preg_match('/^categories/', $mode)) - { - $dolObjectsDeleted = 0; - $dolObjectsNotDeleted = 0; - $synchObjectsDeleted = 0; - $this->initECommerceCategory(); - $arrayECommerceCategoryIds = $this->eCommerceCategory->getAllECommerceCategoryIds($this->eCommerceSite); + //Drop categories + if (empty($mode) || preg_match('/^categories/', $mode)) { + $dolObjectsDeleted = 0; + $dolObjectsNotDeleted = 0; + $synchObjectsDeleted = 0; + $this->initECommerceCategory(); + $arrayECommerceCategoryIds = $this->eCommerceCategory->getAllECommerceCategoryIds($this->eCommerceSite); - $this->db->begin(); + $this->db->begin(); - foreach ($arrayECommerceCategoryIds as $idCategory) - { - $this->initECommerceCategory(); - if ($this->eCommerceCategory->fetch($idCategory) > 0) - { - if ($deletealsoindolibarr) - { - $dbCategory = new Categorie($this->db); - if ($dbCategory->fetch($this->eCommerceCategory->fk_category) > 0) - { - $resultdelete = $dbCategory->delete($this->user); - if ($resultdelete > 0) - $dolObjectsDeleted++; - else - $dolObjectsNotDeleted++; - } - } - if ($this->eCommerceCategory->delete($this->user, 0) > 0) - $synchObjectsDeleted++; - } - } + foreach ($arrayECommerceCategoryIds as $idCategory) { + $this->initECommerceCategory(); + if ($this->eCommerceCategory->fetch($idCategory) > 0) { + if ($deletealsoindolibarr) { + $dbCategory = new Categorie($this->db); + if ($dbCategory->fetch($this->eCommerceCategory->fk_category) > 0) { + $resultdelete = $dbCategory->delete($this->user); + if ($resultdelete > 0) + $dolObjectsDeleted++; + else + $dolObjectsNotDeleted++; + } + } + if ($this->eCommerceCategory->delete($this->user, 0) > 0) + $synchObjectsDeleted++; + } + } - if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolCategorySuccess').($dolObjectsNotDeleted?' ('.$dolObjectsNotDeleted.' ko)':''); - $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchCategorySuccess'); - unset($this->eCommerceCategory); + if ($deletealsoindolibarr) $this->success[] = $dolObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetDolCategorySuccess') . ($dolObjectsNotDeleted ? ' (' . $dolObjectsNotDeleted . ' ko)' : ''); + $this->success[] = $synchObjectsDeleted . ' ' . $this->langs->trans('ECommerceResetSynchCategorySuccess'); + unset($this->eCommerceCategory); - $this->db->commit(); - } + $this->db->commit(); + } eCommerceUtils::stopAndLogStopwatch($stopwatch_id); - } - + } public function __destruct() - { - unset($this->eCommerceRemoteAccess); - } - + { + unset($this->eCommerceRemoteAccess); + } - /** + /** * Function to check if a contact informations passed by params exists in DB. * * @param Contact $contact Object Contact * @return int <0 if KO, >0 id of first contact corresponding if OK */ - function getContactIdFromInfos($contact) + public function getContactIdFromInfos($contact) { global $conf; $contactId = -1; @@ -2499,7 +2303,7 @@ function getContactIdFromInfos($contact) if (isset($contact->phone_pro)) $sql .= ' AND phone LIKE "' . $this->db->escape($phone_pro) . '"'; if (isset($contact->fax)) $sql .= ' AND fax LIKE "' . $this->db->escape($fax) . '"'; if ($socid > 0) $sql .= ' AND fk_soc = "' . $this->db->escape($socid) . '"'; - else if ($socid == -1) $sql .= " AND fk_soc IS NULL"; + elseif ($socid == -1) $sql .= " AND fk_soc IS NULL"; $sql .= ' AND entity IN ('.getEntity('socpeople').')'; $resql = $this->db->query($sql); @@ -3250,7 +3054,7 @@ public function synchronizeProducts($from_date = null, $to_date = null, $remote_ break; } else { $nb_synchronized++; - if($result > 0) $nb_updated++; + if ($result > 0) $nb_updated++; } } } @@ -3329,7 +3133,7 @@ public function synchronizeProduct($product_data, $object_origin = null) $errors[] = $this->db->lasterror(); $error++; } else { - while($obj = $this->db->fetch_object($resql)) { + while ($obj = $this->db->fetch_object($resql)) { $result = $this->unlinkProduct($this->eCommerceSite->id, 0, $obj->remote_id); if ($result < 0) { $error++; @@ -3394,7 +3198,7 @@ public function synchronizeProduct($product_data, $object_origin = null) $errors[] = $this->db->lasterror(); $error++; } else { - while($obj = $this->db->fetch_object($resql)) { + while ($obj = $this->db->fetch_object($resql)) { $result = $this->unlinkProduct($this->eCommerceSite->id, 0, $obj->remote_id); if ($result < 0) { $error++; @@ -3608,7 +3412,7 @@ public function synchronizeProduct($product_data, $object_origin = null) if ($price_base_type_org != $price_base_type || $price_org != $product_data['price'] || (isset($product_data['price_min']) && $price_min_org != $product_data['price_min']) || - price2num((float)$product_data['tax_rate']) != price2num((float)$tax_rate_org) + price2num((float)$product_data['tax_rate']) != price2num((float) $tax_rate_org) ) { if ($product_data['price_min'] === '') { $product_data['price_min'] = $price_min_org <= $product_data['price'] ? $price_min_org : $product_data['price']; @@ -3634,67 +3438,67 @@ public function synchronizeProduct($product_data, $object_origin = null) $this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr' && !empty($product->array_options["options_ecommerceng_wc_manage_stock_{$this->eCommerceSite->id}_{$conf->entity}"]) && empty($product->array_options["options_ecommerceng_wc_dont_update_stock_{$this->eCommerceSite->id}_{$conf->entity}"]) ) { - $product->load_stock(); - - $new_warehouses_stock = array(); - if (!empty($this->eCommerceSite->parameters['enable_warehouse_plugin_support'])) { - dol_include_once('/ecommerceng/class/data/eCommerceRemoteWarehouses.class.php'); - $eCommerceRemoteWarehouses = new eCommerceRemoteWarehouses($this->db); - $remote_warehouses = $eCommerceRemoteWarehouses->get_all($this->eCommerceSite->id); - if (!is_array($remote_warehouses)) { - $error++; - $this->errors[] = $eCommerceRemoteWarehouses->errorsToString(); - } - - if (!$error && !empty($product_data['stock_by_warehouse'])) { - foreach ($product_data['stock_by_warehouse'] as $remote_warehouse_id => $stock) { - $local_warehouse_id = isset($remote_warehouses[$remote_warehouse_id]['warehouse_id']) && $remote_warehouses[$remote_warehouse_id]['warehouse_id'] > 0 ? $remote_warehouses[$remote_warehouse_id]['warehouse_id'] : 0; - if (empty($local_warehouse_id)) { + $product->load_stock(); + + $new_warehouses_stock = array(); + if (!empty($this->eCommerceSite->parameters['enable_warehouse_plugin_support'])) { + dol_include_once('/ecommerceng/class/data/eCommerceRemoteWarehouses.class.php'); + $eCommerceRemoteWarehouses = new eCommerceRemoteWarehouses($this->db); + $remote_warehouses = $eCommerceRemoteWarehouses->get_all($this->eCommerceSite->id); + if (!is_array($remote_warehouses)) { + $error++; + $this->errors[] = $eCommerceRemoteWarehouses->errorsToString(); + } + + if (!$error && !empty($product_data['stock_by_warehouse'])) { + foreach ($product_data['stock_by_warehouse'] as $remote_warehouse_id => $stock) { + $local_warehouse_id = isset($remote_warehouses[$remote_warehouse_id]['warehouse_id']) && $remote_warehouses[$remote_warehouse_id]['warehouse_id'] > 0 ? $remote_warehouses[$remote_warehouse_id]['warehouse_id'] : 0; + if (empty($local_warehouse_id)) { dol_syslog(__METHOD__ . ' Warehouse not configured for remote warehouse ID ' . $remote_warehouse_id . ' so we don\'t process this remote warehouse', LOG_WARNING); // $error++; // $this->errors[] = 'Error - Unknown remote warehouse : ' . $remote_warehouse_id; - } else { - $current_stock = isset($product->stock_warehouse[$local_warehouse_id]->real) ? $product->stock_warehouse[$local_warehouse_id]->real : 0; - $new_warehouses_stock[$local_warehouse_id] = price2num($stock - $current_stock); - } - } - } - } else { - if ($this->eCommerceSite->fk_warehouse > 0) { - $current_stock = isset($product->stock_warehouse[$this->eCommerceSite->fk_warehouse]->real) ? $product->stock_warehouse[$this->eCommerceSite->fk_warehouse]->real : 0; - $new_warehouses_stock[$this->eCommerceSite->fk_warehouse] = price2num($product_data['stock_qty'] - $current_stock); - } else { - $error++; - $this->errors[] = 'SetupOfWarehouseNotDefinedForThisSite'; - } - } - - if (!$error) { - foreach ($new_warehouses_stock as $warehouse_id => $new_stock_delta) { - if (empty($new_stock_delta)) continue; - - // Update/init stock - include_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php'; - $movement = new MouvementStock($this->db); - $movement->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; - - if (isset($object_origin->element) && isset($object_origin->id) && $object_origin->id > 0) { - $movement->origin = $object_origin; - } - $lot = $product->status_batch ? '000000' : null; - if ($new_stock_delta < 0) { - $result = $movement->livraison($this->user, $product->id, $warehouse_id, abs($new_stock_delta), 0, $langs->trans($new_product ? 'ECommerceStockInitFromWooSync' : 'ECommerceStockUpdateFromWooSync'), '', '', $lot); - } else { - $result = $movement->reception($this->user, $product->id, $warehouse_id, $new_stock_delta, 0, $langs->trans($new_product ? 'ECommerceStockInitFromWooSync' : 'ECommerceStockUpdateFromWooSync'), '', '', $lot); - } - if ($result <= 0) { - $this->errors[] = $this->langs->trans('ECommerceErrorUpdateProductStock'); - if (!empty($movement->error)) $this->errors[] = $movement->error; - $this->errors = array_merge($this->errors, $movement->errors); - $error++; - } - } - } + } else { + $current_stock = isset($product->stock_warehouse[$local_warehouse_id]->real) ? $product->stock_warehouse[$local_warehouse_id]->real : 0; + $new_warehouses_stock[$local_warehouse_id] = price2num($stock - $current_stock); + } + } + } + } else { + if ($this->eCommerceSite->fk_warehouse > 0) { + $current_stock = isset($product->stock_warehouse[$this->eCommerceSite->fk_warehouse]->real) ? $product->stock_warehouse[$this->eCommerceSite->fk_warehouse]->real : 0; + $new_warehouses_stock[$this->eCommerceSite->fk_warehouse] = price2num($product_data['stock_qty'] - $current_stock); + } else { + $error++; + $this->errors[] = 'SetupOfWarehouseNotDefinedForThisSite'; + } + } + + if (!$error) { + foreach ($new_warehouses_stock as $warehouse_id => $new_stock_delta) { + if (empty($new_stock_delta)) continue; + + // Update/init stock + include_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php'; + $movement = new MouvementStock($this->db); + $movement->context['fromsyncofecommerceid'] = $this->eCommerceSite->id; + + if (isset($object_origin->element) && isset($object_origin->id) && $object_origin->id > 0) { + $movement->origin = $object_origin; + } + $lot = $product->status_batch ? '000000' : null; + if ($new_stock_delta < 0) { + $result = $movement->livraison($this->user, $product->id, $warehouse_id, abs($new_stock_delta), 0, $langs->trans($new_product ? 'ECommerceStockInitFromWooSync' : 'ECommerceStockUpdateFromWooSync'), '', '', $lot); + } else { + $result = $movement->reception($this->user, $product->id, $warehouse_id, $new_stock_delta, 0, $langs->trans($new_product ? 'ECommerceStockInitFromWooSync' : 'ECommerceStockUpdateFromWooSync'), '', '', $lot); + } + if ($result <= 0) { + $this->errors[] = $this->langs->trans('ECommerceErrorUpdateProductStock'); + if (!empty($movement->error)) $this->errors[] = $movement->error; + $this->errors = array_merge($this->errors, $movement->errors); + $error++; + } + } + } } // Set update date of the product with last update date from site @@ -3893,8 +3697,9 @@ public function synchronizeProduct($product_data, $object_origin = null) $this->eCommerceProduct->last_update = $product_data['last_update']; if ($this->eCommerceSite->stock_sync_direction == 'ecommerce2dolibarr') $this->eCommerceProduct->last_update_stock = $product_data['last_update']; $this->eCommerceProduct->fk_product = $product->id > 0 ? $product->id : 0; - $this->eCommerceProduct->remote_id = $product_data['remote_id']; - $this->eCommerceProduct->lang = $product_data['language']; + $this->eCommerceProduct->remote_id = $product_data['remote_id']; + $this->eCommerceProduct->lang = $product_data['language']; + $this->eCommerceProduct->other_data = $product_data['other_data']; // Update link if ($this->eCommerceProduct->id > 0) { @@ -4278,22 +4083,22 @@ public function synchronizeOrder($order_data, $dont_synchronize_products = false } } - // Set third party language - //--------------------------- - if (!$error) { - $third_party = new Societe($this->db); - $third_party->fetch($third_party_id); - if (empty($third_party->default_lang) && !empty($order_data['language']) && $order_data['language'] != 'ec_none') { - $third_party->default_lang = $order_data['language']; - - $result = $third_party->update($third_party->id, $this->user); - if ($result < 0) { - $this->errors[] = $this->langs->trans('ECommerceErrorUpdateThirdPartyLanguage', $third_party->id); - $this->errors[] = $third_party->errorsToString(); - $error++; - } - } - } + // Set third party language + //--------------------------- + if (!$error) { + $third_party = new Societe($this->db); + $third_party->fetch($third_party_id); + if (empty($third_party->default_lang) && !empty($order_data['language']) && $order_data['language'] != 'ec_none') { + $third_party->default_lang = $order_data['language']; + + $result = $third_party->update($third_party->id, $this->user); + if ($result < 0) { + $this->errors[] = $this->langs->trans('ECommerceErrorUpdateThirdPartyLanguage', $third_party->id); + $this->errors[] = $third_party->errorsToString(); + $error++; + } + } + } // Set the order //--------------------------- @@ -4953,17 +4758,17 @@ public function synchronizeInvoiceFromOrder($order_data, $dont_synchronize_produ if (isset($third_party_id)) { $third_party = new Societe($this->db); $third_party->fetch($third_party_id); - // Set third party language - if (empty($third_party->default_lang) && !empty($order_data['language']) && $order_data['language'] != 'ec_none') { - $third_party->default_lang = $order_data['language']; - - $result = $third_party->update($third_party->id, $this->user); - if ($result < 0) { - $this->errors[] = $this->langs->trans('ECommerceErrorUpdateThirdPartyLanguage', $third_party->id); - $this->errors[] = $third_party->errorsToString(); - $error++; - } - } + // Set third party language + if (empty($third_party->default_lang) && !empty($order_data['language']) && $order_data['language'] != 'ec_none') { + $third_party->default_lang = $order_data['language']; + + $result = $third_party->update($third_party->id, $this->user); + if ($result < 0) { + $this->errors[] = $this->langs->trans('ECommerceErrorUpdateThirdPartyLanguage', $third_party->id); + $this->errors[] = $third_party->errorsToString(); + $error++; + } + } $isDepositType = isset($this->eCommerceSite->parameters['create_invoice_type']) && $this->eCommerceSite->parameters['create_invoice_type'] == Facture::TYPE_DEPOSIT; $typeAmount = isset($this->eCommerceSite->parameters['order_actions']['create_invoice_deposit_type']) ? $this->eCommerceSite->parameters['order_actions']['create_invoice_deposit_type'] : ''; @@ -5200,7 +5005,7 @@ public function synchronizeInvoiceFromOrder($order_data, $dont_synchronize_produ } } $invoice->fetch($invoice->id); // Reload to get new records - if (empty($invoice->total_ttc) || (empty($invoice->paye) && ((string)$invoice->getRemainToPay()) == 0)) { + if (empty($invoice->total_ttc) || (empty($invoice->paye) && ((string) $invoice->getRemainToPay()) == 0)) { $result = $invoice->set_paid($this->user); if ($result < 0) { $this->errors[] = $this->langs->trans('ECommerceErrorInvoiceSetPaid'); @@ -5457,7 +5262,7 @@ public function synchronizeInvoiceFromOrder($order_data, $dont_synchronize_produ // Deal with format differences between message and signature (text / HTML) if (dol_textishtml($message) && !dol_textishtml($substitutionarray['__USER_SIGNATURE__'])) { $substitutionarray['__USER_SIGNATURE__'] = dol_nl2br($substitutionarray['__USER_SIGNATURE__']); - } else if (!dol_textishtml($message) && dol_textishtml($substitutionarray['__USER_SIGNATURE__'])) { + } elseif (!dol_textishtml($message) && dol_textishtml($substitutionarray['__USER_SIGNATURE__'])) { $message = dol_nl2br($message); } @@ -6021,7 +5826,7 @@ public function synchronizeInvoiceRefundsFromOrder($order_data, $dont_synchroniz } } $invoice_refund->fetch($invoice_refund->id); // Reload to get new records - if (empty($invoice_refund->total_ttc) || (empty($invoice_refund->paye) && ((string)$invoice_refund->getRemainToPay()) == 0)) { + if (empty($invoice_refund->total_ttc) || (empty($invoice_refund->paye) && ((string) $invoice_refund->getRemainToPay()) == 0)) { $result = $invoice_refund->set_paid($this->user); if ($result < 0) { $this->errors[] = $this->langs->trans('ECommerceErrorInvoiceSetPaid'); @@ -6448,7 +6253,7 @@ public function addProductLines(&$object, $items, $order_data, &$warehouseByLine if ($isDepositType && in_array($typeAmount, array('amount', 'variable'))) { /** - * @var Facture $object + * @var Facture $object */ $amountdeposit = array(); $order_total_ttc = price2num($order_data['payment_amount_ttc'], 'MT'); @@ -6636,7 +6441,7 @@ public function addProductLines(&$object, $items, $order_data, &$warehouseByLine $fk_parent_line = isset($parent_match[$item['parent_item_id']]) ? $parent_match[$item['parent_item_id']] : 0; if ($object->element == 'commande') { /** - * @var Commande $object + * @var Commande $object */ $result = $object->addline($description, $price, $item['qty'], $item['tva_tx'], $item['local_tax1_tx'], $item['local_tax2_tx'], $fk_product, $discount, 0, 0, 'HT', 0, '', '', @@ -6644,7 +6449,7 @@ public function addProductLines(&$object, $items, $order_data, &$warehouseByLine 0, '', 0, 0); } else { // if ($object->element == 'facture') /** - * @var Facture $object + * @var Facture $object */ $result = $object->addline($description, $price, $item['qty'], $item['tva_tx'], $item['local_tax1_tx'], $item['local_tax2_tx'], $fk_product, $discount, '', '', 0, 0, '', 'HT', @@ -6755,7 +6560,7 @@ public function searchAndAddContact(&$object, &$contact_data, $order_data, $cont $result = $this->addUpdateContact($object, $new_object, $result, $contact_type); if ($result < 0) { $error++; - } elseif ($update_object_socid && $contact_data['fk_soc'] > 0 && $third_party_id != $contact_data['fk_soc']) { + } elseif ($update_object_socid && $contact_data['fk_soc'] > 0 && $object->socid != $contact_data['fk_soc']) { // Update thirdparty of the order $object->socid = $contact_data['fk_soc']; $result = $object->update($this->user); @@ -6816,7 +6621,7 @@ public function addContacts(&$object, &$order_data, $new_object = true) // Add sales contact if (!$error && $this->eCommerceSite->parameters['default_sales_representative_follow'] > 0 && $new_object) { // Todo update this contact when update order ? - $result = $this->addUpdateContact($object, $new_order, $this->eCommerceSite->parameters['default_sales_representative_follow'], 'SALESREPFOLL', 'internal'); + $result = $this->addUpdateContact($object, $new_object, $this->eCommerceSite->parameters['default_sales_representative_follow'], 'SALESREPFOLL', 'internal'); if ($result < 0) { $error++; } @@ -6945,7 +6750,7 @@ public function getThirdPartyByNameAndZip($name, $zip = '', $site_id = 0) if ($site_id > 0) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "ecommerce_societe AS es ON es.fk_societe = s.rowid"; $sql .= " WHERE (s.nom = '$name' OR s.name_alias = '$name')"; if (!empty($zip)) $sql .= " AND s.zip = '$zip'"; - else $sql .= " AND (s.zip IS NULL OR s.zip = '')"; + else $sql .= " AND (s.zip IS NULL OR s.zip = '')"; if ($site_id > 0) $sql .= " AND es.fk_site = $site_id"; $sql .= " AND s.status = 1"; $sql .= " AND s.entity IN (" . getEntity('societe') . ")"; @@ -7044,7 +6849,7 @@ public function getContactInfosFromData($contact_data, $company_id = 0) $sql .= ' AND fk_soc = ' . $this->db->escape($company_id); } else { if ($socid > 0) $sql .= ' AND fk_soc = ' . $this->db->escape($socid); - else if ($socid == -1) $sql .= " AND fk_soc IS NULL"; + elseif ($socid == -1) $sql .= " AND fk_soc IS NULL"; } $sql .= ' AND entity IN ('.getEntity('socpeople').')'; @@ -7235,12 +7040,12 @@ public function addLineToObject($object, $desc, $pu_ht, $qty, $txtva, $total_ht, global $mysoc, $conf, $langs, $user; dol_syslog(__METHOD__ . " object_element={$object->element}, object_id={$object->id}, desc=$desc, pu_ht=$pu_ht," . - " qty=$qty, txtva=$txtva, total_ht=$total_ht, total_tva=$total_tva, total_ttc=$total_ttc, fk_product=$fk_product, type=$type,". - " label=$label, array_options=".json_encode($array_options) . ", fk_fournprice=$fk_fournprice, pa_ht=$pa_ht,". - " txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, total_localtax1=$total_localtax1, total_localtax2=$total_localtax2,". - " remise_percent=$remise_percent, fk_unit=$fk_unit, special_code=$special_code, info_bits=$info_bits, fk_remise_except=$fk_remise_except,". - " date_start=$date_start, date_end=$date_end, fk_parent_line=$fk_parent_line, rang=$rang, origin=$origin, origin_id=$origin_id,". - " ventil=$ventil, situation_percent=$situation_percent, fk_prev_id=$fk_prev_id,". + " qty=$qty, txtva=$txtva, total_ht=$total_ht, total_tva=$total_tva, total_ttc=$total_ttc, fk_product=$fk_product, type=$type," . + " label=$label, array_options=" . json_encode($array_options) . ", fk_fournprice=$fk_fournprice, pa_ht=$pa_ht," . + " txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, total_localtax1=$total_localtax1, total_localtax2=$total_localtax2," . + " remise_percent=$remise_percent, fk_unit=$fk_unit, special_code=$special_code, info_bits=$info_bits, fk_remise_except=$fk_remise_except," . + " date_start=$date_start, date_end=$date_end, fk_parent_line=$fk_parent_line, rang=$rang, origin=$origin, origin_id=$origin_id," . + " ventil=$ventil, situation_percent=$situation_percent, fk_prev_id=$fk_prev_id," . " pu_ht_devise=$pu_ht_devise, multicurrency_total_ht=$multicurrency_total_ht, multicurrency_total_tva=$multicurrency_total_tva, multicurrency_total_ttc=$multicurrency_total_ttc", LOG_DEBUG); if ($object->statut == $object::STATUS_DRAFT) { @@ -7259,8 +7064,8 @@ public function addLineToObject($object, $desc, $pu_ht, $qty, $txtva, $total_ht, if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; if (empty($object->fk_multicurrency)) $object->fk_multicurrency = 0; if (empty($fk_prev_id)) $fk_prev_id = 'null'; - if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; - if (empty($ventil)) $ventil=0; + if (!isset($situation_percent) || $situation_percent > 100 || (string)$situation_percent == '') $situation_percent = 100; + if (empty($ventil)) $ventil = 0; $remise_percent = price2num($remise_percent); $qty = price2num($qty); diff --git a/class/business/eCommerceUtils.class.php b/class/business/eCommerceUtils.class.php index 3c9d565..20f0173 100755 --- a/class/business/eCommerceUtils.class.php +++ b/class/business/eCommerceUtils.class.php @@ -31,51 +31,51 @@ */ class eCommerceUtils { - public $error; - public $errors=array(); - public $success; - public $langs; - public $user; - - /** - * @var DoliDB Database handler - */ + public $error; + public $errors=array(); + public $success; + public $langs; + public $user; + + /** + * @var DoliDB Database handler + */ public $db; /** * @var array List of chronometer data */ - protected static $chronometer = array(); - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - global $langs, $user; - - $this->langs = $langs; - $this->user = $user; - $this->db = $db; - } - - /** - * Synchronize all new movement stocks from dolibarr to site (cron) - * - * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) - */ - public function cronSynchronizeStocksToSite() - { - global $conf, $user, $langs; - - $langs->load('ecommerceng@ecommerceng'); - $error = 0; - $output = ''; - - $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__); + protected static $chronometer = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $langs, $user; + + $this->langs = $langs; + $this->user = $user; + $this->db = $db; + } + + /** + * Synchronize all new movement stocks from dolibarr to site (cron) + * + * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) + */ + public function cronSynchronizeStocksToSite() + { + global $conf, $user, $langs; + + $langs->load('ecommerceng@ecommerceng'); + $error = 0; + $output = ''; + + $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__); $eCommerceSite = new eCommerceSite($this->db); $sites = $eCommerceSite->listSites('object'); @@ -266,89 +266,83 @@ public function cronSynchronizeStocksToSite() $this->db->free($resql); } - eCommerceUtils::stopAndLogStopwatch($stopwatch_id); + eCommerceUtils::stopAndLogStopwatch($stopwatch_id); - if (!$error) { - $output .= $langs->trans('ECommerceSynchronizeStocksToSiteSuccess'); - $this->error = ""; - $this->errors = array(); - $this->output = $output; - $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => ""); + if (!$error) { + $output .= $langs->trans('ECommerceSynchronizeStocksToSiteSuccess'); + $this->error = ""; + $this->errors = array(); + $this->output = $output; + $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => ""); - return 0; - } else { - $output = $langs->trans('ECommerceErrorWhenSynchronizeStocksToSite') . ":
" . $output; - dol_syslog(__METHOD__ . " Error: " . $output, LOG_ERR); + return 0; + } else { + $output = $langs->trans('ECommerceErrorWhenSynchronizeStocksToSite') . ":
" . $output; + dol_syslog(__METHOD__ . " Error: " . $output, LOG_ERR); - $this->error = $output; - $this->errors = array(); - return -1; - } - } + $this->error = $output; + $this->errors = array(); + return -1; + } + } - /** - * Sync all + /** + * Sync all * CAN BE A CRON TASK - * - * @param int $toNb Max nb to synch + * + * @param int $toNb Max nb to synch * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) - */ - public function synchAll($toNb=0) - { - global $db; - - $toDate = 0; - - $this->output = ''; - $this->error=''; - - $error=0; - - $eCommerceSite = new eCommerceSite($db); - $sites = $eCommerceSite->listSites('object'); - - // Loop on each site - foreach($sites as $site) - { - $site->cleanOrphelins(); - - $synchro = new eCommerceSynchro($db, $site, $toDate, $toNb); // $synchro->toDate will be set to dol_now if toDate no defined. - - dol_syslog("site.php Try to connect to eCommerce site ".$site->name); - $synchro->connect(); - if (count($synchro->errors)) - { - $error++; - setEventMessages($synchro->error, $synchro->errors, 'errors'); - } - - if (! $error) - { - $result=0; - if ($result >= 0) $result=$synchro->synchCategory($toNb); - if ($result >= 0) $result=$synchro->synchProduct(array(), $toNb); - if ($result >= 0) $result=$synchro->synchSociete(array(), $toNb); - if ($result >= 0) $result=$synchro->synchCommande(array(), $toNb); - if ($result >= 0) $result=$synchro->synchFacture($toNb); - - if ($result >= 0) $result=$synchro->synchDtoECategory($toNb); - if ($result >= 0) $result=$synchro->synchDtoEProduct($toNb); + */ + public function synchAll($toNb=0) + { + global $db; + + $toDate = 0; + + $this->output = ''; + $this->error = ''; + + $error = 0; + + $eCommerceSite = new eCommerceSite($db); + $sites = $eCommerceSite->listSites('object'); + + // Loop on each site + foreach ($sites as $site) { + $site->cleanOrphelins(); + + $synchro = new eCommerceSynchro($db, $site, $toDate, $toNb); // $synchro->toDate will be set to dol_now if toDate no defined. + + dol_syslog("site.php Try to connect to eCommerce site " . $site->name); + $synchro->connect(); + if (count($synchro->errors)) { + $error++; + setEventMessages($synchro->error, $synchro->errors, 'errors'); } - if ($error || $result < 0) - { - $this->output .= 'Error during automatic synchronization of site '.$site->name."\n"; - $this->error .= 'Error during automatic synchronization of site '.$site->name.": ".$synchro->error; + if (!$error) { + $result = 0; + if ($result >= 0) $result = $synchro->synchCategory($toNb); + if ($result >= 0) $result = $synchro->synchProduct(array(), $toNb); + if ($result >= 0) $result = $synchro->synchSociete(array(), $toNb); + if ($result >= 0) $result = $synchro->synchCommande(array(), $toNb); + if ($result >= 0) $result = $synchro->synchFacture($toNb); + + if ($result >= 0) $result = $synchro->synchDtoECategory($toNb); + if ($result >= 0) $result = $synchro->synchDtoEProduct($toNb); } - else - { - $this->output .= 'Automatic synchronization of site '.$site->name.' done'."\n"; + + if ($error || $result < 0) { + $this->output .= 'Error during automatic synchronization of site ' . $site->name . "\n"; + $this->error .= 'Error during automatic synchronization of site ' . $site->name . ": " . $synchro->error; + } else { + $this->output .= 'Automatic synchronization of site ' . $site->name . ' done' . "\n"; } } - if (! $error) return 0; + if (!$error) return 0; else return 1; - } + } /** * Start stopwatch @@ -451,8 +445,8 @@ static public function stopAndLogStopwatch($stopwatch_id) */ public static function microTimeToTime($micro_time) { - $hours = (int)($micro_time / 60 / 60); - $minutes = (int)(($micro_time / 60) - $hours * 60); + $hours = (int) ($micro_time / 60 / 60); + $minutes = (int) (($micro_time / 60) - $hours * 60); $seconds = $micro_time - $hours * 60 * 60 - $minutes * 60; return sprintf("%02d:%02d:%09.6f", $hours, $minutes, $seconds); } diff --git a/class/data/eCommerceCategory.class.php b/class/data/eCommerceCategory.class.php index accd79e..a40ba7a 100644 --- a/class/data/eCommerceCategory.class.php +++ b/class/data/eCommerceCategory.class.php @@ -33,636 +33,598 @@ */ class eCommerceCategory // extends CommonObject { - - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors = array(); //!< To return several error codes (or messages) - //var $element='skeleton'; //!< Id that identify managed objects - var $table_element = 'ecommerce_category'; //!< Name of table without prefix where object is stored - var $id; - var $label; - var $type; - var $description; - var $fk_category; - var $fk_site; - var $remote_id; - var $remote_parent_id; - var $last_update; - - /** - * Constructor - * - * @param DoliDB $DB Database handler - */ - function __construct($DB) - { - $this->db = $DB; - - return 1; - } - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger = 0) - { - global $conf, $langs; - $error = 0; - - // Clean parameters - if (isset($this->fk_category)) - $this->fk_category = intval($this->fk_category); - if (isset($this->fk_site)) - $this->fk_site = intval($this->fk_site); - if (isset($this->remote_id)) - $this->remote_id = trim($this->remote_id); - if (isset($this->remote_parent_id)) - $this->remote_parent_id = trim($this->remote_parent_id); - - // Check parameters - // Put here code to add control on parameters values - - // Insert request - $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . "("; - $sql.= " label,type,description,fk_category,fk_site,remote_id,remote_parent_id,last_update"; - $sql.= ") VALUES ("; - $sql.= " '" . $this->db->escape($this->label) . "',"; - $sql.= " '" . $this->db->escape($this->type) . "',"; - $sql.= " '" . $this->db->escape($this->description) . "',"; - $sql.= " " . $this->db->escape($this->fk_category) . ","; - $sql.= " " . $this->db->escape($this->fk_site) . ","; - $sql.= " " . (isset($this->remote_id) ? intval($this->remote_id) : 0) . ","; - $sql.= " " . (isset($this->remote_parent_id) ? intval($this->remote_parent_id) : 0) . ","; - $sql.= " " . ($this->last_update > 0 ? "'" . $this->db->idate($this->last_update) . "'" : "NULL"); - $sql.= ")"; - - $this->db->begin(); - - dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->errors[] = "Error " . $this->db->lasterror(); - } - - if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "mytable"); - - if (!$notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } - } - - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); - $this->error.=($this->error ? ', ' . $errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else - { - $this->db->commit(); - return $this->id; - } - } - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT "; - $sql.= "t.rowid,"; - $sql.= "t.label,"; - $sql.= "t.type,"; - $sql.= "t.description,"; - $sql.= "t.fk_category,"; - $sql.= "t.fk_site,"; - $sql.= "t.remote_id,"; - $sql.= "t.remote_parent_id,"; - $sql.= "t.last_update"; - - $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; - $sql.= " WHERE t.rowid = " . $id; - - dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->label = $obj->label; - $this->type = $obj->type; - $this->description = $obj->description; - $this->fk_category = $obj->fk_category; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->remote_parent_id = $obj->remote_parent_id; - $this->last_update = $obj->last_update; - } - $this->db->free($resql); - - return 1; - } else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); - return -1; - } - } - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user = 0, $notrigger = 0) - { - global $conf, $langs; - $error = 0; - - // Clean parameters - if (isset($this->fk_category)) - $this->fk_category = intval($this->fk_category); - if (isset($this->fk_site)) - $this->fk_site = intval($this->fk_site); - if (isset($this->remote_id)) - $this->remote_id = trim($this->remote_id); - if (isset($this->remote_parent_id)) - $this->remote_parent_id = trim($this->remote_parent_id); - if (isset($this->last_update)) - $this->last_update = trim($this->last_update); - //... - // Check parameters - // Put here code to add control on parameters values - // Update request - $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET"; - $sql.= " label='" . $this->db->escape($this->label) . "',"; - $sql.= " type=" . (isset($this->type) ? intval($this->type) : 0) . ","; - $sql.= " description='" . $this->db->escape($this->description) . "',"; - $sql.= " fk_category=" . (isset($this->fk_category) ? intval($this->fk_category) : 0) . ","; - $sql.= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; - $sql.= " remote_id=" . (isset($this->remote_id) ? intval($this->remote_id) : 0) . ","; - $sql.= " remote_parent_id=" . (isset($this->remote_parent_id) ? intval($this->remote_parent_id) : 0) . ","; - $sql.= " last_update=" . ($this->last_update > 0 ? "'" . $this->db->idate($this->last_update) . "'" : "null") . ""; - $sql.= " WHERE rowid=" . $this->id; - - $this->db->begin(); - - dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->errors[] = "Error " . $this->db->lasterror(); - } - - if (!$error) - { - if (!$notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } - } - - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); - $this->error.=($this->error ? ', ' . $errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else - { - $this->db->commit(); - return 1; - } - } - - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function delete($user, $notrigger = 0) - { - global $conf, $langs; - $error = 0; - - $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql.= " WHERE rowid=" . $this->id; - - $this->db->begin(); - - dol_syslog(get_class($this) . "::delete sql=" . $sql); - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->errors[] = "Error " . $this->db->lasterror(); - } - - if (!$error) - { - if (!$notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } - } - - // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); - $this->error.=($this->error ? ', ' . $errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else - { - $this->db->commit(); - return 1; - } - } - - /** - * Get the last date of the last updated category - * - * @param int $site eCommerceSite id | * for each sites - * @return datetime - */ - public function getLastUpdate($site) - { - global $langs; - $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; - $sql.= " WHERE t.fk_site = " . $site; - dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); - - $lastdate = null; - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - if ($obj->lastdate != null) - $lastdate = $this->db->jdate($obj->lastdate); - } - $this->db->free($resql); - } - else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); - } - return $lastdate; - } - - /** - * Function to compare date in remoteCatToCheck and date into sync table to see if category was changed on Magento side - * - * @param int $siteId site id from eCommerceSynchro - * @param string $toDate $toDate is now from eCommerceSynchro. Not used. - * @param string $remoteCatToCheck Magento category cutted from magento tree (is an array) - * @return 1 to add this category to update array, 0 to not add this category - */ - public function checkForUpdate($siteId, $toDate, $remoteCatToCheck) - { - global $langs; - $updateRequired = 0; // If any error occurs, category won't appears in update array - - $sql = "SELECT t.last_update as lastdate, t.remote_parent_id as parentid, t.fk_category FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; - $sql.= " WHERE t.remote_id='" . $this->db->escape($remoteCatToCheck['category_id']) . "' AND t.fk_site = " . $siteId; - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $diffdates = false; - $diffvalues = false; - if (empty($remoteCatToCheck['updated_at'])) { - $catObj = new Categorie($this->db); - $ret = $catObj->fetch($obj->fk_category); - if ($ret > 0) { - $diffvalues = $catObj->label != trim($remoteCatToCheck['name']) || $catObj->description != trim($remoteCatToCheck['description']); - } - } else { - $now = $toDate; // Dolibarr's category time - $lu = $this->db->jdate($obj->lastdate); // date of last update process - $lumage = strtotime($remoteCatToCheck['updated_at']); - //var_dump($lu); - //var_dump($lumage); - $diffdates = $lu < $lumage; - } - - $updateRequired = ($obj->parentid != $remoteCatToCheck['parent_id'] || $diffdates || $diffvalues) ? 1 : 0; - } else - { - $updateRequired = 1; - } - $this->db->free($resql); - } - else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::checkForUpdate " . $this->error, LOG_ERR); - return -1; - } - return $updateRequired; - } - - /** - * Load object in memory from database by remote_id - * - * @param int $remoteId string remote_id - * @param int $siteId int fk_site - * @return int <0 if KO or not found, >0 if OK - */ - public function fetchByRemoteId($remoteId, $siteId) - { - global $langs; - $sql = "SELECT "; - $sql.= "t.rowid,"; - $sql.= "t.label,"; - $sql.= "t.type,"; - $sql.= "t.description,"; - $sql.= "t.fk_category,"; - $sql.= "t.fk_site,"; - $sql.= "t.remote_id,"; - $sql.= "t.remote_parent_id,"; - $sql.= "t.last_update"; - $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; - $sql.= " WHERE t.fk_site = " . $siteId; - $sql.= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; - - dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->label = $obj->label; - $this->type = $obj->type; - $this->description = $obj->description; - $this->fk_category = $obj->fk_category; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->remote_parent_id = $obj->remote_parent_id; - $this->last_update = $obj->last_update; - - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return 0; - } else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); - return -1; - } - } - - /** - * Function used to call a fetchByRemoteId by fKCat (to check if an eCommerceCat - * exists corresponding with the importRoot defined in eCommerceSite) - * - * @param int $fKCategory $fKCategory from eCommerceSite - * @param int $siteId eCommerceSite Id - * @return fetchByRemoteId's result, -2 if error in this method - */ - public function fetchByFKCategory($fKCategory, $siteId) - { - global $langs; - - $sql = "SELECT "; - $sql.= "t.remote_id"; - $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; - $sql.= " WHERE t.fk_site = " . $siteId; - $sql.= " AND t.fk_category= " . $fKCategory; - - dol_syslog(get_class($this) . "::fetchByFKCategory sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - $resCall = $this->fetchByRemoteId($obj->remote_id, $siteId); - - $this->db->free($resql); - return $resCall; - } - $this->db->free($resql); - return -2; - } else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::fetchByFKCategory " . $this->error, LOG_ERR); - return -2; - } - } - - /** - * Function to put each category of a tree in a unique array. Children are always after parents. - * - * @param array $tree Array containing arrays of the same kind - * @return array array containing each category on a unique level (without the tree root) - */ - public function cuttingCategoryTreeFromMagentoToDolibarr($tree) - { - foreach ($tree['children'] as $subCat) - { - // For each child, we check if it has children to, and call this function again in this case - if (!empty($subCat['children'])) - // We put the return of this call in a temp array - $subRes = array_values(self::cuttingCategoryTreeFromMagentoToDolibarr($subCat)); - - array_pop($subCat); // Now children are useless in $subcat, we can pop it (to relieve array work) - $res[] = $subCat; // We add the popped $subcat to $res - // $subres is a one-leveled array, so we iterate over it and put each cat it contains in $res - if ($subRes) - { - array_reverse($subRes); // For children of a child to be position-ordered after its parent - foreach ($subRes as $cat) - $res[] = $cat; // We add children behind parent - } - } - return $res; - } - - /** - * Function to put each category of a tree in a unique array. Children are always after parents. - * - * @param array $tree Array containing arrays of the same kind - * @param array $resanswer Array containing each category on a unique level (without the tree root) - * @return void - */ - public static function cuttingCategoryTreeFromMagentoToDolibarrNew($tree, &$resanswer) - { - $tmp=$tree; - if (isset($tmp['level']) && $tmp['level']==0) $tmp=$tree['children']; - - foreach ($tmp as $subCat) - { - $savchildren = null; - if (isset($subCat['children'])) - { - $savchildren=$subCat['children']; - unset($subCat['children']); - } - - //var_dump($subCat); - - $resanswer[] = $subCat; // We add the popped $subcat to $res - - // For each child, we check if it has children to, and call this function again in this case - if (!empty($savchildren)) - { - // We put the return of this call in a temp array - self::cuttingCategoryTreeFromMagentoToDolibarrNew($savchildren, $resanswer); - } - } - } - - /** - * Function to return list of id of Dolibarr categories from a list of remoteCategoriesIds - * - * @param array $ids Array of remote ids + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors = array(); //!< To return several error codes (or messages) + //public $element='skeleton'; //!< Id that identify managed objects + public $table_element = 'ecommerce_category'; //!< Name of table without prefix where object is stored + public $id; + public $label; + public $type; + public $description; + public $fk_category; + public $fk_site; + public $remote_id; + public $remote_parent_id; + public $last_update; + public $other_data; + + /** + * Constructor + * + * @param DoliDB $DB Database handler + */ + public function __construct($DB) + { + $this->db = $DB; + + return 1; + } + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + if (isset($this->fk_category)) + $this->fk_category = intval($this->fk_category); + if (isset($this->fk_site)) + $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) + $this->remote_id = trim($this->remote_id); + if (isset($this->remote_parent_id)) + $this->remote_parent_id = trim($this->remote_parent_id); + + // Check parameters + // Put here code to add control on parameters values + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . "("; + $sql .= " label,type,description,fk_category,fk_site,remote_id,remote_parent_id,last_update,other_data"; + $sql .= ") VALUES ("; + $sql .= " '" . $this->db->escape($this->label) . "',"; + $sql .= " '" . $this->db->escape($this->type) . "',"; + $sql .= " '" . $this->db->escape($this->description) . "',"; + $sql .= " " . $this->db->escape($this->fk_category) . ","; + $sql .= " " . $this->db->escape($this->fk_site) . ","; + $sql .= " " . (isset($this->remote_id) ? intval($this->remote_id) : 0) . ","; + $sql .= " " . (isset($this->remote_parent_id) ? intval($this->remote_parent_id) : 0) . ","; + $sql .= " " . ($this->last_update > 0 ? "'" . $this->db->idate($this->last_update) . "'" : "NULL") . ","; + $sql .= " " . (!empty($this->other_data) ? "'" . $this->db->escape(json_encode($this->other_data)) . "'" : "NULL"); + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "mytable"); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT "; + $sql .= "t.rowid,"; + $sql .= "t.label,"; + $sql .= "t.type,"; + $sql .= "t.description,"; + $sql .= "t.fk_category,"; + $sql .= "t.fk_site,"; + $sql .= "t.remote_id,"; + $sql .= "t.remote_parent_id,"; + $sql .= "t.last_update,"; + $sql .= "t.other_data"; + + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->label = $obj->label; + $this->type = $obj->type; + $this->description = $obj->description; + $this->fk_category = $obj->fk_category; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->remote_parent_id = $obj->remote_parent_id; + $this->last_update = $obj->last_update; + $this->other_data = !empty($obj->other_data) ? json_decode($obj->other_data, true) : []; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + if (isset($this->fk_category)) + $this->fk_category = intval($this->fk_category); + if (isset($this->fk_site)) + $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) + $this->remote_id = trim($this->remote_id); + if (isset($this->remote_parent_id)) + $this->remote_parent_id = trim($this->remote_parent_id); + if (isset($this->last_update)) + $this->last_update = trim($this->last_update); + //... + // Check parameters + // Put here code to add control on parameters values + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET"; + $sql .= " label='" . $this->db->escape($this->label) . "',"; + $sql .= " type=" . (isset($this->type) ? intval($this->type) : 0) . ","; + $sql .= " description='" . $this->db->escape($this->description) . "',"; + $sql .= " fk_category=" . (isset($this->fk_category) ? intval($this->fk_category) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id=" . (isset($this->remote_id) ? intval($this->remote_id) : 0) . ","; + $sql .= " remote_parent_id=" . (isset($this->remote_parent_id) ? intval($this->remote_parent_id) : 0) . ","; + $sql .= " last_update=" . ($this->last_update > 0 ? "'" . $this->db->idate($this->last_update) . "'" : "null") . ","; + $sql .= " other_data=" . (!empty($this->other_data) ? "'" . $this->db->escape(json_encode($this->other_data)) . "'" : "NULL") . ""; + $sql .= " WHERE rowid=" . $this->id; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE rowid=" . $this->id; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::delete sql=" . $sql); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Get the last date of the last updated category + * + * @param int $site eCommerceSite id | * for each sites + * @return datetime + */ + public function getLastUpdate($site) + { + global $langs; + $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; + $sql .= " WHERE t.fk_site = " . $site; + dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); + + $lastdate = null; + + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + if ($obj->lastdate != null) + $lastdate = $this->db->jdate($obj->lastdate); + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); + } + return $lastdate; + } + + /** + * Function to compare date in remoteCatToCheck and date into sync table to see if category was changed on Magento side + * + * @param int $siteId site id from eCommerceSynchro + * @param string $toDate $toDate is now from eCommerceSynchro. Not used. + * @param string $remoteCatToCheck Magento category cutted from magento tree (is an array) + * @return 1 to add this category to update array, 0 to not add this category + */ + public function checkForUpdate($siteId, $toDate, $remoteCatToCheck) + { + global $langs; + $updateRequired = 0; // If any error occurs, category won't appears in update array + + $sql = "SELECT t.last_update as lastdate, t.remote_parent_id as parentid, t.fk_category FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; + $sql .= " WHERE t.remote_id='" . $this->db->escape($remoteCatToCheck['category_id']) . "' AND t.fk_site = " . $siteId; + + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $diffdates = false; + $diffvalues = false; + if (empty($remoteCatToCheck['updated_at'])) { + $catObj = new Categorie($this->db); + $ret = $catObj->fetch($obj->fk_category); + if ($ret > 0) { + $diffvalues = $catObj->label != trim($remoteCatToCheck['name']) || $catObj->description != trim($remoteCatToCheck['description']); + } + } else { + $now = $toDate; // Dolibarr's category time + $lu = $this->db->jdate($obj->lastdate); // date of last update process + $lumage = strtotime($remoteCatToCheck['updated_at']); + //var_dump($lu); + //var_dump($lumage); + $diffdates = $lu < $lumage; + } + + $updateRequired = ($obj->parentid != $remoteCatToCheck['parent_id'] || $diffdates || $diffvalues) ? 1 : 0; + } else { + $updateRequired = 1; + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::checkForUpdate " . $this->error, LOG_ERR); + return -1; + } + return $updateRequired; + } + + /** + * Load object in memory from database by remote_id + * + * @param int $remoteId string remote_id + * @param int $siteId int fk_site + * @return int <0 if KO or not found, >0 if OK + */ + public function fetchByRemoteId($remoteId, $siteId) + { + global $langs; + $sql = "SELECT "; + $sql .= "t.rowid,"; + $sql .= "t.label,"; + $sql .= "t.type,"; + $sql .= "t.description,"; + $sql .= "t.fk_category,"; + $sql .= "t.fk_site,"; + $sql .= "t.remote_id,"; + $sql .= "t.remote_parent_id,"; + $sql .= "t.last_update,"; + $sql .= "t.other_data"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND (t.remote_id = '" . $this->db->escape($remoteId) . "'"; + $sql .= " OR JSON_SEARCH(t.other_data, 'one', '" . $this->db->escape($remoteId) . "', NULL, '$.translations_ids') IS NOT NULL)"; + + dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->label = $obj->label; + $this->type = $obj->type; + $this->description = $obj->description; + $this->fk_category = $obj->fk_category; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->remote_parent_id = $obj->remote_parent_id; + $this->last_update = $obj->last_update; + $this->other_data = !empty($obj->other_data) ? json_decode($obj->other_data, true) : []; + + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return 0; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Function used to call a fetchByRemoteId by fKCat (to check if an eCommerceCat + * exists corresponding with the importRoot defined in eCommerceSite) + * + * @param int $fKCategory $fKCategory from eCommerceSite + * @param int $siteId eCommerceSite Id + * @return fetchByRemoteId's result, -2 if error in this method + */ + public function fetchByFKCategory($fKCategory, $siteId) + { + global $langs; + + $sql = "SELECT "; + $sql .= "t.rowid"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.fk_category= " . $fKCategory; + + dol_syslog(get_class($this) . "::fetchByFKCategory sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + $resCall = $this->fetch($obj->rowid); + + $this->db->free($resql); + return $resCall; + } + $this->db->free($resql); + return -2; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByFKCategory " . $this->error, LOG_ERR); + return -2; + } + } + + /** + * Function to put each category of a tree in a unique array. Children are always after parents. + * + * @param array $tree Array containing arrays of the same kind + * @return array array containing each category on a unique level (without the tree root) + */ + public function cuttingCategoryTreeFromMagentoToDolibarr($tree) + { + foreach ($tree['children'] as $subCat) { + // For each child, we check if it has children to, and call this function again in this case + if (!empty($subCat['children'])) + // We put the return of this call in a temp array + $subRes = array_values(self::cuttingCategoryTreeFromMagentoToDolibarr($subCat)); + + array_pop($subCat); // Now children are useless in $subcat, we can pop it (to relieve array work) + $res[] = $subCat; // We add the popped $subcat to $res + // $subres is a one-leveled array, so we iterate over it and put each cat it contains in $res + if ($subRes) { + array_reverse($subRes); // For children of a child to be position-ordered after its parent + foreach ($subRes as $cat) + $res[] = $cat; // We add children behind parent + } + } + return $res; + } + + /** + * Function to put each category of a tree in a unique array. Children are always after parents. + * + * @param array $tree Array containing arrays of the same kind + * @param array $resanswer Array containing each category on a unique level (without the tree root) + * @return void + */ + public static function cuttingCategoryTreeFromMagentoToDolibarrNew($tree, &$resanswer) + { + $tmp = $tree; + if (isset($tmp['level']) && $tmp['level'] == 0) $tmp = $tree['children']; + + foreach ($tmp as $subCat) { + $savchildren = null; + if (isset($subCat['children'])) { + $savchildren = $subCat['children']; + unset($subCat['children']); + } + + //var_dump($subCat); + + $resanswer[] = $subCat; // We add the popped $subcat to $res + + // For each child, we check if it has children to, and call this function again in this case + if (!empty($savchildren)) { + // We put the return of this call in a temp array + self::cuttingCategoryTreeFromMagentoToDolibarrNew($savchildren, $resanswer); + } + } + } + + /** + * Function to return list of id of Dolibarr categories from a list of remoteCategoriesIds + * + * @param array $ids Array of remote ids * @param int $siteId eCommerceSite Id - * @return array Array of categories' ids - */ - public function getDolibarrCategoryFromRemoteIds($ids, $siteId) - { - if (count($ids)) - { - $catsIds = array(); - $idsCount = count($ids); - $ii = 0; - - $sql = "SELECT fk_category FROM " . MAIN_DB_PREFIX . $this->table_element; + * @return array Array of categories' ids + */ + public function getDolibarrCategoryFromRemoteIds($ids, $siteId) + { + if (count($ids)) { + $catsIds = array(); + $idsCount = count($ids); + $ii = 0; + + $sql = "SELECT fk_category FROM " . MAIN_DB_PREFIX . $this->table_element; $sql .= " WHERE fk_site = " . $siteId; - $sql .= " AND remote_id IN("; - foreach ($ids as $remoteId) - { - $ii++; - $sql .= "'".$this->db->escape($remoteId)."'" . ($ii == $idsCount ? ")" : ","); - } - - dol_syslog(get_class($this) . "::getDolibarrCategoryFromRemoteIds sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - - if ($resql) - { - $ii = $this->db->num_rows($resql); - - while ($ii > 0) { - $obj = $this->db->fetch_object($resql); - $catsIds[] = intval($obj->fk_category); - $ii--; - } - $this->db->free($resql); - } else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::getDolibarrCategoryFromRemoteIds " . $this->error, LOG_ERR); - } - - return $catsIds; - } - } - - /** - * Select all the ids from eCommerceCategory for a site - * - * @param ECommerceSite $eCommerceSite Object eCommerceSite - * @return array synchObject ids for this site - */ - public function getAllECommerceCategoryIds($eCommerceSite) - { - global $langs; - - $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_category"; - $sql.= " WHERE fk_site = " . $eCommerceSite->id . " AND fk_category <> " . intval($eCommerceSite->fk_cat_product); - dol_syslog(get_class($this) . "::getAllECommerceCategoryIds sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while ($ii < $num) { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } else - { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::getAllECommerceCategoryIds " . $this->error, LOG_ERR); - return -1; - } - } - + $sql .= " AND (remote_id IN("; + $or = []; + foreach ($ids as $remoteId) { + $ii++; + $sql .= "'" . $this->db->escape($remoteId) . "'" . ($ii == $idsCount ? ")" : ","); + $or[] = "JSON_SEARCH(other_data, 'one', '" . $this->db->escape($remoteId) . "', NULL, '$.translations_ids') IS NOT NULL"; + } + $sql .= " OR " . implode(" OR ", $or) . ")"; + + dol_syslog(get_class($this) . "::getDolibarrCategoryFromRemoteIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $ii = $this->db->num_rows($resql); + + while ($ii > 0) { + $obj = $this->db->fetch_object($resql); + $catsIds[] = intval($obj->fk_category); + $ii--; + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getDolibarrCategoryFromRemoteIds " . $this->error, LOG_ERR); + } + + return $catsIds; + } + } + + /** + * Select all the ids from eCommerceCategory for a site + * + * @param ECommerceSite $eCommerceSite Object eCommerceSite + * @return array synchObject ids for this site + */ + public function getAllECommerceCategoryIds($eCommerceSite) + { + global $langs; + + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_category"; + $sql .= " WHERE fk_site = " . $eCommerceSite->id . " AND fk_category <> " . intval($eCommerceSite->fk_cat_product); + dol_syslog(get_class($this) . "::getAllECommerceCategoryIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceCategoryIds " . $this->error, LOG_ERR); + return -1; + } + } } diff --git a/class/data/eCommerceCommande.class.php b/class/data/eCommerceCommande.class.php index 5b54fda..02382d4 100644 --- a/class/data/eCommerceCommande.class.php +++ b/class/data/eCommerceCommande.class.php @@ -20,274 +20,265 @@ class eCommerceCommande { - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors=array(); //!< To return several error codes (or messages) - //var $element='ecommerce_commande.sql'; //!< Id that identify managed objects - //var $table_element='ecommerce_commande.sql'; //!< Name of table without prefix where object is stored - - var $id; - var $fk_commande; - var $fk_site; - var $remote_id; - var $last_update; - - /** - * Constructor - * - * @param DoliDB $DB Database handler - */ - function __construct($DB) - { - $this->db = $DB; - return 1; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors=array(); //!< To return several error codes (or messages) + //public $element='ecommerce_commande.sql'; //!< Id that identify managed objects + //public $table_element='ecommerce_commande.sql'; //!< Name of table without prefix where object is stored + + public $id; + public $fk_commande; + public $fk_site; + public $remote_id; + public $last_update; + + /** + * Constructor + * + * @param DoliDB $DB Database handler + */ + public function __construct($DB) + { + $this->db = $DB; + return 1; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande=intval($this->fk_commande); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_commande)) $this->fk_commande = intval($this->fk_commande); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_commande("; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_commande("; - $sql.= "fk_commande,"; - $sql.= "fk_site,"; - $sql.= "remote_id,"; - $sql.= "last_update"; + $sql .= "fk_commande,"; + $sql .= "fk_site,"; + $sql .= "remote_id,"; + $sql .= "last_update"; - $sql.= ") VALUES ("; + $sql .= ") VALUES ("; - $sql.= " ".(isset($this->fk_commande)?intval($this->fk_commande):0).","; - $sql.= " ".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " ".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " ".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " " . (isset($this->fk_commande) ? intval($this->fk_commande) : 0) . ","; + $sql .= " " . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " " . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " " . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= ")"; + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_commande"); + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_commande"); - if (! $notrigger) { + if (!$notrigger) { //// Call triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface = new Interfaces($this->db); $result = $interface->run_triggers('ECOMMERCECOMMANDE_CREATE', $this, $user, $langs, $conf); - if ($result < 0) { $error++; $this->errors = $interface->errors; } + if ($result < 0) { + $error++; + $this->errors = $interface->errors; + } //// End call triggers } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_commande,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_commande as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_commande = $obj->fk_commande; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - } - $this->db->free($resql); - - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_commande,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_commande as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_commande = $obj->fk_commande; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande=intval($this->fk_commande); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_commande)) $this->fk_commande = intval($this->fk_commande); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_commande SET"; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_commande SET"; - $sql.= " fk_commande=".(isset($this->fk_commande)?intval($this->fk_commande):0).","; - $sql.= " fk_site=".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " remote_id=".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " last_update=".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " fk_commande=" . (isset($this->fk_commande) ? intval($this->fk_commande) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id=" . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " last_update=" . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); return 1; } - } + } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0) + public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_commande"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_commande"; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } @@ -301,152 +292,136 @@ function delete($user, $notrigger=0) public function getLastUpdate($siteId) { global $langs; - $sql = "SELECT MAX(t.last_update) as lastdate FROM ".MAIN_DB_PREFIX."ecommerce_commande as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - dol_syslog(get_class($this)."::getLastUpdate sql=".$sql, LOG_DEBUG); - - $lastdate = null; - - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . "ecommerce_commande as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); + + $lastdate = null; + + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); if ($obj->lastdate != null) - $lastdate = $this->db->jdate($obj->lastdate); - } - $this->db->free($resql); - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getLastUpdate ".$this->error, LOG_ERR); - } - return $lastdate; + $lastdate = $this->db->jdate($obj->lastdate); + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); + } + return $lastdate; } /** - * Load object in memory from database by remote_id - * @param $remoteId string remote_id - * @param $siteId int fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * @param $remoteId string remote_id + * @param $siteId int fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByRemoteId($remoteId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_commande,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_commande as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; - dol_syslog(get_class($this)."::fetchByRemoteId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_commande = $obj->fk_commande; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByRemoteId ".$this->error, LOG_ERR); - return -1; - } - } + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_commande,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_commande as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; + dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_commande = $obj->fk_commande; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); + return -1; + } + } /** - * Load object in memory from database by dolibarr commande_id - * - * @param int $commandeId Order id in dolibarr - * @param int $siteId ID fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by dolibarr commande_id + * + * @param int $commandeId Order id in dolibarr + * @param int $siteId ID fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByCommandeId($commandeId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_commande,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_commande as t"; - $sql.= " WHERE t.fk_commande = ".$commandeId; - $sql.= " AND t.fk_site = ".$siteId; - dol_syslog(get_class($this)."::fetchByCommandeId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_commande = $obj->fk_commande; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByCommandeId ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Select all the ids from eCommerceCommande for a site - * @param int siteId - * @return array synchObject ids for this site - */ - public function getAllECommerceCommandeIds($siteId) - { - global $langs; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ecommerce_commande"; - $sql.= " WHERE fk_site = ".$siteId; - dol_syslog(get_class($this)."::getAllECommerceCommandeIds sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while($ii < $num) - { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getAllECommerceCommandeIds ".$this->error, LOG_ERR); - return -1; - } - } + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_commande,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_commande as t"; + $sql .= " WHERE t.fk_commande = " . $commandeId; + $sql .= " AND t.fk_site = " . $siteId; + dol_syslog(get_class($this) . "::fetchByCommandeId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_commande = $obj->fk_commande; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByCommandeId " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Select all the ids from eCommerceCommande for a site + * @param int $siteId Site ID + * @return array synchObject ids for this site + */ + public function getAllECommerceCommandeIds($siteId) + { + global $langs; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_commande"; + $sql .= " WHERE fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getAllECommerceCommandeIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceCommandeIds " . $this->error, LOG_ERR); + return -1; + } + } } diff --git a/class/data/eCommerceFacture.class.php b/class/data/eCommerceFacture.class.php index 3aef6b0..af8e48d 100644 --- a/class/data/eCommerceFacture.class.php +++ b/class/data/eCommerceFacture.class.php @@ -20,276 +20,263 @@ class eCommerceFacture // extends CommonObject { - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors=array(); //!< To return several error codes (or messages) - //var $element='ecommerce_facture'; //!< Id that identify managed objects - //var $table_element='ecommerce_facture'; //!< Name of table without prefix where object is stored - - var $id; - var $fk_facture; - var $fk_site; - var $remote_id; - var $last_update; - - /** - * Constructor - * - * @param DoliDB $DB Database handler - */ - function __construct($DB) - { - $this->db = $DB; - return 1; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors=array(); //!< To return several error codes (or messages) + //public $element='ecommerce_facture'; //!< Id that identify managed objects + //public $table_element='ecommerce_facture'; //!< Name of table without prefix where object is stored + + public $id; + public $fk_facture; + public $fk_site; + public $remote_id; + public $last_update; + + /** + * Constructor + * + * @param DoliDB $DB Database handler + */ + public function __construct($DB) + { + $this->db = $DB; + return 1; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_facture)) $this->fk_facture=intval($this->fk_facture); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_facture)) $this->fk_facture = intval($this->fk_facture); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_facture("; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_facture("; - $sql.= "fk_facture,"; - $sql.= "fk_site,"; - $sql.= "remote_id,"; - $sql.= "last_update"; + $sql .= "fk_facture,"; + $sql .= "fk_site,"; + $sql .= "remote_id,"; + $sql .= "last_update"; - $sql.= ") VALUES ("; + $sql .= ") VALUES ("; - $sql.= " ".(isset($this->fk_facture)?intval($this->fk_facture):0).","; - $sql.= " ".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " ".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " ".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " " . (isset($this->fk_facture) ? intval($this->fk_facture) : 0) . ","; + $sql .= " " . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " " . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " " . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= ")"; + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_facture"); - - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_facture"); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_facture,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_facture as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_facture = $obj->fk_facture; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_facture,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_facture as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_facture = $obj->fk_facture; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - } - $this->db->free($resql); - - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * \brief Update database - * \param user User that modify - * \param notrigger 0=launch triggers after, 1=disable triggers - * \return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + } + + + /** + * \brief Update database + * \param user User that modify + * \param notrigger 0=launch triggers after, 1=disable triggers + * \return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_facture)) $this->fk_facture=intval($this->fk_facture); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_facture)) $this->fk_facture = intval($this->fk_facture); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_facture SET"; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_facture SET"; - $sql.= " fk_facture=".(isset($this->fk_facture)?intval($this->fk_facture):0).","; - $sql.= " fk_site=".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " remote_id=".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " last_update=".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " fk_facture=" . (isset($this->fk_facture) ? intval($this->fk_facture) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id=" . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " last_update=" . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); return 1; } - } + } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0) + public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_facture"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_facture"; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } @@ -302,154 +289,138 @@ function delete($user, $notrigger=0) */ public function getLastUpdate($siteId) { - global $langs; - $sql = "SELECT MAX(t.last_update) as lastdate FROM ".MAIN_DB_PREFIX."ecommerce_facture as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - dol_syslog(get_class($this)."::getLastUpdate sql=".$sql, LOG_DEBUG); - - $lastdate = null; - - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - if ($obj->lastdate != null) - $lastdate = $this->db->jdate($obj->lastdate); - } - $this->db->free($resql); - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getLastUpdate ".$this->error, LOG_ERR); - } - return $lastdate; + global $langs; + $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . "ecommerce_facture as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); + + $lastdate = null; + + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + if ($obj->lastdate != null) + $lastdate = $this->db->jdate($obj->lastdate); + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); + } + return $lastdate; } /** - * Load object in memory from database by remote_id - * - * @param $remoteId string remote_id - * @param $siteId int fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * + * @param $remoteId string remote_id + * @param $siteId int fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByRemoteId($remoteId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_facture,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_facture as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.remote_id = '".$this->db->escape($remoteId)."'"; - dol_syslog(get_class($this)."::fetchByRemoteId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_facture = $obj->fk_facture; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByRemoteId ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Load object in memory from database by remote_id - * @param int $factureId Invoice id in Dolibarr - * @param int $siteId ID site - * @return int <0 if KO, >0 if OK - */ - public function fetchByFactureId($factureId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_facture,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_facture as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.fk_facture = ".$factureId; - dol_syslog(get_class($this)."::fetchByFactureId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_facture = $obj->fk_facture; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByFactureId ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Select all the ids from eCommerceFacture for a site - * @param int siteId - * @return array synchObject ids for this site - */ - public function getAllECommerceFactureIds($siteId) - { - global $langs; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ecommerce_facture"; - $sql.= " WHERE fk_site = ".$siteId; - dol_syslog(get_class($this)."::getAllECommerceFactureIds sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while($ii < $num) - { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getAllECommerceFactureIds ".$this->error, LOG_ERR); - return -1; - } - } + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_facture,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_facture as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; + dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_facture = $obj->fk_facture; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Load object in memory from database by remote_id + * @param int $factureId Invoice id in Dolibarr + * @param int $siteId ID site + * @return int <0 if KO, >0 if OK + */ + public function fetchByFactureId($factureId, $siteId) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_facture,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_facture as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.fk_facture = " . $factureId; + dol_syslog(get_class($this) . "::fetchByFactureId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_facture = $obj->fk_facture; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByFactureId " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Select all the ids from eCommerceFacture for a site + * @param int $siteId Site ID + * @return array synchObject ids for this site + */ + public function getAllECommerceFactureIds($siteId) + { + global $langs; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_facture"; + $sql .= " WHERE fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getAllECommerceFactureIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceFactureIds " . $this->error, LOG_ERR); + return -1; + } + } } diff --git a/class/data/eCommercePaymentGateways.class.php b/class/data/eCommercePaymentGateways.class.php index e369626..5253bc0 100755 --- a/class/data/eCommercePaymentGateways.class.php +++ b/class/data/eCommercePaymentGateways.class.php @@ -29,60 +29,60 @@ */ class eCommercePaymentGateways { - /** - * @var DoliDB Database handler. - */ - public $db; - /** - * @var string Error - */ - public $error = ''; - /** - * @var array Errors - */ - public $errors = array(); + /** + * @var DoliDB Database handler. + */ + public $db; + /** + * @var string Error + */ + public $error = ''; + /** + * @var array Errors + */ + public $errors = array(); - public $table_element = 'ecommerceng_payment_gateways'; + public $table_element = 'ecommerceng_payment_gateways'; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Set all payment gateways of a site - * - * @param int $site_id Site ID - * @param array $payment_gateways List of infos of each payment gateway - * @return int >0 if OK, <0 if KO - * @throws Exception - */ - public function set($site_id, $payment_gateways) - { - global $conf, $langs; - dol_syslog(__METHOD__ . " site_id=$site_id, payment_gateways=".json_encode($payment_gateways)); + /** + * Set all payment gateways of a site + * + * @param int $site_id Site ID + * @param array $payment_gateways List of infos of each payment gateway + * @return int >0 if OK, <0 if KO + * @throws Exception + */ + public function set($site_id, $payment_gateways) + { + global $conf, $langs; + dol_syslog(__METHOD__ . " site_id=$site_id, payment_gateways=" . json_encode($payment_gateways)); - $errors = 0; - $this->errors = array(); + $errors = 0; + $this->errors = array(); - // Clean values - $site_id = $site_id > 0 ? $site_id : 0; - $payment_gateways = is_array($payment_gateways) ? $payment_gateways : array(); + // Clean values + $site_id = $site_id > 0 ? $site_id : 0; + $payment_gateways = is_array($payment_gateways) ? $payment_gateways : array(); - // Check values - if ($site_id == 0) { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ECommerceSite")); - return -1; - } + // Check values + if ($site_id == 0) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ECommerceSite")); + return -1; + } - $this->db->begin(); + $this->db->begin(); - if (!$errors) { + if (!$errors) { // Insert values foreach ($payment_gateways as $payment_gateway_id => $infos) { $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(site_id, payment_gateway_id, payment_gateway_label, payment_mode_id, bank_account_id, create_invoice_payment, mail_model_for_send_invoice, supplier_id, product_id_for_fee, create_supplier_invoice_payment, entity) VALUES ('; @@ -130,129 +130,129 @@ public function set($site_id, $payment_gateways) } } - if ($errors) { - $this->db->rollback(); - return -1; - } else { - $this->db->commit(); - return 1; - } - } + if ($errors) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return 1; + } + } - /** - * Get a payment gateway of a site by the payment gateway ID or payment mode ID - * - * @param int $site_id Site ID - * @param string $payment_gateway_id Payment gateway ID on WooCommerce - * @param int $payment_mode_id Payment mode ID on Dolibarr - * @return array|int 0 if not found, <0 if errors or array of infos - * @throws Exception - */ - public function get($site_id, $payment_gateway_id='', $payment_mode_id=0) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id, payment_gateway_id=$payment_gateway_id, payment_mode_id=$payment_mode_id"); + /** + * Get a payment gateway of a site by the payment gateway ID or payment mode ID + * + * @param int $site_id Site ID + * @param string $payment_gateway_id Payment gateway ID on WooCommerce + * @param int $payment_mode_id Payment mode ID on Dolibarr + * @return array|int 0 if not found, <0 if errors or array of infos + * @throws Exception + */ + public function get($site_id, $payment_gateway_id = '', $payment_mode_id = 0) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id, payment_gateway_id=$payment_gateway_id, payment_mode_id=$payment_mode_id"); - $sql = 'SELECT payment_gateway_id, payment_gateway_label, payment_mode_id, bank_account_id, create_invoice_payment, mail_model_for_send_invoice, supplier_id, product_id_for_fee, create_supplier_invoice_payment FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - if ($payment_mode_id > 0) { - $sql .= ' AND payment_mode_id = ' . $payment_mode_id; - } else { - $sql .= " AND payment_gateway_id = '" . $this->db->escape($payment_gateway_id) . "'"; - } - $resql = $this->db->query($sql); - if ($resql) { - if ($this->db->num_rows($resql) == 0) - return 0; + $sql = 'SELECT payment_gateway_id, payment_gateway_label, payment_mode_id, bank_account_id, create_invoice_payment, mail_model_for_send_invoice, supplier_id, product_id_for_fee, create_supplier_invoice_payment FROM ' . MAIN_DB_PREFIX . $this->table_element; + $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + if ($payment_mode_id > 0) { + $sql .= ' AND payment_mode_id = ' . $payment_mode_id; + } else { + $sql .= " AND payment_gateway_id = '" . $this->db->escape($payment_gateway_id) . "'"; + } + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 0) + return 0; - if ($obj = $this->db->fetch_object($resql)) { - $mail_model_for_send_invoice = json_decode($obj->mail_model_for_send_invoice, true); - if (!isset($mail_model_for_send_invoice)) $mail_model_for_send_invoice = array('ec_none' => $obj->mail_model_for_send_invoice); + if ($obj = $this->db->fetch_object($resql)) { + $mail_model_for_send_invoice = json_decode($obj->mail_model_for_send_invoice, true); + if (!isset($mail_model_for_send_invoice)) $mail_model_for_send_invoice = array('ec_none' => $obj->mail_model_for_send_invoice); - return array( - 'payment_gateway_id' => $obj->payment_gateway_id, - 'payment_gateway_label' => $obj->payment_gateway_label, - 'payment_mode_id' => $obj->payment_mode_id, - 'bank_account_id' => $obj->bank_account_id, - 'create_invoice_payment' => !empty($obj->create_invoice_payment) ? 1 : 0, - 'mail_model_for_send_invoice' => $mail_model_for_send_invoice, - 'supplier_id' => $obj->supplier_id, - 'product_id_for_fee' => $obj->product_id_for_fee, - 'create_supplier_invoice_payment' => !empty($obj->create_supplier_invoice_payment) ? 1 : 0, - ); - } - } else { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $errors[] = $this->db->lasterror(); - return -1; - } - } + return array( + 'payment_gateway_id' => $obj->payment_gateway_id, + 'payment_gateway_label' => $obj->payment_gateway_label, + 'payment_mode_id' => $obj->payment_mode_id, + 'bank_account_id' => $obj->bank_account_id, + 'create_invoice_payment' => !empty($obj->create_invoice_payment) ? 1 : 0, + 'mail_model_for_send_invoice' => $mail_model_for_send_invoice, + 'supplier_id' => $obj->supplier_id, + 'product_id_for_fee' => $obj->product_id_for_fee, + 'create_supplier_invoice_payment' => !empty($obj->create_supplier_invoice_payment) ? 1 : 0, + ); + } + } else { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $errors[] = $this->db->lasterror(); + return -1; + } + } - /** - * Get all payment gateway of a site - * - * @param int $site_id Site ID - * @return array|int List of all payment gateway infos - * @throws Exception - */ - public function get_all($site_id) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id"); + /** + * Get all payment gateway of a site + * + * @param int $site_id Site ID + * @return array|int List of all payment gateway infos + * @throws Exception + */ + public function get_all($site_id) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id"); - $payment_gateways = array(); + $payment_gateways = array(); - $sql = 'SELECT payment_gateway_id, payment_gateway_label, payment_mode_id, bank_account_id, create_invoice_payment, mail_model_for_send_invoice, supplier_id, product_id_for_fee, create_supplier_invoice_payment FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $mail_model_for_send_invoice = json_decode($obj->mail_model_for_send_invoice, true); - if (!isset($mail_model_for_send_invoice)) $mail_model_for_send_invoice = array('ec_none' => $obj->mail_model_for_send_invoice); + $sql = 'SELECT payment_gateway_id, payment_gateway_label, payment_mode_id, bank_account_id, create_invoice_payment, mail_model_for_send_invoice, supplier_id, product_id_for_fee, create_supplier_invoice_payment FROM ' . MAIN_DB_PREFIX . $this->table_element; + $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + $mail_model_for_send_invoice = json_decode($obj->mail_model_for_send_invoice, true); + if (!isset($mail_model_for_send_invoice)) $mail_model_for_send_invoice = array('ec_none' => $obj->mail_model_for_send_invoice); - $payment_gateways[$obj->payment_gateway_id] = array( - 'payment_gateway_label' => $obj->payment_gateway_label, - 'payment_mode_id' => $obj->payment_mode_id, - 'bank_account_id' => $obj->bank_account_id, - 'create_invoice_payment' => !empty($obj->create_invoice_payment) ? 1 : 0, - 'mail_model_for_send_invoice' => $mail_model_for_send_invoice, - 'supplier_id' => $obj->supplier_id, - 'product_id_for_fee' => $obj->product_id_for_fee, - 'create_supplier_invoice_payment' => !empty($obj->create_supplier_invoice_payment) ? 1 : 0, - ); - } - } else { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $errors[] = $this->db->lasterror(); - return -1; - } + $payment_gateways[$obj->payment_gateway_id] = array( + 'payment_gateway_label' => $obj->payment_gateway_label, + 'payment_mode_id' => $obj->payment_mode_id, + 'bank_account_id' => $obj->bank_account_id, + 'create_invoice_payment' => !empty($obj->create_invoice_payment) ? 1 : 0, + 'mail_model_for_send_invoice' => $mail_model_for_send_invoice, + 'supplier_id' => $obj->supplier_id, + 'product_id_for_fee' => $obj->product_id_for_fee, + 'create_supplier_invoice_payment' => !empty($obj->create_supplier_invoice_payment) ? 1 : 0, + ); + } + } else { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $errors[] = $this->db->lasterror(); + return -1; + } - return $payment_gateways; - } + return $payment_gateways; + } - /** - * Delete all payment gateway of a site - * - * @param int $site_id Site ID - * @return int >0 if OK, <0 if KO - * @throws Exception - */ - public function delete_all($site_id) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id"); + /** + * Delete all payment gateway of a site + * + * @param int $site_id Site ID + * @return int >0 if OK, <0 if KO + * @throws Exception + */ + public function delete_all($site_id) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id"); - // Delete all line for the site - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - $resql = $this->db->query($sql); - if (!$resql) { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $this->errors[] = $this->db->lasterror(); - return -1; - } + // Delete all line for the site + $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $this->errors[] = $this->db->lasterror(); + return -1; + } - return 1; - } + return 1; + } /** * Method to output saved errors diff --git a/class/data/eCommerceProduct.class.php b/class/data/eCommerceProduct.class.php index def5415..cff18d2 100644 --- a/class/data/eCommerceProduct.class.php +++ b/class/data/eCommerceProduct.class.php @@ -26,283 +26,273 @@ class eCommerceProduct // extends CommonObject //public $element='ecommerce_product'; //!< Id that identify managed objects //public $table_element='ecommerce_product'; //!< Name of table without prefix where object is stored - public $id; - public $fk_product; - public $fk_site; - public $remote_id; - public $lang; - public $last_update; - public $last_update_stock; - - /** - * Constructor - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - return 1; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + public $id; + public $fk_product; + public $fk_site; + public $remote_id; + public $lang; + public $last_update; + public $last_update_stock; + public $other_data; + + /** + * Constructor + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + return 1; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_product)) $this->fk_product=intval($this->fk_product); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->lang)) $this->lang=trim($this->lang); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); - if (isset($this->last_update_stock)) $this->last_update_stock=trim($this->last_update_stock); + if (isset($this->fk_product)) $this->fk_product = intval($this->fk_product); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->lang)) $this->lang = trim($this->lang); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); + if (isset($this->last_update_stock)) $this->last_update_stock = trim($this->last_update_stock); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_product("; - $sql.= "fk_product,"; - $sql.= "fk_site,"; - $sql.= "remote_id,"; - $sql.= "lang,"; - $sql.= "last_update,"; - $sql.= "last_update_stock"; - $sql.= ") VALUES ("; - $sql.= " ".(isset($this->fk_product)?intval($this->fk_product):0).","; - $sql.= " ".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " ".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " ".(!empty($this->lang)?"'".$this->db->escape($this->lang)."'":"null").","; - $sql.= " ".(isset($this->last_update)?"'".$this->last_update."'" : 'null').","; - $sql.= " ".(isset($this->last_update_stock)?"'".$this->last_update_stock."'" : 'null').""; - $sql.= ")"; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_product("; + $sql .= "fk_product,"; + $sql .= "fk_site,"; + $sql .= "remote_id,"; + $sql .= "lang,"; + $sql .= "last_update,"; + $sql .= "last_update_stock,"; + $sql .= "other_data"; + $sql .= ") VALUES ("; + $sql .= " " . (isset($this->fk_product) ? intval($this->fk_product) : 0) . ","; + $sql .= " " . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " " . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " " . (!empty($this->lang) ? "'" . $this->db->escape($this->lang) . "'" : "null") . ","; + $sql .= " " . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ","; + $sql .= " " . (isset($this->last_update_stock) ? "'" . $this->last_update_stock . "'" : 'null') . ","; + $sql .= " " . (!empty($this->other_data) ? "'" . $this->db->escape(json_encode($this->other_data)) . "'" : "NULL"); + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_product"); - - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_product"); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_product,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.lang,"; - $sql.= " t.last_update,"; - $sql.= " t.last_update_stock"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_product as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_product = $obj->fk_product; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->lang = $obj->lang; - $this->last_update = $obj->last_update; - $this->last_update_stock = $obj->last_update_stock; + } + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_product,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.lang,"; + $sql .= " t.last_update,"; + $sql .= " t.last_update_stock,"; + $sql .= " t.other_data"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_product as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_product = $obj->fk_product; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->lang = $obj->lang; + $this->last_update = $obj->last_update; + $this->last_update_stock = $obj->last_update_stock; + $this->other_data = !empty($obj->other_data) ? json_decode($obj->other_data, true) : []; return 1; } - $this->db->free($resql); - return 0; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + $this->db->free($resql); + return 0; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_product)) $this->fk_product=intval($this->fk_product); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->lang)) $this->lang=trim($this->lang); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); - if (isset($this->last_update_stock)) $this->last_update_stock=trim($this->last_update_stock); + if (isset($this->fk_product)) $this->fk_product = intval($this->fk_product); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->lang)) $this->lang = trim($this->lang); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); + if (isset($this->last_update_stock)) $this->last_update_stock = trim($this->last_update_stock); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_product SET"; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_product SET"; - $sql.= " fk_product=".(isset($this->fk_product)?intval($this->fk_product):0).","; - $sql.= " fk_site=".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " remote_id='".$this->db->escape($this->remote_id)."',"; - $sql.= " lang=".(!empty($this->lang)?"'".$this->db->escape($this->lang)."'" : 'null').","; - $sql.= " last_update=".(isset($this->last_update)?"'".$this->last_update."'" : 'null').","; - $sql.= " last_update_stock=".(isset($this->last_update_stock)?"'".$this->last_update_stock."'" : 'null').""; + $sql .= " fk_product=" . (isset($this->fk_product) ? intval($this->fk_product) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id='" . $this->db->escape($this->remote_id) . "',"; + $sql .= " lang=" . (!empty($this->lang) ? "'" . $this->db->escape($this->lang) . "'" : 'null') . ","; + $sql .= " last_update=" . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ","; + $sql .= " last_update_stock=" . (isset($this->last_update_stock) ? "'" . $this->last_update_stock . "'" : 'null') . ","; + $sql .= " other_data=" . (!empty($this->other_data) ? "'" . $this->db->escape(json_encode($this->other_data)) . "'" : "NULL") . ""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); return 1; } - } - + } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0) + public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_product"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_product"; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } @@ -312,43 +302,39 @@ function delete($user, $notrigger=0) * Get the last date of the last updated product * * @param int $siteId eCommerceSite id | * for each sites - * @return datetime + * @return int */ public function getLastUpdate($siteId) { global $langs; - $sql = "SELECT MAX(t.last_update) as lastdate FROM ".MAIN_DB_PREFIX."ecommerce_product as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - dol_syslog(get_class($this)."::getLastUpdate sql=".$sql, LOG_DEBUG); - - $lastdate = null; - - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . "ecommerce_product as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); + + $lastdate = null; + + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); if ($obj->lastdate != null) - $lastdate = $this->db->jdate($obj->lastdate); - } - $this->db->free($resql); - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getLastUpdate ".$this->error, LOG_ERR); - } - return $lastdate; + $lastdate = $this->db->jdate($obj->lastdate); + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); + } + return $lastdate; } /** - * Load object in memory from database by remote_id - * - * @param int $remoteId string remote_id - * @param int $siteId int fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * + * @param int $remoteId string remote_id + * @param int $siteId int fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByRemoteId($remoteId, $siteId) { global $langs; @@ -357,12 +343,14 @@ public function fetchByRemoteId($remoteId, $siteId) $sql .= " t.fk_product,"; $sql .= " t.fk_site,"; $sql .= " t.remote_id,"; - $sql .= " t.lang,"; + $sql .= " t.lang,"; $sql .= " t.last_update,"; - $sql .= " t.last_update_stock"; + $sql .= " t.last_update_stock,"; + $sql .= " t.other_data"; $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_product as t"; $sql .= " WHERE t.fk_site = " . $siteId; - $sql .= " AND t.remote_id LIKE '" . $this->db->escape($remoteId) . "'"; + $sql .= " AND (t.remote_id LIKE '" . $this->db->escape($remoteId) . "'"; + $sql .= " OR JSON_SEARCH(t.other_data, 'one', '" . $this->db->escape($remoteId) . "', NULL, '$.translations_ids') IS NOT NULL)"; dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -373,9 +361,10 @@ public function fetchByRemoteId($remoteId, $siteId) $this->fk_product = $obj->fk_product; $this->fk_site = $obj->fk_site; $this->remote_id = $obj->remote_id; - $this->lang = $obj->lang; + $this->lang = $obj->lang; $this->last_update = $obj->last_update; - $this->last_update_stock = $obj->last_update_stock; + $this->last_update_stock = $obj->last_update_stock; + $this->other_data = !empty($obj->other_data) ? json_decode($obj->other_data, true) : []; $this->db->free($resql); return 1; } elseif ($num > 1) { @@ -397,89 +386,83 @@ public function fetchByRemoteId($remoteId, $siteId) } /** - * Load object in memory from database by remote_id - * - * @param int $productId string product_id - * @param int $siteId int fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * + * @param int $productId string product_id + * @param int $siteId int fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByProductId($productId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_product,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.lang,"; - $sql.= " t.last_update,"; - $sql.= " t.last_update_stock"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_product as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.fk_product = ".$productId; - dol_syslog(get_class($this)."::fetchByProductId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_product = $obj->fk_product; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->lang = $obj->lang; - $this->last_update = $obj->last_update; - $this->last_update_stock = $obj->last_update_stock; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return 0; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByProductId ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Select all the ids from eCommerceProduct for a site - * - * @param int $siteId Id site - * @return array synchObject ids for this site - */ - public function getAllECommerceProductIds($siteId) - { - global $langs; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ecommerce_product"; - $sql.= " WHERE fk_site = ".$siteId; - dol_syslog(get_class($this)."::getAllECommerceProductIds sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while($ii < $num) - { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getAllECommerceProductIds ".$this->error, LOG_ERR); - return -1; - } - } + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_product,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.lang,"; + $sql .= " t.last_update,"; + $sql .= " t.last_update_stock,"; + $sql .= " t.other_data"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_product as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.fk_product = " . $productId; + dol_syslog(get_class($this) . "::fetchByProductId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_product = $obj->fk_product; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->lang = $obj->lang; + $this->last_update = $obj->last_update; + $this->last_update_stock = $obj->last_update_stock; + $this->other_data = !empty($obj->other_data) ? json_decode($obj->other_data, true) : []; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return 0; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByProductId " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Select all the ids from eCommerceProduct for a site + * + * @param int $siteId Id site + * @return array synchObject ids for this site + */ + public function getAllECommerceProductIds($siteId) + { + global $langs; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_product"; + $sql .= " WHERE fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getAllECommerceProductIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceProductIds " . $this->error, LOG_ERR); + return -1; + } + } /** * Method to output saved errors diff --git a/class/data/eCommerceRemoteAccess.class.php b/class/data/eCommerceRemoteAccess.class.php index 7a411bb..5857c61 100644 --- a/class/data/eCommerceRemoteAccess.class.php +++ b/class/data/eCommerceRemoteAccess.class.php @@ -29,184 +29,184 @@ class eCommerceRemoteAccess private $class; private $db; - public $error; + public $error; public $errors; - /** - * Class for access remote sites - * Creates an instance of the appropriate class according to type of site - * - * @param Database $db Databse handler - * @param eCommerceSite $site eCommerceSite - */ - function __construct($db, $site) - { - $this->db = $db; - $this->site = $site; + /** + * Class for access remote sites + * Creates an instance of the appropriate class according to type of site + * + * @param Database $db Databse handler + * @param eCommerceSite $site eCommerceSite + */ + public function __construct($db, $site) + { + $this->db = $db; + $this->site = $site; - $this->setName(); + $this->setName(); - dol_include_once('/ecommerceng/class/data/'.$this->dirName.'/eCommerceRemoteAccess'.$this->className.'.class.php'); + dol_include_once('/ecommerceng/class/data/' . $this->dirName . '/eCommerceRemoteAccess' . $this->className . '.class.php'); - $this->setClass(); + $this->setClass(); - return 1; - } + return 1; + } private function setName() { $types = $this->site->getSiteTypes(); $name = $types[$this->site->type]; - $this->className = str_replace(' ','',ucwords($name)); - $this->dirName = str_replace(' ','',strtolower($name)); + $this->className = str_replace(' ', '', ucwords($name)); + $this->dirName = str_replace(' ', '', strtolower($name)); } - private function setClass() - { - $className = get_class($this).$this->className; - $class = new $className($this->db, $this->site); - $this->class = $class; - } + private function setClass() + { + $className = get_class($this) . $this->className; + $class = new $className($this->db, $this->site); + $this->class = $class; + } public function getClass() { return $this->class; } - /** - * Call the connect method of the class instantiated in the constructor - */ - public function connect() - { + /** + * Call the connect method of the class instantiated in the constructor + */ + public function connect() + { $result = $this->class->connect(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } - - /** - * Get societe to update from instantiated class in the constructor - * - * @param datetime $fromDate Updates from this date - * @param datetime $toDate Updates to this date - * @return array Array of remote societe - */ - public function getSocieteToUpdate($fromDate, $toDate) - { - $result = $this->class->getSocieteToUpdate($fromDate, $toDate); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Get product to update from instantiated class in the constructor - * - * @param datetime $fromDate Updates from this date - * @param datetime $toDate Updates to this date - * @return array Array of remote product - */ - public function getProductToUpdate($fromDate, $toDate) + /** + * Get societe to update from instantiated class in the constructor + * + * @param datetime $fromDate Updates from this date + * @param datetime $toDate Updates to this date + * @return array Array of remote societe + */ + public function getSocieteToUpdate($fromDate, $toDate) { - $result=$this->class->getProductToUpdate($fromDate, $toDate); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->getSocieteToUpdate($fromDate, $toDate); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } + + /** + * Get product to update from instantiated class in the constructor + * + * @param datetime $fromDate Updates from this date + * @param datetime $toDate Updates to this date + * @return array Array of remote product + */ + public function getProductToUpdate($fromDate, $toDate) + { + $result = $this->class->getProductToUpdate($fromDate, $toDate); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Get commande to update from instantiated class in the constructor - * - * @param datetime $fromDate Updates from this date - * @param datetime $toDate Updates to this date - * @return array Array of remote commande or false if error - */ - public function getCommandeToUpdate($fromDate, $toDate) + /** + * Get commande to update from instantiated class in the constructor + * + * @param datetime $fromDate Updates from this date + * @param datetime $toDate Updates to this date + * @return array Array of remote commande or false if error + */ + public function getCommandeToUpdate($fromDate, $toDate) { - $result=$this->class->getCommandeToUpdate($fromDate, $toDate); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->getCommandeToUpdate($fromDate, $toDate); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } - /** - * Get facture to update from instantiated class in the constructor - * - * @param datetime $fromDate Updates from this date - * @param datetime $toDate Updates to this date - * @return array Array of remote facture - */ - public function getFactureToUpdate($fromDate, $toDate) + /** + * Get facture to update from instantiated class in the constructor + * + * @param datetime $fromDate Updates from this date + * @param datetime $toDate Updates to this date + * @return array Array of remote facture + */ + public function getFactureToUpdate($fromDate, $toDate) { - $result=$this->class->getFactureToUpdate($fromDate, $toDate); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->getFactureToUpdate($fromDate, $toDate); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Put the remote data into category dolibarr data from instantiated class in the constructor - * - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrCategory($remoteObject,$toNb=0) + /** + * Put the remote data into category dolibarr data from instantiated class in the constructor + * + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrCategory($remoteObject,$toNb=0) { - $result=$this->class->convertRemoteObjectIntoDolibarrCategory($remoteObject,$toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->convertRemoteObjectIntoDolibarrCategory($remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** - * Put the remote data into societe dolibarr data from instantiated class in the constructor - * + * Put the remote data into societe dolibarr data from instantiated class in the constructor + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrSociete($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) - { - $result=$this->class->convertRemoteObjectIntoDolibarrSociete($from_date, $to_date, $remoteObject, $toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrSociete($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) + { + $result = $this->class->convertRemoteObjectIntoDolibarrSociete($from_date, $to_date, $remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Put the remote data into societe dolibarr data from instantiated class in the constructor - * - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrSocpeople($remoteObject,$toNb=0) + /** + * Put the remote data into societe dolibarr data from instantiated class in the constructor + * + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrSocpeople($remoteObject,$toNb=0) { - $result=$this->class->convertRemoteObjectIntoDolibarrSocpeople($remoteObject,$toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->convertRemoteObjectIntoDolibarrSocpeople($remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Put the remote data into product dolibarr data from instantiated class in the constructor - * + /** + * Put the remote data into product dolibarr data from instantiated class in the constructor + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) - { - $result=$this->class->convertRemoteObjectIntoDolibarrProduct($from_date, $to_date, $remoteObject,$toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) + { + $result = $this->class->convertRemoteObjectIntoDolibarrProduct($from_date, $to_date, $remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -217,42 +217,42 @@ public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_da */ public function checkRemoteProductExist($remote_id) { - $result=$this->class->checkRemoteProductExist($remote_id); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->checkRemoteProductExist($remote_id); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } - /** - * Put the remote data into commande dolibarr data from instantiated class in the constructor - * + /** + * Put the remote data into commande dolibarr data from instantiated class in the constructor + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrCommande($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) - { - $result=$this->class->convertRemoteObjectIntoDolibarrCommande($from_date, $to_date, $remoteObject,$toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrCommande($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) + { + $result = $this->class->convertRemoteObjectIntoDolibarrCommande($from_date, $to_date, $remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Put the remote data into facture dolibarr data from instantiated class in the constructor - * - * @param array $remoteObject Array of remote object - * @param int $toNb Max nb - * @return $dolibarrObject array - */ - public function convertRemoteObjectIntoDolibarrFacture($remoteObject,$toNb=0) + /** + * Put the remote data into facture dolibarr data from instantiated class in the constructor + * + * @param array $remoteObject Array of remote object + * @param int $toNb Max nb + * @return $dolibarrObject array + */ + public function convertRemoteObjectIntoDolibarrFacture($remoteObject,$toNb=0) { - $result=$this->class->convertRemoteObjectIntoDolibarrFacture($remoteObject,$toNb); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->convertRemoteObjectIntoDolibarrFacture($remoteObject, $toNb); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } @@ -264,9 +264,9 @@ public function convertRemoteObjectIntoDolibarrFacture($remoteObject,$toNb=0) */ public function convertOrderDataIntoProcessedData($remote_data) { - $result=$this->class->convertOrderDataIntoProcessedData($remote_data); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->convertOrderDataIntoProcessedData($remote_data); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } @@ -278,24 +278,24 @@ public function convertOrderDataIntoProcessedData($remote_data) */ public function convertProductDataIntoProcessedData($remote_data) { - $result=$this->class->convertProductDataIntoProcessedData($remote_data); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->convertProductDataIntoProcessedData($remote_data); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } - /** - * Get a commande from instantiated class in the constructor - * - * @param int $remoteCommandeId string - * @return array dolibarrObject array - */ + /** + * Get a commande from instantiated class in the constructor + * + * @param int $remoteCommandeId string + * @return array dolibarrObject array + */ public function getRemoteCommande($remoteCommandeId) { - $result=$this->class->getRemoteCommande($remoteCommandeId); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->getRemoteCommande($remoteCommandeId); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -305,10 +305,10 @@ public function getRemoteCommande($remoteCommandeId) */ public function getRemoteCategoryTree() { - $result=$this->class->getRemoteCategoryTree(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->getRemoteCategoryTree(); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -324,18 +324,18 @@ public function getRemoteCategoryTree() return $result; }*/ - /** - * Get list of address id for a customer - * - * @param int $remote_thirdparty_id Remote thirdparty id - * @return $dolibarrObject array - */ - public function getRemoteAddressIdForSociete($remote_thirdparty_id) - { - $result=$this->class->getRemoteAddressIdForSociete($remote_thirdparty_id); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + /** + * Get list of address id for a customer + * + * @param int $remote_thirdparty_id Remote thirdparty id + * @return $dolibarrObject array + */ + public function getRemoteAddressIdForSociete($remote_thirdparty_id) + { + $result = $this->class->getRemoteAddressIdForSociete($remote_thirdparty_id); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -346,10 +346,10 @@ public function getRemoteAddressIdForSociete($remote_thirdparty_id) */ public function getCategoryData($category_id) { - $result=$this->class->getCategoryData($category_id); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->getCategoryData($category_id); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } @@ -362,10 +362,10 @@ public function getCategoryData($category_id) */ public function updateRemoteProduct($remote_product_id, $object) { - $result=$this->class->updateRemoteProduct($remote_product_id, $object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteProduct($remote_product_id, $object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -378,10 +378,10 @@ public function updateRemoteProduct($remote_product_id, $object) */ public function updateRemoteStockProduct($remote_product_id, $product, &$eCommerceProduct) { - $result=$this->class->updateRemoteStockProduct($remote_product_id, $product, $eCommerceProduct); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteStockProduct($remote_product_id, $product, $eCommerceProduct); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -393,10 +393,10 @@ public function updateRemoteStockProduct($remote_product_id, $product, &$eCommer */ public function updateRemoteSociete($remote_societe_id, $object) { - $result=$this->class->updateRemoteSociete($remote_societe_id, $object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteSociete($remote_societe_id, $object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -408,10 +408,10 @@ public function updateRemoteSociete($remote_societe_id, $object) */ public function updateRemoteSocpeople($remote_contact_id, $object) { - $result=$this->class->updateRemoteSocpeople($remote_contact_id, $object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteSocpeople($remote_contact_id, $object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -423,10 +423,10 @@ public function updateRemoteSocpeople($remote_contact_id, $object) */ public function updateRemoteCommande($remote_order_id, $object) { - $result=$this->class->updateRemoteCommande($remote_order_id, $object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteCommande($remote_order_id, $object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** @@ -438,98 +438,98 @@ public function updateRemoteCommande($remote_order_id, $object) */ public function updateRemoteFactue($remote_invoice_id, $object) { - $result=$this->class->updateRemoteFacture($remote_invoice_id, $object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->updateRemoteFacture($remote_invoice_id, $object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } /** - * Create a remote livraison from instantiated class in the constructor - * - * @param Object $livraison Object livraison - * @param int $remote_order_id String id remote order - * @return bool - */ + * Create a remote livraison from instantiated class in the constructor + * + * @param Object $livraison Object livraison + * @param int $remote_order_id String id remote order + * @return bool + */ public function createRemoteLivraison($livraison, $remote_order_id) { - $result=$this->class->createRemoteLivraison($livraison, $remote_order_id); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; + $result = $this->class->createRemoteLivraison($livraison, $remote_order_id); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; } - /** - * Create a remote product - * - * @param Object $object Object product - * @return bool - */ - public function createRemoteProduct($object) - { - $result=$this->class->createRemoteProduct($object); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } - - /** - * Create batch remote categories - * - * @param array $batch Array of object category - * @return bool|array - */ - public function createRemoteCategories($batch) - { - $result=$this->class->createRemoteCategories($batch); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } - - /** - * Create batch remote products - * - * @param array $batch Array of id product - * @return array - */ - public function batchUpdateRemoteProducts($batch) - { - $result=$this->class->batchUpdateRemoteProducts($batch); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } - - /** - * Send a file for remote commande - * - * @param int $order_remote_id Id of order on remote ecommerce - * @param Object $object Object product - * @param string $file File path - * @param Translate $outputlangs Lang output object - * @return bool - */ - public function sendFileForCommande($order_remote_id, $object, $file, $outputlangs) - { - $result=$this->class->sendFileForCommande($order_remote_id, $object, $file, $outputlangs); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } - - /** - * Get all payment gateways - * - * @return array|false List of payment gateways or false if error - */ - public function getAllPaymentGateways() - { - $result=$this->class->getAllPaymentGateways(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; - return $result; - } + /** + * Create a remote product + * + * @param Object $object Object product + * @return bool + */ + public function createRemoteProduct($object) + { + $result = $this->class->createRemoteProduct($object); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } + + /** + * Create batch remote categories + * + * @param array $batch Array of object category + * @return bool|array + */ + public function createRemoteCategories($batch) + { + $result = $this->class->createRemoteCategories($batch); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } + + /** + * Create batch remote products + * + * @param array $batch Array of id product + * @return array + */ + public function batchUpdateRemoteProducts($batch) + { + $result = $this->class->batchUpdateRemoteProducts($batch); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } + + /** + * Send a file for remote commande + * + * @param int $order_remote_id Id of order on remote ecommerce + * @param Object $object Object product + * @param string $file File path + * @param Translate $outputlangs Lang output object + * @return bool + */ + public function sendFileForCommande($order_remote_id, $object, $file, $outputlangs) + { + $result = $this->class->sendFileForCommande($order_remote_id, $object, $file, $outputlangs); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } + + /** + * Get all payment gateways + * + * @return array|false List of payment gateways or false if error + */ + public function getAllPaymentGateways() + { + $result = $this->class->getAllPaymentGateways(); + $this->error = $this->class->error; + $this->errors = $this->class->errors; + return $result; + } /** * Get all remote warehouses @@ -538,9 +538,9 @@ public function getAllPaymentGateways() */ public function getAllRemoteWarehouses() { - $result=$this->class->getAllRemoteWarehouses(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->getAllRemoteWarehouses(); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } @@ -551,9 +551,9 @@ public function getAllRemoteWarehouses() */ public function getAllRemoteShippingZones() { - $result=$this->class->getAllRemoteShippingZones(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->getAllRemoteShippingZones(); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } @@ -565,9 +565,9 @@ public function getAllRemoteShippingZones() */ public function getAllRemoteShippingZoneMethods($remote_zone_id) { - $result=$this->class->getAllRemoteShippingZoneMethods($remote_zone_id); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->getAllRemoteShippingZoneMethods($remote_zone_id); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } @@ -578,20 +578,20 @@ public function getAllRemoteShippingZoneMethods($remote_zone_id) */ public function getAllWebHooks() { - $result=$this->class->getAllWebHooks(); - $this->error=$this->class->error; - $this->errors=$this->class->errors; + $result = $this->class->getAllWebHooks(); + $this->error = $this->class->error; + $this->errors = $this->class->errors; return $result; } - /** - * Method to output saved errors - * - * @param string $separator Separator between each error - * @return string String with errors - */ - public function errorsToString($separator = ', ') - { - return $this->error . (is_array($this->errors) ? (!empty($this->error) ? $separator : '') . join($separator, $this->errors) : ''); - } + /** + * Method to output saved errors + * + * @param string $separator Separator between each error + * @return string String with errors + */ + public function errorsToString($separator = ', ') + { + return $this->error . (is_array($this->errors) ? (!empty($this->error) ? $separator : '') . join($separator, $this->errors) : ''); + } } diff --git a/class/data/eCommerceRemoteShippingZoneMethods.class.php b/class/data/eCommerceRemoteShippingZoneMethods.class.php index 001b9f6..8e766af 100644 --- a/class/data/eCommerceRemoteShippingZoneMethods.class.php +++ b/class/data/eCommerceRemoteShippingZoneMethods.class.php @@ -182,7 +182,7 @@ public function set($site_id, $remote_shipping_zone_methods) * @return array|int 0 if not found, <0 if errors or array of infos * @throws Exception */ - public function get($site_id, $remote_instance_id=0, $remote_method_id='') + public function get($site_id, $remote_instance_id = 0, $remote_method_id = '') { global $conf; dol_syslog(__METHOD__ . " site_id=$site_id, remote_instance_id=$remote_instance_id, remote_method_id=$remote_method_id"); diff --git a/class/data/eCommerceRemoteShippingZones.class.php b/class/data/eCommerceRemoteShippingZones.class.php index 65efe09..2694495 100644 --- a/class/data/eCommerceRemoteShippingZones.class.php +++ b/class/data/eCommerceRemoteShippingZones.class.php @@ -151,7 +151,7 @@ public function set($site_id, $remote_shipping_zones) * @return array|int 0 if not found, <0 if errors or array of infos * @throws Exception */ - public function get($site_id, $remote_id='') + public function get($site_id, $remote_id = '') { global $conf; dol_syslog(__METHOD__ . " site_id=$site_id, remote_id=$remote_id"); diff --git a/class/data/eCommerceRemoteWarehouses.class.php b/class/data/eCommerceRemoteWarehouses.class.php index a4a2fb4..a900ebe 100644 --- a/class/data/eCommerceRemoteWarehouses.class.php +++ b/class/data/eCommerceRemoteWarehouses.class.php @@ -29,40 +29,40 @@ */ class eCommerceRemoteWarehouses { - /** - * @var DoliDB Database handler. - */ - public $db; - /** - * @var string Error - */ - public $error = ''; - /** - * @var array Errors - */ - public $errors = array(); + /** + * @var DoliDB Database handler. + */ + public $db; + /** + * @var string Error + */ + public $error = ''; + /** + * @var array Errors + */ + public $errors = array(); - public $table_element = 'ecommerceng_remote_warehouses'; + public $table_element = 'ecommerceng_remote_warehouses'; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Set all remote warehouse of a site - * - * @param int $site_id Site ID - * @param array $remote_warehouses List of infos of each remote warehouse - * @return int >0 if OK, <0 if KO - * @throws Exception - */ - public function set($site_id, $remote_warehouses) + /** + * Set all remote warehouse of a site + * + * @param int $site_id Site ID + * @param array $remote_warehouses List of infos of each remote warehouse + * @return int >0 if OK, <0 if KO + * @throws Exception + */ + public function set($site_id, $remote_warehouses) { global $conf, $langs; dol_syslog(__METHOD__ . " site_id=$site_id, remote_warehouses=" . json_encode($remote_warehouses)); @@ -109,7 +109,7 @@ public function set($site_id, $remote_warehouses) // Update values $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; $sql .= " remote_code = '" . $this->db->escape($infos['remote_code']) . "'"; - $sql .= ", remote_name = '" . $this->db->escape($infos['remote_name']) . "'"; + $sql .= ", remote_name = '" . $this->db->escape($infos['remote_name']) . "'"; $sql .= ", warehouse_id = " . ($infos['warehouse_id'] > 0 ? $infos['warehouse_id'] : 'NULL'); $sql .= ', set_even_if_empty_stock = ' . (!empty($infos['set_even_if_empty_stock']) ? 1 : 'NULL'); $sql .= ', old_entry = ' . (!empty($infos['old_entry']) ? 1 : 'NULL'); @@ -122,7 +122,7 @@ public function set($site_id, $remote_warehouses) $sql .= $site_id; $sql .= ", '" . $this->db->escape($infos['remote_code']) . "'"; $sql .= ", '" . $this->db->escape($infos['remote_id']) . "'"; - $sql .= ", '" . $this->db->escape($infos['remote_name']) . "'"; + $sql .= ", '" . $this->db->escape($infos['remote_name']) . "'"; $sql .= ', ' . ($infos['warehouse_id'] > 0 ? $infos['warehouse_id'] : 'NULL'); $sql .= ', ' . (!empty($infos['set_even_if_empty_stock']) ? 1 : 'NULL'); $sql .= ', ' . (!empty($infos['old_entry']) ? 1 : 'NULL'); @@ -147,110 +147,110 @@ public function set($site_id, $remote_warehouses) } } - /** - * Get a remote warehouse of a site by the remote warehouse code or warehouse id - * - * @param int $site_id Site ID + /** + * Get a remote warehouse of a site by the remote warehouse code or warehouse id + * + * @param int $site_id Site ID * @param string $remote_id Remote warehouse ID on site - * @param int $warehouse_id Warehouse ID on Dolibarr - * @return array|int 0 if not found, <0 if errors or array of infos - * @throws Exception - */ - public function get($site_id, $remote_id='', $warehouse_id=0) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id, remote_code=$remote_code, warehouse_id=$warehouse_id"); + * @param int $warehouse_id Warehouse ID on Dolibarr + * @return array|int 0 if not found, <0 if errors or array of infos + * @throws Exception + */ + public function get($site_id, $remote_id = '', $warehouse_id = 0) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id, remote_id=$remote_id, warehouse_id=$warehouse_id"); - $sql = 'SELECT remote_code, remote_id, remote_name, warehouse_id, set_even_if_empty_stock, old_entry FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - if ($warehouse_id > 0) { + $sql = 'SELECT remote_code, remote_id, remote_name, warehouse_id, set_even_if_empty_stock, old_entry FROM ' . MAIN_DB_PREFIX . $this->table_element; + $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + if ($warehouse_id > 0) { $sql .= ' AND warehouse_id = ' . $warehouse_id; $sql .= ' AND old_entry IS NULL'; } else { - $sql .= " AND remote_id = '" . $this->db->escape($remote_id) . "'"; - } - $resql = $this->db->query($sql); - if ($resql) { - if ($this->db->num_rows($resql) == 0) - return 0; + $sql .= " AND remote_id = '" . $this->db->escape($remote_id) . "'"; + } + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 0) + return 0; - if ($obj = $this->db->fetch_object($resql)) { - return array( + if ($obj = $this->db->fetch_object($resql)) { + return array( 'remote_code' => $obj->remote_code, - 'remote_id' => $obj->remote_id, + 'remote_id' => $obj->remote_id, 'remote_name' => $obj->remote_name, 'warehouse_id' => $obj->warehouse_id > 0 ? $obj->warehouse_id : 0, 'set_even_if_empty_stock' => !empty($obj->set_even_if_empty_stock) ? 1 : 0, 'old_entry' => !empty($obj->old_entry) ? 1 : 0, - ); - } - } else { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $this->errors[] = $this->db->lasterror(); - return -1; - } - } + ); + } + } else { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $this->errors[] = $this->db->lasterror(); + return -1; + } + } - /** - * Get all remote warehouses of a site - * - * @param int $site_id Site ID - * @return array|int List of all remote warehouses infos - * @throws Exception - */ - public function get_all($site_id) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id"); + /** + * Get all remote warehouses of a site + * + * @param int $site_id Site ID + * @return array|int List of all remote warehouses infos + * @throws Exception + */ + public function get_all($site_id) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id"); - $warehouses = array(); + $warehouses = array(); - $sql = 'SELECT remote_code, remote_id, remote_name, warehouse_id, set_even_if_empty_stock, old_entry FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { + $sql = 'SELECT remote_code, remote_id, remote_name, warehouse_id, set_even_if_empty_stock, old_entry FROM ' . MAIN_DB_PREFIX . $this->table_element; + $sql .= ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $warehouses[$obj->remote_id] = array( - 'remote_code' => $obj->remote_code, + 'remote_code' => $obj->remote_code, 'remote_id' => $obj->remote_id, - 'remote_name' => $obj->remote_name, - 'warehouse_id' => $obj->warehouse_id, - 'set_even_if_empty_stock' => !empty($obj->set_even_if_empty_stock) ? 1 : 0, + 'remote_name' => $obj->remote_name, + 'warehouse_id' => $obj->warehouse_id, + 'set_even_if_empty_stock' => !empty($obj->set_even_if_empty_stock) ? 1 : 0, 'old_entry' => !empty($obj->old_entry) ? 1 : 0, - ); - } - } else { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $this->errors[] = $this->db->lasterror(); - return -1; - } + ); + } + } else { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $this->errors[] = $this->db->lasterror(); + return -1; + } - return $warehouses; - } + return $warehouses; + } - /** - * Delete all remote warehouses of a site - * - * @param int $site_id Site ID - * @return int >0 if OK, <0 if KO - * @throws Exception - */ - public function delete_all($site_id) - { - global $conf; - dol_syslog(__METHOD__ . " site_id=$site_id"); + /** + * Delete all remote warehouses of a site + * + * @param int $site_id Site ID + * @return int >0 if OK, <0 if KO + * @throws Exception + */ + public function delete_all($site_id) + { + global $conf; + dol_syslog(__METHOD__ . " site_id=$site_id"); - // Delete all line for the site - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; - $resql = $this->db->query($sql); - if (!$resql) { - dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); - $this->errors[] = $this->db->lasterror(); - return -1; - } + // Delete all line for the site + $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . ' WHERE site_id = ' . $site_id . ' AND entity = ' . $conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + dol_syslog(__METHOD__ . ' SQL: ' . $sql . '; Errors: ' . $this->db->lasterror(), LOG_ERR); + $this->errors[] = $this->db->lasterror(); + return -1; + } - return 1; - } + return 1; + } /** * Method to output saved errors diff --git a/class/data/eCommerceSite.class.php b/class/data/eCommerceSite.class.php index 4b6701b..925b052 100644 --- a/class/data/eCommerceSite.class.php +++ b/class/data/eCommerceSite.class.php @@ -44,14 +44,14 @@ class eCommerceSite // extends CommonObject public $filter_value; public $fk_cat_societe; public $fk_cat_product; - public $fk_anonymous_thirdparty; + public $fk_anonymous_thirdparty; public $fk_warehouse; public $stock_sync_direction; public $last_update; public $timeout; public $debug; public $magento_use_special_price; - public $ecommerce_price_type; + public $ecommerce_price_type; public $entity; public $wordpress_authentication_type; @@ -60,22 +60,22 @@ class eCommerceSite // extends CommonObject public $wordpress_timeout; public $wordpress_debug; - public $parameters; + public $parameters; - public $languages_cached; + public $languages_cached; //The site type name is used to define class name in eCommerceRemoteAccess class - private $siteTypes = array(2=>'woocommerce'); + private $siteTypes = array(2=>'woocommerce'); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } /** @@ -83,7 +83,7 @@ function __construct($db) * * @return void */ - function cleanOrphelins() + public function cleanOrphelins() { $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__); // Clean orphelins entries to have a clean database (having such records should not happen) @@ -113,7 +113,7 @@ function cleanOrphelins() * * @return void */ - function cleanDuplicatesRemoteID() + public function cleanDuplicatesRemoteID() { $stopwatch_id = eCommerceUtils::startAndLogStopwatch(__METHOD__); $ids = array(); @@ -134,194 +134,189 @@ function cleanDuplicatesRemoteID() eCommerceUtils::stopAndLogStopwatch($stopwatch_id); } - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->name)) $this->name=trim($this->name); - if (isset($this->type)) $this->type=trim($this->type); - if (isset($this->webservice_address)) $this->webservice_address=trim($this->webservice_address); - if (isset($this->api_version)) $this->api_version=trim($this->api_version); - if (isset($this->authentication_type)) $this->authentication_type=trim($this->authentication_type); - if (isset($this->user_name)) $this->user_name=trim($this->user_name); - if (isset($this->user_password)) $this->user_password=trim($this->user_password); - if (isset($this->price_level)) $this->price_level=trim($this->price_level); - if (isset($this->filter_label)) $this->filter_label=trim($this->filter_label); - if (isset($this->filter_value)) $this->filter_value=trim($this->filter_value); - if (isset($this->fk_cat_societe)) $this->fk_cat_societe=trim($this->fk_cat_societe); - if (isset($this->fk_cat_product)) $this->fk_cat_product=trim($this->fk_cat_product); - if (isset($this->fk_anonymous_thirdparty)) $this->fk_anonymous_thirdparty=trim($this->fk_anonymous_thirdparty); - if (isset($this->fk_warehouse)) $this->fk_warehouse=trim($this->fk_warehouse); - if (isset($this->stock_sync_direction)) $this->stock_sync_direction=trim($this->stock_sync_direction); - if (isset($this->timeout)) $this->timeout=trim($this->timeout); - - if (isset($this->wordpress_authentication_type)) $this->wordpress_authentication_type=trim($this->wordpress_authentication_type); - if (isset($this->wordpress_authentication_login)) $this->wordpress_authentication_login=trim($this->wordpress_authentication_login); - if (isset($this->wordpress_authentication_password)) $this->wordpress_authentication_password=trim($this->wordpress_authentication_password); - if (isset($this->wordpress_timeout)) $this->wordpress_timeout=trim($this->wordpress_timeout); + if (isset($this->name)) $this->name = trim($this->name); + if (isset($this->type)) $this->type = trim($this->type); + if (isset($this->webservice_address)) $this->webservice_address = trim($this->webservice_address); + if (isset($this->api_version)) $this->api_version = trim($this->api_version); + if (isset($this->authentication_type)) $this->authentication_type = trim($this->authentication_type); + if (isset($this->user_name)) $this->user_name = trim($this->user_name); + if (isset($this->user_password)) $this->user_password = trim($this->user_password); + if (isset($this->price_level)) $this->price_level = trim($this->price_level); + if (isset($this->filter_label)) $this->filter_label = trim($this->filter_label); + if (isset($this->filter_value)) $this->filter_value = trim($this->filter_value); + if (isset($this->fk_cat_societe)) $this->fk_cat_societe = trim($this->fk_cat_societe); + if (isset($this->fk_cat_product)) $this->fk_cat_product = trim($this->fk_cat_product); + if (isset($this->fk_anonymous_thirdparty)) $this->fk_anonymous_thirdparty = trim($this->fk_anonymous_thirdparty); + if (isset($this->fk_warehouse)) $this->fk_warehouse = trim($this->fk_warehouse); + if (isset($this->stock_sync_direction)) $this->stock_sync_direction = trim($this->stock_sync_direction); + if (isset($this->timeout)) $this->timeout = trim($this->timeout); + + if (isset($this->wordpress_authentication_type)) $this->wordpress_authentication_type = trim($this->wordpress_authentication_type); + if (isset($this->wordpress_authentication_login)) $this->wordpress_authentication_login = trim($this->wordpress_authentication_login); + if (isset($this->wordpress_authentication_password)) $this->wordpress_authentication_password = trim($this->wordpress_authentication_password); + if (isset($this->wordpress_timeout)) $this->wordpress_timeout = trim($this->wordpress_timeout); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_site("; - $sql.= "name,"; - $sql.= "type,"; - $sql.= "webservice_address,"; - $sql.= "api_version,"; - $sql.= "authentication_type,"; - $sql.= "user_name,"; - $sql.= "user_password,"; - $sql.= "price_level,"; - $sql.= "filter_label,"; - $sql.= "filter_value,"; - $sql.= "fk_cat_societe,"; - $sql.= "fk_cat_product,"; - $sql.= "fk_anonymous_thirdparty,"; - $sql.= "fk_warehouse,"; - $sql.= "stock_sync_direction,"; - $sql.= "last_update,"; - $sql.= "timeout,"; - $sql.= "debug,"; - $sql.= "magento_use_special_price,"; - $sql.= "ecommerce_price_type,"; - $sql.= "wordpress_authentication_type,"; - $sql.= "wordpress_authentication_login,"; - $sql.= "wordpress_authentication_password,"; - $sql.= "wordpress_timeout,"; - $sql.= "wordpress_debug,"; - $sql.= "parameters,"; - $sql.= "entity"; - $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->name)?'NULL':"'".$this->db->escape($this->name)."'").","; - $sql.= " ".(! isset($this->type)?'NULL':"'".$this->type."'").","; - $sql.= " ".(! isset($this->webservice_address)?'NULL':"'".$this->db->escape($this->webservice_address)."'").","; - $sql.= " ".(! isset($this->api_version)?'NULL':"'".$this->db->escape($this->api_version)."'").","; - $sql.= " ".(! isset($this->authentication_type)?'NULL':"'".$this->db->escape($this->authentication_type)."'").","; - $sql.= " ".(! isset($this->user_name)?'NULL':"'".$this->db->escape($this->user_name)."'").","; - $sql.= " ".(! isset($this->user_password)?'NULL':"'".$this->db->escape($this->user_password)."'").","; - $sql.= " ".(! isset($this->price_level)?'1':"'".$this->db->escape($this->price_level)."'").","; - $sql.= " ".(! isset($this->filter_label)?'NULL':"'".$this->db->escape($this->filter_label)."'").","; - $sql.= " ".(! isset($this->filter_value)?'NULL':"'".$this->db->escape($this->filter_value)."'").","; - $sql.= " ".($this->fk_cat_societe > 0 ? $this->fk_cat_societe : "0").","; - $sql.= " ".($this->fk_cat_product > 0 ? $this->fk_cat_product : "0").","; - $sql.= " ".($this->fk_anonymous_thirdparty > 0 ? $this->fk_anonymous_thirdparty : "NULL").","; - $sql.= " ".($this->fk_warehouse > 0 ? $this->fk_warehouse : "NULL").","; - $sql.= " ".($this->stock_sync_direction ? "'".$this->stock_sync_direction."'" : "'none'").","; - $sql.= " ".(! isset($this->last_update) || strlen($this->last_update)==0?'NULL':"'".$this->db->idate($this->last_update)."'").","; - $sql.= " ".(! isset($this->timeout)?'30':"'".intval($this->timeout)."'").","; - $sql.= " ".(! empty($this->debug)?'1':"NULL").","; - $sql.= " ".(! isset($this->magento_use_special_price)?'0':"'".intval($this->magento_use_special_price)."'").","; - $sql.= " ".(! isset($this->ecommerce_price_type)?"'HT'":"'".$this->ecommerce_price_type."'").","; - $sql.= " ".(! isset($this->wordpress_authentication_type)?"NULL":"'".$this->db->escape($this->wordpress_authentication_type)."'").","; - $sql.= " ".(! isset($this->wordpress_authentication_login)?"NULL":"'".$this->db->escape($this->wordpress_authentication_login)."'").","; - $sql.= " ".(! isset($this->wordpress_authentication_password)?"NULL":"'".$this->db->escape($this->wordpress_authentication_password)."'").","; - $sql.= " ".(! isset($this->wordpress_timeout)?'30':"'".intval($this->wordpress_timeout)."'").","; - $sql.= " ".(! empty($this->wordpress_debug)?'1':"NULL").","; - $sql.= " ".(! isset($this->parameters)?"NULL":"'".$this->db->escape(json_encode($this->parameters))."'").","; - $sql.= " ".$conf->entity.""; - $sql.= ")"; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_site("; + $sql .= "name,"; + $sql .= "type,"; + $sql .= "webservice_address,"; + $sql .= "api_version,"; + $sql .= "authentication_type,"; + $sql .= "user_name,"; + $sql .= "user_password,"; + $sql .= "price_level,"; + $sql .= "filter_label,"; + $sql .= "filter_value,"; + $sql .= "fk_cat_societe,"; + $sql .= "fk_cat_product,"; + $sql .= "fk_anonymous_thirdparty,"; + $sql .= "fk_warehouse,"; + $sql .= "stock_sync_direction,"; + $sql .= "last_update,"; + $sql .= "timeout,"; + $sql .= "debug,"; + $sql .= "magento_use_special_price,"; + $sql .= "ecommerce_price_type,"; + $sql .= "wordpress_authentication_type,"; + $sql .= "wordpress_authentication_login,"; + $sql .= "wordpress_authentication_password,"; + $sql .= "wordpress_timeout,"; + $sql .= "wordpress_debug,"; + $sql .= "parameters,"; + $sql .= "entity"; + $sql .= ") VALUES ("; + $sql .= " " . (!isset($this->name) ? 'NULL' : "'" . $this->db->escape($this->name) . "'") . ","; + $sql .= " " . (!isset($this->type) ? 'NULL' : "'" . $this->type . "'") . ","; + $sql .= " " . (!isset($this->webservice_address) ? 'NULL' : "'" . $this->db->escape($this->webservice_address) . "'") . ","; + $sql .= " " . (!isset($this->api_version) ? 'NULL' : "'" . $this->db->escape($this->api_version) . "'") . ","; + $sql .= " " . (!isset($this->authentication_type) ? 'NULL' : "'" . $this->db->escape($this->authentication_type) . "'") . ","; + $sql .= " " . (!isset($this->user_name) ? 'NULL' : "'" . $this->db->escape($this->user_name) . "'") . ","; + $sql .= " " . (!isset($this->user_password) ? 'NULL' : "'" . $this->db->escape($this->user_password) . "'") . ","; + $sql .= " " . (!isset($this->price_level) ? '1' : "'" . $this->db->escape($this->price_level) . "'") . ","; + $sql .= " " . (!isset($this->filter_label) ? 'NULL' : "'" . $this->db->escape($this->filter_label) . "'") . ","; + $sql .= " " . (!isset($this->filter_value) ? 'NULL' : "'" . $this->db->escape($this->filter_value) . "'") . ","; + $sql .= " " . ($this->fk_cat_societe > 0 ? $this->fk_cat_societe : "0") . ","; + $sql .= " " . ($this->fk_cat_product > 0 ? $this->fk_cat_product : "0") . ","; + $sql .= " " . ($this->fk_anonymous_thirdparty > 0 ? $this->fk_anonymous_thirdparty : "NULL") . ","; + $sql .= " " . ($this->fk_warehouse > 0 ? $this->fk_warehouse : "NULL") . ","; + $sql .= " " . ($this->stock_sync_direction ? "'" . $this->stock_sync_direction . "'" : "'none'") . ","; + $sql .= " " . (!isset($this->last_update) || strlen($this->last_update) == 0 ? 'NULL' : "'" . $this->db->idate($this->last_update) . "'") . ","; + $sql .= " " . (!isset($this->timeout) ? '30' : "'" . intval($this->timeout) . "'") . ","; + $sql .= " " . (!empty($this->debug) ? '1' : "NULL") . ","; + $sql .= " " . (!isset($this->magento_use_special_price) ? '0' : "'" . intval($this->magento_use_special_price) . "'") . ","; + $sql .= " " . (!isset($this->ecommerce_price_type) ? "'HT'" : "'" . $this->ecommerce_price_type . "'") . ","; + $sql .= " " . (!isset($this->wordpress_authentication_type) ? "NULL" : "'" . $this->db->escape($this->wordpress_authentication_type) . "'") . ","; + $sql .= " " . (!isset($this->wordpress_authentication_login) ? "NULL" : "'" . $this->db->escape($this->wordpress_authentication_login) . "'") . ","; + $sql .= " " . (!isset($this->wordpress_authentication_password) ? "NULL" : "'" . $this->db->escape($this->wordpress_authentication_password) . "'") . ","; + $sql .= " " . (!isset($this->wordpress_timeout) ? '30' : "'" . intval($this->wordpress_timeout) . "'") . ","; + $sql .= " " . (!empty($this->wordpress_debug) ? '1' : "NULL") . ","; + $sql .= " " . (!isset($this->parameters) ? "NULL" : "'" . $this->db->escape(json_encode($this->parameters)) . "'") . ","; + $sql .= " " . $conf->entity . ""; + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_site"); - - // create an entry for anonymous company - $eCommerceSociete = new eCommerceSociete($this->db); - $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; - $eCommerceSociete->fk_site = $this->id; - $eCommerceSociete->remote_id = 0; - if ($eCommerceSociete->create($user)<0) - { - $error++; - $this->errors[]="Error ".$this->db->lasterror(); - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_site"); + + // create an entry for anonymous company + $eCommerceSociete = new eCommerceSociete($this->db); + $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; + $eCommerceSociete->fk_site = $this->id; + $eCommerceSociete->remote_id = 0; + if ($eCommerceSociete->create($user) < 0) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; } - } - - - /** - * Load object in memory from database - * - * @param int $id Id of object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.name,"; - $sql.= " t.type,"; - $sql.= " t.webservice_address,"; - $sql.= " t.api_version,"; - $sql.= " t.authentication_type,"; - $sql.= " t.user_name,"; - $sql.= " t.user_password,"; - $sql.= " t.price_level,"; - $sql.= " t.filter_label,"; - $sql.= " t.filter_value,"; - $sql.= " t.fk_cat_societe,"; - $sql.= " t.fk_cat_product,"; - $sql.= " t.fk_anonymous_thirdparty,"; - $sql.= " t.fk_warehouse,"; - $sql.= " t.stock_sync_direction,"; - $sql.= " t.last_update,"; - $sql.= " t.timeout,"; - $sql.= " t.debug,"; - $sql.= " t.magento_use_special_price,"; - $sql.= " t.ecommerce_price_type,"; - $sql.= " t.wordpress_authentication_type,"; - $sql.= " t.wordpress_authentication_login,"; - $sql.= " t.wordpress_authentication_password,"; - $sql.= " t.wordpress_timeout,"; - $sql.= " t.wordpress_debug,"; - $sql.= " t.parameters,"; - $sql.= " t.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_site as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; + } + + + /** + * Load object in memory from database + * + * @param int $id Id of object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.name,"; + $sql .= " t.type,"; + $sql .= " t.webservice_address,"; + $sql .= " t.api_version,"; + $sql .= " t.authentication_type,"; + $sql .= " t.user_name,"; + $sql .= " t.user_password,"; + $sql .= " t.price_level,"; + $sql .= " t.filter_label,"; + $sql .= " t.filter_value,"; + $sql .= " t.fk_cat_societe,"; + $sql .= " t.fk_cat_product,"; + $sql .= " t.fk_anonymous_thirdparty,"; + $sql .= " t.fk_warehouse,"; + $sql .= " t.stock_sync_direction,"; + $sql .= " t.last_update,"; + $sql .= " t.timeout,"; + $sql .= " t.debug,"; + $sql .= " t.magento_use_special_price,"; + $sql .= " t.ecommerce_price_type,"; + $sql .= " t.wordpress_authentication_type,"; + $sql .= " t.wordpress_authentication_login,"; + $sql .= " t.wordpress_authentication_password,"; + $sql .= " t.wordpress_timeout,"; + $sql .= " t.wordpress_debug,"; + $sql .= " t.parameters,"; + $sql .= " t.entity"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_site as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; $this->name = $obj->name; $this->type = $obj->type; @@ -330,12 +325,12 @@ function fetch($id) $this->authentication_type = $obj->authentication_type; $this->user_name = $obj->user_name; $this->user_password = $obj->user_password; - $this->price_level = $obj->price_level; + $this->price_level = $obj->price_level; $this->filter_label = $obj->filter_label; $this->filter_value = $obj->filter_value; $this->fk_cat_societe = $obj->fk_cat_societe; $this->fk_cat_product = $obj->fk_cat_product; - $this->fk_anonymous_thirdparty = $obj->fk_anonymous_thirdparty; + $this->fk_anonymous_thirdparty = $obj->fk_anonymous_thirdparty; $this->fk_warehouse = $obj->fk_warehouse; $this->stock_sync_direction = $obj->stock_sync_direction; $this->last_update = $this->db->jdate($obj->last_update); @@ -351,211 +346,202 @@ function fetch($id) $this->wordpress_timeout = $obj->wordpress_timeout > 0 ? $obj->wordpress_timeout : ''; $this->wordpress_debug = !empty($obj->wordpress_debug); - $this->parameters = json_decode($obj->parameters, true); - - return 1; - } - $this->db->free($resql); - - return 0; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + $this->parameters = json_decode($obj->parameters, true); + + return 1; + } + $this->db->free($resql); + + return 0; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user=0, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->name)) $this->name=trim($this->name); - if (isset($this->type)) $this->type=trim($this->type); - if (isset($this->webservice_address)) $this->webservice_address=trim($this->webservice_address); - if (isset($this->api_version)) $this->api_version=trim($this->api_version); - if (isset($this->authentication_type)) $this->authentication_type=trim($this->authentication_type); - if (isset($this->user_name)) $this->user_name=trim($this->user_name); - if (isset($this->user_password)) $this->user_password=trim($this->user_password); - if (isset($this->price_level)) $this->price_level=trim($this->price_level); - if (isset($this->filter_label)) $this->filter_label=trim($this->filter_label); - if (isset($this->filter_value)) $this->filter_value=trim($this->filter_value); - if (isset($this->fk_cat_societe)) $this->fk_cat_societe=trim($this->fk_cat_societe); - if (isset($this->fk_cat_product)) $this->fk_cat_product=trim($this->fk_cat_product); - if (isset($this->fk_anonymous_thirdparty)) $this->fk_anonymous_thirdparty=trim($this->fk_anonymous_thirdparty); - if (isset($this->fk_warehouse)) $this->fk_warehouse=trim($this->fk_warehouse); - if (isset($this->timeout)) $this->timeout=trim($this->timeout); - if (isset($this->wordpress_authentication_type)) $this->wordpress_authentication_type=trim($this->wordpress_authentication_type); - if (isset($this->wordpress_authentication_login)) $this->wordpress_authentication_login=trim($this->wordpress_authentication_login); - if (isset($this->wordpress_authentication_password)) $this->wordpress_authentication_password=trim($this->wordpress_authentication_password); - if (isset($this->wordpress_timeout)) $this->wordpress_timeout=trim($this->wordpress_timeout); + if (isset($this->name)) $this->name = trim($this->name); + if (isset($this->type)) $this->type = trim($this->type); + if (isset($this->webservice_address)) $this->webservice_address = trim($this->webservice_address); + if (isset($this->api_version)) $this->api_version = trim($this->api_version); + if (isset($this->authentication_type)) $this->authentication_type = trim($this->authentication_type); + if (isset($this->user_name)) $this->user_name = trim($this->user_name); + if (isset($this->user_password)) $this->user_password = trim($this->user_password); + if (isset($this->price_level)) $this->price_level = trim($this->price_level); + if (isset($this->filter_label)) $this->filter_label = trim($this->filter_label); + if (isset($this->filter_value)) $this->filter_value = trim($this->filter_value); + if (isset($this->fk_cat_societe)) $this->fk_cat_societe = trim($this->fk_cat_societe); + if (isset($this->fk_cat_product)) $this->fk_cat_product = trim($this->fk_cat_product); + if (isset($this->fk_anonymous_thirdparty)) $this->fk_anonymous_thirdparty = trim($this->fk_anonymous_thirdparty); + if (isset($this->fk_warehouse)) $this->fk_warehouse = trim($this->fk_warehouse); + if (isset($this->timeout)) $this->timeout = trim($this->timeout); + if (isset($this->wordpress_authentication_type)) $this->wordpress_authentication_type = trim($this->wordpress_authentication_type); + if (isset($this->wordpress_authentication_login)) $this->wordpress_authentication_login = trim($this->wordpress_authentication_login); + if (isset($this->wordpress_authentication_password)) $this->wordpress_authentication_password = trim($this->wordpress_authentication_password); + if (isset($this->wordpress_timeout)) $this->wordpress_timeout = trim($this->wordpress_timeout); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_site SET"; - - $sql.= " name=".(isset($this->name)?"'".$this->db->escape($this->name)."'":"null").","; - $sql.= " type=".(isset($this->type)?$this->type:"null").","; - $sql.= " webservice_address=".(isset($this->webservice_address)?"'".$this->db->escape($this->webservice_address)."'":"null").","; - $sql.= " api_version=".(isset($this->api_version)?"'".$this->db->escape($this->api_version)."'":"null").","; - $sql.= " authentication_type=".(isset($this->authentication_type)?"'".$this->db->escape($this->authentication_type)."'":"null").","; - $sql.= " user_name=".(isset($this->user_name)?"'".$this->db->escape($this->user_name)."'":"null").","; - $sql.= " user_password=".(isset($this->user_password)?"'".$this->db->escape($this->user_password)."'":"null").","; - $sql.= " price_level=".(isset($this->price_level)?"'".$this->db->escape($this->price_level)."'":"1").","; - $sql.= " filter_label=".(isset($this->filter_label)?"'".$this->db->escape($this->filter_label)."'":"null").","; - $sql.= " filter_value=".(isset($this->filter_value)?"'".$this->db->escape($this->filter_value)."'":"null").","; - $sql.= " fk_cat_societe=".($this->fk_cat_societe > 0 ? $this->fk_cat_societe:"0").","; - $sql.= " fk_cat_product=".($this->fk_cat_product > 0 ? $this->fk_cat_product:"0").","; - $sql.= " fk_anonymous_thirdparty=".($this->fk_anonymous_thirdparty > 0 ? $this->fk_anonymous_thirdparty:"null").","; - $sql.= " fk_warehouse=".($this->fk_warehouse > 0 ? $this->fk_warehouse:"null").","; - $sql.= " stock_sync_direction=".($this->stock_sync_direction ? "'".$this->stock_sync_direction."'":"'none'").","; - $sql.= " last_update=".((isset($this->last_update) && $this->last_update != '') ? "'".$this->db->idate($this->last_update)."'" : 'null').","; - $sql.= " timeout=".(isset($this->timeout)? "'".intval($this->timeout)."'" : '30').","; - $sql.= " debug=".(!empty($this->debug)? "1" : 'NULL').","; - $sql.= " magento_use_special_price=".(isset($this->magento_use_special_price)? "'".intval($this->magento_use_special_price)."'" : '0').","; - $sql.= " ecommerce_price_type=".(isset($this->ecommerce_price_type)? "'".$this->ecommerce_price_type."'" : 'HT').","; - $sql.= " wordpress_authentication_type=".(isset($this->wordpress_authentication_type)?"'".$this->db->escape($this->wordpress_authentication_type)."'":"NULL").","; - $sql.= " wordpress_authentication_login=".(isset($this->wordpress_authentication_login)?"'".$this->db->escape($this->wordpress_authentication_login)."'":"NULL").","; - $sql.= " wordpress_authentication_password=".(isset($this->wordpress_authentication_password)?"'".$this->db->escape($this->wordpress_authentication_password)."'":"NULL").","; - $sql.= " wordpress_timeout=".(isset($this->wordpress_timeout)? "'".intval($this->wordpress_timeout)."'" : '30').","; - $sql.= " wordpress_debug=".(!empty($this->wordpress_debug)? "1" : 'NULL').","; - $sql.= " parameters=".(isset($this->parameters)?"'".$this->db->escape(json_encode($this->parameters))."'":"NULL").""; - $sql.= " WHERE rowid=".$this->id; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_site SET"; + + $sql .= " name=" . (isset($this->name) ? "'" . $this->db->escape($this->name) . "'" : "null") . ","; + $sql .= " type=" . (isset($this->type) ? $this->type : "null") . ","; + $sql .= " webservice_address=" . (isset($this->webservice_address) ? "'" . $this->db->escape($this->webservice_address) . "'" : "null") . ","; + $sql .= " api_version=" . (isset($this->api_version) ? "'" . $this->db->escape($this->api_version) . "'" : "null") . ","; + $sql .= " authentication_type=" . (isset($this->authentication_type) ? "'" . $this->db->escape($this->authentication_type) . "'" : "null") . ","; + $sql .= " user_name=" . (isset($this->user_name) ? "'" . $this->db->escape($this->user_name) . "'" : "null") . ","; + $sql .= " user_password=" . (isset($this->user_password) ? "'" . $this->db->escape($this->user_password) . "'" : "null") . ","; + $sql .= " price_level=" . (isset($this->price_level) ? "'" . $this->db->escape($this->price_level) . "'" : "1") . ","; + $sql .= " filter_label=" . (isset($this->filter_label) ? "'" . $this->db->escape($this->filter_label) . "'" : "null") . ","; + $sql .= " filter_value=" . (isset($this->filter_value) ? "'" . $this->db->escape($this->filter_value) . "'" : "null") . ","; + $sql .= " fk_cat_societe=" . ($this->fk_cat_societe > 0 ? $this->fk_cat_societe : "0") . ","; + $sql .= " fk_cat_product=" . ($this->fk_cat_product > 0 ? $this->fk_cat_product : "0") . ","; + $sql .= " fk_anonymous_thirdparty=" . ($this->fk_anonymous_thirdparty > 0 ? $this->fk_anonymous_thirdparty : "null") . ","; + $sql .= " fk_warehouse=" . ($this->fk_warehouse > 0 ? $this->fk_warehouse : "null") . ","; + $sql .= " stock_sync_direction=" . ($this->stock_sync_direction ? "'" . $this->stock_sync_direction . "'" : "'none'") . ","; + $sql .= " last_update=" . ((isset($this->last_update) && $this->last_update != '') ? "'" . $this->db->idate($this->last_update) . "'" : 'null') . ","; + $sql .= " timeout=" . (isset($this->timeout) ? "'" . intval($this->timeout) . "'" : '30') . ","; + $sql .= " debug=" . (!empty($this->debug) ? "1" : 'NULL') . ","; + $sql .= " magento_use_special_price=" . (isset($this->magento_use_special_price) ? "'" . intval($this->magento_use_special_price) . "'" : '0') . ","; + $sql .= " ecommerce_price_type=" . (isset($this->ecommerce_price_type) ? "'" . $this->ecommerce_price_type . "'" : 'HT') . ","; + $sql .= " wordpress_authentication_type=" . (isset($this->wordpress_authentication_type) ? "'" . $this->db->escape($this->wordpress_authentication_type) . "'" : "NULL") . ","; + $sql .= " wordpress_authentication_login=" . (isset($this->wordpress_authentication_login) ? "'" . $this->db->escape($this->wordpress_authentication_login) . "'" : "NULL") . ","; + $sql .= " wordpress_authentication_password=" . (isset($this->wordpress_authentication_password) ? "'" . $this->db->escape($this->wordpress_authentication_password) . "'" : "NULL") . ","; + $sql .= " wordpress_timeout=" . (isset($this->wordpress_timeout) ? "'" . intval($this->wordpress_timeout) . "'" : '30') . ","; + $sql .= " wordpress_debug=" . (!empty($this->wordpress_debug) ? "1" : 'NULL') . ","; + $sql .= " parameters=" . (isset($this->parameters) ? "'" . $this->db->escape(json_encode($this->parameters)) . "'" : "NULL") . ""; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $eCommerceSociete = new eCommerceSociete($this->db); - if ($eCommerceSociete->fetchByRemoteId(0, $this->id) > 0) { - if (isset($this->fk_anonymous_thirdparty)) { - // update an entry for anonymous company - $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; - if ($eCommerceSociete->update($user) < 0) { - $error++; - $this->errors[] = "Error " . $this->db->lasterror(); - } - } else { - // delete an entry for anonymous company - if ($eCommerceSociete->delete($user) < 0) { - $error++; - $this->errors[] = "Error " . $this->db->lasterror(); - } - } - } else { - // create an entry for anonymous company - $eCommerceSociete = new eCommerceSociete($this->db); - $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; - $eCommerceSociete->fk_site = $this->id; - $eCommerceSociete->remote_id = 0; - if ($eCommerceSociete->create($user)<0) - { - $error++; - $this->errors[]="Error ".$this->db->lasterror(); - } - } - - if (! $notrigger && !$error) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + if (!$error) { + $eCommerceSociete = new eCommerceSociete($this->db); + if ($eCommerceSociete->fetchByRemoteId(0, $this->id) > 0) { + if (isset($this->fk_anonymous_thirdparty)) { + // update an entry for anonymous company + $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; + if ($eCommerceSociete->update($user) < 0) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } else { + // delete an entry for anonymous company + if ($eCommerceSociete->delete($user) < 0) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + } else { + // create an entry for anonymous company + $eCommerceSociete = new eCommerceSociete($this->db); + $eCommerceSociete->fk_societe = $this->fk_anonymous_thirdparty; + $eCommerceSociete->fk_site = $this->id; + $eCommerceSociete->remote_id = 0; + if ($eCommerceSociete->create($user) < 0) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + + if (!$notrigger && !$error) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); return 1; } - } + } - /** + /** * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0) + public function delete($user, $notrigger=0) { global $conf, $langs; - $error=0; + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_site"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_site"; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } @@ -569,49 +555,43 @@ function delete($user, $notrigger=0) * @param int $fromid Id of object to clone * @return int New id of clone */ - function createFromClone($fromid) + public function createFromClone($fromid) { - global $user,$langs; + global $user, $langs; - $error=0; + $error = 0; - $object=new Ecommerce_site($this->db); + $object = new Ecommerce_site($this->db); $this->db->begin(); // Load source object $object->fetch($fromid); - $object->id=0; - $object->statut=0; + $object->id = 0; + $object->statut = 0; // Clear fields // ... // Create clone - $result=$object->create($user); + $result = $object->create($user); // Other options - if ($result < 0) - { - $this->error=$object->error; + if ($result < 0) { + $this->error = $object->error; $error++; } - if (! $error) - { - + if (!$error) { } // End - if (! $error) - { + if (!$error) { $this->db->commit(); return $object->id; - } - else - { + } else { $this->db->rollback(); return -1; } @@ -624,36 +604,36 @@ function createFromClone($fromid) * * @return void */ - function initAsSpecimen() + public function initAsSpecimen() { - $this->id=0; - - $this->name=''; - $this->type=''; - $this->webservice_address=''; - $this->api_version=''; - $this->authentication_type=''; - $this->user_name=''; - $this->user_password=''; - $this->price_level=''; - $this->filter_label=''; - $this->filter_value=''; - $this->fk_cat_societe=''; - $this->fk_cat_product=''; - $this->fk_anonymous_thirdparty=''; - $this->fk_warehouse=''; - $this->stock_sync_direction='none'; - $this->last_update=''; - $this->timeout=''; - $this->debug=''; - $this->magento_use_special_price=''; - $this->ecommerce_price_type=''; - $this->wordpress_authentication_type=''; - $this->wordpress_authentication_login=''; - $this->wordpress_authentication_password=''; - $this->wordpress_timeout=''; - $this->wordpress_debug=''; - $this->parameters=''; + $this->id = 0; + + $this->name = ''; + $this->type = ''; + $this->webservice_address = ''; + $this->api_version = ''; + $this->authentication_type = ''; + $this->user_name = ''; + $this->user_password = ''; + $this->price_level = ''; + $this->filter_label = ''; + $this->filter_value = ''; + $this->fk_cat_societe = ''; + $this->fk_cat_product = ''; + $this->fk_anonymous_thirdparty = ''; + $this->fk_warehouse = ''; + $this->stock_sync_direction = 'none'; + $this->last_update = ''; + $this->timeout = ''; + $this->debug = ''; + $this->magento_use_special_price = ''; + $this->ecommerce_price_type = ''; + $this->wordpress_authentication_type = ''; + $this->wordpress_authentication_login = ''; + $this->wordpress_authentication_password = ''; + $this->wordpress_timeout = ''; + $this->wordpress_debug = ''; + $this->parameters = ''; } /** @@ -663,7 +643,7 @@ function initAsSpecimen() * @param boolean $all_entity List site from all entities * @return eCommerceSite[] List of sites */ - function listSites($mode='array', $all_entity = false) + public function listSites($mode='array', $all_entity = false) { $list = array(); @@ -694,30 +674,30 @@ function listSites($mode='array', $all_entity = false) return $list; } - /** - * Check if type site is created - * - * @param integer $typeSite Type of site - * @return boolean true if type site has created - */ - function hasTypeSite($typeSite) - { - $sql = "SELECT"; - $sql.= " count(*) AS count"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_site as t"; - $sql.= " WHERE t.type=".$typeSite; - $sql.= " AND t.entity IN (" . getEntity('ecommerceng') . ")"; - - $result = $this->db->query($sql); - if ($result) { - $obj = $this->db->fetch_object($result); - if ($obj->count > 0) { - return true; - } - } - - return false; - } + /** + * Check if type site is created + * + * @param integer $typeSite Type of site + * @return boolean true if type site has created + */ + public function hasTypeSite($typeSite) + { + $sql = "SELECT"; + $sql .= " count(*) AS count"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_site as t"; + $sql .= " WHERE t.type=" . $typeSite; + $sql .= " AND t.entity IN (" . getEntity('ecommerceng') . ")"; + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + if ($obj->count > 0) { + return true; + } + } + + return false; + } /** * Return list of available site types @@ -737,11 +717,11 @@ public function getSiteTypes() */ public function getFrontUrl() { - // Try to guess public home page of ecommerce web site from the api url - $url=preg_replace('/index\.php\/api.*$/', '', $this->webservice_address); - $url=preg_replace('/\/api\/.*$/', '', $url); - if ($url && ! preg_match('/\/$/', $url)) $url.='/'; - return $url; + // Try to guess public home page of ecommerce web site from the api url + $url = preg_replace('/index\.php\/api.*$/', '', $this->webservice_address); + $url = preg_replace('/\/api\/.*$/', '', $url); + if ($url && !preg_match('/\/$/', $url)) $url .= '/'; + return $url; } /** @@ -751,17 +731,17 @@ public function getFrontUrl() */ public function getBackUrl() { - // Try to guess public home page of ecommerce web site from the api url - $url=$this->getFrontUrl(); + // Try to guess public home page of ecommerce web site from the api url + $url = $this->getFrontUrl(); switch ($this->type) { case 1: // Magento - $url.='index.php/admin'; + $url .= 'index.php/admin'; break; case 2: // Woocommerce - $url.=(substr($url, -1, 1)!='/'?'/':'').'wp-admin'; + $url .= (substr($url, -1, 1) != '/' ? '/' : '') . 'wp-admin'; break; } - return $url; + return $url; } /** @@ -771,7 +751,7 @@ public function getBackUrl() * @param int $entity Entity to get * @return int < 0 if KO, >= 0 if OK */ - function setEntityValues($entity) + public function setEntityValues($entity) { global $conf; diff --git a/class/data/eCommerceSociete.class.php b/class/data/eCommerceSociete.class.php index c65473a..0729b54 100644 --- a/class/data/eCommerceSociete.class.php +++ b/class/data/eCommerceSociete.class.php @@ -20,287 +20,276 @@ class eCommerceSociete // extends CommonObject { - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors=array(); //!< To return several error codes (or messages) - //var $element='ecommerce_societe'; //!< Id that identify managed objects - //var $table_element='ecommerce_societe'; //!< Name of table without prefix where object is stored - - var $id; - var $fk_societe; - var $fk_site; - var $remote_id; - var $last_update; - - /** - * Database access to ecommerce_societe - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - return 1; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors=array(); //!< To return several error codes (or messages) + //public $element='ecommerce_societe'; //!< Id that identify managed objects + //public $table_element='ecommerce_societe'; //!< Name of table without prefix where object is stored + + public $id; + public $fk_societe; + public $fk_site; + public $remote_id; + public $last_update; + + /** + * Database access to ecommerce_societe + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + return 1; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_societe)) $this->fk_societe=intval($this->fk_societe); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_societe)) $this->fk_societe = intval($this->fk_societe); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_societe("; - $sql.= "fk_societe,"; - $sql.= "fk_site,"; - $sql.= "remote_id,"; - $sql.= "last_update"; - $sql.= ") VALUES ("; - $sql.= " ".(isset($this->fk_societe)?intval($this->fk_societe):0).","; - $sql.= " ".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " ".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " ".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; - $sql.= ")"; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_societe("; + $sql .= "fk_societe,"; + $sql .= "fk_site,"; + $sql .= "remote_id,"; + $sql .= "last_update"; + $sql .= ") VALUES ("; + $sql .= " " . (isset($this->fk_societe) ? intval($this->fk_societe) : 0) . ","; + $sql .= " " . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " " . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " " . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_societe"); - if (! ($this->id > 0)) dol_syslog("last_insert_id did not return an int", LOG_ERR); - - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_societe"); + if (!($this->id > 0)) dol_syslog("last_insert_id did not return an int", LOG_ERR); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_societe,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_societe as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_societe = $obj->fk_societe; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_societe,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_societe as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_societe = $obj->fk_societe; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - } - $this->db->free($resql); - - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user=0, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_societe)) $this->fk_societe=intval($this->fk_societe); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_societe)) $this->fk_societe = intval($this->fk_societe); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_societe SET"; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_societe SET"; - $sql.= " fk_societe=".(isset($this->fk_societe)?intval($this->fk_societe):0).","; - $sql.= " fk_site=".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " remote_id=".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " last_update=".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " fk_societe=" . (isset($this->fk_societe) ? intval($this->fk_societe) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id=" . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " last_update=" . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } - } + } - /** + /** * Delete object in database * - * @param $user User that delete - * @param $notrigger 0=launch triggers after, 1=disable triggers - * @param $sitename Site name to update alias + * @param $user User that delete + * @param $notrigger 0=launch triggers after, 1=disable triggers + * @param $sitename Site name to update alias * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0, $sitename='') + public function delete($user, $notrigger=0, $sitename='') { global $conf, $langs; - $error=0; + $error = 0; - dol_syslog("Delete into ecommerce_societe sitename=".$sitename); + dol_syslog("Delete into ecommerce_societe sitename=" . $sitename); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_societe"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_societe"; + $sql .= " WHERE rowid=" . $this->id; - $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql2.= " SET name_alias = NULL where name_alias = '".$sitename.' id '.$this->remote_id."'"; // Magento id xxx + $sql2 = "UPDATE " . MAIN_DB_PREFIX . "societe"; + $sql2 .= " SET name_alias = NULL where name_alias = '" . $sitename . ' id ' . $this->remote_id . "'"; // Magento id xxx $sql2 .= " AND entity IN (" . getEntity('societe') . ")"; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if ($sitename) - { - $resql2 = $this->db->query($sql2); - if (! $resql2) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if ($sitename) { + $resql2 = $this->db->query($sql2); + if (!$resql2) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } @@ -316,83 +305,75 @@ public function getLastUpdate($site) { global $langs; - $sql = "SELECT MAX(t.last_update) as lastdate FROM ".MAIN_DB_PREFIX."ecommerce_societe as t"; - $sql.= " WHERE t.fk_site = ".$site; - dol_syslog(get_class($this)."::getLastUpdate sql=".$sql, LOG_DEBUG); + $sql = "SELECT MAX(t.last_update) as lastdate FROM " . MAIN_DB_PREFIX . "ecommerce_societe as t"; + $sql .= " WHERE t.fk_site = " . $site; + dol_syslog(get_class($this) . "::getLastUpdate sql=" . $sql, LOG_DEBUG); - $lastdate = null; + $lastdate = null; - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); if ($obj->lastdate != null) - $lastdate = $this->db->jdate($obj->lastdate); - } - $this->db->free($resql); - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getLastUpdate ".$this->error, LOG_ERR); - } - return $lastdate; + $lastdate = $this->db->jdate($obj->lastdate); + } + $this->db->free($resql); + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getLastUpdate " . $this->error, LOG_ERR); + } + return $lastdate; } /** - * Load object in memory from database by remote_id - * - * @param string $remoteId remote_id - * @param int $siteId fk_site - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * + * @param string $remoteId remote_id + * @param int $siteId fk_site + * @return int <0 if KO, >0 if OK + */ public function fetchByRemoteId($remoteId, $siteId) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_societe,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_societe as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.remote_id = '".$this->db->escape($remoteId)."'"; - dol_syslog(get_class($this)."::fetchByRemoteId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_societe = $obj->fk_societe; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByRemoteId ".$this->error, LOG_ERR); - return -1; - } - } + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_societe,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_societe as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; + dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_societe = $obj->fk_societe; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); + return -1; + } + } /** - * Load object in memory from database by fk_societe + * Load object in memory from database by fk_societe * - * @param int $fkSociete fk_societe - * @param int $siteId fk_site - * @return int|array <0 if KO, list of links if OK - */ + * @param int $fkSociete fk_societe + * @param int $siteId fk_site + * @return int|array <0 if KO, list of links if OK + */ public function getAllLinksByFkSociete($fkSociete, $siteId) { global $langs; @@ -431,38 +412,34 @@ public function getAllLinksByFkSociete($fkSociete, $siteId) } /** - * Select all the ids from eCommerceSociete for a site - * - * @param int siteId - * @return array synchObject ids for this site - */ - public function getAllECommerceSocieteIds($siteId) - { - global $langs; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ecommerce_societe"; - $sql.= " WHERE fk_site = ".$siteId; - dol_syslog(get_class($this)."::getAllECommerceSocieteIds sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while($ii < $num) - { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getAllECommerceSocieteIds ".$this->error, LOG_ERR); - return -1; - } - } + * Select all the ids from eCommerceSociete for a site + * + * @param int $siteId Site ID + * @return array synchObject ids for this site + */ + public function getAllECommerceSocieteIds($siteId) + { + global $langs; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_societe"; + $sql .= " WHERE fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getAllECommerceSocieteIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceSocieteIds " . $this->error, LOG_ERR); + return -1; + } + } } diff --git a/class/data/eCommerceSocpeople.class.php b/class/data/eCommerceSocpeople.class.php index c736b72..9a566da 100644 --- a/class/data/eCommerceSocpeople.class.php +++ b/class/data/eCommerceSocpeople.class.php @@ -20,433 +20,408 @@ class eCommerceSocpeople // extends CommonObject { - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors=array(); //!< To return several error codes (or messages) - //var $element='ecommerce_socpeople'; //!< Id that identify managed objects - //var $table_element='ecommerce_socpeople'; //!< Name of table without prefix where object is stored - - var $id; - var $fk_socpeople; - var $fk_site; - var $remote_id; - var $type; - var $last_update; - - const CONTACT_TYPE_COMPANY = 1; - const CONTACT_TYPE_ORDER = 2; - const CONTACT_TYPE_INVOICE = 3; - const CONTACT_TYPE_DELIVERY = 4; - - /** - * Constructor - * - * @param DoliDB $DB Database handler - */ - function __construct($DB) - { - $this->db = $DB; - return 1; - } - - - /** - * Create in database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors=array(); //!< To return several error codes (or messages) + //public $element='ecommerce_socpeople'; //!< Id that identify managed objects + //public $table_element='ecommerce_socpeople'; //!< Name of table without prefix where object is stored + + public $id; + public $fk_socpeople; + public $fk_site; + public $remote_id; + public $type; + public $last_update; + + const CONTACT_TYPE_COMPANY = 1; + const CONTACT_TYPE_ORDER = 2; + const CONTACT_TYPE_INVOICE = 3; + const CONTACT_TYPE_DELIVERY = 4; + + /** + * Constructor + * + * @param DoliDB $DB Database handler + */ + public function __construct($DB) + { + $this->db = $DB; + return 1; + } + + + /** + * Create in database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_socpeople)) $this->fk_socpeople=intval($this->fk_socpeople); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->type)) $this->type=intval($this->type); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_socpeople)) $this->fk_socpeople = intval($this->fk_socpeople); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->type)) $this->type = intval($this->type); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."ecommerce_socpeople("; + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ecommerce_socpeople("; - $sql.= "fk_socpeople,"; - $sql.= "fk_site,"; - $sql.= "remote_id,"; - $sql.= "type,"; - $sql.= "last_update"; + $sql .= "fk_socpeople,"; + $sql .= "fk_site,"; + $sql .= "remote_id,"; + $sql .= "type,"; + $sql .= "last_update"; - $sql.= ") VALUES ("; + $sql .= ") VALUES ("; - $sql.= " ".(isset($this->fk_socpeople)?intval($this->fk_socpeople):0).","; - $sql.= " ".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " ".(isset($this->remote_id)?"'".$this->remote_id."'":"").","; - $sql.= " ".(isset($this->type)?intval($this->type):1).","; - $sql.= " ".(isset($this->last_update)?"'".$this->db->idate($this->last_update)."'" : 'null').""; + $sql .= " " . (isset($this->fk_socpeople) ? intval($this->fk_socpeople) : 0) . ","; + $sql .= " " . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " " . (isset($this->remote_id) ? "'" . $this->remote_id . "'" : "") . ","; + $sql .= " " . (isset($this->type) ? intval($this->type) : 1) . ","; + $sql .= " " . (isset($this->last_update) ? "'" . $this->db->idate($this->last_update) . "'" : 'null') . ""; - $sql.= ")"; + $sql .= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecommerce_socpeople"); - - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ecommerce_socpeople"); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); - return $this->id; + return $this->id; } - } - - - /** - * Load object in memory from database - * - * @param int $id id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_socpeople,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.type,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_socpeople as t"; - $sql.= " WHERE t.rowid = ".$id; - - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_socpeople = $obj->fk_socpeople; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->type = $obj->type; - $this->last_update = $obj->last_update; - } - $this->db->free($resql); - - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); - return -1; - } - } - - - /** - * \brief Update database - * \param user User that modify - * \param notrigger 0=launch triggers after, 1=disable triggers - * \return int <0 if KO, >0 if OK - */ - function update($user=0, $notrigger=0) - { - global $conf, $langs; - $error=0; + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_socpeople,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.type,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_socpeople as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_socpeople = $obj->fk_socpeople; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->type = $obj->type; + $this->last_update = $obj->last_update; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + + /** + * \brief Update database + * \param user User that modify + * \param notrigger 0=launch triggers after, 1=disable triggers + * \return int <0 if KO, >0 if OK + */ + public function update($user=0, $notrigger=0) + { + global $conf, $langs; + $error = 0; // Clean parameters - if (isset($this->fk_socpeople)) $this->fk_socpeople=intval($this->fk_socpeople); - if (isset($this->fk_site)) $this->fk_site=intval($this->fk_site); - if (isset($this->remote_id)) $this->remote_id=trim($this->remote_id); - if (isset($this->type)) $this->type=intval($this->type); - if (isset($this->last_update)) $this->last_update=trim($this->last_update); + if (isset($this->fk_socpeople)) $this->fk_socpeople = intval($this->fk_socpeople); + if (isset($this->fk_site)) $this->fk_site = intval($this->fk_site); + if (isset($this->remote_id)) $this->remote_id = trim($this->remote_id); + if (isset($this->type)) $this->type = intval($this->type); + if (isset($this->last_update)) $this->last_update = trim($this->last_update); // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."ecommerce_socpeople SET"; + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ecommerce_socpeople SET"; - $sql.= " fk_socpeople=".(isset($this->fk_socpeople)?intval($this->fk_socpeople):0).","; - $sql.= " fk_site=".(isset($this->fk_site)?intval($this->fk_site):0).","; - $sql.= " remote_id=".(isset($this->remote_id)?"'".$this->db->escape($this->remote_id)."'":"").","; - $sql.= " type=".(isset($this->type)?intval($this->type):1).","; - $sql.= " last_update=".(isset($this->last_update)?"'".$this->last_update."'" : 'null').""; + $sql .= " fk_socpeople=" . (isset($this->fk_socpeople) ? intval($this->fk_socpeople) : 0) . ","; + $sql .= " fk_site=" . (isset($this->fk_site) ? intval($this->fk_site) : 0) . ","; + $sql .= " remote_id=" . (isset($this->remote_id) ? "'" . $this->db->escape($this->remote_id) . "'" : "") . ","; + $sql .= " type=" . (isset($this->type) ? intval($this->type) : 1) . ","; + $sql .= " last_update=" . (isset($this->last_update) ? "'" . $this->last_update . "'" : 'null') . ""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } - $this->db->rollback(); - return -1*$error; } - else - { + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { $this->db->commit(); return 1; } - } + } - /** + /** * \brief Delete object in database - * \param user User that delete - * \param notrigger 0=launch triggers after, 1=disable triggers + * \param user User that delete + * \param notrigger 0=launch triggers after, 1=disable triggers * \return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0) + public function delete($user, $notrigger=0) { global $conf, $langs; - $error=0; + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecommerce_socpeople"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ecommerce_socpeople"; + $sql .= " WHERE rowid=" . $this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this) . "::delete sql=" . $sql); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. - - //// Call triggers - //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + // want this action call a trigger. + + //// Call triggers + //include_once(DOL_DOCUMENT_ROOT . "/core/interfaces.class.php"); + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers } } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; - } - else - { + return -1 * $error; + } else { $this->db->commit(); return 1; } } /** - * Load object in memory from database by remote_id - * - * @param $remoteId string remote_id - * @param $siteId int fk_site - * @param $typeId int contact type (1=>'company', 2=>'order', 3=>'invoice', 4=>'delivery') - * @return int <0 if KO, >0 if OK - */ + * Load object in memory from database by remote_id + * + * @param $remoteId string remote_id + * @param $siteId int fk_site + * @param $typeId int contact type (1=>'company', 2=>'order', 3=>'invoice', 4=>'delivery') + * @return int <0 if KO, >0 if OK + */ public function fetchByRemoteId($remoteId, $typeId, $siteId) - { - // Clean parameters - if (isset($remoteId)) $remoteId=trim($remoteId); - if (isset($typeId)) $typeId=intval($typeId); - if (isset($siteId)) $siteId=intval($siteId); - - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_socpeople,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.type,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_socpeople as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.type = ".$typeId; - $sql.= " AND t.remote_id = '".$this->db->escape($remoteId)."'"; - dol_syslog(get_class($this)."::fetchByRemoteId sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)==1) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_socpeople = $obj->fk_socpeople; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->type = $obj->type; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByRemoteId ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Load object in memory from database by fkContact - * - * @param $fkSocpeople int fk_contact - * @param $siteId int fk_site - * @return int <0 if KO, >0 if OK - */ - public function fetchByFkSocpeople($fkSocpeople, $siteId) - { - // Clean parameters - if (isset($fkSocpeople)) $fkSocpeople=trim($fkSocpeople); - if (isset($siteId)) $siteId=intval($siteId); - - global $langs; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_socpeople,"; - $sql.= " t.fk_site,"; - $sql.= " t.remote_id,"; - $sql.= " t.type,"; - $sql.= " t.last_update"; - $sql.= " FROM ".MAIN_DB_PREFIX."ecommerce_socpeople as t"; - $sql.= " WHERE t.fk_site = ".$siteId; - $sql.= " AND t.type = 1"; // TODO what about other types ? - $sql.= " AND t.fk_socpeople = ".$fkSocpeople; - dol_syslog(get_class($this)."::fetchByFkSocpeople sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql) > 0) - { - $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_socpeople = $obj->fk_socpeople; - $this->fk_site = $obj->fk_site; - $this->remote_id = $obj->remote_id; - $this->type = $obj->type; - $this->last_update = $obj->last_update; - $this->db->free($resql); - return 1; - } - $this->db->free($resql); - return -1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByFkSocpeople ".$this->error, LOG_ERR); - return -1; - } - } + { + // Clean parameters + if (isset($remoteId)) $remoteId = trim($remoteId); + if (isset($typeId)) $typeId = intval($typeId); + if (isset($siteId)) $siteId = intval($siteId); + + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_socpeople,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.type,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_socpeople as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.type = " . $typeId; + $sql .= " AND t.remote_id = '" . $this->db->escape($remoteId) . "'"; + dol_syslog(get_class($this) . "::fetchByRemoteId sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_socpeople = $obj->fk_socpeople; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->type = $obj->type; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByRemoteId " . $this->error, LOG_ERR); + return -1; + } + } /** - * Select all the ids from eCommerceSocpeople for a site - * @param int siteId - * @return array synchObject ids for this site - */ - public function getAllECommerceSocpeopleIds($siteId) - { - global $langs; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ecommerce_socpeople"; - $sql.= " WHERE fk_site = ".$siteId; - dol_syslog(get_class($this)."::getAllECommerceSocpeopleIds sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if ($resql) - { - $idsArray = array(); - $num = $this->db->num_rows($resql); - $ii = 0; - while($ii < $num) - { - $obj = $this->db->fetch_object($resql); - $idsArray[] = intval($obj->rowid); - $ii++; - } - $this->db->free($resql); - return $idsArray; - } - else - { - $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getAllECommerceSocpeopleIds ".$this->error, LOG_ERR); - return -1; - } - } + * Load object in memory from database by fkContact + * + * @param $fkSocpeople int fk_contact + * @param $siteId int fk_site + * @return int <0 if KO, >0 if OK + */ + public function fetchByFkSocpeople($fkSocpeople, $siteId) + { + // Clean parameters + if (isset($fkSocpeople)) $fkSocpeople = trim($fkSocpeople); + if (isset($siteId)) $siteId = intval($siteId); + + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_socpeople,"; + $sql .= " t.fk_site,"; + $sql .= " t.remote_id,"; + $sql .= " t.type,"; + $sql .= " t.last_update"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ecommerce_socpeople as t"; + $sql .= " WHERE t.fk_site = " . $siteId; + $sql .= " AND t.type = 1"; // TODO what about other types ? + $sql .= " AND t.fk_socpeople = " . $fkSocpeople; + dol_syslog(get_class($this) . "::fetchByFkSocpeople sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) > 0) { + $obj = $this->db->fetch_object($resql); + $this->id = $obj->rowid; + $this->fk_socpeople = $obj->fk_socpeople; + $this->fk_site = $obj->fk_site; + $this->remote_id = $obj->remote_id; + $this->type = $obj->type; + $this->last_update = $obj->last_update; + $this->db->free($resql); + return 1; + } + $this->db->free($resql); + return -1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetchByFkSocpeople " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Select all the ids from eCommerceSocpeople for a site + * @param int siteId + * @return array synchObject ids for this site + */ + public function getAllECommerceSocpeopleIds($siteId) + { + global $langs; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ecommerce_socpeople"; + $sql .= " WHERE fk_site = " . $siteId; + dol_syslog(get_class($this) . "::getAllECommerceSocpeopleIds sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $idsArray = array(); + $num = $this->db->num_rows($resql); + $ii = 0; + while ($ii < $num) { + $obj = $this->db->fetch_object($resql); + $idsArray[] = intval($obj->rowid); + $ii++; + } + $this->db->free($resql); + return $idsArray; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getAllECommerceSocpeopleIds " . $this->error, LOG_ERR); + return -1; + } + } } diff --git a/class/data/woocommerce/eCommerceRemoteAccessWoocommerce.class.php b/class/data/woocommerce/eCommerceRemoteAccessWoocommerce.class.php index b028a7b..e93ad4d 100755 --- a/class/data/woocommerce/eCommerceRemoteAccessWoocommerce.class.php +++ b/class/data/woocommerce/eCommerceRemoteAccessWoocommerce.class.php @@ -37,59 +37,59 @@ */ class eCommerceRemoteAccessWoocommerce { - /** - * eCommerceSite object. - * - * @var eCommerceSite - */ - private $site; - - /** - * @var eCommerceSociete - */ - private $eCommerceSociete; - /** - * @var eCommerceProduct - */ - private $eCommerceProduct; - /** - * @var eCommerceCommande - */ - private $eCommerceCommande; - - /** - * Woocommerce client. - * - * @var eCommerceClientWooCommerceApi - */ - public $client; - /** - * WordPress client. - * - * @var eCommerceClientWordpressApi - */ + /** + * eCommerceSite object. + * + * @var eCommerceSite + */ + private $site; + + /** + * @var eCommerceSociete + */ + private $eCommerceSociete; + /** + * @var eCommerceProduct + */ + private $eCommerceProduct; + /** + * @var eCommerceCommande + */ + private $eCommerceCommande; + + /** + * Woocommerce client. + * + * @var eCommerceClientWooCommerceApi + */ + public $client; + /** + * WordPress client. + * + * @var eCommerceClientWordpressApi + */ public $worpressclient; - /** - * Dolibarr tax rates. - * - * @var array - */ - private $dolibarrTaxes; - - /** - * Woocommerce taxes. - * - * @var array - */ - private $woocommerceTaxes; - - /** - * Database handler. - * - * @var DoliDB - */ - private $db; + /** + * Dolibarr tax rates. + * + * @var array + */ + private $dolibarrTaxes; + + /** + * Woocommerce taxes. + * + * @var array + */ + private $woocommerceTaxes; + + /** + * Database handler. + * + * @var DoliDB + */ + private $db; /** * Error. @@ -98,26 +98,26 @@ class eCommerceRemoteAccessWoocommerce */ public $error; - /** - * Errors list. - * - * @var array - */ - public $errors; - - /** - * GMT timezone. - * - * @var DateTimeZone - */ - public $gmtTimeZone; - - /** - * Current timezone. - * - * @var DateTimeZone - */ - public $currentTimeZone; + /** + * Errors list. + * + * @var array + */ + public $errors; + + /** + * GMT timezone. + * + * @var DateTimeZone + */ + public $gmtTimeZone; + + /** + * Current timezone. + * + * @var DateTimeZone + */ + public $currentTimeZone; /** * Woocommerce taxes classes cached. @@ -164,60 +164,60 @@ class eCommerceRemoteAccessWoocommerce */ private static $disable_put_post_to_api = false; - /** - * Constructor - * @param DoliDB $db Database handler - * @param eCommerceSite $site eCommerceSite object - */ - function __construct($db, $site) - { - global $langs; + /** + * Constructor + * @param DoliDB $db Database handler + * @param eCommerceSite $site eCommerceSite object + */ + public function __construct($db, $site) + { + global $langs; - $langs->load("ecommerce@ecommerceng"); + $langs->load("ecommerce@ecommerceng"); - $this->db = $db; - $this->site = $site; + $this->db = $db; + $this->site = $site; $this->error = ''; $this->errors = []; - $this->gmtTimeZone = new DateTimeZone('GMT'); - $this->currentTimeZone = new DateTimeZone(date_default_timezone_get()); - - return 1; - } - - /** - * Instanciate eCommerceSociete data class access - */ - private function initECommerceSociete() - { - $this->eCommerceSociete = new eCommerceSociete($this->db); - } - - /** - * Instanciate eCommerceProduct data class access - */ - private function initECommerceProduct() - { - $this->eCommerceProduct = new eCommerceProduct($this->db); - } - - /** - * Instanciate eCommerceCommande data class access - */ - private function initECommerceCommande() - { - $this->eCommerceCommande = new eCommerceCommande($this->db); - } - - /** - * Connect to API - * - * @return boolean True if OK, False if KO - */ - public function connect() - { - dol_syslog(__METHOD__ . " - site ID {$this->site->id}", LOG_DEBUG); + $this->gmtTimeZone = new DateTimeZone('GMT'); + $this->currentTimeZone = new DateTimeZone(date_default_timezone_get()); + + return 1; + } + + /** + * Instanciate eCommerceSociete data class access + */ + private function initECommerceSociete() + { + $this->eCommerceSociete = new eCommerceSociete($this->db); + } + + /** + * Instanciate eCommerceProduct data class access + */ + private function initECommerceProduct() + { + $this->eCommerceProduct = new eCommerceProduct($this->db); + } + + /** + * Instanciate eCommerceCommande data class access + */ + private function initECommerceCommande() + { + $this->eCommerceCommande = new eCommerceCommande($this->db); + } + + /** + * Connect to API + * + * @return boolean True if OK, False if KO + */ + public function connect() + { + dol_syslog(__METHOD__ . " - site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); $this->client = new eCommerceClientWooCommerceApi($this->db, $this->site->debug); @@ -229,43 +229,43 @@ public function connect() } $this->worpressclient = new eCommerceClientWordpressApi($this->db, $this->site->wordpress_debug); - $result = $this->worpressclient->connection($this->site); - if ($result < 0) { + $result = $this->worpressclient->connection($this->site); + if ($result < 0) { $this->errors[] = $this->worpressclient->errorsToString(); dol_syslog(__METHOD__ . ' - Error:' . $this->errorsToString(), LOG_ERR); return false; } - dol_syslog(__METHOD__ . " - end, ok", LOG_DEBUG); - return true; - } - - /** - * Call Woocommerce API to get last updated companies. We are interested here by list of id only. We will retreive properties later. - * - * @param int $fromDate From date - * @param int $toDate To date - * - * @return array|boolean List of companies ID to update or false if error - */ - public function getSocieteToUpdate($fromDate, $toDate) - { - dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . - ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + dol_syslog(__METHOD__ . " - end, ok", LOG_DEBUG); + return true; + } + + /** + * Call Woocommerce API to get last updated companies. We are interested here by list of id only. We will retreive properties later. + * + * @param int $fromDate From date + * @param int $toDate To date + * + * @return array|boolean List of companies ID to update or false if error + */ + public function getSocieteToUpdate($fromDate, $toDate) + { + dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . + ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; $this->errors = array(); $this->initECommerceSociete(); - $last_update = []; - $result = []; - $idxPage = 1; - $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); - $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; - $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; - - $no_more = false; + $last_update = []; + $result = []; + $idxPage = 1; + $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; + $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; + + $no_more = false; do { - $filters = [ + $filters = [ 'page' => $idxPage++, 'per_page' => $per_page, 'orderby' => 'registered_date', @@ -283,75 +283,75 @@ public function getSocieteToUpdate($fromDate, $toDate) if (!isset($page)) $page = array(); - foreach ($page as $customer) { - $id = $customer['id']; - $date_customer = $this->getDateTimeFromGMTDateTime(/*!empty($customer['date_modified_gmt']) ? $customer['date_modified_gmt'] : */$customer['date_created_gmt']); - $update_customer = false; - if ($from_date == $date_customer) { - if ($this->eCommerceSociete->fetchByRemoteId($id, $this->site->id) > 0) { - if (isset($this->eCommerceSociete->last_update) && !empty($this->eCommerceSociete->last_update)) { - $date = new DateTime(dol_print_date($this->eCommerceSociete->last_update, 'standard')); - if ($date < $from_date) { - $update_customer = true; - } - } - } else { - $update_customer = true; - } - } - - if ($update_customer || (!isset($from_date) || $from_date < $date_customer) && (!isset($to_date) || $date_customer <= $to_date)) { - $result[$id] = $id; - $last_update[$id] = $date_customer->format('Y-m-d H:i:s'); - } else { - $no_more = true; - } - - if ($no_more) break; - } - - if ($no_more) break; + foreach ($page as $customer) { + $id = $customer['id']; + $date_customer = $this->getDateTimeFromGMTDateTime(/*!empty($customer['date_modified_gmt']) ? $customer['date_modified_gmt'] : */ $customer['date_created_gmt']); + $update_customer = false; + if ($from_date == $date_customer) { + if ($this->eCommerceSociete->fetchByRemoteId($id, $this->site->id) > 0) { + if (isset($this->eCommerceSociete->last_update) && !empty($this->eCommerceSociete->last_update)) { + $date = new DateTime(dol_print_date($this->eCommerceSociete->last_update, 'standard')); + if ($date < $from_date) { + $update_customer = true; + } + } + } else { + $update_customer = true; + } + } + + if ($update_customer || (!isset($from_date) || $from_date < $date_customer) && (!isset($to_date) || $date_customer <= $to_date)) { + $result[$id] = $id; + $last_update[$id] = $date_customer->format('Y-m-d H:i:s'); + } else { + $no_more = true; + } + + if ($no_more) break; + } + + if ($no_more) break; } while (count($page) == $per_page); - //important - order by last update - if (count($result)) { - array_multisort($last_update, SORT_ASC, $result); - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $result; - } - - /** - * Call Woocommerce API to get last updated products. We are interested here by list of id only. We will retreive properties later. - * - * @param int $fromDate From date - * @param int $toDate To date - * - * @return array|boolean List of products ID to update or false if error - */ - public function getProductToUpdate($fromDate, $toDate) - { - dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . - ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + //important - order by last update + if (count($result)) { + array_multisort($last_update, SORT_ASC, $result); + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $result; + } + + /** + * Call Woocommerce API to get last updated products. We are interested here by list of id only. We will retreive properties later. + * + * @param int $fromDate From date + * @param int $toDate To date + * + * @return array|boolean List of products ID to update or false if error + */ + public function getProductToUpdate($fromDate, $toDate) + { + dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . + ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; $this->errors = array(); $this->initECommerceProduct(); - $last_update = []; - $product_variation = []; - $result = []; - $idxPage = 1; - $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); - $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; - $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; - - $filter = ['limit' => $per_page]; - if (isset($fromDate) && !empty($fromDate)) $filter['updated_at_min'] = dol_print_date($fromDate - (24 * 60 * 60), 'dayrfc'); - if (isset($toDate) && !empty($toDate)) $filter['updated_at_max'] = dol_print_date($toDate + (24 * 60 * 60), 'dayrfc'); + $last_update = []; + $product_variation = []; + $result = []; + $idxPage = 1; + $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; + $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; + + $filter = ['limit' => $per_page]; + if (isset($fromDate) && !empty($fromDate)) $filter['updated_at_min'] = dol_print_date($fromDate - (24 * 60 * 60), 'dayrfc'); + if (isset($toDate) && !empty($toDate)) $filter['updated_at_max'] = dol_print_date($toDate + (24 * 60 * 60), 'dayrfc'); do { - $filters = [ + $filters = [ 'page' => $idxPage++, 'filter' => $filter, 'fields' => 'id,created_at,updated_at,variations', @@ -367,105 +367,105 @@ public function getProductToUpdate($fromDate, $toDate) if (!isset($page) || !isset($page['products'])) $page['products'] = array(); - foreach ($page['products'] as $product) { - $id = $product['id']; - $update = false; - $date_product = $this->getDateTimeFromGMTDateTime(!empty($product['updated_at']) ? $product['updated_at'] : $product['created_at']); - $update_parent = false; - if ($from_date == $date_product) { - if ($this->eCommerceProduct->fetchByRemoteId($id, $this->site->id) > 0) { - if (isset($this->eCommerceProduct->last_update) && !empty($this->eCommerceProduct->last_update)) { - $date = new DateTime(dol_print_date($this->eCommerceProduct->last_update, 'standard')); - if ($date < $from_date) { - $update_parent = true; - } - } - } else { - $update_parent = true; - } - } - - // Product - if ($update_parent || (!isset($from_date) || $from_date < $date_product) && (!isset($to_date) || $date_product <= $to_date)) { - $result[$id] = $id; - $last_update[$id] = $date_product->format('Y-m-d H:i:s'); - $product_variation[$id] = 0; - $update = true; - } - - // Variations - foreach ($product['variations'] as $variation) { - $id = $product['id'] . '|' . $variation['id']; - $date_variation = $this->getDateTimeFromGMTDateTime(!empty($variation['updated_at']) ? $variation['updated_at'] : $variation['created_at']); - $update_variante = false; - if ($from_date == $date_product) { - if ($this->eCommerceProduct->fetchByRemoteId($id, $this->site->id) > 0) { - if (isset($this->eCommerceProduct->last_update) && !empty($this->eCommerceProduct->last_update)) { - $date = new DateTime(dol_print_date($this->eCommerceProduct->last_update, 'standard')); - if ($date < $from_date) { - $update_variante = true; - } - } - } else { - $update_variante = true; - } - } - - if ($update || $update_variante || ((!isset($from_date) || $from_date < $date_variation) && (!isset($to_date) || $date_variation <= $to_date))) { - $result[$id] = $id; - $last_update[$id] = $date_product->format('Y-m-d H:i:s'); //$date_product > $date_variation ? $date_product->format('Y-m-d H:i:s') : $date_variation->format('Y-m-d H:i:s'); - $product_variation[$id] = 1; - } - } - } + foreach ($page['products'] as $product) { + $id = $product['id']; + $update = false; + $date_product = $this->getDateTimeFromGMTDateTime(!empty($product['updated_at']) ? $product['updated_at'] : $product['created_at']); + $update_parent = false; + if ($from_date == $date_product) { + if ($this->eCommerceProduct->fetchByRemoteId($id, $this->site->id) > 0) { + if (isset($this->eCommerceProduct->last_update) && !empty($this->eCommerceProduct->last_update)) { + $date = new DateTime(dol_print_date($this->eCommerceProduct->last_update, 'standard')); + if ($date < $from_date) { + $update_parent = true; + } + } + } else { + $update_parent = true; + } + } + + // Product + if ($update_parent || (!isset($from_date) || $from_date < $date_product) && (!isset($to_date) || $date_product <= $to_date)) { + $result[$id] = $id; + $last_update[$id] = $date_product->format('Y-m-d H:i:s'); + $product_variation[$id] = 0; + $update = true; + } + + // Variations + foreach ($product['variations'] as $variation) { + $id = $product['id'] . '|' . $variation['id']; + $date_variation = $this->getDateTimeFromGMTDateTime(!empty($variation['updated_at']) ? $variation['updated_at'] : $variation['created_at']); + $update_variante = false; + if ($from_date == $date_product) { + if ($this->eCommerceProduct->fetchByRemoteId($id, $this->site->id) > 0) { + if (isset($this->eCommerceProduct->last_update) && !empty($this->eCommerceProduct->last_update)) { + $date = new DateTime(dol_print_date($this->eCommerceProduct->last_update, 'standard')); + if ($date < $from_date) { + $update_variante = true; + } + } + } else { + $update_variante = true; + } + } + + if ($update || $update_variante || ((!isset($from_date) || $from_date < $date_variation) && (!isset($to_date) || $date_variation <= $to_date))) { + $result[$id] = $id; + $last_update[$id] = $date_product->format('Y-m-d H:i:s'); //$date_product > $date_variation ? $date_product->format('Y-m-d H:i:s') : $date_variation->format('Y-m-d H:i:s'); + $product_variation[$id] = 1; + } + } + } } while (count($page['products']) == $per_page); - //important - order by last update - if (count($result)) { - uasort($result, function($a, $b) use ($product_variation, $last_update) { - if($last_update[$a] == $last_update[$b]) { - if($product_variation[$a] == $product_variation[$b]) - return strcmp($a, $b); - - return $product_variation[$a] > $product_variation[$b] ? 1 : -1; - } - return $last_update[$a] > $last_update[$b] ? 1 : -1; - }); - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $result; - } - - /** - * Call Woocommerce API to get last updated orders. We are interested here by list of id only. We will retreive properties later. - * - * @param int $fromDate From date - * @param int $toDate To date - * - * @return array|boolean List of orders ID to update or false if error - */ - public function getCommandeToUpdate($fromDate, $toDate) - { - dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . - ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + //important - order by last update + if (count($result)) { + uasort($result, function ($a, $b) use ($product_variation, $last_update) { + if ($last_update[$a] == $last_update[$b]) { + if ($product_variation[$a] == $product_variation[$b]) + return strcmp($a, $b); + + return $product_variation[$a] > $product_variation[$b] ? 1 : -1; + } + return $last_update[$a] > $last_update[$b] ? 1 : -1; + }); + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $result; + } + + /** + * Call Woocommerce API to get last updated orders. We are interested here by list of id only. We will retreive properties later. + * + * @param int $fromDate From date + * @param int $toDate To date + * + * @return array|boolean List of orders ID to update or false if error + */ + public function getCommandeToUpdate($fromDate, $toDate) + { + dol_syslog(__METHOD__ . ": start gt = " . (!empty($fromDate) ? dol_print_date($fromDate, 'standard') : 'none') . + ", lt = " . (!empty($toDate) ? dol_print_date($toDate, 'standard') : 'none') . " for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; $this->errors = array(); $this->initECommerceCommande(); - $last_update = []; - $result = []; - $idxPage = 1; - $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); - $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; - $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; + $last_update = []; + $result = []; + $idxPage = 1; + $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $from_date = isset($fromDate) && !empty($fromDate) ? new DateTime(dol_print_date($fromDate, 'standard')) : null; + $to_date = isset($toDate) && !empty($toDate) ? new DateTime(dol_print_date($toDate, 'standard')) : null; - $filter = ['limit' => $per_page]; - if (isset($fromDate) && !empty($fromDate)) $filter['updated_at_min'] = dol_print_date($fromDate - (24 * 60 * 60), 'dayrfc'); - if (isset($toDate) && !empty($toDate)) $filter['updated_at_max'] = dol_print_date($toDate + (24 * 60 * 60), 'dayrfc'); + $filter = ['limit' => $per_page]; + if (isset($fromDate) && !empty($fromDate)) $filter['updated_at_min'] = dol_print_date($fromDate - (24 * 60 * 60), 'dayrfc'); + if (isset($toDate) && !empty($toDate)) $filter['updated_at_max'] = dol_print_date($toDate + (24 * 60 * 60), 'dayrfc'); do { - $filters = [ + $filters = [ 'page' => $idxPage++, 'filter' => $filter, 'fields' => 'id,created_at,updated_at' @@ -481,53 +481,53 @@ public function getCommandeToUpdate($fromDate, $toDate) if (!isset($page) || !isset($page['orders'])) $page['orders'] = array(); - foreach ($page['orders'] as $order) { - $id = $order['id']; - $date_order = $this->getDateTimeFromGMTDateTime(!empty($order['updated_at']) ? $order['updated_at'] : $order['created_at']); - $update_order = false; - if ($from_date == $date_order) { - if ($this->eCommerceCommande->fetchByRemoteId($id, $this->site->id) > 0) { - if (isset($this->eCommerceCommande->last_update) && !empty($this->eCommerceCommande->last_update)) { - $date = new DateTime(dol_print_date($this->eCommerceCommande->last_update, 'standard')); - if ($date < $from_date) { - $update_order = true; - } - } - } else { - $update_order = true; - } - } - - if ($update_order || (!isset($from_date) || $from_date < $date_order) && (!isset($to_date) || $date_order <= $to_date)) { - $result[$id] = $id; - $last_update[$id] = $date_order->format('Y-m-d H:i:s'); - } - } + foreach ($page['orders'] as $order) { + $id = $order['id']; + $date_order = $this->getDateTimeFromGMTDateTime(!empty($order['updated_at']) ? $order['updated_at'] : $order['created_at']); + $update_order = false; + if ($from_date == $date_order) { + if ($this->eCommerceCommande->fetchByRemoteId($id, $this->site->id) > 0) { + if (isset($this->eCommerceCommande->last_update) && !empty($this->eCommerceCommande->last_update)) { + $date = new DateTime(dol_print_date($this->eCommerceCommande->last_update, 'standard')); + if ($date < $from_date) { + $update_order = true; + } + } + } else { + $update_order = true; + } + } + + if ($update_order || (!isset($from_date) || $from_date < $date_order) && (!isset($to_date) || $date_order <= $to_date)) { + $result[$id] = $id; + $last_update[$id] = $date_order->format('Y-m-d H:i:s'); + } + } } while (count($page['orders']) == $per_page); - //important - order by last update - if (count($result)) { - array_multisort($last_update, SORT_ASC, $result); - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $result; - } - - /** - * Desactivated because is not supported by woocommerce. - * - * @param int $fromDate From date - * @param int $toDate To date - * - * @return array Empty list - */ - public function getFactureToUpdate($fromDate, $toDate) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + //important - order by last update + if (count($result)) { + array_multisort($last_update, SORT_ASC, $result); + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $result; + } + + /** + * Desactivated because is not supported by woocommerce. + * + * @param int $fromDate From date + * @param int $toDate To date + * + * @return array Empty list + */ + public function getFactureToUpdate($fromDate, $toDate) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); return []; - } + } /** * Call Woocommerce API to get company datas and put into dolibarr company class. @@ -538,7 +538,7 @@ public function getFactureToUpdate($fromDate, $toDate) * @param int $toNb Max nb * @return array|boolean List of companies sorted by update time or false if error. */ - public function convertRemoteObjectIntoDolibarrSociete($from_date = null, $to_date = null, $remoteObject = array(), $toNb=0) + public function convertRemoteObjectIntoDolibarrSociete($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) { dol_syslog(__METHOD__ . ": Get " . count($remoteObject) . " remote companies ID: " . implode(', ', $remoteObject) . " for site ID {$this->site->id}", LOG_DEBUG); global $conf, $langs; @@ -654,7 +654,7 @@ public function convertCustomerDataIntoProcessedData($remote_data) if (!empty($remote_data['billing']['first_name']) || !empty($remote_data['billing']['last_name'])) { $firstname = $remote_data['billing']['first_name']; $lastname = $remote_data['billing']['last_name']; - }else { + } else { $firstname = $remote_data['first_name']; $lastname = $remote_data['last_name']; } @@ -701,114 +701,114 @@ public function convertCustomerDataIntoProcessedData($remote_data) return $item; } - /** - * Call Woocommerce API to get contact datas and put into dolibarr contact class. - * - * @param array $remoteCompany Remote company infos - * @return array|boolean List of contact sorted by update time or false if error. - */ - public function convertRemoteObjectIntoDolibarrSocpeople($remoteCompany) - { - dol_syslog(__METHOD__ . ": Get remote contacts ID: {$remoteCompany['id']} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + /** + * Call Woocommerce API to get contact datas and put into dolibarr contact class. + * + * @param array $remoteCompany Remote company infos + * @return array|boolean List of contact sorted by update time or false if error. + */ + public function convertRemoteObjectIntoDolibarrSocpeople($remoteCompany) + { + dol_syslog(__METHOD__ . ": Get remote contacts ID: {$remoteCompany['id']} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; $this->errors = array(); $contacts = []; - $last_update = $this->getDateTimeFromGMTDateTime(/*!empty($remoteCompany['date_modified_gmt']) ? $remoteCompany['date_modified_gmt'] :*/ $remoteCompany['date_created_gmt']); - - $bContact = $remoteCompany['billing']; - if (!empty($bContact['address_1']) || !empty($bContact['address_2']) || !empty($bContact['postcode']) || - !empty($bContact['city']) || !empty($bContact['country']) || - !empty($bContact['email']) || !empty($bContact['company']) || !empty($bContact['phone']) - ) { - $firstname = !empty($bContact['first_name']) ? $bContact['first_name'] : $remoteCompany['first_name']; - $lastname = !empty($bContact['last_name']) ? $bContact['last_name'] : $remoteCompany['last_name']; + $last_update = $this->getDateTimeFromGMTDateTime(/*!empty($remoteCompany['date_modified_gmt']) ? $remoteCompany['date_modified_gmt'] :*/ $remoteCompany['date_created_gmt']); + + $bContact = $remoteCompany['billing']; + if (!empty($bContact['address_1']) || !empty($bContact['address_2']) || !empty($bContact['postcode']) || + !empty($bContact['city']) || !empty($bContact['country']) || + !empty($bContact['email']) || !empty($bContact['company']) || !empty($bContact['phone']) + ) { + $firstname = !empty($bContact['first_name']) ? $bContact['first_name'] : $remoteCompany['first_name']; + $lastname = !empty($bContact['last_name']) ? $bContact['last_name'] : $remoteCompany['last_name']; if (!empty($conf->global->ECOMMERCENG_UPPERCASE_LASTNAME)) { $firstname = dol_ucwords(dol_strtolower($firstname)); $lastname = dol_strtoupper($lastname); } - if (!empty($firstname) && empty($lastname)) { - $lastname = $langs->transnoentitiesnoconv("ECommerceLastNameNotInformed"); - } elseif (empty($firstname) && empty($lastname)) { - $lastname = $langs->transnoentitiesnoconv('ECommerceFirstNameLastNameNotInformed'); - } - $contacts[] = [ - 'remote_id' => null, - 'last_update' => $last_update->format('Y-m-d H:i:s'), - 'firstname' => $firstname, - 'lastname' => $lastname, - 'address' => $bContact['address_1'] . (!empty($bContact['address_1']) && !empty($bContact['address_2']) ? "\n" : "") . $bContact['address_2'], - 'zip' => $bContact['postcode'], - 'town' => $bContact['city'], - 'country_id' => getCountry($bContact['country'], 3), - 'email' => !empty($bContact['email']) ? $bContact['email'] : $remoteCompany['email'], - 'phone' => $bContact['phone'], - 'fax' => null, - ]; - } - - $sContact = $remoteCompany['shipping']; - if (!empty($sContact['address_1']) || !empty($sContact['address_2']) || - !empty($sContact['postcode']) || !empty($sContact['city']) || - !empty($sContact['country']) - ) { - if ($bContact['first_name'] != $sContact['first_name'] || $bContact['last_name'] != $sContact['last_name'] || - $bContact['address_1'] != $sContact['address_1'] || $bContact['address_2'] != $sContact['address_2'] || - $bContact['postcode'] != $sContact['postcode'] || $bContact['city'] != $sContact['city'] || - $bContact['country'] != $sContact['country'] - ) { - $firstname = !empty($sContact['first_name']) ? $sContact['first_name'] : $remoteCompany['first_name']; - $lastname = !empty($sContact['last_name']) ? $sContact['last_name'] : $remoteCompany['last_name']; + if (!empty($firstname) && empty($lastname)) { + $lastname = $langs->transnoentitiesnoconv("ECommerceLastNameNotInformed"); + } elseif (empty($firstname) && empty($lastname)) { + $lastname = $langs->transnoentitiesnoconv('ECommerceFirstNameLastNameNotInformed'); + } + $contacts[] = [ + 'remote_id' => null, + 'last_update' => $last_update->format('Y-m-d H:i:s'), + 'firstname' => $firstname, + 'lastname' => $lastname, + 'address' => $bContact['address_1'] . (!empty($bContact['address_1']) && !empty($bContact['address_2']) ? "\n" : "") . $bContact['address_2'], + 'zip' => $bContact['postcode'], + 'town' => $bContact['city'], + 'country_id' => getCountry($bContact['country'], 3), + 'email' => !empty($bContact['email']) ? $bContact['email'] : $remoteCompany['email'], + 'phone' => $bContact['phone'], + 'fax' => null, + ]; + } + + $sContact = $remoteCompany['shipping']; + if (!empty($sContact['address_1']) || !empty($sContact['address_2']) || + !empty($sContact['postcode']) || !empty($sContact['city']) || + !empty($sContact['country']) + ) { + if ($bContact['first_name'] != $sContact['first_name'] || $bContact['last_name'] != $sContact['last_name'] || + $bContact['address_1'] != $sContact['address_1'] || $bContact['address_2'] != $sContact['address_2'] || + $bContact['postcode'] != $sContact['postcode'] || $bContact['city'] != $sContact['city'] || + $bContact['country'] != $sContact['country'] + ) { + $firstname = !empty($sContact['first_name']) ? $sContact['first_name'] : $remoteCompany['first_name']; + $lastname = !empty($sContact['last_name']) ? $sContact['last_name'] : $remoteCompany['last_name']; if (!empty($conf->global->ECOMMERCENG_UPPERCASE_LASTNAME)) { $firstname = dol_ucwords(dol_strtolower($firstname)); $lastname = dol_strtoupper($lastname); } - if (!empty($firstname) && empty($lastname)) { - $lastname = $langs->transnoentitiesnoconv("ECommerceLastNameNotInformed"); - } elseif (empty($firstname) && empty($lastname)) { - $lastname = $langs->transnoentitiesnoconv('ECommerceFirstNameLastNameNotInformed'); - } - $contacts[] = [ - 'remote_id' => null, - 'last_update' => $last_update->format('Y-m-d H:i:s'), - 'firstname' => $firstname, - 'lastname' => $lastname, - 'address' => $sContact['address_1'] . (!empty($sContact['address_1']) && !empty($sContact['address_2']) ? "\n" : "") . $sContact['address_2'], - 'zip' => $sContact['postcode'], - 'town' => $sContact['city'], - 'country_id' => getCountry($sContact['country'], 3), - 'email' => null, - 'phone' => null, - 'fax' => null, - ]; - } - } - - dol_syslog(__METHOD__ . ": end, converted " . count($contacts) . " remote contacts", LOG_DEBUG); - return $contacts; - } - - /** - * Call Woocommerce API to get product datas and put into dolibarr product class. - * + if (!empty($firstname) && empty($lastname)) { + $lastname = $langs->transnoentitiesnoconv("ECommerceLastNameNotInformed"); + } elseif (empty($firstname) && empty($lastname)) { + $lastname = $langs->transnoentitiesnoconv('ECommerceFirstNameLastNameNotInformed'); + } + $contacts[] = [ + 'remote_id' => null, + 'last_update' => $last_update->format('Y-m-d H:i:s'), + 'firstname' => $firstname, + 'lastname' => $lastname, + 'address' => $sContact['address_1'] . (!empty($sContact['address_1']) && !empty($sContact['address_2']) ? "\n" : "") . $sContact['address_2'], + 'zip' => $sContact['postcode'], + 'town' => $sContact['city'], + 'country_id' => getCountry($sContact['country'], 3), + 'email' => null, + 'phone' => null, + 'fax' => null, + ]; + } + } + + dol_syslog(__METHOD__ . ": end, converted " . count($contacts) . " remote contacts", LOG_DEBUG); + return $contacts; + } + + /** + * Call Woocommerce API to get product datas and put into dolibarr product class. + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date - * @param array $remoteObject List of id of remote products to convert - * @param int $toNb Max nb - * @return array|boolean List of products sorted by update time or false if error. - */ - public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_date = null, $remoteObject = array(), $toNb=0) - { - dol_syslog(__METHOD__ . ": Get " . count($remoteObject) . " remote products ID: " . implode(', ', $remoteObject) . " for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + * @param array $remoteObject List of id of remote products to convert + * @param int $toNb Max nb + * @return array|boolean List of products sorted by update time or false if error. + */ + public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) + { + dol_syslog(__METHOD__ . ": Get " . count($remoteObject) . " remote products ID: " . implode(', ', $remoteObject) . " for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; - if (!empty($conf->global->ECOMMERCENG_DISABLED_PRODUCT_SYNCHRO_STOD)) { - return []; + if (!empty($conf->global->ECOMMERCENG_DISABLED_PRODUCT_SYNCHRO_STOD)) { + return []; } $this->errors = array(); $products = []; - $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); $from_date = isset($from_date) ? dol_print_date($from_date, '%Y-%m-%dT%H:%M:%S') : null; $to_date = isset($to_date) ? dol_print_date($to_date, '%Y-%m-%dT%H:%M:%S') : null; $product_variation_mode_all_to_one = !empty($this->site->parameters['product_variation_mode']) && $this->site->parameters['product_variation_mode'] == 'all_to_one'; @@ -840,8 +840,7 @@ public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_da } else { $filters['include'] = implode(',', $include_ids); } - } - else { + } else { if (isset($from_date)) $filters['after'] = $from_date; if (isset($to_date)) $filters['before'] = $to_date; } @@ -888,7 +887,7 @@ public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_da $requestGroupsVariations = $this->getRequestGroups($include_variation_ids[$product['id']], $nb_max_by_request); foreach ($requestGroupsVariations as $requestVariations) { dol_syslog(__METHOD__ . ": Get " . count($requestVariations) . " products variations of remote product (ID:{$product['id']}): " . implode(', ', $requestVariations), LOG_DEBUG); - $variation_filters = [ + $variation_filters = [ 'per_page' => $nb_max_by_request, 'include' => implode(',', $requestVariations), ]; @@ -920,9 +919,9 @@ public function convertRemoteObjectIntoDolibarrProduct($from_date = null, $to_da if ($toNb > 0 && $nbTotalRecords >= $toNb) break; } while (count($page) == $nb_max_by_request); - dol_syslog(__METHOD__ . ": end, converted " . count($products) . " remote products", LOG_DEBUG); - return $products; - } + dol_syslog(__METHOD__ . ": end, converted " . count($products) . " remote products", LOG_DEBUG); + return $products; + } /** * Call Woocommerce API to check if the remote product exist. @@ -1025,10 +1024,11 @@ public function convertProductDataIntoProcessedData($remote_data, $parent_remote dol_syslog(__METHOD__ . " remote_data=" . json_encode($remote_data), LOG_DEBUG); global $conf, $langs; + $multilangs = !empty($conf->global->MAIN_MULTILANGS) && !empty($this->site->parameters['enable_product_plugin_wpml_support']); $this->errors = array(); $isVariation = isset($parent_remote_data) || $remote_data['parent_id'] > 0; $parent_id = isset($parent_remote_data) ? $parent_remote_data['id'] : ($remote_data['parent_id'] > 0 ? $remote_data['parent_id'] : 0); - if ($isVariation && empty($parent_remote_data) && !empty($parent_id)) { + if ($isVariation && (empty($parent_remote_data) || ($multilangs && empty($parent_remote_data['translations']))) && !empty($parent_id)) { $parent_remote_data = $this->client->sendToApi(eCommerceClientApi::METHOD_GET, 'products/' . $parent_id); if (!isset($parent_remote_data)) { $this->errors[] = $langs->trans('ECommerceWoocommerceConvertRemoteObjectIntoDolibarrProduct', $this->site->name); @@ -1037,6 +1037,15 @@ public function convertProductDataIntoProcessedData($remote_data, $parent_remote return false; } } + if ($multilangs && empty($remote_data['translations'])) { + $remote_data = $this->client->sendToApi(eCommerceClientApi::METHOD_GET, 'products/' . ($isVariation ? $parent_id . '/variations/' : '') . $remote_data['id']); + if (!isset($remote_data)) { + $this->errors[] = $langs->trans('ECommerceWoocommerceConvertRemoteObjectIntoDolibarrProduct', $this->site->name); + $this->errors[] = $this->client->errorsToString(); + dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); + return false; + } + } // if the parent has no variations (ex: webhook of a variation transformed in a simple product before the webhook is precessed) if ($isVariation && empty($parent_remote_data['variations'])) { @@ -1139,7 +1148,7 @@ public function convertProductDataIntoProcessedData($remote_data, $parent_remote } $translates = array(); - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($this->site->parameters['enable_product_plugin_wpml_support'])) { + if ($multilangs) { $language_list = $this->site->getLanguages(); foreach ($language_list as $remote_lang => $language) { if ($remote_lang == 'ec_none') continue; @@ -1181,6 +1190,20 @@ public function convertProductDataIntoProcessedData($remote_data, $parent_remote } } + // Get first remote id and parent remote id (multi-language support) + if ($multilangs) { + if (!empty($remote_data['translations']) && (!$isVariation || !empty($parent_remote_data['translations']))) { + $remote_parent_id = $isVariation ? min($parent_remote_data['translations']) : 0; + $remote_id = min($remote_data['translations']); + $remote_id = ($isVariation ? $remote_parent_id . '|' : '') . $remote_id; + } else { + $this->errors[] = $langs->trans('ECommerceWoocommerceConvertRemoteObjectIntoDolibarrProduct', $this->site->name); + $this->errors[] = "Don't found translates values into remote data"; + dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); + return false; + } + } + $product = [ 'create_date' => strtotime($remote_data['date_created']), 'remote_id' => $remote_id, @@ -1216,6 +1239,37 @@ public function convertProductDataIntoProcessedData($remote_data, $parent_remote ], ]; + if ($multilangs) { + $translations_ids = []; + if (!empty($remote_data['translations'])) { + foreach ($remote_data['translations'] as $l => $id) { + if ($id == $remote_data['id']) continue; + $translations_ids[] = $id; + } + if ($isVariation && !empty($translations_ids)) { + $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $filters = [ + 'per_page' => $nb_max_by_request, + 'include' => implode(',', $translations_ids), + ]; + + $page = $this->client->sendToApi(eCommerceClientApi::METHOD_GET, 'products', [GuzzleHttp\RequestOptions::QUERY => $filters]); + if (!isset($page)) { + $this->errors[] = $langs->trans('ECommerceWoocommerceConvertRemoteObjectIntoDolibarrProduct', $this->site->name); + $this->errors[] = $this->client->errorsToString(); + dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); + return false; + } + + $translations_ids = []; + foreach ($page as $product) { + $translations_ids[] = $product['parent_id'] . '|' . $product['id']; + } + } + } + $product['other_data'] = ['translations_ids' => $translations_ids]; + } + // Synchronize ref if ($productRefSynchDirection == 'etod' || $productRefSynchDirection == 'all') { $product['ref'] = $remote_data['sku']; @@ -1406,19 +1460,19 @@ public function getCleanedRelativeUrl($root_url, $img_url) return $img_url; } - /** - * Call Woocommerce API to get order datas and put into dolibarr order class. - * + /** + * Call Woocommerce API to get order datas and put into dolibarr order class. + * * @param int $from_date Synchronize from date * @param int $to_date Synchronize to date - * @param array $remoteObject List of id of remote orders to convert - * @param int $toNb Max nb - * @return array|boolean List of orders sorted by update time or false if error. - */ - public function convertRemoteObjectIntoDolibarrCommande($from_date = null, $to_date = null, $remoteObject = array(), $toNb=0) - { - dol_syslog(__METHOD__ . ": Get " . count($remoteObject) . " remote orders ID: " . implode(', ', $remoteObject) . " for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + * @param array $remoteObject List of id of remote orders to convert + * @param int $toNb Max nb + * @return array|boolean List of orders sorted by update time or false if error. + */ + public function convertRemoteObjectIntoDolibarrCommande($from_date = null, $to_date = null, $remoteObject = array(), $toNb = 0) + { + dol_syslog(__METHOD__ . ": Get " . count($remoteObject) . " remote orders ID: " . implode(', ', $remoteObject) . " for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; $this->errors = array(); $orders = []; @@ -1541,7 +1595,7 @@ public function convertOrderDataIntoProcessedData($remote_data) $product_variation_mode_all_to_one = !empty($this->site->parameters['product_variation_mode']) && $this->site->parameters['product_variation_mode'] == 'all_to_one'; $order_metadata_product_lines_to_description_etod = !empty($this->site->parameters['order_metadata_product_lines_to_description_etod']); $order_filter_mode_metadata_product_lines_to_description_etod = !empty($this->site->parameters['order_filter_mode_metadata_product_lines_to_description_etod']) ? $this->site->parameters['order_filter_mode_metadata_product_lines_to_description_etod'] : 'exclude'; - $order_filter_keys_metadata_product_lines_to_description_etod = !empty($this->site->parameters['order_filter_keys_metadata_product_lines_to_description_etod']) ? array_filter(array_map('trim', explode(',', (string)$this->site->parameters['order_filter_keys_metadata_product_lines_to_description_etod'])), 'strlen') : array(); + $order_filter_keys_metadata_product_lines_to_description_etod = !empty($this->site->parameters['order_filter_keys_metadata_product_lines_to_description_etod']) ? array_filter(array_map('trim', explode(',', (string) $this->site->parameters['order_filter_keys_metadata_product_lines_to_description_etod'])), 'strlen') : array(); $bundles_ids = []; $parent_match = array(); @@ -2607,25 +2661,25 @@ public function getProductLanguage($remote_product_id, $remote_product_variation * Desactivated because is not supported by woocommerce. * * @param array $remoteObject List of id of remote orders to convert - * @param int $toNb Max nb - * @return array Empty list - */ - public function convertRemoteObjectIntoDolibarrFacture($remoteObject, $toNb=0) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + * @param int $toNb Max nb + * @return array Empty list + */ + public function convertRemoteObjectIntoDolibarrFacture($remoteObject, $toNb = 0) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); return []; - } - - /** - * Get remote category tree - * - * @return array|boolean Array with categories or false if error - */ - public function getRemoteCategoryTree() - { - dol_syslog(__METHOD__ . ": Get remote category tree for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; + } + + /** + * Get remote category tree + * + * @return array|boolean Array with categories or false if error + */ + public function getRemoteCategoryTree() + { + dol_syslog(__METHOD__ . ": Get remote category tree for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; if (!empty($conf->global->ECOMMERCENG_DISABLED_PRODUCT_SYNCHRO_STOD)) { return []; @@ -2633,11 +2687,11 @@ public function getRemoteCategoryTree() $this->errors = array(); $categories = []; - $idxPage = 1; - $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); + $idxPage = 1; + $per_page = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); do { - $filters = [ + $filters = [ 'page' => $idxPage++, 'per_page' => $per_page, ]; @@ -2651,70 +2705,81 @@ public function getRemoteCategoryTree() } if (!isset($page)) $page = array(); - - foreach ($page as $category) { - $categories[$category['id']] = [ - 'category_id' => $category['id'], // id category - 'parent_id' => $category['parent'], - 'label' => $category['name'], - 'name' => $category['name'], - 'description' => $category['description'], - 'updated_at' => '', - ]; - } - } while (count($page) == $per_page); - - // Set tree - foreach ($categories as $category) { - $parent_id = $category['parent_id']; - - if (!empty($parent_id)) { - if (!isset($categories[$parent_id]['children'])) { - $categories[$parent_id]['level'] = 0; - $categories[$parent_id]['children'] = []; - } - - $categories[$parent_id]['children'][] = &$categories[$category['category_id']]; - } - } - - // Make tree - $categories_tree = ['level' => 0, 'children' => []]; - foreach ($categories as $category) { - if (empty($category['parent_id'])) { - $categories_tree['children'][] = $category; - } - } - - dol_syslog(__METHOD__ . ": end, " . count($categories) . " remote category recovered", LOG_DEBUG); - return $categories_tree; - } - - /** - * Desactivated because is not supported by woocommerce. - * - * @param int $remote_company_id Id of company - * - * @return array Array with address id - */ - public function getRemoteAddressIdForSociete($remote_company_id) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); - $this->errors = array(); + $multilangs = !empty($conf->global->MAIN_MULTILANGS) && !empty($this->site->parameters['enable_product_plugin_wpml_support']); + + foreach ($page as $category) { + $categories[$category['id']] = [ + 'category_id' => $category['id'], // id category + 'parent_id' => $category['parent'], + 'label' => $category['name'], + 'name' => $category['name'], + 'description' => $category['description'], + 'updated_at' => '', + ]; + if ($multilangs) { + $translations_ids = []; + if (!empty($category['translations'])) { + foreach ($category['translations'] as $l => $id) { + if ($id == $category['id']) continue; + $translations_ids[] = $id; + } + } + $categories[$category['id']]['other_data'] = ['translations_ids' => $translations_ids]; + } + } + } while (count($page) == $per_page); + + // Set tree + foreach ($categories as $category) { + $parent_id = $category['parent_id']; + + if (!empty($parent_id)) { + if (!isset($categories[$parent_id]['children'])) { + $categories[$parent_id]['level'] = 0; + $categories[$parent_id]['children'] = []; + } + + $categories[$parent_id]['children'][] = &$categories[$category['category_id']]; + } + } + + // Make tree + $categories_tree = ['level' => 0, 'children' => []]; + foreach ($categories as $category) { + if (empty($category['parent_id'])) { + $categories_tree['children'][] = $category; + } + } + + dol_syslog(__METHOD__ . ": end, " . count($categories) . " remote category recovered", LOG_DEBUG); + return $categories_tree; + } + + /** + * Desactivated because is not supported by woocommerce. + * + * @param int $remote_company_id Id of company + * + * @return array Array with address id + */ + public function getRemoteAddressIdForSociete($remote_company_id) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + $this->errors = array(); return [$remote_company_id]; - } - - /** - * Return content of one category - * - * @param int $category_id Remote category id - * - * @return array|boolean Return category data - */ - public function getCategoryData($category_id) - { - dol_syslog(__METHOD__ . ": Get remote category for site ID {$this->site->id}", LOG_DEBUG); - global $langs; + } + + /** + * Return content of one category + * + * @param int $category_id Remote category id + * + * @return array|boolean Return category data + */ + public function getCategoryData($category_id) + { + dol_syslog(__METHOD__ . ": Get remote category for site ID {$this->site->id}", LOG_DEBUG); + global $langs; $this->errors = array(); $category = []; @@ -2740,36 +2805,48 @@ public function getCategoryData($category_id) 'updated_at' => '', ]; - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $category; - } - - /** - * Return content of one order - * - * @param int $remoteOrderId Remote order id - * - * @return array Empty - */ - public function getRemoteCommande($remoteOrderId) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + $multilangs = !empty($conf->global->MAIN_MULTILANGS) && !empty($this->site->parameters['enable_product_plugin_wpml_support']); + if ($multilangs) { + $translations_ids = []; + if (!empty($result['translations'])) { + foreach ($result['translations'] as $l => $id) { + if ($id == $result['id']) continue; + $translations_ids[] = $id; + } + } + $category['other_data'] = ['translations_ids' => $translations_ids]; + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $category; + } + + /** + * Return content of one order + * + * @param int $remoteOrderId Remote order id + * + * @return array Empty + */ + public function getRemoteCommande($remoteOrderId) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); return []; - } - - /** - * Conevrt Object to remote product data - * - * @param int $remote_id Id of product on remote ecommerce - * @param Product $object Product object - * - * @return array Remote product data - */ - public function convertObjectIntoProductData($remote_id, $object) - { - dol_syslog(__METHOD__ . ": Update the remote product ID $remote_id for Dolibarr product ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs, $user; + } + + /** + * Conevrt Object to remote product data + * + * @param int $remote_id Id of product on remote ecommerce + * @param Product $object Product object + * + * @return array Remote product data + */ + public function convertObjectIntoProductData($remote_id, $object) + { + dol_syslog(__METHOD__ . ": Update the remote product ID $remote_id for Dolibarr product ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs, $user; $this->errors = array(); $return_data = array(); @@ -2778,23 +2855,23 @@ public function convertObjectIntoProductData($remote_id, $object) $isProductVariation = false; $isProductVariationHasOne = false; - $remote_product_id = $remote_id; + $remote_product_id = $remote_id; $remote_product_variation_ids = array(); - if (preg_match('/^(\d+)\|(\d+)$/', $remote_id, $idsProduct) == 1) { // Variations - $isProductVariation = true; - $remote_product_id = $idsProduct[1]; + if (preg_match('/^(\d+)\|(\d+)$/', $remote_id, $idsProduct) == 1) { // Variations + $isProductVariation = true; + $remote_product_id = $idsProduct[1]; $remote_product_variation_ids[] = $idsProduct[2]; - } + } - $productSynchPrice = isset($this->site->parameters['product_synch_price']) ? $this->site->parameters['product_synch_price'] : 'regular'; - $productImageSynchDirection = isset($this->site->parameters['product_synch_direction']['image']) ? $this->site->parameters['product_synch_direction']['image'] : ''; - $productRefSynchDirection = isset($this->site->parameters['product_synch_direction']['ref']) ? $this->site->parameters['product_synch_direction']['ref'] : ''; - $productDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['description']) ? $this->site->parameters['product_synch_direction']['description'] : ''; - $productShortDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['short_description']) ? $this->site->parameters['product_synch_direction']['short_description'] : ''; + $productSynchPrice = isset($this->site->parameters['product_synch_price']) ? $this->site->parameters['product_synch_price'] : 'regular'; + $productImageSynchDirection = isset($this->site->parameters['product_synch_direction']['image']) ? $this->site->parameters['product_synch_direction']['image'] : ''; + $productRefSynchDirection = isset($this->site->parameters['product_synch_direction']['ref']) ? $this->site->parameters['product_synch_direction']['ref'] : ''; + $productDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['description']) ? $this->site->parameters['product_synch_direction']['description'] : ''; + $productShortDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['short_description']) ? $this->site->parameters['product_synch_direction']['short_description'] : ''; $productWeightSynchDirection = isset($this->site->parameters['product_synch_direction']['weight']) ? $this->site->parameters['product_synch_direction']['weight'] : ''; $productDimensionSynchDirection = isset($this->site->parameters['product_synch_direction']['dimension']) ? $this->site->parameters['product_synch_direction']['dimension'] : ''; - $productTaxSynchDirection = isset($this->site->parameters['product_synch_direction']['tax']) ? $this->site->parameters['product_synch_direction']['tax'] : ''; - $productStatusSynchDirection = isset($this->site->parameters['product_synch_direction']['status']) ? $this->site->parameters['product_synch_direction']['status'] : ''; + $productTaxSynchDirection = isset($this->site->parameters['product_synch_direction']['tax']) ? $this->site->parameters['product_synch_direction']['tax'] : ''; + $productStatusSynchDirection = isset($this->site->parameters['product_synch_direction']['status']) ? $this->site->parameters['product_synch_direction']['status'] : ''; $product_variation_mode_all_to_one = !empty($this->site->parameters['product_variation_mode']) && $this->site->parameters['product_variation_mode'] == 'all_to_one'; if ($product_variation_mode_all_to_one) { @@ -2808,60 +2885,60 @@ public function convertObjectIntoProductData($remote_id, $object) // Convert Weight $from_unit = $object->weight_units; - $to_unit = isset($this->site->parameters['product_weight_units']) ? $this->site->parameters['product_weight_units'] : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?0:$conf->global->MAIN_WEIGHT_DEFAULT_UNIT); - $totalWeight = weight_convert((double)$object->weight, $from_unit, $to_unit); + $to_unit = isset($this->site->parameters['product_weight_units']) ? $this->site->parameters['product_weight_units'] : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? 0 : $conf->global->MAIN_WEIGHT_DEFAULT_UNIT); + $totalWeight = weight_convert((double) $object->weight, $from_unit, $to_unit); // Convert Dimension $from_unit = $object->width_units; $to_unit = isset($this->site->parameters['product_direction_units']) ? $this->site->parameters['product_direction_units'] : -2; // -2 = cm - $totalWidth = weight_convert((double)$object->width, $from_unit, $to_unit); + $totalWidth = weight_convert((double) $object->width, $from_unit, $to_unit); $from_unit = $object->height_units; - $totalHeight = weight_convert((double)$object->height, $from_unit, $to_unit); + $totalHeight = weight_convert((double) $object->height, $from_unit, $to_unit); $from_unit = $object->length_units; - $totalLength = weight_convert((double)$object->length, $from_unit, $to_unit); + $totalLength = weight_convert((double) $object->length, $from_unit, $to_unit); - // Price + // Price // $error_price = 0; - if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - $price_level = !empty($this->site->price_level) ? $this->site->price_level : 1; - if ($this->site->ecommerce_price_type == 'TTC') { + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + $price_level = !empty($this->site->price_level) ? $this->site->price_level : 1; + if ($this->site->ecommerce_price_type == 'TTC') { // if ($object->multiprices_base_type[$price_level] == 'TTC' || $object->multiprices_ttc[$price_level] == 0) { - $price = $object->multiprices_ttc[$price_level]; + $price = $object->multiprices_ttc[$price_level]; // } else { // $error_price++; // } - } else { + } else { // if ($object->multiprices_base_type[$price_level] == 'TTC' && $object->multiprices[$price_level] != 0) { // $error_price++; // } else { - $price = $object->multiprices[$price_level]; + $price = $object->multiprices[$price_level]; // } - } - } else { - if ($this->site->ecommerce_price_type == 'TTC') { + } + } else { + if ($this->site->ecommerce_price_type == 'TTC') { // if ($object->price_base_type == 'TTC' || $object->price_ttc == 0) { - $price = $object->price_ttc; + $price = $object->price_ttc; // } else { // $error_price++; // } - } else { + } else { // if ($object->price_base_type == 'TTC' && $object->price != 0) { // $error_price++; // } else { - $price = $object->price; + $price = $object->price; // } - } - } + } + } // if ($error_price) { // $error_msg = $langs->trans('ECommerceWoocommerceErrorBaseTypeOfProductWithSiteParameter', $object->ref, $this->site->ecommerce_price_type, $this->site->name); // $this->errors[] = $error_msg; // dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_ERR); // return array(); // } - $regular_price = $object->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"]; + $regular_price = $object->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"]; - $sale_price = price2num($object->array_options["options_ecommerceng_wc_sale_price_{$this->site->id}_{$conf->entity}"]); - if (!empty($sale_price)) { + $sale_price = price2num($object->array_options["options_ecommerceng_wc_sale_price_{$this->site->id}_{$conf->entity}"]); + if (!empty($sale_price)) { $date_on_sale_from = $object->array_options["options_ecommerceng_wc_date_on_sale_from_{$this->site->id}_{$conf->entity}"]; if (!empty($date_on_sale_from)) { $date_on_sale_from = $this->getDateTimeToGMTDateTime(is_numeric($date_on_sale_from) ? dol_print_date($date_on_sale_from, '%Y-%m-%dT%H:%M:%S') : $date_on_sale_from); @@ -2882,12 +2959,12 @@ public function convertObjectIntoProductData($remote_id, $object) $date_on_sale_to = ''; } - // images - $images = []; - if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { - // Get current images - $current_images = []; - if (!empty($remote_product_id)) { + // images + $images = []; + if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { + // Get current images + $current_images = []; + if (!empty($remote_product_id)) { if ($isProductVariation) { // Variations foreach ($remote_product_variation_ids as $remote_product_variation_id) { $results = $this->client->sendToApi(eCommerceClientApi::METHOD_GET, "products/{$remote_product_id}/variations/{$remote_product_variation_id}"); @@ -2919,16 +2996,16 @@ public function convertObjectIntoProductData($remote_id, $object) } } - // Product - Images properties - $entity = isset($object->entity) ? $object->entity : $conf->entity; - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs - if ($object->type == Product::TYPE_PRODUCT) { - $dir = $conf->product->multidir_output[$entity] . '/' . substr(substr("000" . $object->id, -2), 1, 1) . '/' . substr(substr("000" . $object->id, -2), 0, 1) . '/' . $object->id . "/photos/"; - } else { - $dir = $conf->service->multidir_output[$entity] . '/' . substr(substr("000" . $object->id, -2), 1, 1) . '/' . substr(substr("000" . $object->id, -2), 0, 1) . '/' . $object->id . "/photos/"; - } - } else { - if (version_compare(DOL_VERSION, "13.0.0") >= 0) { + // Product - Images properties + $entity = isset($object->entity) ? $object->entity : $conf->entity; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs + if ($object->type == Product::TYPE_PRODUCT) { + $dir = $conf->product->multidir_output[$entity] . '/' . substr(substr("000" . $object->id, -2), 1, 1) . '/' . substr(substr("000" . $object->id, -2), 0, 1) . '/' . $object->id . "/photos/"; + } else { + $dir = $conf->service->multidir_output[$entity] . '/' . substr(substr("000" . $object->id, -2), 1, 1) . '/' . substr(substr("000" . $object->id, -2), 0, 1) . '/' . $object->id . "/photos/"; + } + } else { + if (version_compare(DOL_VERSION, "13.0.0") >= 0) { if ($object->type == Product::TYPE_PRODUCT) { $dir = $conf->product->multidir_output[$entity] . '/' . get_exdir(0, 0, 0, 1, $object, 'product') . '/'; } else { @@ -2941,7 +3018,7 @@ public function convertObjectIntoProductData($remote_id, $object) $dir = $conf->service->multidir_output[$entity] . '/' . get_exdir(0, 0, 0, 0, $object, 'product') . dol_sanitizeFileName($object->ref) . '/'; } } - } + } // $photos = $object->liste_photos($dir); // foreach ($photos as $index => $photo) { // $img = []; @@ -2986,7 +3063,7 @@ public function convertObjectIntoProductData($remote_id, $object) // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; if ($dir) { - $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir); + $relativedir = preg_replace('/^' . preg_quote(DOL_DATA_ROOT, '/') . '/', '', $dir); $relativedir = preg_replace('/^[\\/]/', '', $relativedir); } @@ -3027,10 +3104,10 @@ public function convertObjectIntoProductData($remote_id, $object) break; } } - } + } - // Product - Meta data properties - if (empty($object->array_options)) $object->fetch_optionals(); + // Product - Meta data properties + if (empty($object->array_options)) $object->fetch_optionals(); // Multi-languages $translates = array(); @@ -3048,118 +3125,118 @@ public function convertObjectIntoProductData($remote_id, $object) $return_data['translates'] = $translates; // Variations - if ($isProductVariation || $isProductVariationHasOne) { - /* - // Product variation - Downloads properties - $downloads = [ - [ - 'name' => '', // string File name. - 'file' => '', // string File URL. - ], - ]; - - // Product variation - Dimensions properties - $dimensions = [ - 'length' => '', // string Product length (cm). - 'width' => '', // string Product width (cm). - 'height' => '', // string Product height (cm). - ]; - - // Product variation - Image properties - $images = [ - [ - 'id' => 0, // integer Image ID. Not required - 'src' => '', // string Image URL. - 'name' => '', // string Image name. - 'alt' => '', // string Image alternative text. - 'position' => 0, // integer Image position. 0 means that the image is featured. - ], - ]; - - // Product variation - Attributes properties - $attributes = [ - [ - 'id' => 0, // integer Attribute ID. - 'name' => '', // string Attribute name. - 'option' => '', // string Selected attribute term name. - ], - ]; - - // Product variation - Meta data properties - $meta_data = [ - 'key' => '', // string Meta key. - 'value' => '', // string Meta value. - ]; - */ - - $variationData = [ - //'description' => nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]), // string Variation description. - //'sku' => $object->ref, // string Unique identifier. - //'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Variation regular price. - //'sale_price' => $sale_price, // string Variation sale price. - //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. - 'date_on_sale_from_gmt' => $date_on_sale_from, // date-time Start date of sale price, as GMT. - //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. - 'date_on_sale_to_gmt' => $date_on_sale_to, // date-time End date of sale price, in the site’s timezone. - //'visible' => '', // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is true. - //'virtual' => $object->type == Product::TYPE_SERVICE, // boolean If the variation is virtual. Default is false. - //'downloadable' => '', // boolean If the variation is downloadable. Default is false. - //'downloads' => $downloads, // array List of downloadable files. See Product variation - Downloads properties - //'download_limit' => '', // integer Number of times downloadable files can be downloaded after purchase. Default is -1. - //'download_expiry' => '', // integer Number of days until access to downloadable files expires. Default is -1. - //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. - //'tax_class' => '', // string Tax class. - //'manage_stock' => $initial_data || !empty($object->array_options["options_ecommerceng_wc_manage_stock_{$this->site->id}_{$conf->entity}"]), // boolean Stock management at variation level. Default is false. - //'stock_quantity' => '', // integer Stock quantity. - //'in_stock' => '', // boolean Controls whether or not the variation is listed as “in stock” or “out of stock” on the frontend. Default is true. - //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. - //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Variation weight (kg). - //'dimensions' => $dimensions, // object Variation dimensions. See Product variation - Dimensions properties - //'shipping_class' => '', // string Shipping class slug. - //'image' => (!empty($images) ? $images[0] : ''), // object Variation image data. See Product variation - Image properties - //'attributes' => $attributes, // array List of attributes. See Product variation - Attributes properties - //'menu_order' => '', // integer Menu order, used to custom sort products. - //'meta_data' => $meta_data, // array Meta data. See Product variation - Meta data properties - ]; + if ($isProductVariation || $isProductVariationHasOne) { + /* + // Product variation - Downloads properties + $downloads = [ + [ + 'name' => '', // string File name. + 'file' => '', // string File URL. + ], + ]; + + // Product variation - Dimensions properties + $dimensions = [ + 'length' => '', // string Product length (cm). + 'width' => '', // string Product width (cm). + 'height' => '', // string Product height (cm). + ]; + + // Product variation - Image properties + $images = [ + [ + 'id' => 0, // integer Image ID. Not required + 'src' => '', // string Image URL. + 'name' => '', // string Image name. + 'alt' => '', // string Image alternative text. + 'position' => 0, // integer Image position. 0 means that the image is featured. + ], + ]; + + // Product variation - Attributes properties + $attributes = [ + [ + 'id' => 0, // integer Attribute ID. + 'name' => '', // string Attribute name. + 'option' => '', // string Selected attribute term name. + ], + ]; + + // Product variation - Meta data properties + $meta_data = [ + 'key' => '', // string Meta key. + 'value' => '', // string Meta value. + ]; + */ + + $variationData = [ + //'description' => nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]), // string Variation description. + //'sku' => $object->ref, // string Unique identifier. + //'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Variation regular price. + //'sale_price' => $sale_price, // string Variation sale price. + //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. + 'date_on_sale_from_gmt' => $date_on_sale_from, // date-time Start date of sale price, as GMT. + //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. + 'date_on_sale_to_gmt' => $date_on_sale_to, // date-time End date of sale price, in the site’s timezone. + //'visible' => '', // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is true. + //'virtual' => $object->type == Product::TYPE_SERVICE, // boolean If the variation is virtual. Default is false. + //'downloadable' => '', // boolean If the variation is downloadable. Default is false. + //'downloads' => $downloads, // array List of downloadable files. See Product variation - Downloads properties + //'download_limit' => '', // integer Number of times downloadable files can be downloaded after purchase. Default is -1. + //'download_expiry' => '', // integer Number of days until access to downloadable files expires. Default is -1. + //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. + //'tax_class' => '', // string Tax class. + //'manage_stock' => $initial_data || !empty($object->array_options["options_ecommerceng_wc_manage_stock_{$this->site->id}_{$conf->entity}"]), // boolean Stock management at variation level. Default is false. + //'stock_quantity' => '', // integer Stock quantity. + //'in_stock' => '', // boolean Controls whether or not the variation is listed as “in stock” or “out of stock” on the frontend. Default is true. + //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. + //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Variation weight (kg). + //'dimensions' => $dimensions, // object Variation dimensions. See Product variation - Dimensions properties + //'shipping_class' => '', // string Shipping class slug. + //'image' => (!empty($images) ? $images[0] : ''), // object Variation image data. See Product variation - Image properties + //'attributes' => $attributes, // array List of attributes. See Product variation - Attributes properties + //'menu_order' => '', // integer Menu order, used to custom sort products. + //'meta_data' => $meta_data, // array Meta data. See Product variation - Meta data properties + ]; if (is_array($object->context['ec_price_entities']) && in_array($this->site->entity, $object->context['ec_price_entities'])) { $variationData['regular_price'] = $productSynchPrice == 'regular' || $initial_data ? $price : $regular_price; $variationData['sale_price'] = $sale_price; $object->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"] = $variationData['regular_price']; } - if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { - if (!empty($images)) { - $variationData['image'] = $images[0]; - } - } - if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { - $variationData['sku'] = $object->ref; - } - if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { - $variationData['description'] = dol_textishtml($object->array_options["options_ecommerceng_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]); + if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { + if (!empty($images)) { + $variationData['image'] = $images[0]; + } + } + if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { + $variationData['sku'] = $object->ref; + } + if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { + $variationData['description'] = dol_textishtml($object->array_options["options_ecommerceng_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]); if (empty($variationData['description']) || $initial_data) { $variationData['description'] = dol_textishtml($object->description) ? $object->description : nl2br($object->description); $object->array_options["options_ecommerceng_description_{$conf->entity}"] = $variationData['description']; } } - if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { - $variationData['weight'] = (string)(!empty($totalWeight) ? $totalWeight : ''); - } + if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { + $variationData['weight'] = (string) (!empty($totalWeight) ? $totalWeight : ''); + } if ($productDimensionSynchDirection == 'dtoe' || $productDimensionSynchDirection == 'all') { $variationData['dimensions'] = array( - 'length' => (string)(!empty($totalLength) ? $totalLength : ''), - 'width' => (string)(!empty($totalWidth) ? $totalWidth : ''), - 'height' => (string)(!empty($totalHeight) ? $totalHeight : ''), + 'length' => (string) (!empty($totalLength) ? $totalLength : ''), + 'width' => (string) (!empty($totalWidth) ? $totalWidth : ''), + 'height' => (string) (!empty($totalHeight) ? $totalHeight : ''), ); } - if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { - $variationData['tax_status'] = 'none'; + if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { + $variationData['tax_status'] = 'none'; - // Set tax - if (!$initial_data && !empty($object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { - $variationData['tax_status'] = 'taxable'; - $variationData['tax_class'] = $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; + // Set tax + if (!$initial_data && !empty($object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { + $variationData['tax_status'] = 'taxable'; + $variationData['tax_class'] = $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; } elseif ($initial_data && $object->tva_tx > 0) { $tax_class = $this->getTaxClassFromVatRate($object->tva_tx); if (!empty($tax_class)) { @@ -3167,11 +3244,11 @@ public function convertObjectIntoProductData($remote_id, $object) $variationData['tax_class'] = $tax_class; $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"] = $tax_class; } else { - $this->errors[] = $langs->trans('ECommerceWoocommerceErrorTaxClassNotFoundFromTaxRate', $object->tva_tx, $this->site->name, $object->ref . ' - ' . $remote_id); + $this->errors[] = $langs->trans('ECommerceWoocommerceErrorTaxClassNotFoundFromTaxRate', $object->tva_tx, $this->site->name, $object->ref . ' - ' . $remote_id); return array(); } } - } + } $stock_data = $this->convertObjectIntoProductStockData($remote_id, $object); if (!isset($stock_data)) { @@ -3246,8 +3323,8 @@ public function convertObjectIntoProductData($remote_id, $object) } // Product - // 'name' => $object->label, // string Product name. - // 'status' => $object->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. + // 'name' => $object->label, // string Product name. + // 'status' => $object->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. foreach ($remote_product_variation_ids as $remote_product_variation_id) { $return_data['variations'][$remote_product_variation_id] = array( @@ -3256,178 +3333,178 @@ public function convertObjectIntoProductData($remote_id, $object) 'data' => $variationData, ); } - } + } // Product - if (!$isProductVariation || $isProductVariationHasOne) { - /* - // Product - Downloads properties - $downloads = [ - [ - 'name' => '', // string File name. - 'file' => '', // string File URL. - ], - ]; - - // Product - Dimensions properties - $dimensions = [ - 'length' => '', // string Product length (cm). - 'width' => '', // string Product width (cm). - 'height' => '', // string Product height (cm). - ]; - - // Product - Categories properties - $categories = [ - [ - 'id' => 0, // integer Category ID. - ], - ]; - - // Product - Tags properties - $tags = [ - [ - 'id' => 0, // integer Tag ID. - ], - ]; - - // Product - Images properties - $images = [ - [ - 'id' => 0, // integer Image ID. Not required - 'src' => '', // string Image URL. - 'name' => '', // string Image name. - 'alt' => '', // string Image alternative text. - 'position' => 0, // integer Image position. 0 means that the image is featured. - ], - ]; - - // Product - Attributes properties - $attributes = [ - [ - 'id' => 0, // integer Attribute ID. Not required - 'name' => '', // string Attribute name. - 'position' => 0, // integer Attribute position. - 'visible' => false, // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is false. - 'variation' => false, // boolean Define if the attribute can be used as variation. Default is false. - 'options' => [], // array List of available term names of the attribute. - ], - ]; - - // Product - Default attributes properties - $default_attributes = [ - 'id' => 0, // integer Attribute ID. Not required - 'name' => '', // string Attribute name. - 'option' => '', // string Selected attribute term name. - ]; - - // Product - Meta data properties - $meta_data = [ - 'key' => '', // string Meta key. - 'value' => '', // string Meta value. - ]; - */ - - // Get categories - $eCommerceCategory = new eCommerceCategory($this->db); - $cat = new Categorie($this->db); - $categories_list = $cat->containing($object->id, 'product'); - $categories = []; - foreach ($categories_list as $category) { - if ($this->site->fk_cat_product != $category->id) { - $ret = $eCommerceCategory->fetchByFKCategory($category->id, $this->site->id); - if ($ret > 0) { - $categories[] = ['id' => $eCommerceCategory->remote_id]; - } - } - } - - $status = $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; - - $productData = [ - 'name' => $object->label, // string Product name. - //'slug' => '', // string Product slug. - //'type' => '', // string Product type. Options: simple, grouped, external and variable. Default is simple. - //'status' => (!empty($status) ? $status : ''), //$object->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. - //'featured' => false, // boolean Featured product. Default is false. - //'catalog_visibility' => '', // string Catalog visibility. Options: visible, catalog, search and hidden. Default is visible. - //'description' => nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]), // string Product description. - //'short_description' => nl2br($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]), // string Product short description. - //'sku' => $object->ref, // string Unique identifier. - //'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Product regular price. - //'sale_price' => $sale_price, // string Product sale price. - //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. - 'date_on_sale_from_gmt' => $date_on_sale_from, // date-time Start date of sale price, as GMT. - //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. - 'date_on_sale_to_gmt' => $date_on_sale_to, // date-time End date of sale price, in the site’s timezone. - 'virtual' => $object->type == Product::TYPE_SERVICE, // boolean If the product is virtual. Default is false. - //'downloadable' => false, // boolean If the product is downloadable. Default is false. - //'downloads' => $downloads, // array List of downloadable files. See Product - Downloads properties - //'download_limit' => -1, // integer Number of times downloadable files can be downloaded after purchase. Default is -1. - //'download_expiry' => -1, // integer Number of days until access to downloadable files expires. Default is -1. - //'external_url' => '', // string Product external URL. Only for external products. - //'button_text' => '', // string Product external button text. Only for external products. - //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. - //'tax_class' => '', // string Tax class. - //'manage_stock' => $initial_data || !empty($object->array_options["options_ecommerceng_wc_manage_stock_{$this->site->id}_{$conf->entity}"]), // boolean Stock management at product level. Default is false. - //'stock_quantity' => $object->stock_reel, // integer Stock quantity. - //'in_stock' => $object->stock_reel > 0, // boolean Controls whether or not the product is listed as “in stock” or “out of stock” on the frontend. Default is true. - //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. - //'sold_individually' => false, // boolean Allow one item to be bought in a single order. Default is false. - //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Product weight (kg). - //'dimensions' => $dimensions, // object Product dimensions. See Product - Dimensions properties - //'shipping_class' => '', // string Shipping class slug. - //'reviews_allowed' => true, // boolean Allow reviews. Default is true. - //'upsell_ids' => [], // array List of up-sell products IDs. - //'cross_sell_ids' => [], // array List of cross-sell products IDs. - //'parent_id' => 0, // integer Product parent ID. - //'purchase_note' => '', // string Optional note to send the customer after purchase. - 'categories' => $categories, // array List of categories. See Product - Categories properties - //'tags' => $tags, // array List of tags. See Product - Tags properties - //'images' => (!empty($images) ? $images : array()), // object List of images. See Product - Images properties - //'attributes' => $attributes, // array List of attributes. See Product - Attributes properties - //'default_attributes' => $default_attributes, // array Defaults variation attributes. See Product - Default attributes properties - //'menu_order' => 0, // integer Menu order, used to custom sort products. - //'meta_data' => $meta_data, // array Meta data. See Product - Meta data properties - ]; + if (!$isProductVariation || $isProductVariationHasOne) { + /* + // Product - Downloads properties + $downloads = [ + [ + 'name' => '', // string File name. + 'file' => '', // string File URL. + ], + ]; + + // Product - Dimensions properties + $dimensions = [ + 'length' => '', // string Product length (cm). + 'width' => '', // string Product width (cm). + 'height' => '', // string Product height (cm). + ]; + + // Product - Categories properties + $categories = [ + [ + 'id' => 0, // integer Category ID. + ], + ]; + + // Product - Tags properties + $tags = [ + [ + 'id' => 0, // integer Tag ID. + ], + ]; + + // Product - Images properties + $images = [ + [ + 'id' => 0, // integer Image ID. Not required + 'src' => '', // string Image URL. + 'name' => '', // string Image name. + 'alt' => '', // string Image alternative text. + 'position' => 0, // integer Image position. 0 means that the image is featured. + ], + ]; + + // Product - Attributes properties + $attributes = [ + [ + 'id' => 0, // integer Attribute ID. Not required + 'name' => '', // string Attribute name. + 'position' => 0, // integer Attribute position. + 'visible' => false, // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is false. + 'variation' => false, // boolean Define if the attribute can be used as variation. Default is false. + 'options' => [], // array List of available term names of the attribute. + ], + ]; + + // Product - Default attributes properties + $default_attributes = [ + 'id' => 0, // integer Attribute ID. Not required + 'name' => '', // string Attribute name. + 'option' => '', // string Selected attribute term name. + ]; + + // Product - Meta data properties + $meta_data = [ + 'key' => '', // string Meta key. + 'value' => '', // string Meta value. + ]; + */ + + // Get categories + $eCommerceCategory = new eCommerceCategory($this->db); + $cat = new Categorie($this->db); + $categories_list = $cat->containing($object->id, 'product'); + $categories = []; + foreach ($categories_list as $category) { + if ($this->site->fk_cat_product != $category->id) { + $ret = $eCommerceCategory->fetchByFKCategory($category->id, $this->site->id); + if ($ret > 0) { + $categories[] = ['id' => $eCommerceCategory->remote_id]; + } + } + } + + $status = $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; + + $productData = [ + 'name' => $object->label, // string Product name. + //'slug' => '', // string Product slug. + //'type' => '', // string Product type. Options: simple, grouped, external and variable. Default is simple. + //'status' => (!empty($status) ? $status : ''), //$object->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. + //'featured' => false, // boolean Featured product. Default is false. + //'catalog_visibility' => '', // string Catalog visibility. Options: visible, catalog, search and hidden. Default is visible. + //'description' => nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]), // string Product description. + //'short_description' => nl2br($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]), // string Product short description. + //'sku' => $object->ref, // string Unique identifier. + //'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Product regular price. + //'sale_price' => $sale_price, // string Product sale price. + //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. + 'date_on_sale_from_gmt' => $date_on_sale_from, // date-time Start date of sale price, as GMT. + //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. + 'date_on_sale_to_gmt' => $date_on_sale_to, // date-time End date of sale price, in the site’s timezone. + 'virtual' => $object->type == Product::TYPE_SERVICE, // boolean If the product is virtual. Default is false. + //'downloadable' => false, // boolean If the product is downloadable. Default is false. + //'downloads' => $downloads, // array List of downloadable files. See Product - Downloads properties + //'download_limit' => -1, // integer Number of times downloadable files can be downloaded after purchase. Default is -1. + //'download_expiry' => -1, // integer Number of days until access to downloadable files expires. Default is -1. + //'external_url' => '', // string Product external URL. Only for external products. + //'button_text' => '', // string Product external button text. Only for external products. + //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. + //'tax_class' => '', // string Tax class. + //'manage_stock' => $initial_data || !empty($object->array_options["options_ecommerceng_wc_manage_stock_{$this->site->id}_{$conf->entity}"]), // boolean Stock management at product level. Default is false. + //'stock_quantity' => $object->stock_reel, // integer Stock quantity. + //'in_stock' => $object->stock_reel > 0, // boolean Controls whether or not the product is listed as “in stock” or “out of stock” on the frontend. Default is true. + //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. + //'sold_individually' => false, // boolean Allow one item to be bought in a single order. Default is false. + //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Product weight (kg). + //'dimensions' => $dimensions, // object Product dimensions. See Product - Dimensions properties + //'shipping_class' => '', // string Shipping class slug. + //'reviews_allowed' => true, // boolean Allow reviews. Default is true. + //'upsell_ids' => [], // array List of up-sell products IDs. + //'cross_sell_ids' => [], // array List of cross-sell products IDs. + //'parent_id' => 0, // integer Product parent ID. + //'purchase_note' => '', // string Optional note to send the customer after purchase. + 'categories' => $categories, // array List of categories. See Product - Categories properties + //'tags' => $tags, // array List of tags. See Product - Tags properties + //'images' => (!empty($images) ? $images : array()), // object List of images. See Product - Images properties + //'attributes' => $attributes, // array List of attributes. See Product - Attributes properties + //'default_attributes' => $default_attributes, // array Defaults variation attributes. See Product - Default attributes properties + //'menu_order' => 0, // integer Menu order, used to custom sort products. + //'meta_data' => $meta_data, // array Meta data. See Product - Meta data properties + ]; if (is_array($object->context['ec_price_entities']) && in_array($this->site->entity, $object->context['ec_price_entities'])) { $productData['regular_price'] = $productSynchPrice == 'regular' || $initial_data ? $price : $regular_price; $productData['sale_price'] = $sale_price; $object->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"] = $productData['regular_price']; } - if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { - $productData['images'] = (!empty($images) ? $images : array()); - } - if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { - $productData['sku'] = $object->ref; - } - if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { - $productData['description'] = dol_textishtml($object->array_options["options_ecommerceng_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]); + if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { + $productData['images'] = (!empty($images) ? $images : array()); + } + if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { + $productData['sku'] = $object->ref; + } + if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { + $productData['description'] = dol_textishtml($object->array_options["options_ecommerceng_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_description_{$conf->entity}"]); if (empty($productData['description']) || $initial_data) { - $productData['description'] = dol_textishtml($object->description) ? $object->description : nl2br($object->description); + $productData['description'] = dol_textishtml($object->description) ? $object->description : nl2br($object->description); $object->array_options["options_ecommerceng_description_{$conf->entity}"] = $productData['description']; } - } - if ($productShortDescriptionSynchDirection == 'dtoe' || $productShortDescriptionSynchDirection == 'all') { - $productData['short_description'] = dol_textishtml($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_short_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]); - } - if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { - $productData['weight'] = (string)(!empty($totalWeight) ? $totalWeight : ''); - } + } + if ($productShortDescriptionSynchDirection == 'dtoe' || $productShortDescriptionSynchDirection == 'all') { + $productData['short_description'] = dol_textishtml($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]) ? $object->array_options["options_ecommerceng_short_description_{$conf->entity}"] : nl2br($object->array_options["options_ecommerceng_short_description_{$conf->entity}"]); + } + if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { + $productData['weight'] = (string)(!empty($totalWeight) ? $totalWeight : ''); + } if ($productDimensionSynchDirection == 'dtoe' || $productDimensionSynchDirection == 'all') { $productData['dimensions'] = array( - 'length' => (string)(!empty($totalLength) ? $totalLength : ''), - 'width' => (string)(!empty($totalWidth) ? $totalWidth : ''), - 'height' => (string)(!empty($totalHeight) ? $totalHeight : ''), + 'length' => (string)(!empty($totalLength) ? $totalLength : ''), + 'width' => (string)(!empty($totalWidth) ? $totalWidth : ''), + 'height' => (string)(!empty($totalHeight) ? $totalHeight : ''), ); } - if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { - $productData['tax_status'] = 'none'; + if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { + $productData['tax_status'] = 'none'; - // Set tax - if (!$initial_data && !empty($object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { - $productData['tax_status'] = 'taxable'; - $productData['tax_class'] = $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; + // Set tax + if (!$initial_data && !empty($object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { + $productData['tax_status'] = 'taxable'; + $productData['tax_class'] = $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; } elseif ($initial_data && $object->tva_tx > 0) { $tax_class = $this->getTaxClassFromVatRate($object->tva_tx); if (!empty($tax_class)) { @@ -3435,13 +3512,13 @@ public function convertObjectIntoProductData($remote_id, $object) $productData['tax_class'] = $tax_class; $object->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"] = $tax_class; } else { - $this->errors[] = $langs->trans('ECommerceWoocommerceErrorTaxClassNotFoundFromTaxRate', $object->tva_tx, $this->site->name, $object->ref . ' - ' . $remote_id); + $this->errors[] = $langs->trans('ECommerceWoocommerceErrorTaxClassNotFoundFromTaxRate', $object->tva_tx, $this->site->name, $object->ref . ' - ' . $remote_id); return array(); } } - } - if ($productStatusSynchDirection == 'dtoe' || $productStatusSynchDirection == 'all') { - $productData['status'] = (!empty($status) ? $status : ($object->status ? 'publish' : 'draft')); + } + if ($productStatusSynchDirection == 'dtoe' || $productStatusSynchDirection == 'all') { + $productData['status'] = (!empty($status) ? $status : ($object->status ? 'publish' : 'draft')); $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"] = $productData['status']; } @@ -3452,17 +3529,17 @@ public function convertObjectIntoProductData($remote_id, $object) $productData = array_merge($productData, $stock_data); } - // Synch extrafields <=> metadatas and attributes - if (!empty($object->array_options)) { + // Synch extrafields <=> metadatas and attributes + if (!empty($object->array_options)) { foreach ($object->array_options as $key => $value) { - $cr_key = substr($key, 8); - if (preg_match('/^ecommerceng_/', $cr_key)) continue; + $cr_key = substr($key, 8); + if (preg_match('/^ecommerceng_/', $cr_key)) continue; // Synch extrafields <=> metadatas if (!empty($this->site->parameters['extra_fields']['product']['activated']['mdt'][$cr_key])) { $data_key = $this->site->parameters['extra_fields']['product']['values']['mdt'][$cr_key]; if (!empty($data_key)) { - $productData['meta_data'][] = array('key' => $data_key, 'value' => (string) $value); + $productData['meta_data'][] = array('key' => $data_key, 'value' => (string)$value); } } @@ -3474,17 +3551,17 @@ public function convertObjectIntoProductData($remote_id, $object) $productData['attributes'][] = array('id' => $data_key, 'visible' => $show_attr != 2, 'options' => !empty($value) ? explode(',', $value) : array()); } } - } - } + } + } - $return_data['product'] = array( + $return_data['product'] = array( 'remote_id' => $remote_product_id, 'data' => $productData, ); - } + } - return $return_data; - } + return $return_data; + } /** * Convert Object to remote product stock data @@ -3705,19 +3782,19 @@ public function updateRemoteProduct($remote_id, $object) return true; } - /** - * Update the remote stock of product - * - * @param int $remote_id Id of product on remote ecommerce + /** + * Update the remote stock of product + * + * @param int $remote_id Id of product on remote ecommerce * @param Product $product Product object * @param eCommerceProduct $eCommerceProduct Product link * - * @return boolean True or false - */ - public function updateRemoteStockProduct($remote_id, $product, &$eCommerceProduct) - { - dol_syslog(__METHOD__ . ": Update stock of the remote product ID $remote_id for product ID {$product->id} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs, $user; + * @return boolean True or false + */ + public function updateRemoteStockProduct($remote_id, $product, &$eCommerceProduct) + { + dol_syslog(__METHOD__ . ": Update stock of the remote product ID $remote_id for product ID {$product->id} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs, $user; $this->errors = array(); @@ -3883,7 +3960,7 @@ public function updateRemoteStockProduct($remote_id, $product, &$eCommerceProduc } if (isset($result['translations'])) { - foreach ((array)$result['translations'] as $product_id) { + foreach ((array) $result['translations'] as $product_id) { $result2 = $this->client->sendToApi(eCommerceClientApi::METHOD_GET, "products/{$product_id}"); if (!isset($result2)) { $this->errors[] = $langs->trans('ECommerceWoocommerceGetTranslatedProductVariation', $product_id, $remote_product_variation_id, $remote_product_id, $this->site->name); @@ -3913,7 +3990,7 @@ public function updateRemoteStockProduct($remote_id, $product, &$eCommerceProduc } if (isset($result['translations'])) { - foreach ((array)$result['translations'] as $product_id) { + foreach ((array) $result['translations'] as $product_id) { $res = $this->client->sendToApi(eCommerceClientApi::METHOD_PUT, "products/{$product_id}", [GuzzleHttp\RequestOptions::FORM_PARAMS => $stock_data]); if (!isset($res)) { $this->errors[] = $langs->trans('ECommerceWoocommerceUpdateRemoteStockTranslatedProduct', $stock_data['stock_quantity'], $product_id, $remote_id, $this->site->name); @@ -3926,22 +4003,22 @@ public function updateRemoteStockProduct($remote_id, $product, &$eCommerceProduc } } - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return true; - } + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return true; + } - /** - * Update the remote company - * - * @param int $remote_id Id of company on remote ecommerce - * @param Societe $object Societe object - * - * @return boolean True or false - */ - public function updateRemoteSociete($remote_id, $object) - { - dol_syslog(__METHOD__ . ": Update the remote company ID $remote_id for Dolibarr company ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); - global $langs, $user; + /** + * Update the remote company + * + * @param int $remote_id Id of company on remote ecommerce + * @param Societe $object Societe object + * + * @return boolean True or false + */ + public function updateRemoteSociete($remote_id, $object) + { + dol_syslog(__METHOD__ . ": Update the remote company ID $remote_id for Dolibarr company ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); + global $langs, $user; $this->errors = array(); /* @@ -3951,14 +4028,14 @@ public function updateRemoteSociete($remote_id, $object) 'value' => '', // string Meta value. ]; */ - $companyData = [ - //'email' => $object->email, // string The email address for the customer. MANDATORY - //'first_name' => '', // string Customer first name. - //'last_name' => $object->name, // string Customer last name. - //'username' => '', // string Customer login name. - //'password' => '', // string Customer password. - //'meta_data' => $meta_data, // array Meta data. See Customer - Meta data properties - ]; + $companyData = [ + //'email' => $object->email, // string The email address for the customer. MANDATORY + //'first_name' => '', // string Customer first name. + //'last_name' => $object->name, // string Customer last name. + //'username' => '', // string Customer login name. + //'password' => '', // string Customer password. + //'meta_data' => $meta_data, // array Meta data. See Customer - Meta data properties + ]; // Synch extrafields <=> metadatas and attributes if (!empty($object->array_options)) { @@ -3984,70 +4061,70 @@ public function updateRemoteSociete($remote_id, $object) return false; } - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return true; - } + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return true; + } - /** - * Update the remote contact - * - * @param int $remote_id Id of contact on remote ecommerce - * @param Contact $object Contact object - * - * @return boolean True or false - */ - public function updateRemoteSocpeople($remote_id, $object) - { - dol_syslog(__METHOD__ . ": Update the remote contact ID $remote_id for Dolibarr contact ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs, $user; + /** + * Update the remote contact + * + * @param int $remote_id Id of contact on remote ecommerce + * @param Contact $object Contact object + * + * @return boolean True or false + */ + public function updateRemoteSocpeople($remote_id, $object) + { + dol_syslog(__METHOD__ . ": Update the remote contact ID $remote_id for Dolibarr contact ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs, $user; $this->errors = array(); // Get societe - //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - //$societe = new Societe($this->db); - //$societe->fetch($object->socid); - - $billingName = (empty($conf->global->ECOMMERCENG_BILLING_CONTACT_NAME) ? 'Billing' : $conf->global->ECOMMERCENG_BILLING_CONTACT_NAME); // Contact name treated as billing address. - $shippingName = (empty($conf->global->ECOMMERCENG_SHIPPING_CONTACT_NAME) ? 'Shipping' : $conf->global->ECOMMERCENG_SHIPPING_CONTACT_NAME); // Contact name treated as shipping address. - - if ($object->lastname == $billingName) { - $address = explode("\n", $object->address); - // Billing - $contactData = [ - 'billing' => [ - //'first_name' => '', // string First name. - //'last_name' => '', // string Last name. - //'company' => $societe->name, // string Company name. - 'address_1' => isset($address[0]) ? $address[0] : '', // string Address line 1 - 'address_2' => isset($address[1]) ? implode(" ", array_slice($address, 1)) : '', // string Address line 2 - 'city' => $object->town, // string City name. - //'state' => '', // string ISO code or name of the state, province or district. - 'postcode' => $object->zip, // string Postal code. - 'country' => getCountry($object->country_id, 2), // string ISO code of the country. - 'email' => $object->email, // string Email address. - 'phone' => $object->phone_pro, // string Phone number. - ], - ]; - } elseif ($object->lastname == $shippingName) { - $address = explode("\n", $object->address); - // Shipping - $contactData = [ - 'shipping' => [ - //'first_name' => '', // string First name. - //'last_name' => '', // string Last name. - //'company' => $societe->name, // string Company name. - 'address_1' => isset($address[0]) ? $address[0] : '', // string Address line 1 - 'address_2' => isset($address[1]) ? implode(" ", array_slice($address, 1)) : '', // string Address line 2 - 'city' => $object->town, // string City name. - //'state' => '', // string ISO code or name of the state, province or district. - 'postcode' => $object->zip, // string Postal code. - 'country' => getCountry($object->country_id, 2), // string ISO code of the country. - ], - ]; - } - - if (isset($contactData)) { - if (preg_match('/^(\d+)\|(\d+)$/', $remote_id, $idsCustomer)) { + //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; + //$societe = new Societe($this->db); + //$societe->fetch($object->socid); + + $billingName = (empty($conf->global->ECOMMERCENG_BILLING_CONTACT_NAME) ? 'Billing' : $conf->global->ECOMMERCENG_BILLING_CONTACT_NAME); // Contact name treated as billing address. + $shippingName = (empty($conf->global->ECOMMERCENG_SHIPPING_CONTACT_NAME) ? 'Shipping' : $conf->global->ECOMMERCENG_SHIPPING_CONTACT_NAME); // Contact name treated as shipping address. + + if ($object->lastname == $billingName) { + $address = explode("\n", $object->address); + // Billing + $contactData = [ + 'billing' => [ + //'first_name' => '', // string First name. + //'last_name' => '', // string Last name. + //'company' => $societe->name, // string Company name. + 'address_1' => isset($address[0]) ? $address[0] : '', // string Address line 1 + 'address_2' => isset($address[1]) ? implode(" ", array_slice($address, 1)) : '', // string Address line 2 + 'city' => $object->town, // string City name. + //'state' => '', // string ISO code or name of the state, province or district. + 'postcode' => $object->zip, // string Postal code. + 'country' => getCountry($object->country_id, 2), // string ISO code of the country. + 'email' => $object->email, // string Email address. + 'phone' => $object->phone_pro, // string Phone number. + ], + ]; + } elseif ($object->lastname == $shippingName) { + $address = explode("\n", $object->address); + // Shipping + $contactData = [ + 'shipping' => [ + //'first_name' => '', // string First name. + //'last_name' => '', // string Last name. + //'company' => $societe->name, // string Company name. + 'address_1' => isset($address[0]) ? $address[0] : '', // string Address line 1 + 'address_2' => isset($address[1]) ? implode(" ", array_slice($address, 1)) : '', // string Address line 2 + 'city' => $object->town, // string City name. + //'state' => '', // string ISO code or name of the state, province or district. + 'postcode' => $object->zip, // string Postal code. + 'country' => getCountry($object->country_id, 2), // string ISO code of the country. + ], + ]; + } + + if (isset($contactData)) { + if (preg_match('/^(\d+)\|(\d+)$/', $remote_id, $idsCustomer)) { $result = $this->client->sendToApi(eCommerceClientApi::METHOD_PUT, "customers/{$idsCustomer[1]}", [GuzzleHttp\RequestOptions::FORM_PARAMS => $contactData]); if (!isset($result)) { $this->errors[] = $langs->trans('ECommerceWoocommerceUpdateRemoteSocpeople', $idsCustomer[1], $this->site->name); @@ -4055,67 +4132,67 @@ public function updateRemoteSocpeople($remote_id, $object) dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); return false; } - } - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return true; - } - - /** - * Update the remote order - * - * @param int $remote_id Id of order on remote ecommerce - * @param Commande $object Commande object - * - * @return boolean True or false - */ - public function updateRemoteCommande($remote_id, $object) - { - dol_syslog(__METHOD__ . ": Update the remote order ID $remote_id for Dolibarr order ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs, $user; + } + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return true; + } + + /** + * Update the remote order + * + * @param int $remote_id Id of order on remote ecommerce + * @param Commande $object Commande object + * + * @return boolean True or false + */ + public function updateRemoteCommande($remote_id, $object) + { + dol_syslog(__METHOD__ . ": Update the remote order ID $remote_id for Dolibarr order ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs, $user; $this->errors = array(); $status = ''; - if (isset($this->site->parameters['order_status_dtoe'][$object->statut])) - $status = $this->site->parameters['order_status_dtoe'][$object->statut]; + if (isset($this->site->parameters['order_status_dtoe'][$object->statut])) + $status = $this->site->parameters['order_status_dtoe'][$object->statut]; - if (!empty($status)) { - $object->fetch_optionals(); + if (!empty($status)) { + $object->fetch_optionals(); - require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; - $efields = new ExtraFields($this->db); - $efields->fetch_name_optionals_label('commande', true); + require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + $efields = new ExtraFields($this->db); + $efields->fetch_name_optionals_label('commande', true); if (version_compare(DOL_VERSION, "13.0.0") >= 0) { $options_list = isset($efields->attributes['commande']['param']["ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]['options']) ? $efields->attributes['commande']['param']["ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]['options'] : null; } else { $options_list = isset($efields->attribute_param["ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]['options']) ? $efields->attribute_param["ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]['options'] : null; } - $order_status = array(); - if (is_array($options_list)) { - foreach ($options_list as $key => $value) { - $status_lvl = 0; - if (($pos = strpos($key , '_')) > 0) { - $status_key = substr($key, $pos + 1); - $status_lvl = substr($key, 0, $pos); - } - $order_status[$status_key] = $status_lvl; - } - } - - $wc_status = $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; - if ($order_status[$status] < $order_status[$wc_status] && - !empty($this->site->parameters['order_status_dtoe_check_lvl_status'])) $status = $wc_status; - - $orderData = [ - 'status' => $status, // string Order status. Options: pending, processing, on-hold, completed, cancelled, refunded and failed. - ]; - - // Synch extrafields <=> metadatas - if (!empty($object->array_options)) { - foreach ($object->array_options as $key => $value) { - $cr_key = substr($key, 8); - if (preg_match('/^ecommerceng_/', $cr_key)) continue; + $order_status = array(); + if (is_array($options_list)) { + foreach ($options_list as $key => $value) { + $status_lvl = 0; + if (($pos = strpos($key, '_')) > 0) { + $status_key = substr($key, $pos + 1); + $status_lvl = substr($key, 0, $pos); + } + $order_status[$status_key] = $status_lvl; + } + } + + $wc_status = $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; + if ($order_status[$status] < $order_status[$wc_status] && + !empty($this->site->parameters['order_status_dtoe_check_lvl_status'])) $status = $wc_status; + + $orderData = [ + 'status' => $status, // string Order status. Options: pending, processing, on-hold, completed, cancelled, refunded and failed. + ]; + + // Synch extrafields <=> metadatas + if (!empty($object->array_options)) { + foreach ($object->array_options as $key => $value) { + $cr_key = substr($key, 8); + if (preg_match('/^ecommerceng_/', $cr_key)) continue; if (!empty($this->site->parameters['extra_fields']['commande']['activated']['dft'][$cr_key])) { $data_key = $this->site->parameters['extra_fields']['commande']['values']['dft'][$cr_key]; @@ -4129,8 +4206,8 @@ public function updateRemoteCommande($remote_id, $object) $variationData['meta_data'][] = array('key' => $data_key, 'value' => $value); } } - } - } + } + } $result = $this->client->sendToApi(eCommerceClientApi::METHOD_PUT, "orders/{$remote_id}", [GuzzleHttp\RequestOptions::FORM_PARAMS => $orderData]); if (!isset($result)) { @@ -4140,55 +4217,55 @@ public function updateRemoteCommande($remote_id, $object) return false; } - $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"] = $order_status[$status] . '_' . $status; - $object->insertExtraFields(); - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return true; - } - - /** - * Desactivated because is not supported by woocommerce. - * - * @param int $remote_id Id of invoice on remote ecommerce - * @param Facture $object Invoice object - * - * @return boolean True or false - */ - public function updateRemoteFacture($remote_id, $object) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + $object->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"] = $order_status[$status] . '_' . $status; + $object->insertExtraFields(); + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return true; + } + + /** + * Desactivated because is not supported by woocommerce. + * + * @param int $remote_id Id of invoice on remote ecommerce + * @param Facture $object Invoice object + * + * @return boolean True or false + */ + public function updateRemoteFacture($remote_id, $object) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); return true; - } - - /** - * Desactivated because is not supported by woocommerce. - * - * @param int $livraison Object shipment ? - * @param int $remote_order_id Id of remote order - * - * @return boolean True or false - */ - public function createRemoteLivraison($livraison, $remote_order_id) - { - dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); + } + + /** + * Desactivated because is not supported by woocommerce. + * + * @param int $livraison Object shipment ? + * @param int $remote_order_id Id of remote order + * + * @return boolean True or false + */ + public function createRemoteLivraison($livraison, $remote_order_id) + { + dol_syslog(__METHOD__ . ": Desactivated for site ID {$this->site->id}", LOG_DEBUG); $this->errors = array(); return true; - } - - /** - * Create product - * - * @param Product $object Object product - * - * @return boolean|array False or data (Id, url, ...) of remote product created - */ - public function createRemoteProduct($object) - { - dol_syslog(__METHOD__ . ": Create product from Dolibarr product ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs, $user; + } + + /** + * Create product + * + * @param Product $object Object product + * + * @return boolean|array False or data (Id, url, ...) of remote product created + */ + public function createRemoteProduct($object) + { + dol_syslog(__METHOD__ . ": Create product from Dolibarr product ID {$object->id} for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs, $user; $this->errors = array(); $filters = ['sku' => $object->ref]; @@ -4244,76 +4321,76 @@ public function createRemoteProduct($object) /** * Create batch categories - * - * @param array $batch Array of object category - * - * @return bool|array Array of association id <=> remote id - */ - public function createRemoteCategories($batch) - { - $ids = implode(', ', array_keys($batch)); - dol_syslog(__METHOD__ . ": Create batch categories from Dolibarr categories IDs: '{$ids}' for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; - - $this->errors = array(); - - // Set datas to create - $cats_by_level = array(); - $cats_slug_id = array(); - foreach ($batch as $cat_id => $category) { - if ($category['level'] == 1) continue; - - $slug = 'cat_'.$cat_id; - - $categoryData = [ - 'name' => $category['label'], // string Category name. - 'slug' => $slug, // string An alphanumeric identifier for the resource unique to its type. - 'parent' => $category['level'] > 2 ? $category['fk_parent'] : null, // integer The ID for the parent of the resource. - 'description' => $category['description'], // string HTML description of the resource. - //'display' => '', // string Category archive display type. Options: default, products, subcategories and both. Default is default. - //'images' => $images, // object Image data. See Product category - Image properties - //'menu_order' => 0, // integer Menu order, used to custom sort the resource. - ]; - - $cats_slug_id[$slug] = $cat_id; - $cats_by_level[$category['level']][] = $categoryData; - } - ksort($cats_by_level); - - // Create categories on Woocommerce - $countCreated = 0; - $cats_id_remote_id = array(); - $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_BATCH) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_BATCH, 100); - foreach ($cats_by_level as $lvl => $group) { - foreach ($group as $key => $categoryData) { - if (isset($cats_id_remote_id[$categoryData['parent']])) { - $group[$key]['parent'] = $cats_id_remote_id[$categoryData['parent']]['remote_id']; - } elseif ($categoryData['parent'] > 0) { - $sql="SELECT remote_id FROM ".MAIN_DB_PREFIX."ecommerce_category WHERE fk_category =".$categoryData['parent']; - $resql=$this->db->query($sql); - if ($resql) { - if ($this->db->num_rows($resql)==1) { - $obj = $this->db->fetch_object($resql); - $group[$key]['parent'] = $obj->remote_id; - } else { - - $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotFound', $this->site->name, $categoryData['name'], $categoryData['slug']); - dol_syslog(__METHOD__ . - ': Error:' . $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotFound', $this->site->name, $categoryData['name'], $categoryData['slug']), LOG_ERR); - return false; - } - } else { - - $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotCreated', $this->site->name, $categoryData['name'], $categoryData['slug']); - dol_syslog(__METHOD__ . - ': Error:' . $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotCreated', $this->site->name, $categoryData['name'], $categoryData['slug']), LOG_ERR); - return false; - } - } - } - - $requestGroups = $this->getRequestGroups($group, $nb_max_by_request); - foreach ($requestGroups as $request) { + * + * @param array $batch Array of object category + * + * @return bool|array Array of association id <=> remote id + */ + public function createRemoteCategories($batch) + { + $ids = implode(', ', array_keys($batch)); + dol_syslog(__METHOD__ . ": Create batch categories from Dolibarr categories IDs: '{$ids}' for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; + + $this->errors = array(); + + // Set datas to create + $cats_by_level = array(); + $cats_slug_id = array(); + foreach ($batch as $cat_id => $category) { + if ($category['level'] == 1) continue; + + $slug = 'cat_' . $cat_id; + + $categoryData = [ + 'name' => $category['label'], // string Category name. + 'slug' => $slug, // string An alphanumeric identifier for the resource unique to its type. + 'parent' => $category['level'] > 2 ? $category['fk_parent'] : null, // integer The ID for the parent of the resource. + 'description' => $category['description'], // string HTML description of the resource. + //'display' => '', // string Category archive display type. Options: default, products, subcategories and both. Default is default. + //'images' => $images, // object Image data. See Product category - Image properties + //'menu_order' => 0, // integer Menu order, used to custom sort the resource. + ]; + + $cats_slug_id[$slug] = $cat_id; + $cats_by_level[$category['level']][] = $categoryData; + } + ksort($cats_by_level); + + // Create categories on Woocommerce + $countCreated = 0; + $cats_id_remote_id = array(); + $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_BATCH) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_BATCH, 100); + foreach ($cats_by_level as $lvl => $group) { + foreach ($group as $key => $categoryData) { + if (isset($cats_id_remote_id[$categoryData['parent']])) { + $group[$key]['parent'] = $cats_id_remote_id[$categoryData['parent']]['remote_id']; + } elseif ($categoryData['parent'] > 0) { + $sql = "SELECT remote_id FROM " . MAIN_DB_PREFIX . "ecommerce_category WHERE fk_category =" . $categoryData['parent']; + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql) == 1) { + $obj = $this->db->fetch_object($resql); + $group[$key]['parent'] = $obj->remote_id; + } else { + + $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotFound', $this->site->name, $categoryData['name'], $categoryData['slug']); + dol_syslog(__METHOD__ . + ': Error:' . $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotFound', $this->site->name, $categoryData['name'], $categoryData['slug']), LOG_ERR); + return false; + } + } else { + + $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotCreated', $this->site->name, $categoryData['name'], $categoryData['slug']); + dol_syslog(__METHOD__ . + ': Error:' . $langs->trans('ECommerceWoocommerceCreateRemoteCategoryParentNotCreated', $this->site->name, $categoryData['name'], $categoryData['slug']), LOG_ERR); + return false; + } + } + } + + $requestGroups = $this->getRequestGroups($group, $nb_max_by_request); + foreach ($requestGroups as $request) { $results = $this->client->sendToApi(eCommerceClientApi::METHOD_PUT, "products/categories/batch", [GuzzleHttp\RequestOptions::FORM_PARAMS => ['create' => $request]]); if (!isset($results)) { $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteBatchCategories', $this->site->name); @@ -4322,40 +4399,40 @@ public function createRemoteCategories($batch) return false; } - $results = isset($results['create']) ? $results['create'] : array(); - foreach ($results as $key => $item) { - if (isset($item['error'])) { - $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchCategory', $request[$key]['slug'], $this->site->name) . $item['error']['code'] . ': ' . $item['error']['message'] . ' (data : ' . json_encode($item['error']['data']) . ' )'; - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ' - Error: ' . $error_msg, LOG_ERR); - } else { + $results = isset($results['create']) ? $results['create'] : array(); + foreach ($results as $key => $item) { + if (isset($item['error'])) { + $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchCategory', $request[$key]['slug'], $this->site->name) . $item['error']['code'] . ': ' . $item['error']['message'] . ' (data : ' . json_encode($item['error']['data']) . ' )'; + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ' - Error: ' . $error_msg, LOG_ERR); + } else { $cats_id_remote_id[$cats_slug_id[$item['slug']]] = array('remote_id' => $item['id'], 'remote_parent_id' => $item['parent']); - } - } - } - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $cats_id_remote_id; - } - - /** - * Batch update products to ECommerce - * - * @param array $batch Array of id of product - * - * @return array Array of association id <=> remote id - */ - public function batchUpdateRemoteProducts($batch) - { - $ids = implode(', ', $batch); - dol_syslog(__METHOD__ . ": Create batch products from Dolibarr products IDs: '{$ids}' for site ID {$this->site->id}", LOG_DEBUG); - global $conf, $langs; - - return array(); // Todo to remake + } + } + } + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $cats_id_remote_id; + } + + /** + * Batch update products to ECommerce + * + * @param array $batch Array of id of product + * + * @return array Array of association id <=> remote id + */ + public function batchUpdateRemoteProducts($batch) + { + $ids = implode(', ', $batch); + dol_syslog(__METHOD__ . ": Create batch products from Dolibarr products IDs: '{$ids}' for site ID {$this->site->id}", LOG_DEBUG); + global $conf, $langs; + + return array(); // Todo to remake $this->errors = array(); - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; $product_static = new Product($this->db); $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_BATCH) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_BATCH, 100); @@ -4549,79 +4626,79 @@ public function batchUpdateRemoteProducts($batch) $this->errors = array(); $productSynchPrice = isset($this->site->parameters['product_synch_price']) ? $this->site->parameters['product_synch_price'] : 'regular'; - $productImageSynchDirection = isset($this->site->parameters['product_synch_direction']['image']) ? $this->site->parameters['product_synch_direction']['image'] : ''; - $productRefSynchDirection = isset($this->site->parameters['product_synch_direction']['ref']) ? $this->site->parameters['product_synch_direction']['ref'] : ''; - $productDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['description']) ? $this->site->parameters['product_synch_direction']['description'] : ''; - $productShortDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['short_description']) ? $this->site->parameters['product_synch_direction']['short_description'] : ''; - $productWeightSynchDirection = isset($this->site->parameters['product_synch_direction']['weight']) ? $this->site->parameters['product_synch_direction']['weight'] : ''; - $productTaxSynchDirection = isset($this->site->parameters['product_synch_direction']['tax']) ? $this->site->parameters['product_synch_direction']['tax'] : ''; - $productStatusSynchDirection = isset($this->site->parameters['product_synch_direction']['status']) ? $this->site->parameters['product_synch_direction']['status'] : ''; - - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $product_static = new Product($this->db); - - // Set datas to create - $prod_sku_id = array(); - $products = array(); - $variations = array(); - foreach ($batch as $product_id => $batch_infos) { - if ($product_static->fetch($product_id) > 0) { - $sku = $product_static->ref; - - $isProductVariation = false; - if ($batch_infos['type'] == 'update') { - $remote_product_id = $batch_infos['remote_id']; - $remote_product_variation_id = 0; - if (preg_match('/^(\d+)\|(\d+)$/', $batch_infos['remote_id'], $idsProduct) == 1) { // Variations - $isProductVariation = true; - $remote_product_id = $idsProduct[1]; - $remote_product_variation_id = $idsProduct[2]; - } - } + $productImageSynchDirection = isset($this->site->parameters['product_synch_direction']['image']) ? $this->site->parameters['product_synch_direction']['image'] : ''; + $productRefSynchDirection = isset($this->site->parameters['product_synch_direction']['ref']) ? $this->site->parameters['product_synch_direction']['ref'] : ''; + $productDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['description']) ? $this->site->parameters['product_synch_direction']['description'] : ''; + $productShortDescriptionSynchDirection = isset($this->site->parameters['product_synch_direction']['short_description']) ? $this->site->parameters['product_synch_direction']['short_description'] : ''; + $productWeightSynchDirection = isset($this->site->parameters['product_synch_direction']['weight']) ? $this->site->parameters['product_synch_direction']['weight'] : ''; + $productTaxSynchDirection = isset($this->site->parameters['product_synch_direction']['tax']) ? $this->site->parameters['product_synch_direction']['tax'] : ''; + $productStatusSynchDirection = isset($this->site->parameters['product_synch_direction']['status']) ? $this->site->parameters['product_synch_direction']['status'] : ''; + + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + $product_static = new Product($this->db); + + // Set datas to create + $prod_sku_id = array(); + $products = array(); + $variations = array(); + foreach ($batch as $product_id => $batch_infos) { + if ($product_static->fetch($product_id) > 0) { + $sku = $product_static->ref; + + $isProductVariation = false; + if ($batch_infos['type'] == 'update') { + $remote_product_id = $batch_infos['remote_id']; + $remote_product_variation_id = 0; + if (preg_match('/^(\d+)\|(\d+)$/', $batch_infos['remote_id'], $idsProduct) == 1) { // Variations + $isProductVariation = true; + $remote_product_id = $idsProduct[1]; + $remote_product_variation_id = $idsProduct[2]; + } + } // Convert Weight $from_unit = $product_static->weight_units; - $to_unit = isset($this->site->parameters['product_weight_units']) ? $this->site->parameters['product_weight_units'] : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?0:$conf->global->MAIN_WEIGHT_DEFAULT_UNIT); - $totalWeight = weight_convert((double)$product_static->weight, $from_unit, $to_unit); - - // Price - $error_price = 0; - if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - $price_level = !empty($this->site->price_level) ? $this->site->price_level : 1; - if ($this->site->ecommerce_price_type == 'TTC') { - if ($product_static->multiprices_base_type[$price_level] == 'TTC') { - $price = $product_static->multiprices_ttc[$price_level]; - } else { - $error_price++; - } - } else { - if ($product_static->multiprices_base_type[$price_level] == 'TTC') { - $error_price++; - } else { - $price = $product_static->multiprices[$price_level]; - } - } - } else { - if ($this->site->ecommerce_price_type == 'TTC') { - if ($product_static->price_base_type == 'TTC') { - $price = $product_static->price_ttc; - } else { - $error_price++; - } - } else { - if ($product_static->price_base_type == 'TTC') { - $error_price++; - } else { - $price = $product_static->price; - } - } - } - if ($error_price) { - $error_msg = $langs->trans('ECommerceWoocommerceErrorBaseTypeOfProductWithSiteParameter', $product_static->ref, $this->site->ecommerce_price_type, $this->site->name); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_ERR); - continue; - } + $to_unit = isset($this->site->parameters['product_weight_units']) ? $this->site->parameters['product_weight_units'] : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? 0 : $conf->global->MAIN_WEIGHT_DEFAULT_UNIT); + $totalWeight = weight_convert((double) $product_static->weight, $from_unit, $to_unit); + + // Price + $error_price = 0; + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + $price_level = !empty($this->site->price_level) ? $this->site->price_level : 1; + if ($this->site->ecommerce_price_type == 'TTC') { + if ($product_static->multiprices_base_type[$price_level] == 'TTC') { + $price = $product_static->multiprices_ttc[$price_level]; + } else { + $error_price++; + } + } else { + if ($product_static->multiprices_base_type[$price_level] == 'TTC') { + $error_price++; + } else { + $price = $product_static->multiprices[$price_level]; + } + } + } else { + if ($this->site->ecommerce_price_type == 'TTC') { + if ($product_static->price_base_type == 'TTC') { + $price = $product_static->price_ttc; + } else { + $error_price++; + } + } else { + if ($product_static->price_base_type == 'TTC') { + $error_price++; + } else { + $price = $product_static->price; + } + } + } + if ($error_price) { + $error_msg = $langs->trans('ECommerceWoocommerceErrorBaseTypeOfProductWithSiteParameter', $product_static->ref, $this->site->ecommerce_price_type, $this->site->name); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error:' . $error_msg, LOG_ERR); + continue; + } // // images // $images = []; @@ -4723,227 +4800,227 @@ public function batchUpdateRemoteProducts($batch) // } // } - // Product - Meta data properties - $product_static->fetch_optionals(); - - /* - // Product - Downloads properties - $downloads = [ - [ - 'name' => '', // string File name. - 'file' => '', // string File URL. - ], - ]; - - // Product - Dimensions properties - $dimensions = [ - 'length' => '', // string Product length (cm). - 'width' => '', // string Product width (cm). - 'height' => '', // string Product height (cm). - ]; - - // Product - Categories properties - $categories = [ - [ - 'id' => 0, // integer Category ID. - ], - ]; - - // Product - Tags properties - $tags = [ - [ - 'id' => 0, // integer Tag ID. - ], - ]; - - // Product - Images properties - $images = [ - [ - 'id' => 0, // integer Image ID. Not required - 'src' => '', // string Image URL. - 'name' => '', // string Image name. - 'alt' => '', // string Image alternative text. - 'position' => 0, // integer Image position. 0 means that the image is featured. - ], - ]; - - // Product - Attributes properties - $attributes = [ - [ - 'id' => 0, // integer Attribute ID. Not required - 'name' => '', // string Attribute name. - 'position' => 0, // integer Attribute position. - 'visible' => false, // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is false. - 'variation' => false, // boolean Define if the attribute can be used as variation. Default is false. - 'options' => [], // array List of available term names of the attribute. - ], - ]; - - // Product - Default attributes properties - $default_attributes = [ - 'id' => 0, // integer Attribute ID. Not required - 'name' => '', // string Attribute name. - 'option' => '', // string Selected attribute term name. - ]; - - // Product - Meta data properties - $meta_data = [ - 'key' => '', // string Meta key. - 'value' => '', // string Meta value. - ]; - */ - - // Get categories - $eCommerceCategory = new eCommerceCategory($this->db); - $cat = new Categorie($this->db); - $categories_list = $cat->containing($product_static->id, 'product'); - $categories = []; - foreach ($categories_list as $category) { - if ($this->site->fk_cat_product != $category->id) { - $ret = $eCommerceCategory->fetchByFKCategory($category->id, $this->site->id); - if ($ret > 0) { - $categories[] = ['id' => $eCommerceCategory->remote_id]; - } - } - } - - $status = $product_static->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; - $description = $product_static->array_options["options_ecommerceng_description_{$conf->entity}"]; - $regular_price = $product_static->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"]; - $sale_price = $product_static->array_options["options_ecommerceng_wc_sale_price_{$this->site->id}_{$conf->entity}"]; - $date_on_sale_from = $product_static->array_options["options_ecommerceng_wc_date_on_sale_from_{$this->site->id}_{$conf->entity}"]; - $date_on_sale_to = $product_static->array_options["options_ecommerceng_wc_date_on_sale_to_{$this->site->id}_{$conf->entity}"]; - - // Product - $productData = [ - 'name' => $product_static->label, // string Product name. - //'slug' => '', // string Product slug. - //'type' => '', // string Product type. Options: simple, grouped, external and variable. Default is simple. - //'status' => (!empty($status) ? $status : 'publish'), //$product_static->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. - //'featured' => false, // boolean Featured product. Default is false. - //'catalog_visibility' => '', // string Catalog visibility. Options: visible, catalog, search and hidden. Default is visible. - //'description' => (!empty($description) ? $description : $product_static->description), // string Product description. - //'short_description' => $product_static->array_options["options_ecommerceng_short_description_{$conf->entity}"], // string Product short description. - //'sku' => $sku, // string Unique identifier. - 'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Product regular price. - //'sale_price' => $productSynchPrice == 'selling' ? $price : $sale_price, // string Product sale price. - //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. - //'date_on_sale_from_gmt' => '', // date-time Start date of sale price, as GMT. - //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. - //'date_on_sale_to_gmt' => '', // date-time End date of sale price, in the site’s timezone. - //'virtual' => $product_static->type == Product::TYPE_SERVICE, // boolean If the product is virtual. Default is false. - //'downloadable' => false, // boolean If the product is downloadable. Default is false. - //'downloads' => $downloads, // array List of downloadable files. See Product - Downloads properties - //'download_limit' => -1, // integer Number of times downloadable files can be downloaded after purchase. Default is -1. - //'download_expiry' => -1, // integer Number of days until access to downloadable files expires. Default is -1. - //'external_url' => '', // string Product external URL. Only for external products. - //'button_text' => '', // string Product external button text. Only for external products. - //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. - //'tax_class' => '', // string Tax class. - //'manage_stock' => false, // boolean Stock management at product level. Default is false. - //'stock_quantity' => $product_static->stock_reel, // integer Stock quantity. - //'in_stock' => $product_static->stock_reel > 0, // boolean Controls whether or not the product is listed as “in stock” or “out of stock” on the frontend. Default is true. - //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. - //'sold_individually' => false, // boolean Allow one item to be bought in a single order. Default is false. - //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Product weight (kg). - //'dimensions' => $dimensions, // object Product dimensions. See Product - Dimensions properties - //'shipping_class' => '', // string Shipping class slug. - //'reviews_allowed' => true, // boolean Allow reviews. Default is true. - //'upsell_ids' => [], // array List of up-sell products IDs. - //'cross_sell_ids' => [], // array List of cross-sell products IDs. - //'parent_id' => 0, // integer Product parent ID. - //'purchase_note' => '', // string Optional note to send the customer after purchase. - 'categories' => $categories, // array List of categories. See Product - Categories properties - //'tags' => $tags, // array List of tags. See Product - Tags properties - //'images' => $images, // object List of images. See Product - Images properties - //'attributes' => $attributes, // array List of attributes. See Product - Attributes properties - //'default_attributes' => $default_attributes, // array Defaults variation attributes. See Product - Default attributes properties - //'menu_order' => 0, // integer Menu order, used to custom sort products. - //'meta_data' => $meta_data, // array Meta data. See Product - Meta data properties - ]; - - if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { - $productData['images'] = $images; - } - if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { - $productData['sku'] = $sku; - } - if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { - $productData['description'] = (!empty($description) ? $description : $product_static->description); - } - if ($productShortDescriptionSynchDirection == 'dtoe' || $productShortDescriptionSynchDirection == 'all') { - $productData['short_description'] = $product_static->array_options["options_ecommerceng_short_description_{$conf->entity}"]; - } - if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { - $productData['weight'] = (!empty($totalWeight) ? $totalWeight : ''); - } - if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { - $productData['tax_status'] = 'none'; - - // Set tax - if (!empty($product_static->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { - $productData['tax_status'] = 'taxable'; - $productData['tax_class'] = $product_static->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; - } - } - if ($productStatusSynchDirection == 'dtoe' || $productStatusSynchDirection == 'all') { - $productData['status'] = (!empty($status) ? $status : 'publish'); - } - - // Synch extrafields <=> metadatas - if (!empty($product_static->array_options)) { - foreach ($product_static->array_options as $key => $value) { - $cr_key = substr($key, 8); - if (preg_match('/^ecommerceng_/', $cr_key)) continue; - $options_saved = $this->site->parameters['ef_crp']['product'][$cr_key]; - if ($options_saved['activated']) { - $rm_key = $cr_key; - if (isset($options_saved['correspondences'])) $rm_key = $options_saved['correspondences']; - $productData['meta_data'][] = array('key' => $rm_key, 'value' => $value); - } - } - } - - $productData['batch_type'] = $batch_infos['type']; - if ($batch_infos['type'] == 'update') { - $productData['id'] = $remote_product_id; - if ($isProductVariation) { // Variations - $productData['id'] = $remote_product_variation_id; - unset($productData['name']); - if (isset($productData['status'])) unset($productData['status']); - if (isset($productData['short_description'])) unset($productData['short_description']); - unset($productData['categories']); - if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { - if (!empty($images)) { - $productData['image'] = $images[0]; - } - } - } - } - - $prod_sku_id[$sku] = $product_id; - if ($isProductVariation) { - $variations[$remote_product_id][$product_id] = $productData; - } else { - $products[$product_id] = $productData; - } - } - } - - $prods_id_remote_id = array(); - $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_BATCH) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_BATCH, 100); - - // Create products on Woocommerce - $requestGroups = $this->getRequestGroups($products, $nb_max_by_request); - foreach ($requestGroups as $request) { - $batch_datas = array(); - foreach ($request as $product_id => $productData) { - $batch_type = $productData['batch_type']; - unset($productData['batch_type']); - $batch_datas[$batch_type][$product_id] = $productData; - } - - $error = 0; + // Product - Meta data properties + $product_static->fetch_optionals(); + + /* + // Product - Downloads properties + $downloads = [ + [ + 'name' => '', // string File name. + 'file' => '', // string File URL. + ], + ]; + + // Product - Dimensions properties + $dimensions = [ + 'length' => '', // string Product length (cm). + 'width' => '', // string Product width (cm). + 'height' => '', // string Product height (cm). + ]; + + // Product - Categories properties + $categories = [ + [ + 'id' => 0, // integer Category ID. + ], + ]; + + // Product - Tags properties + $tags = [ + [ + 'id' => 0, // integer Tag ID. + ], + ]; + + // Product - Images properties + $images = [ + [ + 'id' => 0, // integer Image ID. Not required + 'src' => '', // string Image URL. + 'name' => '', // string Image name. + 'alt' => '', // string Image alternative text. + 'position' => 0, // integer Image position. 0 means that the image is featured. + ], + ]; + + // Product - Attributes properties + $attributes = [ + [ + 'id' => 0, // integer Attribute ID. Not required + 'name' => '', // string Attribute name. + 'position' => 0, // integer Attribute position. + 'visible' => false, // boolean Define if the attribute is visible on the “Additional information” tab in the product’s page. Default is false. + 'variation' => false, // boolean Define if the attribute can be used as variation. Default is false. + 'options' => [], // array List of available term names of the attribute. + ], + ]; + + // Product - Default attributes properties + $default_attributes = [ + 'id' => 0, // integer Attribute ID. Not required + 'name' => '', // string Attribute name. + 'option' => '', // string Selected attribute term name. + ]; + + // Product - Meta data properties + $meta_data = [ + 'key' => '', // string Meta key. + 'value' => '', // string Meta value. + ]; + */ + + // Get categories + $eCommerceCategory = new eCommerceCategory($this->db); + $cat = new Categorie($this->db); + $categories_list = $cat->containing($product_static->id, 'product'); + $categories = []; + foreach ($categories_list as $category) { + if ($this->site->fk_cat_product != $category->id) { + $ret = $eCommerceCategory->fetchByFKCategory($category->id, $this->site->id); + if ($ret > 0) { + $categories[] = ['id' => $eCommerceCategory->remote_id]; + } + } + } + + $status = $product_static->array_options["options_ecommerceng_wc_status_{$this->site->id}_{$conf->entity}"]; + $description = $product_static->array_options["options_ecommerceng_description_{$conf->entity}"]; + $regular_price = $product_static->array_options["options_ecommerceng_wc_regular_price_{$this->site->id}_{$conf->entity}"]; + $sale_price = $product_static->array_options["options_ecommerceng_wc_sale_price_{$this->site->id}_{$conf->entity}"]; + $date_on_sale_from = $product_static->array_options["options_ecommerceng_wc_date_on_sale_from_{$this->site->id}_{$conf->entity}"]; + $date_on_sale_to = $product_static->array_options["options_ecommerceng_wc_date_on_sale_to_{$this->site->id}_{$conf->entity}"]; + + // Product + $productData = [ + 'name' => $product_static->label, // string Product name. + //'slug' => '', // string Product slug. + //'type' => '', // string Product type. Options: simple, grouped, external and variable. Default is simple. + //'status' => (!empty($status) ? $status : 'publish'), //$product_static->status ? 'publish' : 'pending', // string Product status (post status). Options: draft, pending, private and publish. Default is publish. + //'featured' => false, // boolean Featured product. Default is false. + //'catalog_visibility' => '', // string Catalog visibility. Options: visible, catalog, search and hidden. Default is visible. + //'description' => (!empty($description) ? $description : $product_static->description), // string Product description. + //'short_description' => $product_static->array_options["options_ecommerceng_short_description_{$conf->entity}"], // string Product short description. + //'sku' => $sku, // string Unique identifier. + 'regular_price' => $productSynchPrice == 'regular' ? $price : $regular_price, // string Product regular price. + //'sale_price' => $productSynchPrice == 'selling' ? $price : $sale_price, // string Product sale price. + //'date_on_sale_from' => '', // date-time Start date of sale price, in the site’s timezone. + //'date_on_sale_from_gmt' => '', // date-time Start date of sale price, as GMT. + //'date_on_sale_to' => '', // date-time End date of sale price, in the site’s timezone. + //'date_on_sale_to_gmt' => '', // date-time End date of sale price, in the site’s timezone. + //'virtual' => $product_static->type == Product::TYPE_SERVICE, // boolean If the product is virtual. Default is false. + //'downloadable' => false, // boolean If the product is downloadable. Default is false. + //'downloads' => $downloads, // array List of downloadable files. See Product - Downloads properties + //'download_limit' => -1, // integer Number of times downloadable files can be downloaded after purchase. Default is -1. + //'download_expiry' => -1, // integer Number of days until access to downloadable files expires. Default is -1. + //'external_url' => '', // string Product external URL. Only for external products. + //'button_text' => '', // string Product external button text. Only for external products. + //'tax_status' => 'none', // string Tax status. Options: taxable, shipping and none. Default is taxable. + //'tax_class' => '', // string Tax class. + //'manage_stock' => false, // boolean Stock management at product level. Default is false. + //'stock_quantity' => $product_static->stock_reel, // integer Stock quantity. + //'in_stock' => $product_static->stock_reel > 0, // boolean Controls whether or not the product is listed as “in stock” or “out of stock” on the frontend. Default is true. + //'backorders' => '', // string If managing stock, this controls if backorders are allowed. Options: no, notify and yes. Default is no. + //'sold_individually' => false, // boolean Allow one item to be bought in a single order. Default is false. + //'weight' => (!empty($totalWeight) ? $totalWeight : ''), // string Product weight (kg). + //'dimensions' => $dimensions, // object Product dimensions. See Product - Dimensions properties + //'shipping_class' => '', // string Shipping class slug. + //'reviews_allowed' => true, // boolean Allow reviews. Default is true. + //'upsell_ids' => [], // array List of up-sell products IDs. + //'cross_sell_ids' => [], // array List of cross-sell products IDs. + //'parent_id' => 0, // integer Product parent ID. + //'purchase_note' => '', // string Optional note to send the customer after purchase. + 'categories' => $categories, // array List of categories. See Product - Categories properties + //'tags' => $tags, // array List of tags. See Product - Tags properties + //'images' => $images, // object List of images. See Product - Images properties + //'attributes' => $attributes, // array List of attributes. See Product - Attributes properties + //'default_attributes' => $default_attributes, // array Defaults variation attributes. See Product - Default attributes properties + //'menu_order' => 0, // integer Menu order, used to custom sort products. + //'meta_data' => $meta_data, // array Meta data. See Product - Meta data properties + ]; + + if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { + $productData['images'] = $images; + } + if ($productRefSynchDirection == 'dtoe' || $productRefSynchDirection == 'all') { + $productData['sku'] = $sku; + } + if ($productDescriptionSynchDirection == 'dtoe' || $productDescriptionSynchDirection == 'all') { + $productData['description'] = (!empty($description) ? $description : $product_static->description); + } + if ($productShortDescriptionSynchDirection == 'dtoe' || $productShortDescriptionSynchDirection == 'all') { + $productData['short_description'] = $product_static->array_options["options_ecommerceng_short_description_{$conf->entity}"]; + } + if ($productWeightSynchDirection == 'dtoe' || $productWeightSynchDirection == 'all') { + $productData['weight'] = (!empty($totalWeight) ? $totalWeight : ''); + } + if ($productTaxSynchDirection == 'dtoe' || $productTaxSynchDirection == 'all') { + $productData['tax_status'] = 'none'; + + // Set tax + if (!empty($product_static->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"])) { + $productData['tax_status'] = 'taxable'; + $productData['tax_class'] = $product_static->array_options["options_ecommerceng_tax_class_{$this->site->id}_{$conf->entity}"]; + } + } + if ($productStatusSynchDirection == 'dtoe' || $productStatusSynchDirection == 'all') { + $productData['status'] = (!empty($status) ? $status : 'publish'); + } + + // Synch extrafields <=> metadatas + if (!empty($product_static->array_options)) { + foreach ($product_static->array_options as $key => $value) { + $cr_key = substr($key, 8); + if (preg_match('/^ecommerceng_/', $cr_key)) continue; + $options_saved = $this->site->parameters['ef_crp']['product'][$cr_key]; + if ($options_saved['activated']) { + $rm_key = $cr_key; + if (isset($options_saved['correspondences'])) $rm_key = $options_saved['correspondences']; + $productData['meta_data'][] = array('key' => $rm_key, 'value' => $value); + } + } + } + + $productData['batch_type'] = $batch_infos['type']; + if ($batch_infos['type'] == 'update') { + $productData['id'] = $remote_product_id; + if ($isProductVariation) { // Variations + $productData['id'] = $remote_product_variation_id; + unset($productData['name']); + if (isset($productData['status'])) unset($productData['status']); + if (isset($productData['short_description'])) unset($productData['short_description']); + unset($productData['categories']); + if ($productImageSynchDirection == 'dtoe' || $productImageSynchDirection == 'all') { + if (!empty($images)) { + $productData['image'] = $images[0]; + } + } + } + } + + $prod_sku_id[$sku] = $product_id; + if ($isProductVariation) { + $variations[$remote_product_id][$product_id] = $productData; + } else { + $products[$product_id] = $productData; + } + } + } + + $prods_id_remote_id = array(); + $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_BATCH) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_BATCH, 100); + + // Create products on Woocommerce + $requestGroups = $this->getRequestGroups($products, $nb_max_by_request); + foreach ($requestGroups as $request) { + $batch_datas = array(); + foreach ($request as $product_id => $productData) { + $batch_type = $productData['batch_type']; + unset($productData['batch_type']); + $batch_datas[$batch_type][$product_id] = $productData; + } + + $error = 0; $stopwatch_id = -1; try { @@ -4951,52 +5028,52 @@ public function batchUpdateRemoteProducts($batch) if (!self::$disable_put_post_to_api) $results = $this->client->post("products/batch", $batch_datas); eCommerceUtils::stopAndLogStopwatch($stopwatch_id); dol_syslog(__METHOD__ . " - Send POST to API 'products/batch' : Data: " . json_encode($batch_datas), LOG_NOTICE); - } catch (HttpClientException $fault) { + } catch (HttpClientException $fault) { eCommerceUtils::stopAndLogStopwatch($stopwatch_id); $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()); - dol_syslog(__METHOD__ . - ': Error:' . $langs->transnoentitiesnoconv('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()) . - ' - Request:' . json_encode($fault->getRequest()) . ' - Response:' . json_encode($fault->getResponse()), LOG_ERR); - $error++; - } - - $created = isset($results->create) ? $results->create : array(); - foreach ($created as $key => $item) { - if (isset($item->error)) { - $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProduct', $request[$key]['sku'], $this->site->name,$item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); - } else { - $prods_id_remote_id['create'][$prod_sku_id[$item->sku]] = $item->id; - } - } - $updated = isset($results->update) ? $results->update : array(); - foreach ($updated as $key => $item) { - if (isset($item->error)) { - $error_msg = $langs->trans('ECommerceWoocommerceUpdateRemoteBatchProduct', $request[$key]['sku'], $this->site->name,$item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); - } else { - $prods_id_remote_id['update'][$prod_sku_id[$item->sku]] = $item->id; - } - } - if ($error) { - return $prods_id_remote_id; - } - } - - // Create variations on Woocommerce - foreach ($variations as $remote_product_id => $product_variations) { - $requestGroups = $this->getRequestGroups($product_variations, $nb_max_by_request); - foreach ($requestGroups as $request) { - $batch_datas = array(); - foreach ($request as $product_id => $variationData) { - $batch_type = $variationData['batch_type']; - unset($variationData['batch_type']); - $batch_datas[$batch_type][$product_id] = $variationData; - } - - $error = 0; + dol_syslog(__METHOD__ . + ': Error:' . $langs->transnoentitiesnoconv('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()) . + ' - Request:' . json_encode($fault->getRequest()) . ' - Response:' . json_encode($fault->getResponse()), LOG_ERR); + $error++; + } + + $created = isset($results->create) ? $results->create : array(); + foreach ($created as $key => $item) { + if (isset($item->error)) { + $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); + } else { + $prods_id_remote_id['create'][$prod_sku_id[$item->sku]] = $item->id; + } + } + $updated = isset($results->update) ? $results->update : array(); + foreach ($updated as $key => $item) { + if (isset($item->error)) { + $error_msg = $langs->trans('ECommerceWoocommerceUpdateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); + } else { + $prods_id_remote_id['update'][$prod_sku_id[$item->sku]] = $item->id; + } + } + if ($error) { + return $prods_id_remote_id; + } + } + + // Create variations on Woocommerce + foreach ($variations as $remote_product_id => $product_variations) { + $requestGroups = $this->getRequestGroups($product_variations, $nb_max_by_request); + foreach ($requestGroups as $request) { + $batch_datas = array(); + foreach ($request as $product_id => $variationData) { + $batch_type = $variationData['batch_type']; + unset($variationData['batch_type']); + $batch_datas[$batch_type][$product_id] = $variationData; + } + + $error = 0; $stopwatch_id = -1; try { @@ -5004,59 +5081,59 @@ public function batchUpdateRemoteProducts($batch) if (!self::$disable_put_post_to_api) $results = $this->client->post("products/$remote_product_id/variations/batch", $batch_datas); eCommerceUtils::stopAndLogStopwatch($stopwatch_id); dol_syslog(__METHOD__ . " - Send POST to API 'products/$remote_product_id/variations/batch' : Data: " . json_encode($batch_datas), LOG_NOTICE); - } catch (HttpClientException $fault) { + } catch (HttpClientException $fault) { eCommerceUtils::stopAndLogStopwatch($stopwatch_id); $this->errors[] = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()); - dol_syslog(__METHOD__ . - ': Error:' . $langs->transnoentitiesnoconv('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()) . - ' - Request:' . json_encode($fault->getRequest()) . ' - Response:' . json_encode($fault->getResponse()), LOG_ERR); - $error++; - } - - $created = isset($results->create) ? $results->create : array(); - foreach ($created as $key => $item) { - if (isset($item->error)) { - $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); - } else { - $prods_id_remote_id['create'][$prod_sku_id[$item->sku]] = $remote_product_id.'|'.$item->id; - } - } - $updated = isset($results->update) ? $results->update : array(); - foreach ($updated as $key => $item) { - if (isset($item->error)) { - $error_msg = $langs->trans('ECommerceWoocommerceUpdateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); - $this->errors[] = $error_msg; - dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); - } else { - $prods_id_remote_id['update'][$prod_sku_id[$item->sku]] = $remote_product_id.'|'.$item->id; - } - } - if ($error) { - return $prods_id_remote_id; - } - } - } - - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $prods_id_remote_id; - } - - /** - * Send a file for remote order - * - * @param int $order_remote_id Id of order on remote ecommerce - * @param Object $object Object (invoice or shipping) - * @param string $file File path - * @param Translate $outputlangs Lang output object - * - * @return bool - */ - public function sendFileForCommande($order_remote_id, $object, $file, $outputlangs) - { - dol_syslog(__METHOD__ . ": Send file '$file' for remote order ID $order_remote_id for site ID {$this->site->id}", LOG_DEBUG); - global $langs; + dol_syslog(__METHOD__ . + ': Error:' . $langs->transnoentitiesnoconv('ECommerceWoocommerceCreateRemoteBatchProducts', $this->site->name, $fault->getCode() . ': ' . $fault->getMessage()) . + ' - Request:' . json_encode($fault->getRequest()) . ' - Response:' . json_encode($fault->getResponse()), LOG_ERR); + $error++; + } + + $created = isset($results->create) ? $results->create : array(); + foreach ($created as $key => $item) { + if (isset($item->error)) { + $error_msg = $langs->trans('ECommerceWoocommerceCreateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); + } else { + $prods_id_remote_id['create'][$prod_sku_id[$item->sku]] = $remote_product_id . '|' . $item->id; + } + } + $updated = isset($results->update) ? $results->update : array(); + foreach ($updated as $key => $item) { + if (isset($item->error)) { + $error_msg = $langs->trans('ECommerceWoocommerceUpdateRemoteBatchProduct', $request[$key]['sku'], $this->site->name, $item->error->code . ': ' . $item->error->message . ' (data : ' . json_encode($item->error->data) . ' )'); + $this->errors[] = $error_msg; + dol_syslog(__METHOD__ . ': Error: ' . $error_msg, LOG_ERR); + } else { + $prods_id_remote_id['update'][$prod_sku_id[$item->sku]] = $remote_product_id . '|' . $item->id; + } + } + if ($error) { + return $prods_id_remote_id; + } + } + } + + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $prods_id_remote_id; + } + + /** + * Send a file for remote order + * + * @param int $order_remote_id Id of order on remote ecommerce + * @param Object $object Object (invoice or shipping) + * @param string $file File path + * @param Translate $outputlangs Lang output object + * + * @return bool + */ + public function sendFileForCommande($order_remote_id, $object, $file, $outputlangs) + { + dol_syslog(__METHOD__ . ": Send file '$file' for remote order ID $order_remote_id for site ID {$this->site->id}", LOG_DEBUG); + global $langs; $this->errors = array(); @@ -5070,23 +5147,23 @@ public function sendFileForCommande($order_remote_id, $object, $file, $outputlan $data = [ [ - 'name' => 'slug', + 'name' => 'slug', 'contents' => $order_remote_id . '_' . $object->element, ], [ - 'name' => 'author', + 'name' => 'author', 'contents' => $order_data['customer_id'], ], [ - 'name' => 'post', + 'name' => 'post', 'contents' => $order_remote_id, ], [ - 'name' => 'ping_status', + 'name' => 'ping_status', 'contents' => 'closed', ], [ - 'name' => 'comment_status', + 'name' => 'comment_status', 'contents' => 'closed', ], ]; @@ -5099,42 +5176,42 @@ public function sendFileForCommande($order_remote_id, $object, $file, $outputlan $cFile = '@' . realpath($file); } $data[] = [ - 'name' => 'file', + 'name' => 'file', 'filename' => basename($file), 'contents' => $cFile, // 'headers' => [ 'Content-Type' => $content_type ], ]; $data['file'] = $cFile; } else { - $this->errors[] = array('File not found ("'.$file.'").'); + $this->errors[] = array('File not found ("' . $file . '").'); return false; } // Send file to WordPress - $result = $this->worpressclient->sendToApi(eCommerceClientApi::METHOD_POST, "media", [ GuzzleHttp\RequestOptions::MULTIPART => $data ]); - if ($result === null) { - $this->errors[] = $langs->trans('ECommerceWoocommerceSendFileForCommandeInWordpress', $order_remote_id, $this->site->name, $this->worpressclient->errorsToString('; ')); - dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); - return false; - } - - // Set meta data in remote commande - $commandeData = [ - 'meta_data' => [ - [ - 'key' => 'file_for_' . $object->element.'_id', - 'value' => $result['id'], - ], - [ - 'key' => 'file_for_' . $object->element.'_link', - 'value' => $result['link'], - ], - [ - 'key' => 'file_for_' . $object->element.'_source_url', - 'value' => $result['source_url'], - ], - ] - ]; + $result = $this->worpressclient->sendToApi(eCommerceClientApi::METHOD_POST, "media", [GuzzleHttp\RequestOptions::MULTIPART => $data]); + if ($result === null) { + $this->errors[] = $langs->trans('ECommerceWoocommerceSendFileForCommandeInWordpress', $order_remote_id, $this->site->name, $this->worpressclient->errorsToString('; ')); + dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); + return false; + } + + // Set meta data in remote commande + $commandeData = [ + 'meta_data' => [ + [ + 'key' => 'file_for_' . $object->element . '_id', + 'value' => $result['id'], + ], + [ + 'key' => 'file_for_' . $object->element . '_link', + 'value' => $result['link'], + ], + [ + 'key' => 'file_for_' . $object->element . '_source_url', + 'value' => $result['source_url'], + ], + ] + ]; $result = $this->client->sendToApi(eCommerceClientApi::METHOD_PUT, "orders/{$order_remote_id}", [GuzzleHttp\RequestOptions::FORM_PARAMS => $commandeData]); if (!isset($result)) { $this->errors[] = $langs->trans('ECommerceWoocommerceSendFileForCommande', $order_remote_id, $this->site->name); @@ -5143,9 +5220,9 @@ public function sendFileForCommande($order_remote_id, $object, $file, $outputlan return false; } - dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return true; - } + dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return true; + } /** * Retrieve Dolibarr taxes info from remote data @@ -5447,14 +5524,14 @@ public function getAllWoocommerceTaxRate() return $taxClassesTable; } - /** - * Get all payment gateways - * - * @return array|false List of payment gateways or false if error - */ - public function getAllPaymentGateways() - { - dol_syslog(__METHOD__ . ": Retrieve all Woocommerce payment gateways", LOG_DEBUG); + /** + * Get all payment gateways + * + * @return array|false List of payment gateways or false if error + */ + public function getAllPaymentGateways() + { + dol_syslog(__METHOD__ . ": Retrieve all Woocommerce payment gateways", LOG_DEBUG); global $conf, $langs; $nb_max_by_request = empty($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL) ? 100 : min($conf->global->ECOMMERCENG_MAXSIZE_MULTICALL, 100); @@ -5462,7 +5539,7 @@ public function getAllPaymentGateways() $paymentGatewaysTable = []; $idxPage = 1; do { - $filters = [ + $filters = [ 'page' => $idxPage++, 'per_page' => $nb_max_by_request, ]; @@ -5482,9 +5559,9 @@ public function getAllPaymentGateways() } } while (count($payment_gateways) == $nb_max_by_request); - dol_syslog(__METHOD__ . ": end, return: ".json_encode($paymentGatewaysTable), LOG_DEBUG); - return $paymentGatewaysTable; - } + dol_syslog(__METHOD__ . ": end, return: " . json_encode($paymentGatewaysTable), LOG_DEBUG); + return $paymentGatewaysTable; + } /** * Get all remote warehouses @@ -5508,7 +5585,7 @@ public function getAllRemoteWarehouses() $remote_warehouses = $this->worpressclient->sendToApi(eCommerceClientApi::METHOD_GET, $plugin_support == 'wmlim' ? 'locations' : 'location'); if (!isset($remote_warehouses)) { $this->errors[] = $langs->trans('ECommerceWoocommerceGetAllWoocommerceRemoteWarehouses', $this->site->name); - $this->errors[] = $this->worpressclient->errorsToString(); + $this->errors[] = $this->worpressclient->errorsToString(); dol_syslog(__METHOD__ . ': Error:' . $this->errorsToString(), LOG_ERR); return false; } @@ -5665,7 +5742,7 @@ public function getAllWebHooks() * @param string $replacement Replacement text * @return string Replaced text */ - function replace4byte($string, $replacement = '') + public function replace4byte($string, $replacement = '') { return preg_replace('%(?: \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 @@ -5674,39 +5751,39 @@ function replace4byte($string, $replacement = '') )%xs', $replacement, $string); } - /** - * Get request groups of ID for get datas of remotes objects. - * - * @param array $remoteObject List of ids of remote objects - * @param int $nb_max_by_request Nb remote ID by request - * @param int $toNb Max nb - * @return array List of request groups of ID - */ - private function getRequestGroups($remoteObject, $nb_max_by_request, $toNb=0) - { - //dol_syslog(__METHOD__ . ": Get request groups of ID: " . implode(', ', $remoteObject), LOG_DEBUG); - - $idx = 0; - $request = []; - $request_groups = []; - - if (isset($remoteObject)) { - foreach ($remoteObject as $remote_object_id) { - if ($toNb > 0 && $idx > $toNb) break; - - if (($idx++ % $nb_max_by_request) == 0) { - if (count($request)) $request_groups[] = $request; - $request = []; - } - - $request[] = $remote_object_id; - } - } - if (count($request)) $request_groups[] = $request; - - //dol_syslog(__METHOD__ . ": end", LOG_DEBUG); - return $request_groups; - } + /** + * Get request groups of ID for get datas of remotes objects. + * + * @param array $remoteObject List of ids of remote objects + * @param int $nb_max_by_request Nb remote ID by request + * @param int $toNb Max nb + * @return array List of request groups of ID + */ + private function getRequestGroups($remoteObject, $nb_max_by_request, $toNb=0) + { + //dol_syslog(__METHOD__ . ": Get request groups of ID: " . implode(', ', $remoteObject), LOG_DEBUG); + + $idx = 0; + $request = []; + $request_groups = []; + + if (isset($remoteObject)) { + foreach ($remoteObject as $remote_object_id) { + if ($toNb > 0 && $idx > $toNb) break; + + if (($idx++ % $nb_max_by_request) == 0) { + if (count($request)) $request_groups[] = $request; + $request = []; + } + + $request[] = $remote_object_id; + } + } + if (count($request)) $request_groups[] = $request; + + //dol_syslog(__METHOD__ . ": end", LOG_DEBUG); + return $request_groups; + } /** * Get DateTime object in current timezone from gmt date time. @@ -5744,10 +5821,10 @@ private function getDateTimeToGMTDateTime($datetime) return $dt; } - public function __destruct() - { - ini_set("memory_limit", "528M"); - } + public function __destruct() + { + ini_set("memory_limit", "528M"); + } /** * Method to output saved errors diff --git a/sql/llx_ecommerce_category.sql b/sql/llx_ecommerce_category.sql index edbcf4f..87fbcb2 100644 --- a/sql/llx_ecommerce_category.sql +++ b/sql/llx_ecommerce_category.sql @@ -25,8 +25,9 @@ create table llx_ecommerce_category fk_category integer NOT NULL, fk_site integer NOT NULL, remote_id integer NOT NULL, - remote_parent_id integer DEFAULT NULL, - last_update datetime DEFAULT NULL + remote_parent_id integer DEFAULT NULL, + other_data text DEFAULT NULL, + last_update datetime DEFAULT NULL ) ENGINE=InnoDB COMMENT='Table transition remote site - Dolibarr'; diff --git a/sql/llx_ecommerce_product.sql b/sql/llx_ecommerce_product.sql index 78ad2bd..f3d0b97 100644 --- a/sql/llx_ecommerce_product.sql +++ b/sql/llx_ecommerce_product.sql @@ -22,6 +22,7 @@ CREATE TABLE llx_ecommerce_product ( fk_site integer NOT NULL, remote_id varchar(255) NOT NULL, lang varchar(255) default NULL, + other_data text DEFAULT NULL, last_update datetime default NULL, last_update_stock datetime default NULL ) ENGINE=InnoDB COMMENT='Table transition remote site - Dolibarr'; diff --git a/sql/update.sql b/sql/update.sql index dc5711d..1eb7f14 100644 --- a/sql/update.sql +++ b/sql/update.sql @@ -59,3 +59,7 @@ ALTER TABLE llx_ecommerceng_payment_gateways CHANGE COLUMN mail_model_for_send_i -- v4.1.57 ALTER TABLE llx_ecommerceng_remote_warehouses DROP INDEX uk_ecommerceng_remote_warehouses; ALTER TABLE llx_ecommerceng_remote_warehouses ADD UNIQUE INDEX uk_ecommerceng_remote_warehouses(site_id,remote_id,entity); + +-- v14.0.8 +ALTER TABLE llx_ecommerce_category ADD COLUMN other_data text DEFAULT NULL after remote_parent_id; +ALTER TABLE llx_ecommerce_product ADD COLUMN other_data text DEFAULT NULL after lang;