diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 0900f11ed29..bb04f6e9359 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -2990,7 +2990,6 @@ class Product extends CommonObject $sql .= " JOIN ".MAIN_DB_PREFIX."commande c ON el.fk_source = c.rowid "; $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id); dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE); - $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql) > 0) { @@ -2999,6 +2998,24 @@ class Product extends CommonObject } } + $this->stats_commande['qty'] -= $adeduire; + } else { + //For every order having invoice already validated we need to decrease stock cause it's in physical stock + $adeduire = 0; + $sql = 'SELECT sum(fd.qty) as count FROM '.MAIN_DB_PREFIX.'facturedet fd '; + $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON fd.fk_facture = f.rowid '; + $sql .= ' JOIN '.MAIN_DB_PREFIX."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'"; + $sql .= ' JOIN '.MAIN_DB_PREFIX.'commande c ON el.fk_source = c.rowid '; + $sql .= ' WHERE c.fk_statut IN ('.$this->db->sanitize($filtrestatut).') AND f.fk_statut > '.Facture::STATUS_DRAFT.' AND fd.fk_product = '.((int) $this->id); + dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE); + $resql = $this->db->query($sql); + if($resql) { + if($this->db->num_rows($resql) > 0) { + $obj = $this->db->fetch_object($resql); + $adeduire += $obj->count; + } + } + $this->stats_commande['qty'] -= $adeduire; } }