From a7813c37a1dee3b5ba8d2e4da451e0f16e96f519 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Mon, 12 Dec 2016 12:36:00 +0100 Subject: [PATCH 01/41] init inventory integration --- htdocs/core/class/coreobject.class.php | 214 ++++++++++ htdocs/inventory/ajax/ajax.inventory.php | 50 +++ htdocs/inventory/class/inventory.class.php | 466 +++++++++++++++++++++ 3 files changed, 730 insertions(+) create mode 100644 htdocs/core/class/coreobject.class.php create mode 100644 htdocs/inventory/ajax/ajax.inventory.php create mode 100644 htdocs/inventory/class/inventory.class.php diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php new file mode 100644 index 00000000000..1cc68f38cb7 --- /dev/null +++ b/htdocs/core/class/coreobject.class.php @@ -0,0 +1,214 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/class/coreobject.inventory.php + * \ingroup core + * \brief File of class to manage all object. Might be replace or merge into commonobject + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; + +class CoreObject extends CommonObject { + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB &$db) { + + $this->db = &$db; + + $this->date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? + } + + private function init() { + + $this->id = 0; + $this->datec = time(); + $this->tms = time(); + + if(!empty($this->__fields)) { + foreach ($this->__fields as $field=>$info) { + + if($this->is_date($info)){ + $this->{$field} = time(); + } + elseif($this->is_array($info)){ + $this->{$field} = array(); + } + elseif($this->is_int($info)){ + $this->{$field} = (int)0; + } + elseif($this->is_float($info)) { + $this->{$field} = (double)0; + } + else{ + $this->{$field} = ''; + } + } + + $this->to_delete=false; + + return true; + } + else{ + return false; + } + + } + + + private function is_date(Array &$info){ + + if(is_array($info)) { + if(isset($info['type']) && $info['type']=='date') return true; + else return false; + } + else return false; + } + + private function is_array($info) { + + if(is_array($info)) { + if(isset($info['type']) && $info['type']=='array') return true; + else return false; + } + else return false; + } + + + private function is_null($info){ + if(is_array($info)) { + if(isset($info['type']) && $info['type']=='null') return true; + else return false; + } + else return false; + } + + private function is_int($info){ + + if(is_array($info)) { + if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true; + else return false; + } + else return false; + } + private function _is_float($info){ + if(is_array($info)) { + if(isset($info['type']) && $info['type']=='float') return true; + else return false; + } else return false; + } + + private function _is_text($info){ + if(is_array($info)) { + if(isset($info['type']) && $info['type']=='text') return true; + else return false; + } else return false; + } + private function _is_index($info){ + if(is_array($info)) { + if(isset($info['index']) && $info['index']==true) return true; + else return false; + } else return false; + } + + private function set_save_query(){ + + $query=array( + 'rowid'=>$this->id + ,'datec'=>($this->id>0 ? $this->db->jdate($this->datec) : time()) + ,'tms'=>time() + ); + + foreach ($this->__fields as $field=>$info) { + + if($this->_is_date($info)){ + if(empty($this->{$field})){ + $query[$field] = $this->date_0; + } + else{ + $query[$field] = $this->db->jdate($this->{$field}); + } + } + else if($this->is_array($info)){ + $query[$field] = serialize($this->{$field}); + } + + else if($this->is_int($info)){ + $query[$field] = (int)price2num($this->{$field}); + } + + else if($this->_is_float($info)){ + $query[$field] = (double)price2num($this->{$field}); + } + + elseif($this->_is_null($info)) { + $query[$field] = (is_null($this->{$field}) || (empty($this->{$field}) && $this->{$field}!==0 && $this->{$field}!=='0')?null:$this->{$field}); + } + else{ + $query[$field] = $this->{$field}; + } + + } + + return $query; + } + + + public function fetch($id, $loadChild = true) { + + if(empty($id)) return false; + + $res = $db->query( 'SELECT '.$this->get_field_list().'datec,tms + FROM '.$this->table_element.' + WHERE rowid='.$id ); + if($obj = $db->fetch_object($res)) { + $this->rowid=$id; + + $this->set_vars_by_db($db); + + $this->datec=$this->db->idate($obj->datec); + $this->tms=$this->db->idate($obj->tms); + + if($loadChild) $this->loadChild($db); + + $this->run_trigger($db, 'load'); + + return $this->id; + } + else { + return false; + } + + } + public function update() { + + + + } + public function create() { + + + + } + + +} diff --git a/htdocs/inventory/ajax/ajax.inventory.php b/htdocs/inventory/ajax/ajax.inventory.php new file mode 100644 index 00000000000..34efecfab8f --- /dev/null +++ b/htdocs/inventory/ajax/ajax.inventory.php @@ -0,0 +1,50 @@ +rights->inventory->write) { echo -1; exit; } + + $fk_det_inventory = GETPOST('fk_det_inventory'); + + $det = new Inventorydet; + if( $det->load($PDOdb, $fk_det_inventory)) { + $det->qty_view+=GETPOST('qty'); + $det->save($PDOdb); + + echo $det->qty_view; + } + else { + echo -2; + } + + break; + + case 'pmp': + if (!$user->rights->inventory->write || !$user->rights->inventory->changePMP) { echo -1; exit; } + + $fk_det_inventory = GETPOST('fk_det_inventory'); + + $det = new Inventorydet; + if( $det->load($PDOdb, $fk_det_inventory)) { + $det->new_pmp=price2num(GETPOST('pmp')); + $det->save($PDOdb); + + echo $det->new_pmp; + } + else { + echo -2; + } + + break; + + } + diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php new file mode 100644 index 00000000000..808dd7933be --- /dev/null +++ b/htdocs/inventory/class/inventory.class.php @@ -0,0 +1,466 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/inventory/class/product.inventory.php + * \ingroup product + * \brief File of class to manage predefined products stock + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + +class Inventory extends CoreObject +{ + + public $element='inventory'; + public $table_element='inventory'; + public $fk_element='fk_inventory'; + protected $childtables=array('inventorydet'); // To test if we can delete object + protected $isnolinkedbythird = 1; // No field fk_soc + protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + + /** + * Warehouse Id + * @var int + */ + public $fk_warehouse; + /** + * Entity Id + * @var int + */ + public $entity; + + /** + * Status + * @var int + */ + public $status; + /** + * Inventory Date + * @var date + */ + public $date_inventory; + /** + * Inventory Title + * @var string + */ + public $title; + + private $__fields=array( + 'fk_warehouse'=>array('type'=>'integer','index'=>true) + ,'entity'=>array('type'=>'integer','index'=>true) + ,'status'=>array('type'=>'integer','index'=>true) + ,'date_inventory'=>array('type'=>'date') + ,'title'=>array('type'=>'string') + ); + + function __construct() + { + + parent::init(); + + $this->_init_vars(); + + $this->start(); + + $this->setChild('Inventorydet','fk_inventory'); + + $this->status = 0; + $this->entity = $conf->entity; + $this->errors = array(); + $this->amount = 0; + + } + + function sort_det() + { + usort($this->Inventorydet, array('Inventory', 'customSort')); + } + + function load(&$PDOdb, $id,$annexe = true) + { + + if(!$annexe) $this->withChild = false; + + $res = parent::load($PDOdb, $id); + $this->sort_det(); + + $this->amount = 0; + foreach($this->Inventorydet as &$det){ + $this->amount+=$det->qty_view * $det->pmp; + } + + return $res; + } + + + function customSort(&$objA, &$objB) + { + global $db; + + $r = strcmp(strtoupper(trim($objA->product->ref)), strtoupper(trim($objB->product->ref))); + + if ($r < 0) $r = -1; + elseif ($r > 0) $r = 1; + else $r = 0; + + return $r; + } + + function changePMP(&$PDOdb) { + + foreach ($this->Inventorydet as $k => &$Inventorydet) + { + + if($Inventorydet->new_pmp>0) { + $Inventorydet->pmp = $Inventorydet->new_pmp; + $Inventorydet->new_pmp = 0; + + $PDOdb->Execute("UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$Inventorydet->pmp." + WHERE rowid = ".$Inventorydet->fk_product ); + + if((float)DOL_VERSION<4.0) { + + $PDOdb->Execute("UPDATE ".MAIN_DB_PREFIX."product_stock SET pmp=".$Inventorydet->pmp." + WHERE fk_entrepot = ".$this->fk_warehouse." AND fk_product = ".$Inventorydet->fk_product) ; + + } + + } + } + + parent::save($PDOdb); + + } + + function save(&$PDOdb) + { + //si on valide l'inventaire on sauvegarde le stock à cette instant + if ($this->status) + { + $this->regulate($PDOdb); + } + + parent::save($PDOdb); + } + + function set_values($Tab) + { + global $db,$langs; + + if (isset($Tab['qty_to_add'])) + { + foreach ($Tab['qty_to_add'] as $k => $qty) + { + $qty = (float) price2num($qty); + + if ($qty < 0) + { + $this->errors[] = $langs->trans('inventoryErrorQtyAdd'); + return 0; + } + + $product = new Product($db); + $product->fetch($this->Inventorydet[$k]->fk_product); + + $this->Inventorydet[$k]->pmp = $product->pmp; + $this->Inventorydet[$k]->qty_view += $qty; + } + } + + return parent::set_values($Tab); + } + + function deleteAllLine(&$PDOdb) { + + foreach($this->Inventorydet as &$det) { + $det->to_delete = true; + } + + $this->save($PDOdb); + + $this->Inventorydet=array(); + + } + + function add_product(&$PDOdb, $fk_product, $fk_entrepot='') { + + $k = $this->addChild($PDOdb, 'Inventorydet'); + $det = &$this->Inventorydet[$k]; + + $det->fk_inventory = $this->getId(); + $det->fk_product = $fk_product; + $det->fk_warehouse = empty($fk_entrepot) ? $this->fk_warehouse : $fk_entrepot; + + $det->load_product(); + + $date = $this->get_date('date_inventory', 'Y-m-d'); + if(empty($date))$date = $this->get_date('date_cre', 'Y-m-d'); + $det->setStockDate($PDOdb, $date , $fk_entrepot); + + } + + function correct_stock($fk_product, $id_entrepot, $nbpiece, $movement, $label='', $price=0, $inventorycode='') + { + global $conf, $db, $langs, $user; + + /* duplication method product to add datem */ + if ($id_entrepot) + { + $db->begin(); + + require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php'; + + $op[0] = "+".trim($nbpiece); + $op[1] = "-".trim($nbpiece); + + $datem = empty($conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT) ? dol_now() : $this->date_inventory; + + $movementstock=new MouvementStock($db); + $result=$movementstock->_create($user,$fk_product,$id_entrepot,$op[$movement],$movement,$price,$label,$inventorycode, $datem); + + if ($result >= 0) + { + $db->commit(); + return 1; + } + else + { + $this->error=$movementstock->error; + $this->errors=$movementstock->errors; + + $db->rollback(); + return -1; + } + } + } + + function regulate(&$PDOdb) + { + global $db,$user,$langs,$conf; + + if($conf->global->INVENTORY_DISABLE_VIRTUAL){ + $pdt_virtuel = false; + // Test si pdt virtuel est activé + if($conf->global->PRODUIT_SOUSPRODUITS) + { + $pdt_virtuel = true; + $conf->global->PRODUIT_SOUSPRODUITS = 0; + } + } + + foreach ($this->Inventorydet as $k => $Inventorydet) + { + $product = new Product($db); + $product->fetch($Inventorydet->fk_product); + + /* + * Ancien code qui était pourri et qui modifié la valeur du stock théorique si le parent était déstocké le même jour que l'enfant + * + * $product->load_stock(); + $Inventorydet->qty_stock = $product->stock_warehouse[$this->fk_warehouse]->real; + + if(date('Y-m-d', $this->date_inventory) < date('Y-m-d')) { + $TRes = $Inventorydet->getPmpStockFromDate($PDOdb, date('Y-m-d', $this->date_inventory), $this->fk_warehouse); + $Inventorydet->qty_stock = $TRes[1]; + } + */ + if ($Inventorydet->qty_view != $Inventorydet->qty_stock) + { + $Inventorydet->qty_regulated = $Inventorydet->qty_view - $Inventorydet->qty_stock; + $nbpiece = abs($Inventorydet->qty_regulated); + $movement = (int) ($Inventorydet->qty_view < $Inventorydet->qty_stock); // 0 = add ; 1 = remove + + $href = dol_buildpath('/inventory/inventory.php?id='.$this->getId().'&action=view', 1); + + if(empty($this->title)) + $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock', $href, $this->getId())); + else + $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStockWithNomInventaire', $href, $this->title)); + } + } + + if($conf->global->INVENTORY_DISABLE_VIRTUAL){ + // Test si pdt virtuel était activé avant la régule + if($pdt_virtuel) $conf->global->PRODUIT_SOUSPRODUITS = 1; + } + + return 1; + } + + static function getLink($id) { + global $langs; + + $PDOdb=new TPDOdb; + + $i = new Inventory; + $i->load($PDOdb, $id, false); + + $title = !empty($i->title) ? $i->title : $langs->trans('inventoryTitle').' '.$i->getId(); + + return ''.img_picto('','object_list.png','',0).' '.$title.''; + + } +} + +class Inventorydet extends TObjetStd +{ + function __construct() + { + global $conf; + + $this->set_table(MAIN_DB_PREFIX.'inventorydet'); + $this->TChamps = array(); + $this->add_champs('fk_inventory,fk_warehouse,fk_product,entity', 'type=entier;'); + $this->add_champs('qty_view,qty_stock,qty_regulated,pmp,pa,new_pmp', 'type=float;'); + + $this->_init_vars(); + $this->start(); + + $this->entity = $conf->entity; + $this->errors = array(); + + $this->product = null; + + $this->current_pa = 0; + + } + + function load(&$PDOdb, $id) + { + global $conf; + + $res = parent::load($PDOdb, $id); + $this->load_product(); + $this->fetch_current_pa(); + + return $res; + } + + function fetch_current_pa() { + global $db,$conf; + + if(empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) return false; + + if($this->pa>0){ + $this->current_pa = $this->pa; + } + else { + + dol_include_once('/fourn/class/fournisseur.product.class.php'); + $p= new ProductFournisseur($db); + $p->find_min_price_product_fournisseur($this->fk_product); + + if($p->fourn_qty>0) $this->current_pa = $p->fourn_price / $p->fourn_qty; + } + return true; + } + + function setStockDate(&$PDOdb, $date, $fk_warehouse) { + + list($pmp,$stock) = $this->getPmpStockFromDate($PDOdb, $date, $fk_warehouse); + + $this->qty_stock = $stock; + $this->pmp = $pmp; + + $last_pa = 0; + $sql = "SELECT price FROM ".MAIN_DB_PREFIX."stock_mouvement + WHERE fk_entrepot=".$fk_warehouse." + AND fk_product=".$this->fk_product." + AND (origintype='order_supplier' || origintype='invoice_supplier') + AND price>0 + AND datem<='".$date." 23:59:59' + ORDER BY datem DESC LIMIT 1"; + + $PDOdb->Execute($sql); + + if($obj = $PDOdb->Get_line()) { + $last_pa = $obj->price; + } + + $this->pa = $last_pa; + /* var_dump($fk_warehouse,$this->product->stock_warehouse,$this->pmp, $this->pa, $this->qty_stock); + exit;*/ + } + + function getPmpStockFromDate(&$PDOdb, $date, $fk_warehouse){ + + $res = $this->product->load_stock(); + + if($res>0) { + $stock = isset($this->product->stock_warehouse[$fk_warehouse]->real) ? $this->product->stock_warehouse[$fk_warehouse]->real : 0; + + if((float)DOL_VERSION<4.0) { + $pmp = isset($this->product->stock_warehouse[$fk_warehouse]->pmp) ? $this->product->stock_warehouse[$fk_warehouse]->pmp : 0; + } + else{ + $pmp = $this->product->pmp; + } + + } + + //On récupère tous les mouvements de stocks du produit entre aujourd'hui et la date de l'inventaire + $sql = "SELECT value, price + FROM ".MAIN_DB_PREFIX."stock_mouvement + WHERE fk_product = ".$this->product->id." + AND fk_entrepot = ".$fk_warehouse." + AND datem > '".date('Y-m-d 23:59:59',strtotime($date))."' + ORDER BY datem DESC"; + + //echo $sql.'
'; + $PDOdb->Execute($sql); + $TMouvementStock = $PDOdb->Get_All(); + $laststock = $stock; + $lastpmp = $pmp; + //Pour chacun des mouvements on recalcule le PMP et le stock physique + foreach($TMouvementStock as $mouvement){ + + //150 + //if($this->product->id==394) echo 'laststock = '.$stock.'
'; + + //9.33 + //if($this->product->id==394) echo 'lastpmp = '.$pmp.'
'; + $price = ($mouvement->price>0 && $mouvement->value>0) ? $mouvement->price : $lastpmp; + + $stock_value = $laststock * $lastpmp; + + $laststock -= $mouvement->value; + + $last_stock_value = $stock_value - ($mouvement->value * $price); + + $lastpmp = ($laststock != 0) ? $last_stock_value / $laststock : $lastpmp; + + + + } + + return array($lastpmp,$laststock); + } + + function load_product() + { + global $db; + + if($this->fk_product>0) { + $this->product = new Product($db); + $this->product->fetch($this->fk_product); + } + + } + +} From cdfbed5d084215994320f82bd98315373e018034 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Mon, 12 Dec 2016 17:36:22 +0100 Subject: [PATCH 02/41] new listview --- htdocs/core/class/class.listview.php | 1216 ++++++++++++++++++++ htdocs/inventory/class/inventory.class.php | 64 +- 2 files changed, 1270 insertions(+), 10 deletions(-) create mode 100644 htdocs/core/class/class.listview.php diff --git a/htdocs/core/class/class.listview.php b/htdocs/core/class/class.listview.php new file mode 100644 index 00000000000..f37fc9a1628 --- /dev/null +++ b/htdocs/core/class/class.listview.php @@ -0,0 +1,1216 @@ + + + This program and all files within this directory and sub directory + is free software: you can redistribute it and/or modify it under + the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +class Listview { + + function __construct( $id ) { + + $this->id = $id; + + $this->TTotalTmp=array(); + + $this->sql = ''; + + } + private function init(&$TParam) { + + global $conf, $langs; + + if(!isset($TParam['hide']))$TParam['hide']=array(); + if(!isset($TParam['link']))$TParam['link']=array(); + if(!isset($TParam['type']))$TParam['type']=array(); + if(!isset($TParam['orderby']['noOrder']))$TParam['orderby']['noOrder']=array(); + if(!isset($TParam['no-select'])) $TParam['no-select'] = 1; + + if(!isset($TParam['liste']))$TParam['liste']=array(); + $TParam['liste'] = array_merge(array( + 'messageNothing'=>"Il n'y a aucun élément à afficher." + ,'picto_precedent'=>'<' + ,'picto_suivant'=>'>' + ,'order_down'=>img_down() + ,'order_up'=>img_up() + ,'noheader'=>0 + ,'useBottomPagination'=>0 + ,'image'=>'' + ,'titre'=>'Liste' + ,'orderDown'=>'' + ,'orderUp'=>'' + ,'id'=>$this->id + ,'picto_search'=>img_picto('Search', 'search.png') + ,'head_search'=>'' + ,'export'=>array() + ,'view_type'=>'' + ),$TParam['liste']); + + if(empty($TParam['limit']))$TParam['limit']=array(); + if(!empty($_REQUEST['TListTBS'][$this->id]['page'])) $TParam['limit']['page'] = $_REQUEST['TListTBS'][$this->id]['page']; + + $TParam['limit']=array_merge(array('page'=>1, 'nbLine'=>$conf->liste_limit, 'global'=>0), $TParam['limit']); + + if(!empty($_REQUEST['TListTBS'][$this->id]['orderBy'])) { + $TParam['orderBy'] = $_REQUEST['TListTBS'][$this->id]['orderBy']; + } + + // print_r($TParam); + } + private function getSearchNull($key, &$TParam) { + return !empty($TParam['search'][$key]['allow_is_null']); + } + private function getSearchKey($key, &$TParam) { + + $TPrefixe=array(); + if(!empty($TParam['search'][$key]['table'])) { + if (!is_array($TParam['search'][$key]['table'])) $TParam['search'][$key]['table'] = array($TParam['search'][$key]['table']); + + foreach ($TParam['search'][$key]['table'] as $prefix_table) { + $TPrefixe[] = '`'.$prefix_table.'`.'; + } + } + + $TKey=array(); + if(!empty($TParam['search'][$key]['field'])) { + if (!is_array($TParam['search'][$key]['field'])) $TParam['search'][$key]['field'] = array($TParam['search'][$key]['field']); + + foreach ($TParam['search'][$key]['field'] as $i => $field) { + $prefixe = !empty($TPrefixe[$i]) ? $TPrefixe[$i] : $TPrefixe[0]; + $TKey[] = $prefixe.'`'. $field .'`'; + } + } else { + $TKey[] =$TPrefixe[0].'`'. strtr($key,';','*').'`'; + } + + return $TKey; + } + private function getSearchValue($value) { + $value = strtr(trim($value),';','*'); + + return $value; + } + + private function dateToSQLDate($date) { + + list($dd,$mm,$aaaa) = explode('/', substr($date,0,10)); + + $value = date('Y-m-d', mktime(0,0,0,$mm,$dd,$aaaa)); + + return $value; + } + + private function addSqlFromTypeDate(&$TSQLMore, &$value, $sKey, $sBindKey) + { + if(is_array($value)) + { + + unset($this->TBind[$sBindKey]); + // Si le type de "recherche" est "calendars" on a 2 champs de transmis, [début et fin] ou [que début] ou [que fin] => un BETWEEN Sql serait utile que dans le 1er cas + // donc l'utilisation des opérateur >= et <= permettent un fonctionnement générique + $TSQLDate=array(); + if(!empty($value['deb'])) + { + $valueDeb = $this->dateToSQLDate($value['deb']); + + if(isset($this->TBind[$sBindKey.'_start'])) // TODO can't use this in query case + { + $this->TBind[$sBindKey.'_start'] = $valueDeb; + } + + $TSQLDate[]=$sKey." >= '".$valueDeb." 00:00:00'" ; + + } + + if(!empty($value['fin'])) + { + $valueFin = $this->dateToSQLDate($value['fin']); + if(isset($this->TBind[$sBindKey.'_end'])) { // TODO can't use this in query case + $this->TBind[$sBindKey.'_end'] = $valueFin; + } + + $TSQLDate[]=$sKey." <= '".$valueFin." 23:59:59'" ; + + } + + if(!empty($TSQLDate)) $TSQLMore[] = implode(' AND ', $TSQLDate); + } + else + { + // Sinon je communique une date directement au format d/m/Y et la méthode du dessous reformat en Y-m-d + $value = $this->dateToSQLDate($value); + if(isset($this->TBind[$sBindKey])) + { + $this->TBind[$sBindKey] = $value; + } + else + { + // Le % en fin de chaine permet de trouver un resultat si le contenu est au format Y-m-d H:i:s et non en Y-m-d + $TSQLMore[]=$sKey." LIKE '".$value."%'" ; + } + } + } + + private function addSqlFromOther(&$TSQLMore, &$value, &$TParam, $sKey, $sBindKey, $key) + { + + $value = $this->getSearchValue($value); + + if(isset($TParam['operator'][$key])) + { + if($TParam['operator'][$key] == '<' || $TParam['operator'][$key] == '>' || $TParam['operator'][$key]=='=') + { + $TSQLMore[] = $sKey . ' ' . $TParam['operator'][$key] . ' "' . $value . '"'; + } + elseif ($TParam['operator'][$key]=='IN') + { + $TSQLMore[] = $sKey . ' ' . $TParam['operator'][$key] . ' (' . $value . ')'; + } + else + { + if(strpos($value,'%')===false) $value = '%'.$value.'%'; + $TSQLMore[]=$sKey." LIKE '".addslashes($value)."'" ; + } + } + else + { + if(strpos($value,'%')===false) $value = '%'.$value.'%'; + $TSQLMore[]=$sKey." LIKE '".addslashes($value)."'" ; + } + + + } + + private function search($sql,&$TParam) { + + if(!empty($_REQUEST['TListTBS'][$this->id]['search'])) { + $sqlGROUPBY=''; + if(strpos($sql,'GROUP BY')!==false) { //TODO regex + list($sql, $sqlGROUPBY) = explode('GROUP BY', $sql); + } + + if(strpos($sql,'WHERE ')===false)$sql.=' WHERE 1 '; //TODO regex + + foreach($_REQUEST['TListTBS'][$this->id]['search'] as $key=>$value) + { + $TsKey = $this->getSearchKey($key, $TParam); + $TsBindKey = $this->getTsBindKey($TsKey); + + //if (!empty($value)) var_dump($TsKey, $TsBindKey, '=================================='); + $TSQLMore = array(); + + $allow_is_null = $this->getSearchNull($key,$TParam); + $search_on_null = false; //TODO useless + + foreach ($TsKey as $i => &$sKey) + { + //if (!empty($value)) var_dump($sKey); + $sBindKey = $TsBindKey[$i]; + + if($allow_is_null && !empty($_REQUEST['TListTBS'][$this->id]['search_on_null'][$key])) + { + $this->TBind[$sBindKey.'_null'] = $sKey.' IS NULL '; + $TSQLMore[] = $sKey.' IS NULL '; + $search_on_null = true; + + if(isset($this->TBind[$sBindKey])) $this->TBind[$sBindKey]= ''; + $value = ''; + } + elseif($allow_is_null) + { + $this->TBind[$sBindKey.'_null'] =0; // $sKey.' IS NOT NULL '; + //$TSQLMore[] = $sKey.' IS NOT NULL '; + } + + if($value!='') { // pas empty car biensûr le statut = 0 existe dans de nombreux cas + + if(isset($TParam['type'][$key]) && ($TParam['type'][$key]==='date' || $TParam['type'][$key]==='datetime')) + { + $this->addSqlFromTypeDate($TSQLMore, $value, $sKey, $sBindKey); + } + else + { + $this->addSqlFromOther($TSQLMore, $value, $TParam, $sKey, $sBindKey, $key); + } + } + } + + if(!isset($this->TBind[$sBindKey]) && !empty($TSQLMore)) + { + $sql.=' AND ( '.implode(' OR ',$TSQLMore).' ) '; + } + + } + + if($sqlGROUPBY!='') $sql.=' GROUP BY '.$sqlGROUPBY; + + } + + + return $sql; + } + + private function getViewType(&$TParam) { + if(!empty($TParam['view_type'])) return $TParam['view_type']; + else if (is_string($TParam['type']))return $TParam['type'] ; + else return 'list'; + } + + public function render(&$db,$sql,$TParam=array(),$TBind=array()) { + $this->typeRender = 'sql'; + // print_r($TParam); + $TEntete=array(); + $TChamps=array(); + + $this->init($TParam); + + if(!empty($TBind)) $this->TBind = $TBind; + + $sql = $this->search($sql,$TParam); + $sql = $this->order_by($sql, $TParam); + + $this->parse_sql($db, $TEntete, $TChamps, $TParam, $sql); + + list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + + $view_type = $this->getViewType($TParam); + + if($view_type == 'raw') { + return $this->renderRAW($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); + } + else if($view_type == 'chart') { + return $this->renderChart($TEntete, $TChamps,$TTotal, $TParam); + } + else { + return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); + } + + + } + public function renderDataTableAjax(&$db,$sql,$TParam=array()) { + $this->renderDataTableSQL($db, $sql, $TParam); + } + public function renderDataTableSQL(&$db,$sql,$TParam=array()) { + $this->typeRender = 'dataTableAjax'; + // print_r($TParam); + $TEntete=array(); + $TChamps=array(); + + $this->init($TParam); + + $sql = $this->search($sql,$TParam); + $sql = $this->order_by($sql, $TParam); + + $this->parse_sql($db, $TEntete, $TChamps, $TParam, $sql); + list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + + return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); + + } + public function renderXML(&$db,$xmlString, $TParam=array()) { + $this->typeRender = 'xml'; + + $TEntete=array(); + $TChamps=array(); + + $this->init($TParam); + + $this->parse_xml($db, $TEntete, $TChamps, $TParam,$xmlString); + + list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + + return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); + + } + private function setSearch(&$TEntete, &$TParam) { + global $langs; + + if(empty($TParam['search'])) return array(); + + $TSearch=array(); + $form=new TFormCore; + $form->strict_string_compare = true; + + $nb_search_in_bar = 0; + + if(!empty($TParam['search'])) { + foreach($TEntete as $key=>$libelle) { // init + if(empty($TSearch[$key]))$TSearch[$key]=''; + } + } + foreach($TParam['search'] as $key=>$param_search) { + + + $value = isset($_REQUEST['TListTBS'][$this->id]['search'][$key]) ? $_REQUEST['TListTBS'][$this->id]['search'][$key] : ''; + + $typeRecherche = (is_array($param_search) && isset($param_search['recherche'])) ? $param_search['recherche'] : $param_search; + + if(is_array($typeRecherche)) { + $typeRecherche = array(''=>' ') + $typeRecherche; + $fsearch=$form->combo('','TListTBS['.$this->id.'][search]['.$key.']', $typeRecherche,$value,0,'',' listviewtbs="combo" init-value="'.$value.'" '); + } + else if($typeRecherche==='calendar') { + $fsearch=$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); + } + else if($typeRecherche==='calendars') { + $fsearch=$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.'][deb]',isset($value['deb'])?$value['deb']:'',10,10,' listviewtbs="calendars" ') + .' '.$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.'][fin]',isset($value['fin'])?$value['fin']:'',10,10,' listviewtbs="calendars" '); + } + else if(is_string($typeRecherche)) { + $fsearch=$TParam['search'][$key]; + } + else { + $fsearch=$form->texte('','TListTBS['.$this->id.'][search]['.$key.']',$value,15,255,' listviewtbs="input" '); + } + + if(!empty($param_search['allow_is_null'])) { + $valueNull = isset($_REQUEST['TListTBS'][$this->id]['search_on_null'][$key]) ? 1 : 0; + $fsearch.=' '.$form->checkbox1('', 'TListTBS['.$this->id.'][search_on_null]['.$key.']',1, $valueNull,' onclick=" if($(this).is(\':checked\')){ $(this).prev().val(\'\'); }" ').img_help(1, $langs->trans('SearchOnNUllValue')); + } + + + if(!empty($TEntete[$key]) || $this->getViewType($TParam) == 'chart') { + $TSearch[$key] = $fsearch; + $nb_search_in_bar++; + } + else { + + $libelle = !empty($TParam['title'][$key]) ? $TParam['title'][$key] : $key ; + $TParam['liste']['head_search'].='
'.$libelle.' '.$fsearch.'
'; + } + + } + + $search_button = ' '.$TParam['liste']['picto_search'].''; + + if(!empty($TParam['liste']['head_search'])) { + $TParam['liste']['head_search'].='
'.$langs->trans('Search').' '.$search_button.'
'; + } + + if($nb_search_in_bar>0) { + end($TSearch); + list($key,$v) = each($TSearch); + $TSearch[$key].=$search_button; + } + else{ + $TSearch=array(); + } + + return $TSearch; + } + + /* + * Function analysant et totalisant une colonne + * Supporté : sum, average + */ + private function get_total(&$TChamps, &$TParam) { + $TTotal=$TTotalGroup=array(); + + if(!empty($TParam['math']) && !empty($TChamps[0])) { + + foreach($TChamps[0] as $field=>$value) { + $TTotal[$field]=''; + $TTotalGroup[$field] = ''; + } + + foreach($TParam['math'] as $field=>$typeMath){ + + if(is_array($typeMath)) { + $targetField = $typeMath[1]; + $typeMath = $typeMath[0]; + } + else { + $targetField = $field; + } + + if($typeMath == 'groupsum') { + $TTotalGroup[$field] = array('target'=>$targetField, 'values'=> $this->TTotalTmp['@groupsum'][$targetField]); + + } + else if($typeMath=='average') { + $TTotal[$field]=array_sum($this->TTotalTmp[$targetField]) / count($this->TTotalTmp[$targetField]); + } + elseif($typeMath=='count') { + $TTotal[$field]=count($this->TTotalTmp[$targetField]); + } + else { + $TTotal[$field]=array_sum($this->TTotalTmp[$targetField]); + } + + } + + + } + + return array($TTotal,$TTotalGroup); + } + + private function getJS(&$TParam) { + $javaScript = ''; + + + if($this->typeRender=='dataTable') { + + $javaScript.=' + '; + + $TPagination=array(); + } + elseif($this->typeRender=='dataTableAjax') { + $javaScript.=' + '; + } + + return $javaScript; + } + + private function setExport(&$TParam,$TChamps,$TEntete) { + global $langs; + + $Tab=array(); + if(!empty($TParam['export'])) { + $token = GETPOST('token'); + if(empty($token)) $token = md5($this->id.time().rand(1,9999)); + + $_SESSION['token_list_'.$token] = gzdeflate( serialize( array( + 'title'=>$this->title + ,'sql'=>$this->sql + ,'TBind'=>$this->TBind + ,'TChamps'=>$TChamps + ,'TEntete'=>$TEntete + ) ) ); + + foreach($TParam['export'] as $mode_export) { + + $Tab[] = array( + 'label'=>$langs->trans('Export'.$mode_export) + ,'url'=>dol_buildpath('/abricot/downlist.php',1) + ,'mode'=>$mode_export + ,'token'=>$token + ,'session_name'=>session_name() + ); + + } + + } + + + return $Tab; + } + + private function renderChart(&$TEntete, &$TChamps,&$TTotal, &$TParam) { + + $TData = array(); + $header = ''; + $first = true; + + $TSearch = $this->setSearch($TEntete, $TParam); + $TExport= $this->setExport($TParam, $TChamps, $TEntete); + + if(empty($TParam['xaxis']) && !empty($TEntete)) { + $fieldXaxis = key($TEntete); + } + else { + $fieldXaxis = $TParam['xaxis']; + } + + $TValue=array(); $key = null; + foreach($TEntete as $field=>&$entete) { + if($field!=$fieldXaxis)$TValue[] = addslashes($entete['libelle']); + } + + $header='["'.addslashes( $TEntete[$fieldXaxis]['libelle'] ).'","'.implode('","', $TValue).'"]'; + //var_dump($fieldXaxis, $TChamps); + foreach($TChamps as &$row) { + $TValue=array(); + $key = null; + + foreach($row as $k=>$v) { + + if($k == $fieldXaxis) { + $key = $v; + } + else { + $TValue[] = (float)$v; + } + + } + + if(!is_null($key)) { + if(!isset($TData[$key])) $TData[$key] = $TValue; + else { + foreach($TData[$key] as $k=>$v) { + $TData[$key][$k]+=(float)$TValue[$k]; + } + + } + } + + + } + + $data = $header; + foreach($TData as $key=>$TValue) { + + $data .= ',[ "'.$key.'", '; + foreach($TValue as $v) { + $data.=(float)$v.','; + } + + $data.=' ]'; + } + + $height = empty($TParam['height']) ? 500 : $TParam['height']; + $curveType= empty($TParam['curveType']) ? 'none': $TParam['curveType']; // none or function + $pieHole = empty($TParam['pieHole']) ? 0: $TParam['pieHole']; // none or function + $hAxis = empty($TParam['hAxis']) ? array() : $TParam['hAxis']; // Array of params + $vAxis = empty($TParam['vAxis']) ? array() : $TParam['vAxis']; // Array of params + + // This feature is experimental and may change in future releases + $explorer = empty($TParam['explorer']) ? array() : $TParam['explorer']; // Note: The explorer only works with continuous axes (such as numbers or dates) + + $type = empty($TParam['chartType']) ? 'LineChart' : $TParam['chartType']; + + $html = ''; + + if(!empty($TSearch)) { + + $html.=''; + foreach($TSearch as $field=>$input) { + if(!empty($input)) { + $label = !empty($TParam['title'][$field]) ? $TParam['title'][$field] : $field; + $html.=''; + } + } + + $html.=''; + + } + $javaScript = $this->getJS($TParam); + + $html.=' + +
+ '.$javaScript; + + return $html; + } + + private function addTotalGroup($TChamps,$TTotalGroup) { + global $langs; + + $Tab=array(); + + $proto_total_line = array(); + + $tagbase = $old_tagbase = null; + + $addGroupLine = false; + + foreach($TChamps as $k=>&$line) { + + if(empty($proto_total_line)) { + foreach($line as $field=>$value) { + $proto_total_line[$field] = ''; + } + $group_line = $proto_total_line; + } + + $addGroupLine = false; + + $tagbase = ''; + foreach($line as $field=>$value) { + + if(!empty($TTotalGroup[$field])) { + $tagbase.=$value.'|'; + $group_line[$field] = '
'.(empty($value) ? $langs->trans('Empty') : $value ).' :
'; + $group_line[$TTotalGroup[$field]['target']] = '
'.price($TTotalGroup[$field]['values'][$value]).'
'; + $addGroupLine = true; + } + + } + + if(!is_null($old_tagbase) && $old_tagbase!=$tagbase && $addGroupLine) { + // var_dump(array($k,$tagbase,$old_tagbase,$empty_line)); + $Tab[] = $previous_group_line; + } + + $old_tagbase = $tagbase; + $previous_group_line = $group_line; + $group_line = $proto_total_line; + + $Tab[] = $line; + + + + } + if($addGroupLine) { + $Tab[] = $previous_group_line; + } + + + return $Tab; + } + + private function renderRAW(&$TEntete, &$TChamps, &$TTotal,&$TTotalGroup, &$TParam) { + $TSearch = $this->setSearch($TEntete, $TParam); + $TExport=$this->setExport($TParam, $TChamps, $TEntete); + $TChamps = $this->addTotalGroup($TChamps,$TTotalGroup); + + return array( + 'entete'=>$TEntete + ,'champs'=>$TChamps + ,'recherche'=>$TSearch + ,'total'=>$TTotal + ,'export'=>$TExport + ,'haveExport'=>count($TExport) + , 'id'=>$this->id + , 'nb_columns'=>count($TEntete) + ,'totalNB'=>count($TChamps) + , 'nbSearch'=>count($TSearch) + , 'haveTotal'=>(int)!empty($TTotal) + , 'havePage'=>(int)!empty($TPagination) + ); + } + + private function renderList(&$TEntete, &$TChamps, &$TTotal,&$TTotalGroup, &$TParam) { + $TBS = new TTemplateTBS; + + $javaScript = $this->getJS($TParam); + + if($this->typeRender!='dataTableAjax') { + $TPagination=array( + 'pagination'=>array('pageSize'=>$TParam['limit']['nbLine'], 'pageNum'=>$TParam['limit']['page'], 'blockName'=>'champs', 'totalNB'=>count($TChamps)) + ); + } + else { + $TPagination=array(); + } + + $TSearch = $this->setSearch($TEntete, $TParam); + $TExport=$this->setExport($TParam, $TChamps, $TEntete); + $TChamps = $this->addTotalGroup($TChamps,$TTotalGroup); + + return $TBS->render($this->template + , array( + 'entete'=>$TEntete + ,'champs'=>$TChamps + ,'recherche'=>$TSearch + ,'total'=>$TTotal + ,'export'=>$TExport + ) + , array( + 'liste'=>array_merge(array('haveExport'=>count($TExport), 'id'=>$this->id, 'nb_columns'=>count($TEntete) ,'totalNB'=>count($TChamps), 'nbSearch'=>count($TSearch), 'haveTotal'=>(int)!empty($TTotal), 'havePage'=>(int)!empty($TPagination) ), $TParam['liste']) + ) + , $TPagination + , array() + ) + .$javaScript; + } + public function renderDatatable(&$db, $TField, $TParam) { + $this->typeRender = 'dataTable'; + // on conserve db pour le traitement ultérieur des subQuery + $TEntete=array(); + $TChamps=array(); + + //$TParam['limit']['nbLine'] = 99999; + + $this->init($TParam); + + $this->parse_array($TEntete, $TChamps, $TParam,$TField); + list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + return $this->renderList($TEntete, $TChamps, $TTotal,$TTotalGroup,$TParam); + + } + public function renderArray(&$db,$TField, $TParam=array()) { + $this->typeRender = 'array'; + // on conserve db pour le traitement ultérieur des subQuery + $TEntete=array(); + $TChamps=array(); + + $this->init($TParam); + + $this->parse_array($TEntete, $TChamps, $TParam,$TField); + list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + + $view_type = $this->getViewType($TParam); + + if($view_type == 'raw') { + return $this->renderRAW($TEntete, $TChamps,$TTotal, $TParam); + } + if($view_type == 'chart') { + return $this->renderChart($TEntete, $TChamps,$TTotal, $TParam); + } + else { + return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); + } + } + + private function order_by($sql, &$TParam) { + $first = true; + // print_r($TParam['orderBy']); + if(!empty($TParam['orderBy'])) { + + if(strpos($sql,'LIMIT ')!==false) { + list($sql, $sqlLIMIT) = explode('LIMIT ', $sql); + } + + $sql.=' ORDER BY '; + foreach($TParam['orderBy'] as $field=>$order) { + if(!$first) $sql.=','; + + if($order=='DESC')$TParam['liste']['orderDown'] = $field; + else $TParam['liste']['orderUp'] = $field; + + if(strpos($field,'.')===false) $sql.='`'.$field.'` '.$order; + else $sql.=$field.' '.$order; + + $first=false; + } + + if(!empty($sqlLIMIT))$sql.=' LIMIT '.$sqlLIMIT; + + } + + return $sql; + } + private function parse_xml(&$db, &$TEntete, &$TChamps, &$TParam, $xmlString) { + $xml = simplexml_load_string($xmlString); + $this->THideFlip = array_flip($TParam['hide']); + + $first=true; + foreach($xml->{$TParam['node']['main']}->{$TParam['node']['object']} as $node) { + if($first) { + $this->init_entete($TEntete, $TParam, $node); + $first=false; + } + + $this->set_line($TChamps, $TParam, $node); + } + + } + private function parse_array(&$TEntete, &$TChamps, &$TParam, $TField) { + $first=true; + + $this->THideFlip = array_flip($TParam['hide']); + $this->TTotalTmp=array(); + + if(empty($TField)) return false; + + foreach($TField as $row) { + if($first) { + $this->init_entete($TEntete, $TParam, $row); + $first=false; + } + + $this->set_line($TChamps, $TParam, $row); + } + + } + + private function init_entete(&$TEntete, &$TParam, $currentLine) { + + $TField=$TFieldVisibility=array(); + + foreach ($currentLine as $field => $value) { + $TField[$field]=true; + } + + global $user; + + $contextpage=md5($_SERVER['PHP_SELF']); + if((float)DOL_VERSION>=4.0 && empty($TParam['no-select'])) { + + dol_include_once('/core/class/html.form.class.php'); + + global $db,$conf,$user; + $form=new Form($db); + + $selectedfields = GETPOST('TListTBS_'.$this->id.'_selectedfields'); + + if(!empty($selectedfields)) { + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + $tabparam['MAIN_SELECTEDFIELDS_'.$contextpage]=$selectedfields; + $result=dol_set_user_param($db, $conf, $user, $tabparam); + } + + $tmpvar='MAIN_SELECTEDFIELDS_'.$contextpage; + if (! empty($user->conf->$tmpvar)) { + $tmparray=explode(',', $user->conf->$tmpvar); + $TParam['hide']=array(); + foreach($TField as $field=>$dummy) + { + $libelle = isset($TParam['title'][$field]) ? $TParam['title'][$field] : $field; + + if(!in_array($field,$tmparray)) { + $TParam['hide'][] = $field; + $visible = 0; + } + else{ + $visible = 1; + } + + $TFieldVisibility[$field]=array( + 'label'=>$libelle + ,'checked'=>$visible + ); + + + } + } + else{ + foreach($TField as $field=>$dummy) + { + $libelle = isset($TParam['title'][$field]) ? $TParam['title'][$field] : $field; + $visible = (!in_array($field,$TParam['hide'])) ? 1 : 0; + $TFieldVisibility[$field]=array( + 'label'=>$libelle + ,'checked'=>$visible + ); + } + } + + $selectedfields=$form->multiSelectArrayWithCheckbox('TListTBS_'.$this->id.'_selectedfields', $TFieldVisibility, $contextpage); // This also change content of $arrayfields_0 + + } + + foreach ($currentLine as $field => $value) { + $libelle = isset($TParam['title'][$field]) ? $TParam['title'][$field] : $field; + $visible = (!in_array($field,$TParam['hide'])) ? 1 : 0; + + if($visible) { + $lastfield = $field; + $TEntete[$field] = array( + 'libelle'=>$libelle + ,'order'=>((in_array($field, $TParam['orderby']['noOrder']) || $this->typeRender != 'sql') ? 0 : 1) + ,'width'=>(!empty($TParam['size']['width'][$field]) ? $TParam['size']['width'][$field] : 'auto') + ,'text-align'=>(!empty($TParam['position']['text-align'][$field]) ? $TParam['position']['text-align'][$field] : 'auto') + ,'more'=>'' + ); + + } + } + + if(!empty($selectedfields) && !empty($lastfield)) { + $TEntete[$lastfield]['more']='
'.$selectedfields.'
'; + } + + + /*if(!empty($TParam['search']) && !empty($TEntete)) { + $TEntete['actions']=array('libelle'=>'', 'order'=>0); + }*/ + + } + + private function in_view(&$TParam, $line_number) { + global $conf; +// var_dump($_REQUEST['get-all-for-export']); + if(!empty($_REQUEST['get-all-for-export'])) return true; // doit être dans la vue + + $page_number = !empty($TParam['limit']['page']) ? $TParam['limit']['page'] : 1; + $line_per_page = !empty($TParam['limit']['nbLine']) ? $TParam['limit']['nbLine'] : $conf->liste_limit; + + $start = ($page_number-1) * $line_per_page; + $end = ($page_number* $line_per_page) -1; + + if($line_number>=$start && $line_number<=$end) return true; + else return false; + } + + private function set_line(&$TChamps, &$TParam, $currentLine) { + + global $conf; + + $line_number = count($TChamps); + + if($this->in_view($TParam,$line_number)) { + + $row=array(); $trans = array(); + foreach($currentLine as $field=>$value) { + + if(is_object($value)) { + if(get_class($value)=='stdClass') {$value=print_r($value, true);} + else $value=(string)$value; + } + + if(isset($TParam['subQuery'][$field])) { + $dbSub = new TPDOdb; //TODO finish it + $dbSub->Execute( strtr($TParam['subQuery'][$field], array_merge( $trans, array('@val@'=>$value) )) ); + $subResult = ''; + while($dbSub->Get_line()) { + $subResult.= implode(', ',$dbSub->currentLine).'
'; + } + $value=$subResult; + $dbSub->close(); + } + + $trans['@'.$field.'@'] = $value; + + if(!empty($TParam['math'][$field])) { + $float_value = (double)strip_tags($value); + $this->TTotalTmp[$field][] = $float_value; + } + + if(!in_array($field,$TParam['hide'])) { + $row[$field]=$value; + + if(isset($TParam['eval'][$field]) && in_array($field,array_keys($row))) { + $strToEval = 'return '.strtr( $TParam['eval'][$field] , array_merge( $trans, array('@val@'=>$row[$field]) )).';'; + $row[$field] = eval($strToEval); + } + + if(isset($TParam['type'][$field]) && !isset($TParam['eval'][$field])) { + if($TParam['type'][$field]=='date' + || $TParam['type'][$field]=='datetime' ) { + + if($row[$field] != '0000-00-00 00:00:00' && $row[$field] != '1000-01-01 00:00:00' && $row[$field] != '0000-00-00' && !empty($row[$field])) { + if($TParam['type'][$field]=='datetime')$row[$field] = dol_print_date(strtotime($row[$field]),'dayhoursec'); + else $row[$field] = dol_print_date(strtotime($row[$field]),'day'); + } else { + $row[$field] = ''; + } + } + if($TParam['type'][$field]=='hour') { $row[$field] = date('H:i', strtotime($row[$field])); } + if($TParam['type'][$field]=='money') { $row[$field] = '
'.price($row[$field],0,'',1,-1,2).'
'; } + if($TParam['type'][$field]=='number') { $row[$field] = '
'.price($row[$field]).'
'; } + if($TParam['type'][$field]=='integer') { $row[$field] = '
'.(int)$row[$field].'
'; } + } + + if(isset($TParam['link'][$field])) { + if(empty($row[$field]) && $row[$field]!==0 && $row[$field]!=='0')$row[$field]='(vide)'; + $row[$field]= strtr( $TParam['link'][$field], array_merge( $trans, array('@val@'=>$row[$field]) )) ; + } + + if(isset($TParam['translate'][$field])) { + if(isset($TParam['translate'][$field][''])) unset($TParam['translate'][$field]['']); + $row[$field] = strtr( $row[$field] , $TParam['translate'][$field]); + } + + + } + + + } + } + else{ + $row=array(); + + foreach($currentLine as $field=>&$value) { + if(!isset($this->THideFlip[$field])) { + if(isset($TParam['math'][$field]) && !empty($TParam['math'][$field])) { + $float_value = (double)strip_tags($value); + $this->TTotalTmp[$field][] = $float_value; + } + + $row[$field] = $value; + } + } + } + + if(!empty($TParam['math'][$field])) { + foreach($row as $field=>$value) { + if(!empty($TParam['math'][$field]) && is_array($TParam['math'][$field])) { + $toField = $TParam['math'][$field][1]; + $float_value = (double)strip_tags($row[$toField]); + $this->TTotalTmp['@groupsum'][$toField][ $row[$field] ] +=$float_value; + + } + } + } + $TChamps[] = $row; + } + + private function getBind(&$TParam) { + + $TBind = array(); + foreach($this->TBind as $k=>$v) { + if(!empty($TParam['operator'][$k]) && $TParam['operator'][$k] == 'IN') { + + if($v==='')$TBind[$k] =array("'0'"); + else $TBind[$k] =explode(',', $v); + + } + else{ + $TBind[$k] = $v; + } + + } + + return $TBind; + } + + private function getSQL(&$PDOdb,$sql,&$TParam) { + global $user,$conf; + + $sql=strtr($sql,array( + '@current_user@'=>$user->id + )); + + //AA oui c'est moche mais le bindParam ne prends pas en compte les tableaux pour le IN ce qui est super pénalisant. En attendant de refaire mieux ou d'un coup de main + $TBind = $this->getBind($TParam); + + $sql = preg_replace_callback('/(:[a-z])\w+/i',function($matches) use($TBind,$PDOdb) { + $field = substr($matches[0],1); + if(isset($TBind[$field]) || is_null($TBind[$field]) ) { + + if(is_array($TBind[$field])) { + $r = ''; + foreach($TBind[$field] as $v ){ + if(!empty($r))$r.=','; + $r.=$PDOdb->quote($v); + } + + return $r; + + } + else if(strpos($TBind[$field],' IS NULL') === false) { + return $PDOdb->quote($TBind[$field]); + } + else { + return $TBind[$field]; + } + } + else { + return 'errorBindingField '.$field; + } + + }, $sql); + + + return $sql; + } + + private function limitSQL($sql,&$TParam) { + + if(!empty($TParam['limit']['global']) && strpos($sql,'LIMIT ')===false ) { + + $sql.=' LIMIT '.(int)$TParam['limit']['global']; + + } + + return $sql; + } + + private function parse_sql(&$PDOdb, &$TEntete, &$TChamps,&$TParam, $sql, $TBind=array()) { + + //$sql.=' LIMIT '.($TParam['limit']['page']*$TParam['limit']['nbLine']).','.$TParam['limit']['nbLine']; + $sql = $this->limitSQL($sql, $TParam); + + $this->TTotalTmp=array(); + + $this->sql = $this->getSQL($PDOdb,$sql,$TParam); + $this->THideFlip = array_flip($TParam['hide']); + + $res = $PDOdb->Execute($this->sql); + $first=true; + while($currentLine = $PDOdb->Get_line()) { + if($first) { + $this->init_entete($TEntete, $TParam, $currentLine); + $first = false; + } + + $this->set_line($TChamps, $TParam, $currentLine); + + } + +//pre($TChamps);exit; + + } +} diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index 808dd7933be..60a8dde8652 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -69,9 +69,11 @@ class Inventory extends CoreObject ,'title'=>array('type'=>'string') ); - function __construct() + function __construct(&$db) { + $this->db = &$db; + parent::init(); $this->_init_vars(); @@ -316,22 +318,64 @@ class Inventory extends CoreObject return ''.img_picto('','object_list.png','',0).' '.$title.''; } + + static function getSQL($type) { + global $conf; + + if($type=='All') { + + $sql="SELECT i.rowid, e.label, i.date_inventory, i.fk_warehouse, i.date_cre, i.date_maj, i.status + FROM ".MAIN_DB_PREFIX."inventory i + LEFT JOIN ".MAIN_DB_PREFIX."entrepot e ON (e.rowid = i.fk_warehouse) + WHERE i.entity=".(int) $conf->entity; + + } + + return $sql; + } + } -class Inventorydet extends TObjetStd +class Inventorydet extends CoreObject { - function __construct() + public $element='inventorydet'; + public $table_element='inventorydet'; + protected $isnolinkedbythird = 1; // No field fk_soc + protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + + public $fk_inventory; + public $fk_warehouse; + public $fk_product; + public $entity; + public $qty_view; + public $qty_stock; + public $qty_regulated; + public $pmp; + public $pa; + public $new_pmp; + + private $__fields=array( + 'fk_inventory'=>array('type'=>'int') + ,'fk_warehouse'=>array('type'=>'int') + ,'fk_product'=>array('type'=>'int') + ,'entity'=>array('type'=>'int') + ,'qty_view'=>array('type'=>'float') + ,'qty_stock'=>array('type'=>'float') + ,'qty_regulated'=>array('type'=>'float') + ,'pmp'=>array('type'=>'float') + ,'pa'=>array('type'=>'float') + ,'new_pmp'=>array('type'=>'float') + ); + + + function __construct(&$db) { global $conf; - $this->set_table(MAIN_DB_PREFIX.'inventorydet'); - $this->TChamps = array(); - $this->add_champs('fk_inventory,fk_warehouse,fk_product,entity', 'type=entier;'); - $this->add_champs('qty_view,qty_stock,qty_regulated,pmp,pa,new_pmp', 'type=float;'); - - $this->_init_vars(); - $this->start(); + $this->db = &$db; + parent::init(); + $this->entity = $conf->entity; $this->errors = array(); From dfb9ae234cfe3b156cedba54e72c36d8e88e19ea Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Mon, 12 Dec 2016 19:03:02 +0100 Subject: [PATCH 03/41] debug --- htdocs/core/class/coreobject.class.php | 23 +- ...{class.listview.php => listview.class.php} | 520 +++--------------- htdocs/core/js/listview.js | 143 +++++ htdocs/inventory/class/inventory.class.php | 81 ++- 4 files changed, 266 insertions(+), 501 deletions(-) rename htdocs/core/class/{class.listview.php => listview.class.php} (61%) create mode 100644 htdocs/core/js/listview.js diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 1cc68f38cb7..7d784073412 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -25,7 +25,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; class CoreObject extends CommonObject { - + protected $__fields=array(); /** * Constructor * @@ -38,7 +38,7 @@ class CoreObject extends CommonObject { $this->date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? } - private function init() { + protected function init() { $this->id = 0; $this->datec = time(); @@ -110,20 +110,20 @@ class CoreObject extends CommonObject { } else return false; } - private function _is_float($info){ + private function is_float($info){ if(is_array($info)) { if(isset($info['type']) && $info['type']=='float') return true; else return false; } else return false; } - private function _is_text($info){ + private function is_text($info){ if(is_array($info)) { if(isset($info['type']) && $info['type']=='text') return true; else return false; } else return false; } - private function _is_index($info){ + private function is_index($info){ if(is_array($info)) { if(isset($info['index']) && $info['index']==true) return true; else return false; @@ -172,14 +172,23 @@ class CoreObject extends CommonObject { return $query; } + private function get_field_list(){ + + $keys = array_keys($this->__fields); + + return implode(',', $keys); + } public function fetch($id, $loadChild = true) { if(empty($id)) return false; - $res = $db->query( 'SELECT '.$this->get_field_list().'datec,tms + $sql = 'SELECT '.$this->get_field_list().',datec,tms FROM '.$this->table_element.' - WHERE rowid='.$id ); + WHERE rowid='.$id; + + $res = $this->db->query( $sql ); + var_dump($sql); if($obj = $db->fetch_object($res)) { $this->rowid=$id; diff --git a/htdocs/core/class/class.listview.php b/htdocs/core/class/listview.class.php similarity index 61% rename from htdocs/core/class/class.listview.php rename to htdocs/core/class/listview.class.php index f37fc9a1628..0cedad18855 100644 --- a/htdocs/core/class/class.listview.php +++ b/htdocs/core/class/listview.class.php @@ -20,7 +20,9 @@ class Listview { - function __construct( $id ) { + function __construct(&$db, $id ) { + + $this->db = &$db; $this->id = $id; @@ -263,79 +265,25 @@ class Listview { return $sql; } - private function getViewType(&$TParam) { - if(!empty($TParam['view_type'])) return $TParam['view_type']; - else if (is_string($TParam['type']))return $TParam['type'] ; - else return 'list'; + public function render($sql,$TParam=array()) { + + $THeader=array(); + $TField=array(); + + $this->init($TParam); + + $sql = $this->search($sql,$TParam); + $sql = $this->order_by($sql, $TParam); + + $this->parse_sql($THeader, $TField, $TParam, $sql); + + list($TTotal, $TTotalGroup)=$this->get_total($TField, $TParam); + + return $this->renderList($THeader, $TField,$TTotal,$TTotalGroup, $TParam); + } - public function render(&$db,$sql,$TParam=array(),$TBind=array()) { - $this->typeRender = 'sql'; - // print_r($TParam); - $TEntete=array(); - $TChamps=array(); - - $this->init($TParam); - - if(!empty($TBind)) $this->TBind = $TBind; - - $sql = $this->search($sql,$TParam); - $sql = $this->order_by($sql, $TParam); - - $this->parse_sql($db, $TEntete, $TChamps, $TParam, $sql); - - list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); - - $view_type = $this->getViewType($TParam); - - if($view_type == 'raw') { - return $this->renderRAW($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); - } - else if($view_type == 'chart') { - return $this->renderChart($TEntete, $TChamps,$TTotal, $TParam); - } - else { - return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); - } - - - } - public function renderDataTableAjax(&$db,$sql,$TParam=array()) { - $this->renderDataTableSQL($db, $sql, $TParam); - } - public function renderDataTableSQL(&$db,$sql,$TParam=array()) { - $this->typeRender = 'dataTableAjax'; - // print_r($TParam); - $TEntete=array(); - $TChamps=array(); - - $this->init($TParam); - - $sql = $this->search($sql,$TParam); - $sql = $this->order_by($sql, $TParam); - - $this->parse_sql($db, $TEntete, $TChamps, $TParam, $sql); - list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); - - return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); - - } - public function renderXML(&$db,$xmlString, $TParam=array()) { - $this->typeRender = 'xml'; - - $TEntete=array(); - $TChamps=array(); - - $this->init($TParam); - - $this->parse_xml($db, $TEntete, $TChamps, $TParam,$xmlString); - - list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); - - return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); - - } - private function setSearch(&$TEntete, &$TParam) { + private function setSearch(&$THeader, &$TParam) { global $langs; if(empty($TParam['search'])) return array(); @@ -347,7 +295,7 @@ class Listview { $nb_search_in_bar = 0; if(!empty($TParam['search'])) { - foreach($TEntete as $key=>$libelle) { // init + foreach($THeader as $key=>$libelle) { // init if(empty($TSearch[$key]))$TSearch[$key]=''; } } @@ -382,7 +330,7 @@ class Listview { } - if(!empty($TEntete[$key]) || $this->getViewType($TParam) == 'chart') { + if(!empty($THeader[$key]) || $this->getViewType($TParam) == 'chart') { $TSearch[$key] = $fsearch; $nb_search_in_bar++; } @@ -416,12 +364,12 @@ class Listview { * Function analysant et totalisant une colonne * Supporté : sum, average */ - private function get_total(&$TChamps, &$TParam) { + private function get_total(&$TField, &$TParam) { $TTotal=$TTotalGroup=array(); - if(!empty($TParam['math']) && !empty($TChamps[0])) { + if(!empty($TParam['math']) && !empty($TField[0])) { - foreach($TChamps[0] as $field=>$value) { + foreach($TField[0] as $field=>$value) { $TTotal[$field]=''; $TTotalGroup[$field] = ''; } @@ -460,80 +408,16 @@ class Listview { private function getJS(&$TParam) { $javaScript = ''; - - if($this->typeRender=='dataTable') { - - $javaScript.=' - '; - - $TPagination=array(); - } - elseif($this->typeRender=='dataTableAjax') { - $javaScript.=' - '; - } - return $javaScript; } - private function setExport(&$TParam,$TChamps,$TEntete) { + private function setExport(&$TParam,$TField,$THeader) { global $langs; $Tab=array(); @@ -545,8 +429,8 @@ class Listview { 'title'=>$this->title ,'sql'=>$this->sql ,'TBind'=>$this->TBind - ,'TChamps'=>$TChamps - ,'TEntete'=>$TEntete + ,'TChamps'=>$TField + ,'TEntete'=>$THeader ) ) ); foreach($TParam['export'] as $mode_export) { @@ -567,133 +451,7 @@ class Listview { return $Tab; } - private function renderChart(&$TEntete, &$TChamps,&$TTotal, &$TParam) { - - $TData = array(); - $header = ''; - $first = true; - - $TSearch = $this->setSearch($TEntete, $TParam); - $TExport= $this->setExport($TParam, $TChamps, $TEntete); - - if(empty($TParam['xaxis']) && !empty($TEntete)) { - $fieldXaxis = key($TEntete); - } - else { - $fieldXaxis = $TParam['xaxis']; - } - - $TValue=array(); $key = null; - foreach($TEntete as $field=>&$entete) { - if($field!=$fieldXaxis)$TValue[] = addslashes($entete['libelle']); - } - - $header='["'.addslashes( $TEntete[$fieldXaxis]['libelle'] ).'","'.implode('","', $TValue).'"]'; - //var_dump($fieldXaxis, $TChamps); - foreach($TChamps as &$row) { - $TValue=array(); - $key = null; - - foreach($row as $k=>$v) { - - if($k == $fieldXaxis) { - $key = $v; - } - else { - $TValue[] = (float)$v; - } - - } - - if(!is_null($key)) { - if(!isset($TData[$key])) $TData[$key] = $TValue; - else { - foreach($TData[$key] as $k=>$v) { - $TData[$key][$k]+=(float)$TValue[$k]; - } - - } - } - - - } - - $data = $header; - foreach($TData as $key=>$TValue) { - - $data .= ',[ "'.$key.'", '; - foreach($TValue as $v) { - $data.=(float)$v.','; - } - - $data.=' ]'; - } - - $height = empty($TParam['height']) ? 500 : $TParam['height']; - $curveType= empty($TParam['curveType']) ? 'none': $TParam['curveType']; // none or function - $pieHole = empty($TParam['pieHole']) ? 0: $TParam['pieHole']; // none or function - $hAxis = empty($TParam['hAxis']) ? array() : $TParam['hAxis']; // Array of params - $vAxis = empty($TParam['vAxis']) ? array() : $TParam['vAxis']; // Array of params - - // This feature is experimental and may change in future releases - $explorer = empty($TParam['explorer']) ? array() : $TParam['explorer']; // Note: The explorer only works with continuous axes (such as numbers or dates) - - $type = empty($TParam['chartType']) ? 'LineChart' : $TParam['chartType']; - - $html = ''; - - if(!empty($TSearch)) { - - $html.=''; - foreach($TSearch as $field=>$input) { - if(!empty($input)) { - $label = !empty($TParam['title'][$field]) ? $TParam['title'][$field] : $field; - $html.=''; - } - } - - $html.=''; - - } - $javaScript = $this->getJS($TParam); - - $html.=' - -
- '.$javaScript; - - return $html; - } - - private function addTotalGroup($TChamps,$TTotalGroup) { + private function addTotalGroup($TField,$TTotalGroup) { global $langs; $Tab=array(); @@ -704,7 +462,7 @@ class Listview { $addGroupLine = false; - foreach($TChamps as $k=>&$line) { + foreach($TField as $k=>&$line) { if(empty($proto_total_line)) { foreach($line as $field=>$value) { @@ -748,99 +506,50 @@ class Listview { return $Tab; } - - private function renderRAW(&$TEntete, &$TChamps, &$TTotal,&$TTotalGroup, &$TParam) { - $TSearch = $this->setSearch($TEntete, $TParam); - $TExport=$this->setExport($TParam, $TChamps, $TEntete); - $TChamps = $this->addTotalGroup($TChamps,$TTotalGroup); - - return array( - 'entete'=>$TEntete - ,'champs'=>$TChamps - ,'recherche'=>$TSearch - ,'total'=>$TTotal - ,'export'=>$TExport - ,'haveExport'=>count($TExport) - , 'id'=>$this->id - , 'nb_columns'=>count($TEntete) - ,'totalNB'=>count($TChamps) - , 'nbSearch'=>count($TSearch) - , 'haveTotal'=>(int)!empty($TTotal) - , 'havePage'=>(int)!empty($TPagination) - ); - } - private function renderList(&$TEntete, &$TChamps, &$TTotal,&$TTotalGroup, &$TParam) { - $TBS = new TTemplateTBS; - + private function renderList(&$THeader, &$TField, &$TTotal,&$TTotalGroup, &$TParam) { + $javaScript = $this->getJS($TParam); - if($this->typeRender!='dataTableAjax') { - $TPagination=array( - 'pagination'=>array('pageSize'=>$TParam['limit']['nbLine'], 'pageNum'=>$TParam['limit']['page'], 'blockName'=>'champs', 'totalNB'=>count($TChamps)) - ); - } - else { - $TPagination=array(); - } + $TPagination=array( + 'pagination'=>array('pageSize'=>$TParam['limit']['nbLine'], 'pageNum'=>$TParam['limit']['page'], 'blockName'=>'champs', 'totalNB'=>count($TField)) + ); - $TSearch = $this->setSearch($TEntete, $TParam); - $TExport=$this->setExport($TParam, $TChamps, $TEntete); - $TChamps = $this->addTotalGroup($TChamps,$TTotalGroup); + $TSearch = $this->setSearch($THeader, $TParam); + $TExport=$this->setExport($TParam, $TField, $THeader); + $TField = $this->addTotalGroup($TField,$TTotalGroup); - return $TBS->render($this->template - , array( - 'entete'=>$TEntete - ,'champs'=>$TChamps + var_dump( + array( + 'entete'=>$THeader + ,'champs'=>$TField ,'recherche'=>$TSearch ,'total'=>$TTotal ,'export'=>$TExport ) , array( - 'liste'=>array_merge(array('haveExport'=>count($TExport), 'id'=>$this->id, 'nb_columns'=>count($TEntete) ,'totalNB'=>count($TChamps), 'nbSearch'=>count($TSearch), 'haveTotal'=>(int)!empty($TTotal), 'havePage'=>(int)!empty($TPagination) ), $TParam['liste']) + 'liste'=>array_merge(array('haveExport'=>count($TExport), 'id'=>$this->id, 'nb_columns'=>count($THeader) ,'totalNB'=>count($TField), 'nbSearch'=>count($TSearch), 'haveTotal'=>(int)!empty($TTotal), 'havePage'=>(int)!empty($TPagination) ), $TParam['liste']) ) , $TPagination - , array() - ) - .$javaScript; - } - public function renderDatatable(&$db, $TField, $TParam) { - $this->typeRender = 'dataTable'; - // on conserve db pour le traitement ultérieur des subQuery - $TEntete=array(); - $TChamps=array(); - - //$TParam['limit']['nbLine'] = 99999; - - $this->init($TParam); - - $this->parse_array($TEntete, $TChamps, $TParam,$TField); - list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); - return $this->renderList($TEntete, $TChamps, $TTotal,$TTotalGroup,$TParam); - + + ); + + $javaScript; } + public function renderArray(&$db,$TField, $TParam=array()) { $this->typeRender = 'array'; // on conserve db pour le traitement ultérieur des subQuery - $TEntete=array(); - $TChamps=array(); + $THeader=array(); + $TField=array(); $this->init($TParam); - $this->parse_array($TEntete, $TChamps, $TParam,$TField); - list($TTotal, $TTotalGroup)=$this->get_total($TChamps, $TParam); + $this->parse_array($THeader, $TField, $TParam,$TField); + list($TTotal, $TTotalGroup)=$this->get_total($TField, $TParam); - $view_type = $this->getViewType($TParam); + $this->renderList($THeader, $TField,$TTotal,$TTotalGroup, $TParam); - if($view_type == 'raw') { - return $this->renderRAW($TEntete, $TChamps,$TTotal, $TParam); - } - if($view_type == 'chart') { - return $this->renderChart($TEntete, $TChamps,$TTotal, $TParam); - } - else { - return $this->renderList($TEntete, $TChamps,$TTotal,$TTotalGroup, $TParam); - } } private function order_by($sql, &$TParam) { @@ -848,7 +557,7 @@ class Listview { // print_r($TParam['orderBy']); if(!empty($TParam['orderBy'])) { - if(strpos($sql,'LIMIT ')!==false) { + if(strpos($sql,'LIMIT ')!==false) { //TODO regex list($sql, $sqlLIMIT) = explode('LIMIT ', $sql); } @@ -871,22 +580,8 @@ class Listview { return $sql; } - private function parse_xml(&$db, &$TEntete, &$TChamps, &$TParam, $xmlString) { - $xml = simplexml_load_string($xmlString); - $this->THideFlip = array_flip($TParam['hide']); - - $first=true; - foreach($xml->{$TParam['node']['main']}->{$TParam['node']['object']} as $node) { - if($first) { - $this->init_entete($TEntete, $TParam, $node); - $first=false; - } - - $this->set_line($TChamps, $TParam, $node); - } - - } - private function parse_array(&$TEntete, &$TChamps, &$TParam, $TField) { + + private function parse_array(&$THeader, &$TField, &$TParam, $TField) { $first=true; $this->THideFlip = array_flip($TParam['hide']); @@ -896,16 +591,16 @@ class Listview { foreach($TField as $row) { if($first) { - $this->init_entete($TEntete, $TParam, $row); + $this->init_entete($THeader, $TParam, $row); $first=false; } - $this->set_line($TChamps, $TParam, $row); + $this->set_line($TField, $TParam, $row); } } - private function init_entete(&$TEntete, &$TParam, $currentLine) { + private function init_entete(&$THeader, &$TParam, $currentLine) { $TField=$TFieldVisibility=array(); @@ -977,7 +672,7 @@ class Listview { if($visible) { $lastfield = $field; - $TEntete[$field] = array( + $THeader[$field] = array( 'libelle'=>$libelle ,'order'=>((in_array($field, $TParam['orderby']['noOrder']) || $this->typeRender != 'sql') ? 0 : 1) ,'width'=>(!empty($TParam['size']['width'][$field]) ? $TParam['size']['width'][$field] : 'auto') @@ -989,19 +684,15 @@ class Listview { } if(!empty($selectedfields) && !empty($lastfield)) { - $TEntete[$lastfield]['more']='
'.$selectedfields.'
'; + $THeader[$lastfield]['more']='
'.$selectedfields.'
'; } - /*if(!empty($TParam['search']) && !empty($TEntete)) { - $TEntete['actions']=array('libelle'=>'', 'order'=>0); - }*/ - } private function in_view(&$TParam, $line_number) { global $conf; -// var_dump($_REQUEST['get-all-for-export']); + if(!empty($_REQUEST['get-all-for-export'])) return true; // doit être dans la vue $page_number = !empty($TParam['limit']['page']) ? $TParam['limit']['page'] : 1; @@ -1014,11 +705,11 @@ class Listview { else return false; } - private function set_line(&$TChamps, &$TParam, $currentLine) { + private function set_line(&$TField, &$TParam, $currentLine) { global $conf; - $line_number = count($TChamps); + $line_number = count($TField); if($this->in_view($TParam,$line_number)) { @@ -1114,67 +805,7 @@ class Listview { } } } - $TChamps[] = $row; - } - - private function getBind(&$TParam) { - - $TBind = array(); - foreach($this->TBind as $k=>$v) { - if(!empty($TParam['operator'][$k]) && $TParam['operator'][$k] == 'IN') { - - if($v==='')$TBind[$k] =array("'0'"); - else $TBind[$k] =explode(',', $v); - - } - else{ - $TBind[$k] = $v; - } - - } - - return $TBind; - } - - private function getSQL(&$PDOdb,$sql,&$TParam) { - global $user,$conf; - - $sql=strtr($sql,array( - '@current_user@'=>$user->id - )); - - //AA oui c'est moche mais le bindParam ne prends pas en compte les tableaux pour le IN ce qui est super pénalisant. En attendant de refaire mieux ou d'un coup de main - $TBind = $this->getBind($TParam); - - $sql = preg_replace_callback('/(:[a-z])\w+/i',function($matches) use($TBind,$PDOdb) { - $field = substr($matches[0],1); - if(isset($TBind[$field]) || is_null($TBind[$field]) ) { - - if(is_array($TBind[$field])) { - $r = ''; - foreach($TBind[$field] as $v ){ - if(!empty($r))$r.=','; - $r.=$PDOdb->quote($v); - } - - return $r; - - } - else if(strpos($TBind[$field],' IS NULL') === false) { - return $PDOdb->quote($TBind[$field]); - } - else { - return $TBind[$field]; - } - } - else { - return 'errorBindingField '.$field; - } - - }, $sql); - - - return $sql; + $TField[] = $row; } private function limitSQL($sql,&$TParam) { @@ -1188,29 +819,26 @@ class Listview { return $sql; } - private function parse_sql(&$PDOdb, &$TEntete, &$TChamps,&$TParam, $sql, $TBind=array()) { + private function parse_sql( &$THeader, &$TField,&$TParam, $sql) { + global $db; - //$sql.=' LIMIT '.($TParam['limit']['page']*$TParam['limit']['nbLine']).','.$TParam['limit']['nbLine']; - $sql = $this->limitSQL($sql, $TParam); + $this->sql = $this->limitSQL($sql, $TParam); $this->TTotalTmp=array(); - $this->sql = $this->getSQL($PDOdb,$sql,$TParam); $this->THideFlip = array_flip($TParam['hide']); - $res = $PDOdb->Execute($this->sql); + $res = $db->query($this->sql); $first=true; - while($currentLine = $PDOdb->Get_line()) { + while($currentLine = $db->fetch_object($res)) { if($first) { - $this->init_entete($TEntete, $TParam, $currentLine); + $this->init_entete($THeader, $TParam, $currentLine); $first = false; } - $this->set_line($TChamps, $TParam, $currentLine); + $this->set_line($TField, $TParam, $currentLine); } -//pre($TChamps);exit; - } } diff --git a/htdocs/core/js/listview.js b/htdocs/core/js/listview.js new file mode 100644 index 00000000000..1157c2ef4b8 --- /dev/null +++ b/htdocs/core/js/listview.js @@ -0,0 +1,143 @@ +var TListTBS_include = true; + +function TListTBS_OrderDown(idListe, column) { + var base_url = document.location.href; + + base_url = TListTBS_recup_form_param(idListe,base_url); + base_url = TListTBS_removeParam(base_url,'TListTBS['+encodeURIComponent(idListe)+'][orderBy]'); + + base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + + document.location.href=TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","DESC"); +} +function TListTBS_OrderUp(idListe, column) { + + var base_url = document.location.href; + + base_url = TListTBS_recup_form_param(idListe,base_url); + base_url = TListTBS_removeParam(base_url,'TListTBS['+encodeURIComponent(idListe)+'][orderBy]'); + + base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + + document.location.href=TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","ASC"); +} +function TListTBS_modifyUrl(strURL,paramName,paramNewValue){ + if (strURL.indexOf(paramName+'=')!=-1){ + + var strFirstPart=strURL.substring(0,strURL.indexOf(paramName+'=',0))+paramName+'='; + var strLastPart=""; + if (strURL.indexOf('&',strFirstPart.length-1)>0) + strLastPart=strURL.substring(strURL.indexOf('&',strFirstPart.length-1),strURL.length); + strURL=strFirstPart+paramNewValue+strLastPart; + } + else{ + if (strURL.search('=')!=-1) // permet de verifier s'il y a dej� des param�tres dans l'URL + strURL+='&'+paramName+'='+paramNewValue; + else + strURL+='?'+paramName+'='+paramNewValue; + } + + return strURL; +} +function TListTBS_removeParam(strURL, paramMask) { + var cpt=0; + var url = ''; + + while(strURL.indexOf(paramMask)!=-1 && cpt++ <50){ + var strFirstPart= strURL.substring(0,strURL.indexOf(paramMask)-1); + + var strLastPart=''; + if (strURL.indexOf('&',strFirstPart.length+1)>0) { + strLastPart = strURL.substring(strURL.indexOf('&',strFirstPart.length+1),strURL.length); + } + + url = strFirstPart+strLastPart; + + } + + if(url=='')url = strURL; + + return url; +} + +function TListTBS_recup_form_param(idListe,base_url) { + + $('#'+idListe+' tr.barre-recherche [listviewtbs],#'+idListe+' tr.barre-recherche-head input,#'+idListe+' tr.barre-recherche-head select,#'+idListe+' div.tabsAction input[listviewtbs]').each(function(i,item) { + if($(item).attr("name")) { + base_url = TListTBS_modifyUrl(base_url, $(item).attr("name") , $(item).val()); + } + + }); + + return base_url; +} + +function TListTBS_GoToPage(idListe,pageNumber){ + + var base_url = document.location.href; + + base_url = TListTBS_recup_form_param(idListe,base_url); + base_url =TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][page]",pageNumber); + + base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + + document.location.href=base_url; +} +function TListTBS_submitSearch(obj) { + + $(obj).closest('form').submit(); + //console.log($(obj).closest('form')); +} +function TListTBS_launch_downloadAs(mode,url,token,session_name) { + $('#listTBSdAS_export_form').remove(); + + $form = $('
'); + $form.append(''); + $form.append(''); + $form.append(''); + + $('body').append($form); + + $('#listTBSdAS_export_form').submit(); + +} + +function TListTBS_downloadAs(obj, mode,url,token,session_name) { + + $form = $(obj).closest('form'); + $div = $form.find('div.tabsAction'); + $div.append(''); + $div.append(''); + $div.append(''); + $div.append(''); + $div.append(''); + + TListTBS_submitSearch(obj); +} + +$(document).ready(function() { + $('tr.barre-recherche input').keypress(function(e) { + if(e.which == 13) { + + var id_list = $(this).closest('table').attr('id'); + + $('#'+id_list+' .list-search-link').click(); + + } + }); + + var $_GET = {}; + + document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () { + function decode(s) { + return decodeURIComponent(s.split("+").join(" ")); + } + + $_GET[decode(arguments[1])] = decode(arguments[2]); + }); + + if(typeof $_GET["get-all-for-export"] != "undefined") { + TListTBS_launch_downloadAs($_GET["mode"],$_GET["url"],$_GET["token"],$_GET["session_name"]); + } + +}); diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index 60a8dde8652..f158ab260cf 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -61,7 +61,7 @@ class Inventory extends CoreObject */ public $title; - private $__fields=array( + protected $__fields=array( 'fk_warehouse'=>array('type'=>'integer','index'=>true) ,'entity'=>array('type'=>'integer','index'=>true) ,'status'=>array('type'=>'integer','index'=>true) @@ -69,20 +69,14 @@ class Inventory extends CoreObject ,'title'=>array('type'=>'string') ); - function __construct(&$db) + function __construct(DoliDB &$db) { $this->db = &$db; parent::init(); - $this->_init_vars(); - - $this->start(); - - $this->setChild('Inventorydet','fk_inventory'); - - $this->status = 0; + $this->status = 0; $this->entity = $conf->entity; $this->errors = array(); $this->amount = 0; @@ -94,12 +88,12 @@ class Inventory extends CoreObject usort($this->Inventorydet, array('Inventory', 'customSort')); } - function load(&$PDOdb, $id,$annexe = true) + function fetch($id,$annexe = true) { if(!$annexe) $this->withChild = false; - $res = parent::load($PDOdb, $id); + $res = parent::fetch($id); $this->sort_det(); $this->amount = 0; @@ -124,7 +118,7 @@ class Inventory extends CoreObject return $r; } - function changePMP(&$PDOdb) { + function changePMP() { foreach ($this->Inventorydet as $k => &$Inventorydet) { @@ -133,16 +127,9 @@ class Inventory extends CoreObject $Inventorydet->pmp = $Inventorydet->new_pmp; $Inventorydet->new_pmp = 0; - $PDOdb->Execute("UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$Inventorydet->pmp." + $db->query("UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$Inventorydet->pmp." WHERE rowid = ".$Inventorydet->fk_product ); - if((float)DOL_VERSION<4.0) { - - $PDOdb->Execute("UPDATE ".MAIN_DB_PREFIX."product_stock SET pmp=".$Inventorydet->pmp." - WHERE fk_entrepot = ".$this->fk_warehouse." AND fk_product = ".$Inventorydet->fk_product) ; - - } - } } @@ -150,15 +137,15 @@ class Inventory extends CoreObject } - function save(&$PDOdb) + function update() { //si on valide l'inventaire on sauvegarde le stock à cette instant if ($this->status) { - $this->regulate($PDOdb); + $this->regulate(); } - parent::save($PDOdb); + parent::update(); } function set_values($Tab) @@ -188,24 +175,24 @@ class Inventory extends CoreObject return parent::set_values($Tab); } - function deleteAllLine(&$PDOdb) { + function deleteAllLine() { foreach($this->Inventorydet as &$det) { $det->to_delete = true; } - $this->save($PDOdb); + $this->update(); $this->Inventorydet=array(); } - function add_product(&$PDOdb, $fk_product, $fk_entrepot='') { + function add_product($fk_product, $fk_entrepot='') { - $k = $this->addChild($PDOdb, 'Inventorydet'); + $k = $this->addChild('Inventorydet'); $det = &$this->Inventorydet[$k]; - $det->fk_inventory = $this->getId(); + $det->fk_inventory = $this->id; $det->fk_product = $fk_product; $det->fk_warehouse = empty($fk_entrepot) ? $this->fk_warehouse : $fk_entrepot; @@ -213,16 +200,16 @@ class Inventory extends CoreObject $date = $this->get_date('date_inventory', 'Y-m-d'); if(empty($date))$date = $this->get_date('date_cre', 'Y-m-d'); - $det->setStockDate($PDOdb, $date , $fk_entrepot); + $det->setStockDate( $date , $fk_entrepot); } - function correct_stock($fk_product, $id_entrepot, $nbpiece, $movement, $label='', $price=0, $inventorycode='') + function correct_stock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='') { global $conf, $db, $langs, $user; /* duplication method product to add datem */ - if ($id_entrepot) + if ($fk_warehouse) { $db->begin(); @@ -234,7 +221,7 @@ class Inventory extends CoreObject $datem = empty($conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT) ? dol_now() : $this->date_inventory; $movementstock=new MouvementStock($db); - $result=$movementstock->_create($user,$fk_product,$id_entrepot,$op[$movement],$movement,$price,$label,$inventorycode, $datem); + $result=$movementstock->_create($user,$fk_product,$fk_warehouse,$op[$movement],$movement,$price,$label,$inventorycode, $datem); if ($result >= 0) { @@ -252,7 +239,7 @@ class Inventory extends CoreObject } } - function regulate(&$PDOdb) + function regulate() { global $db,$user,$langs,$conf; @@ -288,10 +275,10 @@ class Inventory extends CoreObject $nbpiece = abs($Inventorydet->qty_regulated); $movement = (int) ($Inventorydet->qty_view < $Inventorydet->qty_stock); // 0 = add ; 1 = remove - $href = dol_buildpath('/inventory/inventory.php?id='.$this->getId().'&action=view', 1); + $href = dol_buildpath('/inventory/inventory.php?id='.$this->id.'&action=view', 1); if(empty($this->title)) - $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock', $href, $this->getId())); + $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock', $href, $this->id)); else $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStockWithNomInventaire', $href, $this->title)); } @@ -306,16 +293,14 @@ class Inventory extends CoreObject } static function getLink($id) { - global $langs; + global $langs,$db; - $PDOdb=new TPDOdb; + $i = new Inventory($db); + $i->fetch($id, false); - $i = new Inventory; - $i->load($PDOdb, $id, false); + $title = !empty($i->title) ? $i->title : $langs->trans('inventoryTitle').' '.$i->id; - $title = !empty($i->title) ? $i->title : $langs->trans('inventoryTitle').' '.$i->getId(); - - return ''.img_picto('','object_list.png','',0).' '.$title.''; + return ''.img_picto('','object_list.png','',0).' '.$title.''; } @@ -354,7 +339,7 @@ class Inventorydet extends CoreObject public $pa; public $new_pmp; - private $__fields=array( + protected $__fields=array( 'fk_inventory'=>array('type'=>'int') ,'fk_warehouse'=>array('type'=>'int') ,'fk_product'=>array('type'=>'int') @@ -385,11 +370,11 @@ class Inventorydet extends CoreObject } - function load(&$PDOdb, $id) + function fetch($id) { global $conf; - $res = parent::load($PDOdb, $id); + $res = parent::fetch($id); $this->load_product(); $this->fetch_current_pa(); @@ -431,9 +416,9 @@ class Inventorydet extends CoreObject AND datem<='".$date." 23:59:59' ORDER BY datem DESC LIMIT 1"; - $PDOdb->Execute($sql); + $res = $db->query($sql); - if($obj = $PDOdb->Get_line()) { + if($obj = $db->fetch_object($res)) { $last_pa = $obj->price; } @@ -467,7 +452,7 @@ class Inventorydet extends CoreObject ORDER BY datem DESC"; //echo $sql.'
'; - $PDOdb->Execute($sql); + $db->query($sql); $TMouvementStock = $PDOdb->Get_All(); $laststock = $stock; $lastpmp = $pmp; From baf1acb4fdb861bf8923f9dfc65adae22befd088 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Tue, 13 Dec 2016 09:17:43 +0100 Subject: [PATCH 04/41] debug --- htdocs/core/class/coreobject.class.php | 80 +++++++++++++++++++--- htdocs/core/class/listview.class.php | 28 +++++--- htdocs/inventory/class/inventory.class.php | 17 +++-- 3 files changed, 101 insertions(+), 24 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 7d784073412..dc52fdd9bf5 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -25,6 +25,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; class CoreObject extends CommonObject { + public $db; + protected $__fields=array(); /** * Constructor @@ -33,8 +35,6 @@ class CoreObject extends CommonObject { */ function __construct(DoliDB &$db) { - $this->db = &$db; - $this->date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? } @@ -179,27 +179,55 @@ class CoreObject extends CommonObject { return implode(',', $keys); } + private function set_vars_by_db(&$obj){ + + foreach ($this->__fields as $field=>$info) { + if($this->is_date($info)){ + if($obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00')$this->{$field} = 0; + else $this->{$field} = strtotime($obj->{$field}); + } + elseif($this->is_array($info)){ + $this->{$field} = @unserialize($obj->{$field}); + //HACK POUR LES DONNES NON UTF8 + if($this->{$field}===FALSE)@unserialize(utf8_decode($obj->{$field})); + } + elseif($this->is_int($info)){ + $this->{$field} = (int)$obj->{$field}; + } + elseif($this->is_float($info)){ + $this->{$field} = (double)$obj->{$field}; + } + elseif($this->is_null($info)){ + $val = $obj->{$field}; + // zero is not null + $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0')?null:$val); + } + else{ + $this->{$field} = $obj->{$field}; + } + + } + } + public function fetch($id, $loadChild = true) { if(empty($id)) return false; $sql = 'SELECT '.$this->get_field_list().',datec,tms - FROM '.$this->table_element.' + FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$id; - + var_dump($sql); $res = $this->db->query( $sql ); - var_dump($sql); - if($obj = $db->fetch_object($res)) { + + if($obj = $this->db->fetch_object($res)) { $this->rowid=$id; - $this->set_vars_by_db($db); + $this->set_vars_by_db($obj); $this->datec=$this->db->idate($obj->datec); $this->tms=$this->db->idate($obj->tms); - if($loadChild) $this->loadChild($db); - - $this->run_trigger($db, 'load'); + if($loadChild) $this->fetchChild(); return $this->id; } @@ -208,6 +236,38 @@ class CoreObject extends CommonObject { } } + + public function fetchChild() { + if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { + + foreach($this->childtables as &$childTable) { + + $className = ucfirst($childTable); + + $this->{$className}=array(); + + $sql = " SELECT rowid FROM ".MAIN_DB_PREFIX.$childTable." WHERE ".$this->fk_element."=".$this->rowid; + $res = $this->db->query($sql); + if($res) { + + while($obj = $db->fetch_object($res)) { + + $o=new $className($this->db); + $o->fetch($obj->rowid); + + $this->{$className}[] = $o; + + } + + } + + } + + } + + } + + public function update() { diff --git a/htdocs/core/class/listview.class.php b/htdocs/core/class/listview.class.php index 0cedad18855..8df337b699c 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/core/class/listview.class.php @@ -820,7 +820,6 @@ class Listview { } private function parse_sql( &$THeader, &$TField,&$TParam, $sql) { - global $db; $this->sql = $this->limitSQL($sql, $TParam); @@ -828,17 +827,26 @@ class Listview { $this->THideFlip = array_flip($TParam['hide']); - $res = $db->query($this->sql); - $first=true; - while($currentLine = $db->fetch_object($res)) { - if($first) { - $this->init_entete($THeader, $TParam, $currentLine); - $first = false; + $res = $this->db->query($this->sql); + if($res!==false) { + + dol_syslog(get_class($this)."::parse_sql id=".$this->id." sql=".$this->sql, LOG_DEBUG); + + $first=true; + while($currentLine = $this->db->fetch_object($res)) { + if($first) { + $this->init_entete($THeader, $TParam, $currentLine); + $first = false; + } + + $this->set_line($TField, $TParam, $currentLine); + } - $this->set_line($TField, $TParam, $currentLine); - } - + else { + dol_syslog(get_class($this)."::parse_sql id=".$this->id." sql=".$this->sql, LOG_ERR); + } + } } diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index f158ab260cf..d092a876ad2 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -69,6 +69,8 @@ class Inventory extends CoreObject ,'title'=>array('type'=>'string') ); + public $db; + function __construct(DoliDB &$db) { @@ -292,15 +294,22 @@ class Inventory extends CoreObject return 1; } + public function getNomUrl($picto = 1) { + global $langs; + + $title = !empty($this->title) ? $this->title : $langs->trans('inventoryTitle').' '.$this->id; + + return ''.($picto ? img_picto('','object_list.png','',0).' ' : '').$title.''; + + } + static function getLink($id) { global $langs,$db; $i = new Inventory($db); $i->fetch($id, false); - $title = !empty($i->title) ? $i->title : $langs->trans('inventoryTitle').' '.$i->id; - - return ''.img_picto('','object_list.png','',0).' '.$title.''; + return $i->getNomUrl(); } @@ -309,7 +318,7 @@ class Inventory extends CoreObject if($type=='All') { - $sql="SELECT i.rowid, e.label, i.date_inventory, i.fk_warehouse, i.date_cre, i.date_maj, i.status + $sql="SELECT i.rowid, e.label, i.date_inventory, i.fk_warehouse, i.datec, i.tms, i.status FROM ".MAIN_DB_PREFIX."inventory i LEFT JOIN ".MAIN_DB_PREFIX."entrepot e ON (e.rowid = i.fk_warehouse) WHERE i.entity=".(int) $conf->entity; From efc22a4cd8b8dc4b6ea9c6be07c37eba0466def6 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Tue, 13 Dec 2016 09:49:59 +0100 Subject: [PATCH 05/41] include default list conception --- htdocs/core/class/coreobject.class.php | 7 +- htdocs/core/class/listview.class.php | 159 +++++++++++++-------- htdocs/inventory/class/inventory.class.php | 11 +- 3 files changed, 113 insertions(+), 64 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index dc52fdd9bf5..96cbbb89a88 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -27,6 +27,8 @@ class CoreObject extends CommonObject { public $db; + public $withChild = true; + protected $__fields=array(); /** * Constructor @@ -216,7 +218,7 @@ class CoreObject extends CommonObject { $sql = 'SELECT '.$this->get_field_list().',datec,tms FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$id; - var_dump($sql); + $res = $this->db->query( $sql ); if($obj = $this->db->fetch_object($res)) { @@ -238,8 +240,8 @@ class CoreObject extends CommonObject { } public function fetchChild() { - if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { + if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { foreach($this->childtables as &$childTable) { $className = ucfirst($childTable); @@ -248,6 +250,7 @@ class CoreObject extends CommonObject { $sql = " SELECT rowid FROM ".MAIN_DB_PREFIX.$childTable." WHERE ".$this->fk_element."=".$this->rowid; $res = $this->db->query($sql); + if($res) { while($obj = $db->fetch_object($res)) { diff --git a/htdocs/core/class/listview.class.php b/htdocs/core/class/listview.class.php index 8df337b699c..db66f9f15a3 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/core/class/listview.class.php @@ -41,33 +41,30 @@ class Listview { if(!isset($TParam['orderby']['noOrder']))$TParam['orderby']['noOrder']=array(); if(!isset($TParam['no-select'])) $TParam['no-select'] = 1; - if(!isset($TParam['liste']))$TParam['liste']=array(); - $TParam['liste'] = array_merge(array( - 'messageNothing'=>"Il n'y a aucun élément à afficher." - ,'picto_precedent'=>'<' - ,'picto_suivant'=>'>' - ,'order_down'=>img_down() - ,'order_up'=>img_up() + if(!isset($TParam['list']))$TParam['list']=array(); + $TParam['list'] = array_merge(array( + 'messageNothing'=>$langs->trans('ListMessageNothingToShow') ,'noheader'=>0 ,'useBottomPagination'=>0 ,'image'=>'' - ,'titre'=>'Liste' + ,'title'=>$langs->trans('List') ,'orderDown'=>'' ,'orderUp'=>'' ,'id'=>$this->id - ,'picto_search'=>img_picto('Search', 'search.png') ,'head_search'=>'' ,'export'=>array() - ,'view_type'=>'' - ),$TParam['liste']); + ,'view_type'=>'' //TODO to include graph or kanban instead of list + ),$TParam['list']); + + $POSTList = GETPOST('Listview'); if(empty($TParam['limit']))$TParam['limit']=array(); - if(!empty($_REQUEST['TListTBS'][$this->id]['page'])) $TParam['limit']['page'] = $_REQUEST['TListTBS'][$this->id]['page']; + if(!empty($POSTList[$this->id]['page'])) $TParam['limit']['page'] = $POSTList[$this->id]['page']; $TParam['limit']=array_merge(array('page'=>1, 'nbLine'=>$conf->liste_limit, 'global'=>0), $TParam['limit']); - if(!empty($_REQUEST['TListTBS'][$this->id]['orderBy'])) { - $TParam['orderBy'] = $_REQUEST['TListTBS'][$this->id]['orderBy']; + if(!empty($POSTList[$this->id]['orderBy'])) { + $TParam['orderBy'] = $POSTList[$this->id]['orderBy']; } // print_r($TParam); @@ -124,9 +121,9 @@ class Listview { // Si le type de "recherche" est "calendars" on a 2 champs de transmis, [début et fin] ou [que début] ou [que fin] => un BETWEEN Sql serait utile que dans le 1er cas // donc l'utilisation des opérateur >= et <= permettent un fonctionnement générique $TSQLDate=array(); - if(!empty($value['deb'])) + if(!empty($value['start'])) { - $valueDeb = $this->dateToSQLDate($value['deb']); + $valueDeb = $this->dateToSQLDate($value['start']); if(isset($this->TBind[$sBindKey.'_start'])) // TODO can't use this in query case { @@ -137,9 +134,9 @@ class Listview { } - if(!empty($value['fin'])) + if(!empty($value['end'])) { - $valueFin = $this->dateToSQLDate($value['fin']); + $valueFin = $this->dateToSQLDate($value['end']); if(isset($this->TBind[$sBindKey.'_end'])) { // TODO can't use this in query case $this->TBind[$sBindKey.'_end'] = $valueFin; } @@ -198,7 +195,7 @@ class Listview { private function search($sql,&$TParam) { - if(!empty($_REQUEST['TListTBS'][$this->id]['search'])) { + if(!empty($_REQUEST['Listview'][$this->id]['search'])) { $sqlGROUPBY=''; if(strpos($sql,'GROUP BY')!==false) { //TODO regex list($sql, $sqlGROUPBY) = explode('GROUP BY', $sql); @@ -206,7 +203,7 @@ class Listview { if(strpos($sql,'WHERE ')===false)$sql.=' WHERE 1 '; //TODO regex - foreach($_REQUEST['TListTBS'][$this->id]['search'] as $key=>$value) + foreach($_REQUEST['Listview'][$this->id]['search'] as $key=>$value) { $TsKey = $this->getSearchKey($key, $TParam); $TsBindKey = $this->getTsBindKey($TsKey); @@ -222,7 +219,7 @@ class Listview { //if (!empty($value)) var_dump($sKey); $sBindKey = $TsBindKey[$i]; - if($allow_is_null && !empty($_REQUEST['TListTBS'][$this->id]['search_on_null'][$key])) + if($allow_is_null && !empty($_REQUEST['Listview'][$this->id]['search_on_null'][$key])) { $this->TBind[$sBindKey.'_null'] = $sKey.' IS NULL '; $TSQLMore[] = $sKey.' IS NULL '; @@ -302,31 +299,31 @@ class Listview { foreach($TParam['search'] as $key=>$param_search) { - $value = isset($_REQUEST['TListTBS'][$this->id]['search'][$key]) ? $_REQUEST['TListTBS'][$this->id]['search'][$key] : ''; + $value = isset($_REQUEST['Listview'][$this->id]['search'][$key]) ? $_REQUEST['Listview'][$this->id]['search'][$key] : ''; $typeRecherche = (is_array($param_search) && isset($param_search['recherche'])) ? $param_search['recherche'] : $param_search; if(is_array($typeRecherche)) { $typeRecherche = array(''=>' ') + $typeRecherche; - $fsearch=$form->combo('','TListTBS['.$this->id.'][search]['.$key.']', $typeRecherche,$value,0,'',' listviewtbs="combo" init-value="'.$value.'" '); + $fsearch=$form->combo('','Listview['.$this->id.'][search]['.$key.']', $typeRecherche,$value,0,'',' listviewtbs="combo" init-value="'.$value.'" '); } else if($typeRecherche==='calendar') { - $fsearch=$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); + $fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); } else if($typeRecherche==='calendars') { - $fsearch=$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.'][deb]',isset($value['deb'])?$value['deb']:'',10,10,' listviewtbs="calendars" ') - .' '.$form->calendrier('','TListTBS['.$this->id.'][search]['.$key.'][fin]',isset($value['fin'])?$value['fin']:'',10,10,' listviewtbs="calendars" '); + $fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.'][start]',isset($value['start'])?$value['start']:'',10,10,' listviewtbs="calendars" ') + .' '.$form->calendrier('','Listview['.$this->id.'][search]['.$key.'][end]',isset($value['end'])?$value['end']:'',10,10,' listviewtbs="calendars" '); } else if(is_string($typeRecherche)) { $fsearch=$TParam['search'][$key]; } else { - $fsearch=$form->texte('','TListTBS['.$this->id.'][search]['.$key.']',$value,15,255,' listviewtbs="input" '); + $fsearch=$form->texte('','Listview['.$this->id.'][search]['.$key.']',$value,15,255,' listviewtbs="input" '); } if(!empty($param_search['allow_is_null'])) { - $valueNull = isset($_REQUEST['TListTBS'][$this->id]['search_on_null'][$key]) ? 1 : 0; - $fsearch.=' '.$form->checkbox1('', 'TListTBS['.$this->id.'][search_on_null]['.$key.']',1, $valueNull,' onclick=" if($(this).is(\':checked\')){ $(this).prev().val(\'\'); }" ').img_help(1, $langs->trans('SearchOnNUllValue')); + $valueNull = isset($_REQUEST['Listview'][$this->id]['search_on_null'][$key]) ? 1 : 0; + $fsearch.=' '.$form->checkbox1('', 'Listview['.$this->id.'][search_on_null]['.$key.']',1, $valueNull,' onclick=" if($(this).is(\':checked\')){ $(this).prev().val(\'\'); }" ').img_help(1, $langs->trans('SearchOnNUllValue')); } @@ -342,7 +339,7 @@ class Listview { } - $search_button = ' '.$TParam['liste']['picto_search'].''; + $search_button = ' '.$TParam['liste']['picto_search'].''; if(!empty($TParam['liste']['head_search'])) { $TParam['liste']['head_search'].='
'.$langs->trans('Search').' '.$search_button.'
'; @@ -519,22 +516,77 @@ class Listview { $TExport=$this->setExport($TParam, $TField, $THeader); $TField = $this->addTotalGroup($TField,$TTotalGroup); - var_dump( - array( - 'entete'=>$THeader - ,'champs'=>$TField - ,'recherche'=>$TSearch - ,'total'=>$TTotal - ,'export'=>$TExport - ) - , array( - 'liste'=>array_merge(array('haveExport'=>count($TExport), 'id'=>$this->id, 'nb_columns'=>count($THeader) ,'totalNB'=>count($TField), 'nbSearch'=>count($TSearch), 'haveTotal'=>(int)!empty($TTotal), 'havePage'=>(int)!empty($TPagination) ), $TParam['liste']) - ) - , $TPagination - - ); + $out = $javaScript; - $javaScript; + $out.=load_fiche_titre($TParam['list']['title']); + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, count($TField), 'title_products.png', 0, '', '', $limit); + /* + $out.=' + + [onshow;block=begin; when [liste.noheader]==0] + + + [onshow;block=end] + + +
+ [liste.image;magnet=img; strconv=no] +
[liste.titre; strconv=no]
+ +
+ + + + + + + + + + + [onshow;block=tr;when [liste.nbSearch]+-0] + + + + + + + + + + + + + + + + + [onshow;block=tr; when [liste.haveTotal]+-0 ] + + + + +
[liste.head_search;strconv=no;magnet=tr]
[entete.libelle;block=th;strconv=no] + [onshow;block=span; when [entete.order]==1][liste.order_down;strconv=no][liste.order_up;strconv=no] + [entete.more;strconv=no;] +
[recherche.val;block=td;strconv=no]
[champs_sub1.val;block=td; strconv=no]
[champs_sub1.val;block=td; strconv=no]
[total.val;block=td;strconv=no;frm=0 000,00]
+ +
+ [onshow;block=div; when [liste.haveExport]+-0 ] + [export.label;block=a;] +
+

+ [liste.messageNothing;strconv=no] [onshow; block=p; when [liste.totalNB]==0] +

';*/ } public function renderArray(&$db,$TField, $TParam=array()) { @@ -611,14 +663,14 @@ class Listview { global $user; $contextpage=md5($_SERVER['PHP_SELF']); - if((float)DOL_VERSION>=4.0 && empty($TParam['no-select'])) { + if(empty($TParam['no-select'])) { dol_include_once('/core/class/html.form.class.php'); global $db,$conf,$user; $form=new Form($db); - $selectedfields = GETPOST('TListTBS_'.$this->id.'_selectedfields'); + $selectedfields = GETPOST('Listview'.$this->id.'_selectedfields'); if(!empty($selectedfields)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; @@ -662,7 +714,7 @@ class Listview { } } - $selectedfields=$form->multiSelectArrayWithCheckbox('TListTBS_'.$this->id.'_selectedfields', $TFieldVisibility, $contextpage); // This also change content of $arrayfields_0 + $selectedfields=$form->multiSelectArrayWithCheckbox('Listview'.$this->id.'_selectedfields', $TFieldVisibility, $contextpage); // This also change content of $arrayfields_0 } @@ -721,17 +773,6 @@ class Listview { else $value=(string)$value; } - if(isset($TParam['subQuery'][$field])) { - $dbSub = new TPDOdb; //TODO finish it - $dbSub->Execute( strtr($TParam['subQuery'][$field], array_merge( $trans, array('@val@'=>$value) )) ); - $subResult = ''; - while($dbSub->Get_line()) { - $subResult.= implode(', ',$dbSub->currentLine).'
'; - } - $value=$subResult; - $dbSub->close(); - } - $trans['@'.$field.'@'] = $value; if(!empty($TParam['math'][$field])) { diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index d092a876ad2..59ad70cec4e 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -87,7 +87,8 @@ class Inventory extends CoreObject function sort_det() { - usort($this->Inventorydet, array('Inventory', 'customSort')); + + if(!empty($this->Inventorydet)) usort($this->Inventorydet, array('Inventory', 'customSort')); } function fetch($id,$annexe = true) @@ -99,8 +100,12 @@ class Inventory extends CoreObject $this->sort_det(); $this->amount = 0; - foreach($this->Inventorydet as &$det){ - $this->amount+=$det->qty_view * $det->pmp; + + if(!empty($this->Inventorydet )) { + foreach($this->Inventorydet as &$det){ + $this->amount+=$det->qty_view * $det->pmp; + } + } return $res; From a636d27ccbfc1e5ea59862af1d7e909b382ffff7 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Wed, 14 Dec 2016 14:34:12 +0100 Subject: [PATCH 06/41] Div --- htdocs/core/class/coreobject.class.php | 22 +- htdocs/core/class/listview.class.php | 144 ++-- htdocs/core/lib/functions.lib.php | 114 ++- htdocs/inventory/class/inventory.class.php | 24 +- htdocs/inventory/img/inventory.png | Bin 0 -> 1802 bytes htdocs/inventory/inventory.php | 797 +++++++++++++++++++++ htdocs/inventory/lib/inventory.lib.php | 245 +++++++ htdocs/inventory/tpl/inventory.tpl.php | 211 ++++++ 8 files changed, 1433 insertions(+), 124 deletions(-) create mode 100644 htdocs/inventory/img/inventory.png create mode 100644 htdocs/inventory/inventory.php create mode 100644 htdocs/inventory/lib/inventory.lib.php create mode 100644 htdocs/inventory/tpl/inventory.tpl.php diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 96cbbb89a88..b7e4b2770e3 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -1,5 +1,7 @@ +/* EXPERIMENTAL + * + * Copyright (C) 2016 ATM Consulting * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -220,9 +222,8 @@ class CoreObject extends CommonObject { WHERE rowid='.$id; $res = $this->db->query( $sql ); - if($obj = $this->db->fetch_object($res)) { - $this->rowid=$id; + $this->id=$id; $this->set_vars_by_db($obj); @@ -248,12 +249,12 @@ class CoreObject extends CommonObject { $this->{$className}=array(); - $sql = " SELECT rowid FROM ".MAIN_DB_PREFIX.$childTable." WHERE ".$this->fk_element."=".$this->rowid; + $sql = " SELECT rowid FROM ".MAIN_DB_PREFIX.$childTable." WHERE ".$this->fk_element."=".$this->id; $res = $this->db->query($sql); if($res) { - - while($obj = $db->fetch_object($res)) { + $Tab=array(); + while($obj = $this->db->fetch_object($res)) { $o=new $className($this->db); $o->fetch($obj->rowid); @@ -282,5 +283,14 @@ class CoreObject extends CommonObject { } + public function get_date($field,$format='') { + if(empty($this->{$field})) return ''; + elseif($this->{$field}<=strtotime('1000-01-01 00:00:00')) return ''; + else { + return dol_print_date($this->{$field}, $format); + } + + } + } diff --git a/htdocs/core/class/listview.class.php b/htdocs/core/class/listview.class.php index db66f9f15a3..e94a648ec27 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/core/class/listview.class.php @@ -1,7 +1,8 @@ + Copyright (C) 2016 ATM Consulting This program and all files within this directory and sub directory is free software: you can redistribute it and/or modify it under @@ -505,88 +506,91 @@ class Listview { } private function renderList(&$THeader, &$TField, &$TTotal,&$TTotalGroup, &$TParam) { - + $javaScript = $this->getJS($TParam); - $TPagination=array( + /*$TPagination=array( 'pagination'=>array('pageSize'=>$TParam['limit']['nbLine'], 'pageNum'=>$TParam['limit']['page'], 'blockName'=>'champs', 'totalNB'=>count($TField)) - ); + );*/ $TSearch = $this->setSearch($THeader, $TParam); $TExport=$this->setExport($TParam, $TField, $THeader); $TField = $this->addTotalGroup($TField,$TTotalGroup); $out = $javaScript; + $out.=load_fiche_titre($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $TParam['limit']['page'], count($TField), 'title_products.png', 0, '', '', $limit); + $out.=' + '; - $out.=load_fiche_titre($TParam['list']['title']); - print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, count($TField), 'title_products.png', 0, '', '', $limit); - /* - $out.='
- - [onshow;block=begin; when [liste.noheader]==0] - - - [onshow;block=end] - - -
- [liste.image;magnet=img; strconv=no] -
[liste.titre; strconv=no]
- -
+ if(!empty($TParam['liste']['head_search'])) { + $out.=' + '.$TParam['liste']['head_search'].' + '; + } + + $out.=''; - - - - - - - - + foreach($THeader as $head) { + $out.=''; + } + + $out.=''; + + if(!empty($TParam['liste']['nbSearch'])) { + $out.=' + + '; + } - [onshow;block=tr;when [liste.nbSearch]+-0] - - - - - - - - - - - - - - - - - [onshow;block=tr; when [liste.haveTotal]+-0 ] - - - - -
[liste.head_search;strconv=no;magnet=tr]
[entete.libelle;block=th;strconv=no] - [onshow;block=span; when [entete.order]==1][liste.order_down;strconv=no][liste.order_up;strconv=no] - [entete.more;strconv=no;] -
'.$head['libelle']; + + if($head['order']) $out.='[onshow;block=span; when [entete.order]==1]'.img_down().' + '.img_up().''; + + $out.=$head['more']; + $out.='
'.img_search().'
[recherche.val;block=td;strconv=no]
[champs_sub1.val;block=td; strconv=no]
[champs_sub1.val;block=td; strconv=no]
[total.val;block=td;strconv=no;frm=0 000,00]
+ $out.=''; -
- [onshow;block=div; when [liste.haveExport]+-0 ] - [export.label;block=a;] -
-

- [liste.messageNothing;strconv=no] [onshow; block=p; when [liste.totalNB]==0] -

';*/ + $class='pair'; + + if(empty($TField)) { + $out.=' + '.$TParam['liste']['messageNothing'].''; + + } + else{ + + foreach($TField as $fields) { //TODO pagination limit + + $class = ($class=='pair') ? 'impair' : 'pair'; + $out.=' '; + + foreach($fields as $field=>$value) { + $out.=''.$value.''; + } + + $out.=''; + + } + + $out.=''; + + if(!empty($TParam['liste']['haveTotal'])) { + $out.=' + '; + + foreach($TTotal as $field=>$total) { + $out.=''.price($total).''; + } + + $out.=''; + } + + } + + + $out.=''; + + return $out; } public function renderArray(&$db,$TField, $TParam=array()) { diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 082177b5cbc..c4b21e4ee82 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3157,7 +3157,7 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', } /** - * Print a title with navigation controls for pagination + * return a title with navigation controls for pagination * * @param string $titre Title to show (required) * @param int $page Numero of page to show in navigation links (required) @@ -3176,7 +3176,7 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', * @param int $hideselectlimit Force to hide select limit * @return void */ -function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=-1, $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0) +function load_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=-1, $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0) { global $conf,$langs; @@ -3196,27 +3196,26 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so $nextpage = 0; } //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage; - - print "\n"; - print "\n"; - print ''; + $out = "\n"; + $out.= "\n"; + $out.='
'; // Left - //if ($picto && $titre) print ''; - print ''; + //if ($picto && $titre) $out.=''; + $out.=''; // Center if ($center) { - print ''; + $out.=''; } // Right - print ''; + $out.=load_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtml, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist + $out.=''; - print '
'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).''; - if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle" id="pictotitle"', $pictoisfullpath); - print '
'.$titre; - if (!empty($titre) && $savtotalnboflines >= 0) print ' ('.$totalnboflines.')'; - print '
'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).''; + if ($picto && $titre) $out.=img_picto('', $picto, 'class="hideonsmartphone valignmiddle" id="pictotitle"', $pictoisfullpath); + $out.='
'.$titre; + if (!empty($titre) && $savtotalnboflines >= 0) $out.=' ('.$totalnboflines.')'; + $out.='
'.$center.''.$center.''; + $out.=''; if ($sortfield) $options .= "&sortfield=".$sortfield; if ($sortorder) $options .= "&sortorder=".$sortorder; // Show navigation bar @@ -3265,15 +3264,39 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'class="active"':'data-role="button"').'>'.($page+1).""; } } - print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtml, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist - print '
'."\n"; - print "\n\n"; + $out.=''."\n"; + $out.="\n\n"; +} +/** + * Print a title with navigation controls for pagination + * + * @param string $titre Title to show (required) + * @param int $page Numero of page to show in navigation links (required) + * @param string $file Url of page (required) + * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder) + * @param string $sortfield Field to sort on ('' by default) + * @param string $sortorder Order to sort ('' by default) + * @param string $center String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction() + * @param int $num Number of records found by select with limit+1 + * @param int $totalnboflines Total number of records/lines for all pages (if known). Use a negative value to not show number. + * @param string $picto Icon to use before title (should be a 32x32 transparent png file) + * @param int $pictoisfullpath 1=Icon name is a full absolute url of image + * @param string $morehtml More html to show + * @param string $morecss More css to the table + * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit). + * @param int $hideselectlimit Force to hide select limit + * @return void + */ +function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=-1, $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0) +{ + echo load_barre_liste($titre, $page, $file, $options, $sortfield, $sortorder, $center, $num, $totalnboflines, $picto, $pictoisfullpath, $morehtml, $morecss, $limit, $hideselectlimit); } /** - * Function to show navigation arrows into lists + * Function to return navigation arrows into lists * * @param int $page Number of page * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"]) @@ -3286,11 +3309,11 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so * @param int $hideselectlimit Force to hide select limit * @return void */ -function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0) +function load_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0) { global $conf, $langs; - print ''."\n"; +} +/** + * Function to show navigation arrows into lists + * + * @param int $page Number of page + * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"]) + * @param string $options Other url paramaters to propagate ("" by default, may include sortfield and sortorder) + * @param integer $nextpage Do we show a next page button + * @param string $betweenarrows HTML content to show between arrows. MUST contains '
  • ' tags or '
  • '. + * @param string $afterarrows HTML content to show after arrows. Must NOT contains '
  • ' tags. + * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit) + * @param int $totalnboflines Total number of records/lines for all pages (if known) + * @param int $hideselectlimit Force to hide select limit + * @return void + */ +function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0) +{ + echo load_fleche_navigation($page, $file, $options, $nextpage, $betweenarrows, $afterarrows, $limit, $totalnboflines, $hideselectlimit); } - /** * Return a string with VAT rate label formated for view output diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index 59ad70cec4e..2a485d24a0a 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -97,17 +97,20 @@ class Inventory extends CoreObject if(!$annexe) $this->withChild = false; $res = parent::fetch($id); - $this->sort_det(); - $this->amount = 0; - - if(!empty($this->Inventorydet )) { - foreach($this->Inventorydet as &$det){ - $this->amount+=$det->qty_view * $det->pmp; - } + if($res>0) { + $this->sort_det(); + $this->amount = 0; + + if(!empty($this->Inventorydet )) { + foreach($this->Inventorydet as &$det){ + $this->amount+=$det->qty_view * $det->pmp; + } + + } } - + return $res; } @@ -312,9 +315,8 @@ class Inventory extends CoreObject global $langs,$db; $i = new Inventory($db); - $i->fetch($id, false); - - return $i->getNomUrl(); + if($i->fetch($id, false)>0) return $i->getNomUrl(); + else return $langs->trans('InventoryUnableToFetchObject'); } diff --git a/htdocs/inventory/img/inventory.png b/htdocs/inventory/img/inventory.png new file mode 100644 index 0000000000000000000000000000000000000000..e54ad0eef7d76b373e8769153f9039a75681ab3b GIT binary patch literal 1802 zcmZ{lX*3(?9>&822~viNsg4qwu~r48mJ=dMOk>Y2Wo%QL#J&qgL@l*c2PvXOtG0v| z4HeOr1QSB3-7rPaP%cHabz5~!I^XVx`~KhO|2yw<&hza#=goC>c7RB$NCN->h$F_% zT}1V70!fN?Y;y7k5rBA<6AA#B1HNX?i;Lcpzg~8*0~~*w2QM0^A_p9Wxf&}X<{#Pf zLy_OigeVkVMD>4k^GijgD5~jbhr)UFO?witIQ+@fjF~H?I=(pFT357=t^NZij3WFj zFYi*ZDNk*}F1=R8%p{L^x47^pp%luFfIw(t>h!td?kG@`R{#YB!ivq=Nfrj%T+I%a zjChs0Jcq(_7*6-de11yg^~Jw;gFK?Q}3f4MRkp824f@t zrkvVOaR~`kL?UsIop#*qk(9)q{v%&`WMXpiIH_i~*;lc*uP?Z~ynM~!_cN)i?r!AX z-s*sfp`lG`YU<<*uZ4w$L^Ugt{L<^!zjf8uueGhLtjKw|yDvIpv3FKe&HYb-!Ql5z zo-ISmDBeAi-?Ox1^70!#l?Se^ub0+xt{^ovHR+L~qFN<+%c&R6aR)&K05lq%xpP5% zHh*bGTq&EfwEHiy-lE&LZ-*Xi&0VXoiHTtfR#)4=K$V7uhTQ6L0>;=FeV3tgSG*su z$l2LNg7Ct33(r(9w%dEUxfKb7LgCcn;-VE2=?sBDrfPBSXumTI3V+;<3O1wxVu;dy zHvM_lO7e1Z!r`*uy}dnqu&kWiWaUfj=IG#qi3jSNEiK2xnrRt;bp;Il{4brYo^(3> z;?djj8e>-E5_z3haQe#h^fVL>hhGM(j|#K0rsSdapNoo2D6}5kbRLg)#ovF)C6h*@ z`Ma%q#K*_yr5wBy_L8tfBEy(@d@7yKcMJ&+uY+a^`4=VzW4(g5+`B24%hMN{$UG!&<3#Oc$YSWcT#vb6^ zK=tcgIXNI``Yeqi+uFfo&d0wUtM)fCGUBBK$mW`XT25-}*K9F0NObn|iaeLfhkiJ& z>&VHr(ZGxv=sKv-W~cPYz+29g8D<(uY** zk~EP848cK2Xy{+8h=t7vjMSfSwTqUPX{u1@70BaR6uX~RQd%;;uob2&QS{^qf(pi* z5gax)HinR1FAKOCk{1SLz3}1TN1vZu8;B_^v>^l9;`h9CGx_ath8jtFEr@ zF^k1=gPlajycsN7)#hI%h*uxxp5-Z1U7Ds17_#UwYj*AFd>|PwZke#<)d3qCo9jlO zDEzrj0|!F2(|daES0Ph%6E2zldTVfBYj#IMPa!HXaeeso#iRIkzi7>Oq>_>noU5x% zVYoB|5{&rXY-%G;oh-*wDdgXlnvK$P?9vM zHqsuwYCq44R1=kFTw7)G>({R`z$&xRyhfLR!%y4U-~dgSsp$;F=+O#we{Dj?TuRgm zP_W&fnO0U-ASKQ0+_Y;sl%NXk0Z8~B*oj1ZN6vL>_z1=bMwV6I9~@})7l(y~ft1i& z=iC}U-nwkAUL+8coOFl2e8g&NGcHUra;pf+Ibc1nMv8U+EWrQwOqGU~mR2tXwwZ+# zGu16x!#8VSy(^oWo5k{b4_0DgV-*$UGuGqD>0o`)K^UZ4<1@A(Sl2sLDq4Saf?roG zr0yf%p6>(AnQuk1=w|1e>2z(e<^{lkXY9l|2b=q#)3&2ICFwH;D#GttLt@~81h{N1 ze0SHuux*I2r^y8d9URi6j9d?OW%az@WD@%2KPcWoAP}%mDc#KL0rf!}!V{Q5y$Eh; z=**+5(Yh>P2dsnZ%0YSuI@*00E_7^7W+t=}U~28r(a{4>b~ejC`*6xTRe&9+?0eDD z;SLT1k6@hbwjaEIi0$;};8#9mdMl&3NgSDNU)3Lf+^Si+QRYh~lW(xupHmDB3>pfb zA{2JR^D|(RXnzYg&)}|wV>r|n~!*{-=s((QAPs}89mf@}7sI@T| z@7dP&c8@LVaBX+FFM51@yeF_L&tArFXJdo-zQ?3I*Xt>!VxOS;N|`f2(cJx#_EGAu zmtGr3VC=0Ono$eIRP=Aa<1Tr{1qH?hTU?6?76D*nXlQ;;bP>ilgt3K@sfCHDo}rP2 kp`jGvVekJ0!Xtx-*OUH#AmM@vSrh;`UUIf;whg%PHyWxmfdBvi literal 0 HcmV?d00001 diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php new file mode 100644 index 00000000000..d46f05059b4 --- /dev/null +++ b/htdocs/inventory/inventory.php @@ -0,0 +1,797 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/inventory/inventory.php + * \ingroup product + * \brief File of class to manage inventory + */ + +require_once '../main.inc.php'; + +ini_set('memory_limit', '512M'); + +require_once DOL_DOCUMENT_ROOT.'/core/class/listview.class.php'; +require_once DOL_DOCUMENT_ROOT.'/inventory/class/inventory.class.php'; +require_once DOL_DOCUMENT_ROOT.'/inventory/lib/inventory.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + +set_time_limit(0); + +if(!$user->rights->inventory->read) accessforbidden(); + +$langs->load("inventory"); + +_action(); + +function _action() +{ + global $user, $db, $conf, $langs; + + /******************************************************************* + * ACTIONS + * + * Put here all code to do according to value of "action" parameter + ********************************************************************/ + + $action=GETPOST('action'); + + switch($action) { + case 'list': + _list(); + + break; + + case 'create': + if (!$user->rights->inventory->create) accessforbidden(); + + $inventory = new Inventory($db); + + _fiche_warehouse($user, $db, $conf, $langs, $inventory); + + break; + + case 'confirmCreate': + if (!$user->rights->inventory->create) accessforbidden(); + + + $inventory = new Inventory($db); + $inventory->set_values($_REQUEST); + + $fk_inventory = $inventory->save(); + $fk_category = (int)GETPOST('fk_category'); + $fk_supplier = (int)GETPOST('fk_supplier'); + $fk_warehouse = (int)GETPOST('fk_warehouse'); + $only_prods_in_stock = (int)GETPOST('OnlyProdsInStock'); + + $e = new Entrepot($db); + $e->fetch($fk_warehouse); + $TChildWarehouses = array($fk_warehouse); + if(method_exists($e, 'get_children_warehouses')) $e->get_children_warehouses($fk_warehouse, $TChildWarehouses); + + $sql = 'SELECT ps.fk_product, ps.fk_entrepot + FROM '.MAIN_DB_PREFIX.'product_stock ps + INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = ps.fk_product) + LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product cp ON (cp.fk_product = p.rowid) + LEFT JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid) + WHERE ps.fk_entrepot IN ('.implode(', ', $TChildWarehouses).')'; + + if($fk_category>0) $sql.= " AND cp.fk_categorie=".$fk_category; + if($fk_supplier>0) $sql.= " AND pfp.fk_soc=".$fk_supplier; + if($only_prods_in_stock>0) $sql.= ' AND ps.reel > 0'; + + $sql.=' GROUP BY ps.fk_product, ps.fk_entrepot + ORDER BY p.ref ASC,p.label ASC'; + + + $Tab = $PDOdb->ExecuteAsArray($sql); + + foreach($Tab as &$row) { + + $inventory->add_product($PDOdb, $row->fk_product, $row->fk_entrepot); + } + + $inventory->save($PDOdb); + + header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->getId().'&action=edit', 1)); + + case 'edit': + if (!$user->rights->inventory->write) accessforbidden(); + + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, __get('action', 'edit', 'string')); + + break; + + case 'save': + if (!$user->rights->inventory->write) accessforbidden(); + + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + $inventory->set_values($_REQUEST); + + if ($inventory->errors) + { + setEventMessage($inventory->errors, 'errors'); + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + } + else + { + $inventory->save($PDOdb); + header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->getId().'&action=view', 1)); + } + + break; + + case 'regulate': + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + if($inventory->status == 0) { + $inventory->status = 1; + $inventory->save($PDOdb); + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + + + } + else { + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + } + + break; + + case 'changePMP': + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + $inventory->changePMP($PDOdb); + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + + break; + + case 'add_line': + if (!$user->rights->inventory->write) accessforbidden(); + + + $id = __get('id', 0, 'int'); + $fk_warehouse = __get('fk_warehouse', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + $type = (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT) ? 'string' : 'int'); //AA heu ? + + $fk_product = __get('fk_product', 0, $type); + + if ($fk_product) + { + $product = new Product($db); + $product->fetch($fk_product); // ! ref TODO vérifier quand même + if($product->type != 0) { + setEventMessage($langs->trans('ThisIsNotAProduct'),'errors'); + } + else{ + + //Check product not already exists + $alreadyExists = false; + foreach ($inventory->Inventorydet as $invdet) + { + if ($invdet->fk_product == $product->id + && $invdet->fk_warehouse == $fk_warehouse) + { + $alreadyExists = true; + break; + } + } + + if (!$alreadyExists) + { + $inventory->add_product($PDOdb, $product->id, $fk_warehouse); + + } + else + { + setEventMessage($langs->trans('inventoryWarningProductAlreadyExists'), 'warnings'); + } + + } + + $inventory->save($PDOdb); + $inventory->sort_det(); + } + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + + break; + + case 'delete_line': + if (!$user->rights->inventory->write) accessforbidden(); + + + //Cette action devrais se faire uniquement si le status de l'inventaire est à 0 mais aucune vérif + $rowid = __get('rowid', 0, 'int'); + $Inventorydet = new Inventory($db); + $Inventorydet->load($PDOdb, $rowid); + $Inventorydet->delete($PDOdb); + + $id = __get('id', 0, 'int'); + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + + break; + case 'flush': + if (!$user->rights->inventory->create) accessforbidden(); + + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + $inventory->deleteAllLine($PDOdb); + + setEventMessage('Inventaire vidé'); + + _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + + + break; + case 'delete': + if (!$user->rights->inventory->create) accessforbidden(); + + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + $inventory->delete($PDOdb); + + header('Location: '.dol_buildpath('/inventory/inventory.php', 1)); + exit; + //_list(); + + case 'printDoc': + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + generateODT($PDOdb, $db, $conf, $langs, $inventory); + break; + + case 'exportCSV': + + $id = __get('id', 0, 'int'); + + $inventory = new Inventory($db); + $inventory->load($PDOdb, $id); + + exportCSV($inventory); + + exit; + break; + + default: + if (!$user->rights->inventory->write) accessforbidden(); + + $id = GETPOST('id'); + + $inventory = new Inventory($db); + $inventory->fetch($id); + + _card($inventory, $action ); + + + break; + } + +} + +function _list() +{ + + global $db, $conf, $langs, $user; + + llxHeader('',$langs->trans('inventoryListTitle'),'',''); + + $inventory = new Inventory($db); + $l = new ListView($db,'listInventory'); + + $THide = array('label'); + + echo $l->render(Inventory::getSQL('All'), array( + 'limit'=>array( + 'nbLine'=>'30' + ) + ,'subQuery'=>array() + ,'link'=>array( + 'fk_warehouse'=>''.img_picto('','object_stock.png','',0).' @label@' + ) + ,'translate'=>array() + ,'hide'=>$THide + ,'type'=>array( + 'date_cre'=>'date' + ,'date_maj'=>'datetime' + ,'date_inventory'=>'date' + ) + ,'liste'=>array( + 'titre'=>$langs->trans('inventoryListTitle') + ,'image'=>img_picto('','title.png', '', 0) + ,'picto_precedent'=>img_picto('','back.png', '', 0) + ,'picto_suivant'=>img_picto('','next.png', '', 0) + ,'noheader'=> (int)isset($_REQUEST['fk_soc']) | (int)isset($_REQUEST['fk_product']) + ,'messageNothing'=>$langs->trans('inventoryListEmpty') + ,'picto_search'=>img_picto('','search.png', '', 0) + ) + ,'title'=>array( + 'rowid'=>$langs->trans('Title') + ,'fk_warehouse'=>$langs->trans('Warehouse') + ,'date_inventory'=>$langs->trans('InventoryDate') + ,'datec'=>$langs->trans('DateCreation') + ,'tms'=>$langs->trans('DateUpdate') + ,'status'=>$langs->trans('Status') + ) + ,'eval'=>array( + 'status' => '(@val@ ? img_picto("'.$langs->trans("inventoryValidate").'", "statut4") : img_picto("'.$langs->trans("inventoryDraft").'", "statut3"))' + ,'rowid'=>'Inventory::getLink(@val@)' + + ) + )); + + + if ($user->rights->inventory->create) + { + print '
    '; + print ''.$langs->trans('inventoryCreate').''; + print '
    '; + } + + llxFooter(''); +} + +function _fiche_warehouse(&$PDOdb, &$user, &$db, &$conf, $langs, $inventory) +{ + dol_include_once('/categories/class/categorie.class.php'); + + llxHeader('',$langs->trans('inventorySelectWarehouse'),'',''); + print dol_get_fiche_head(inventoryPrepareHead($inventory)); + + $form=new TFormCore('inventory.php', 'confirmCreate'); + print $form->hidden('action', 'confirmCreate'); + $form->Set_typeaff('edit'); + + $formproduct = new FormProduct($db); + $formDoli = new Form($db); + + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    trans('Title') ?>texte('', 'title', '',50,255) ?>
    trans('Date') ?>calendrier('', 'date_inventory',time()) ?>
    trans('inventorySelectWarehouse') ?>selectWarehouses('', 'fk_warehouse') ?>
    trans('SelectCategory') ?>select_all_categories(0,'', 'fk_category') ?>
    trans('SelectFournisseur') ?>select_thirdparty('','fk_supplier','s.fournisseur = 1') ?>
    trans('OnlyProdsInStock') ?>
    + '; + print ''; + print ''; + + print $form->end_form(); + llxFooter(''); +} + +function _card(&$inventory, $mode='edit') +{ + global $langs, $conf, $db, $user; + + llxHeader('',$langs->trans('inventoryEdit'),'',''); + + $warehouse = new Entrepot($db); + $warehouse->fetch($inventory->fk_warehouse); + + print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), '&action='.$mode)); + + $lines = array(); + _card_line($inventory, $lines, $form); + + print ''.$langs->trans('inventoryOnDate')." ".$inventory->get_date('date_inventory').'

    '; + + $inventoryTPL = array( + 'id'=> $inventory->id + ,'date_cre' => $inventory->get_date('date_cre', 'd/m/Y') + ,'date_maj' => $inventory->get_date('date_maj', 'd/m/Y H:i') + ,'fk_warehouse' => $inventory->fk_warehouse + ,'status' => $inventory->status + ,'entity' => $inventory->entity + ,'amount' => price( round($inventory->amount,2) ) + ,'amount_actual'=>price (round($inventory->amount_actual,2)) + + ); + + $can_validate = !empty($user->rights->inventory->validate); + $view_url = dol_buildpath('/inventory/inventory.php', 1); + + $view = array( + 'mode' => $mode + ,'url' => dol_buildpath('/inventory/inventory.php', 1) + ,'can_validate' => (int) $user->rights->inventory->validate + ,'is_already_validate' => (int) $inventory->status + ,'token'=>$_SESSION['newtoken'] + ); + + include './tpl/inventory.tpl.php'; + + llxFooter(''); +} + + +function _card_line(&$inventory, &$lines, &$form) +{ + global $db; + $inventory->amount_actual = 0; + + $TCacheEntrepot = array(); + + foreach ($inventory->Inventorydet as $k => $Inventorydet) + { + + $product = & $Inventorydet->product; + $stock = $Inventorydet->qty_stock; + + $pmp = $Inventorydet->pmp; + $pmp_actual = $pmp * $stock; + $inventory->amount_actual+=$pmp_actual; + + $last_pa = $Inventorydet->pa; + $current_pa = $Inventorydet->current_pa; + + $e = new Entrepot($db); + if(!empty($TCacheEntrepot[$Inventorydet->fk_warehouse])) $e = $TCacheEntrepot[$Inventorydet->fk_warehouse]; + elseif($e->fetch($Inventorydet->fk_warehouse) > 0) $TCacheEntrepot[$e->id] = $e; + + $lines[]=array( + 'produit' => $product->getNomUrl(1).' - '.$product->label + ,'entrepot'=>$e->getNomUrl(1) + ,'barcode' => $product->barcode + /*,'qty' => $form->texte('', 'qty_to_add['.$k.']', (isset($_REQUEST['qty_to_add'][$k]) ? $_REQUEST['qty_to_add'][$k] : 0), 8, 0, "style='text-align:center;'") + .($form->type_aff!='view' ? ''.img_picto('Ajouter', 'plus16@inventory').'' : '') + ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 + ,'qty_stock' => $stock + ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 + ,'action' => $user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '' + ,'pmp_stock'=>round($pmp_actual,2) + ,'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2) + ,'pmp_new'=>(!empty($user->rights->inventory->changePMP) ? $form->texte('', 'new_pmp['.$k.']',$Inventorydet->new_pmp, 8, 0, "style='text-align:right;'") + .($form->type_aff!='view' ? ''.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : '') : '' ) + */,'pa_stock'=>round($last_pa * $stock,2) + ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2) + ,'current_pa_stock'=>round($current_pa * $stock,2) + ,'current_pa_actual'=>round($current_pa * $Inventorydet->qty_view,2) + + ,'k'=>$k + ,'id'=>$Inventorydet->id + + ); + } + +} + +function exportCSV(&$inventory) { + global $conf; + + header('Content-Type: application/octet-stream'); + header('Content-disposition: attachment; filename=inventory-'. $inventory->getId().'-'.date('Ymd-His').'.csv'); + header('Pragma: no-cache'); + header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); + header('Expires: 0'); + + echo 'Ref;Label;barcode;qty theorique;PMP;dernier PA;'; + if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) echo 'PA courant;'; + echo 'qty réelle;PMP;dernier PA;'; + if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) echo 'PA courant;'; + echo 'qty regulée;'."\r\n"; + + foreach ($inventory->Inventorydet as $k => $Inventorydet) + { + $product = & $Inventorydet->product; + $stock = $Inventorydet->qty_stock; + + $pmp = $Inventorydet->pmp; + $pmp_actual = $pmp * $stock; + $inventory->amount_actual+=$pmp_actual; + + $last_pa = $Inventorydet->pa; + $current_pa = $Inventorydet->current_pa; + + if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) { + $row=array( + 'produit' => $product->ref + ,'label'=>$product->label + ,'barcode' => $product->barcode + ,'qty_stock' => $stock + ,'pmp_stock'=>round($pmp_actual,2) + ,'pa_stock'=>round($last_pa * $stock,2) + ,'current_pa_stock'=>round($current_pa * $stock,2) + ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 + ,'pmp_actual'=>round($pmp * $Inventorydet->qty_view,2) + ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2) + ,'current_pa_actual'=>round($current_pa * $Inventorydet->qty_view,2) + ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 + + ); + + } + else{ + $row=array( + 'produit' => $product->ref + ,'label'=>$product->label + ,'barcode' => $product->barcode + ,'qty_stock' => $stock + ,'pmp_stock'=>round($pmp_actual,2) + ,'pa_stock'=>round($last_pa * $stock,2) + ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 + ,'pmp_actual'=>round($pmp * $Inventorydet->qty_view,2) + ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2) + + ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 + + ); + + } + + + echo '"'.implode('";"', $row).'"'."\r\n"; + + } + + exit; +} + +function generateODT(&$PDOdb, &$db, &$conf, &$langs, &$inventory) +{ + $TBS=new TTemplateTBS(); + + $InventoryPrint = array(); // Tableau envoyé à la fonction render contenant les informations concernant l'inventaire + + foreach($inventory->Inventorydet as $k => $v) + { + $prod = new Product($db); + $prod->fetch($v->fk_product); + //$prod->fetch_optionals($prod->id); + + $InventoryPrint[] = array( + 'product' => $prod->ref.' - '.$prod->label + , 'qty_view' => $v->qty_view + ); + } + + $warehouse = new Entrepot($db); + $warehouse->fetch($inventory->fk_warehouse); + + $dirName = 'INVENTORY'.$inventory->getId().'('.date("d_m_Y").')'; + $dir = DOL_DATA_ROOT.'/inventory/'.$dirName.'/'; + + @mkdir($dir, 0777, true); + + $template = "templateINVENTORY.odt"; + //$template = "templateOF.doc"; + + $file_gen = $TBS->render(dol_buildpath('inventory/exempleTemplate/'.$template) + ,array( + 'InventoryPrint'=>$InventoryPrint + ) + ,array( + 'date_cre'=>$inventory->get_date('date_cre', 'd/m/Y') + ,'date_maj'=>$inventory->get_date('date_maj', 'd/m/Y H:i') + ,'date_inv'=>$inventory->get_date('date_inventory', 'd/m/Y') + ,'numero'=>empty($inventory->title) ? 'Inventaire n°'.$inventory->getId() : $inventory->title + ,'warehouse'=>$warehouse->libelle + ,'status'=>($inventory->status ? $langs->transnoentitiesnoconv('inventoryValidate') : $langs->transnoentitiesnoconv('inventoryDraft')) + ,'logo'=>DOL_DATA_ROOT."/mycompany/logos/".MAIN_INFO_SOCIETE_LOGO + ) + ,array() + ,array( + 'outFile'=>$dir.$inventory->getId().".odt" + ,"convertToPDF"=>(!empty($conf->global->INVENTORY_GEN_PDF) ? true : false) + ,'charset'=>OPENTBS_ALREADY_UTF8 + + ) + + ); + + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=inventory&entity=".$conf->entity."&file=".$dirName."/".$inventory->getId(). (!empty($conf->global->INVENTORY_GEN_PDF) ? '.pdf' : '.odt') ); + + /* + $size = filesize("./" . basename($file_gen)); + header("Content-Type: application/force-download; name=\"" . basename($file_gen) . "\""); + header("Content-Transfer-Encoding: binary"); + header("Content-Length: $size"); + header("Content-Disposition: attachment; filename=\"" . basename($file_gen) . "\""); + header("Expires: 0"); + header("Cache-Control: no-cache, must-revalidate"); + header("Pragma: no-cache"); + + readfile($file_gen); + */ + + //header("Location: ".DOL_URL_ROOT."/document.php?modulepart=asset&entity=1&file=".$dirName."/".$assetOf->numero.".doc"); + +} +function _footerList($view,$total_pmp,$total_pmp_actual,$total_pa,$total_pa_actual, $total_current_pa,$total_current_pa_actual) { + global $conf,$user,$langs; + + + if ($view['can_validate'] == 1) { ?> + +   + barcode->enabled)) { ?> +   + + + + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo ''.price($total_current_pa).''; + } + ?> +   + + rights->inventory->changePMP)) { + echo ' '; + } + ?> + + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo ''.price($total_current_pa_actual).''; + } + ?> + +   + +   + + + + +   Produit + Entrepôt + barcode->enabled)) { ?> + Code-barre + + + Quantité théorique + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo 'Valeur théorique'; + } + else { + echo 'Valeur théorique'; + } + + ?> + + + Quantité réelle + + + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++; + if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++; + + echo 'Valeur réelle'; + + ?> + + Quantité régulée + + + # + + + + + +   + PMP + Dernier PA + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo 'PA courant'; + } + + ?> +   + PMP + rights->inventory->changePMP)) { + echo ''.$langs->trans('ColumnNewPMP').''; + } + ?> + Dernier PA + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo 'PA courant'; + } + + ?> +   + +   + + + + * Copyright (C) 2015 ATM Consulting + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file lib/inventory.lib.php + * \ingroup inventory + * \brief This file is an example module library + * Put some comments here + */ + +function inventoryAdminPrepareHead() +{ + global $langs, $conf; + + $langs->load("inventory@inventory"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/inventory/admin/inventory_setup.php", 1); + $head[$h][1] = $langs->trans("Parameters"); + $head[$h][2] = 'settings'; + $h++; + $head[$h][0] = dol_buildpath("/inventory/admin/inventory_about.php", 1); + $head[$h][1] = $langs->trans("About"); + $head[$h][2] = 'about'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@inventory:/inventory/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@inventory:/inventory/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'inventory'); + + return $head; +} + +function inventoryPrepareHead(&$inventory, $title='Inventaire', $get='') +{ + return array( + array(dol_buildpath('/inventory/inventory.php?id='.$inventory->id.$get, 1), $title,'inventaire') + ); +} + + + +function inventorySelectProducts(&$inventory) +{ + global $conf,$db; + + $except_product_id = array(); + + foreach ($inventory->Inventorydet as $Inventorydet) + { + $except_product_id[] = $Inventorydet->fk_product; + } + + ob_start(); + $form = new Form($db); + $form->select_produits(-1, 'fk_product'); + + // Il nous faut impérativement une liste custom car il ne faut que les entrepôts de la famille de celui qu'on inventorie + $TChildWarehouses = array($inventory->fk_warehouse); + $e = new Entrepot($db); + $e->fetch($inventory->fk_warehouse); + if(method_exists($e, 'get_children_warehouses')) $e->get_children_warehouses($e->id, $TChildWarehouses); + + $Tab = array(); + $sql = 'SELECT rowid, label + FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid IN('.implode(', ', $TChildWarehouses).')'; + if(method_exists($e, 'get_children_warehouses')) $sql.= ' ORDER BY fk_parent'; + $resql = $db->query($sql); + while($res = $db->fetch_object($resql)) { + $Tab[$res->rowid] = $res->label; + } + print '   '; + print 'Entrepôt : '.$form::selectarray('fk_warehouse', $Tab); + + $select_html = ob_get_clean(); + + return $select_html; +} + +function ajaxAutocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array()) +{ + if (empty($minLength)) $minLength=1; + + $script = ''; + + $script.= ''; + + return $script; +} diff --git a/htdocs/inventory/tpl/inventory.tpl.php b/htdocs/inventory/tpl/inventory.tpl.php new file mode 100644 index 00000000000..d7022245f5b --- /dev/null +++ b/htdocs/inventory/tpl/inventory.tpl.php @@ -0,0 +1,211 @@ + + +status != 1) { ?> + trans('AddInventoryProduct'); ?> : +
    + + + + + + +
    + + +
    + + +
    Cet inventaire est validé
    + + + + + + + $row) { + + $total_pmp+=$row['pmp_stock']; + $total_pa+=$row['pa_stock']; + $total_pmp_actual+=$row['pmp_actual']; + $total_pa_actual+=$row['pa_actual']; + + if($i%20 === 0) + { + _headerList($view); + } // Fin IF principal + ?> + + + + barcode->enabled)) { ?> + + + + + + + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo ''; + $total_current_pa+=$row['current_pa_stock']; + } + + ?> + + + + + rights->inventory->changePMP)) { + echo ''; + } + ?> + + global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ + echo ''; + $total_current_pa_actual+=$row['current_pa_actual']; + } + + ?> + + + + + + + + + + + + +
      '.price($row['current_pa_stock']).'   + + '.$row['pmp_new'].''.price($row['current_pa_actual']).'
    + + +
    + + trans('Print') ?> + trans('ExportCSV') ?> + trans('Modify') ?> + rights->inventory->changePMP)) { + echo ''.$langs->trans('ApplyPMP').''; + } + + if ($can_validate == 1) { ?> + Réguler le stock + + + + + + + Vider +     + Supprimer + +
    + + + + +
    +

    Date de création : get_date('datec') ?> +
    Dernière mise à jour : get_date('tms') ?>

    + + + From 565bcf233276535280c86a16f287df1eae7963a5 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Wed, 14 Dec 2016 16:11:37 +0100 Subject: [PATCH 07/41] debug fetch method --- htdocs/core/class/coreobject.class.php | 76 +++++++++-- htdocs/inventory/class/inventory.class.php | 58 ++++----- htdocs/inventory/inventory.php | 145 ++++++--------------- htdocs/inventory/tpl/inventory.tpl.php | 12 +- 4 files changed, 137 insertions(+), 154 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index b7e4b2770e3..f5e5b0e79a1 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -78,14 +78,20 @@ class CoreObject extends CommonObject { } + private function checkFieldType($field, $type) { + + if( isset($this->__fields[$field]) && method_exists($this, 'is_'.$type)) { + return $this->{'is_'.$type}($this->__fields[$field]); + } + else return false; + + } private function is_date(Array &$info){ - if(is_array($info)) { - if(isset($info['type']) && $info['type']=='date') return true; - else return false; - } + if(isset($info['type']) && $info['type']=='date') return true; else return false; + } private function is_array($info) { @@ -239,7 +245,25 @@ class CoreObject extends CommonObject { } } + public function addChild($tabName, $id='', $key='id', $try_to_load = false) { + if(!empty($id)) { + foreach($this->{$tabName} as $k=>&$object) { + if($object->{$key} === $id) return $k; + } + } + + $k = count($this->{$tabName}); + + $className = ucfirst($tabName); + $this->{$tabName}[$k] = new $className($this->db); + if($id>0 && $key==='id' && $try_to_load) { + $this->{$tabName}[$k]->fetch($id); + } + + + return $k; + } public function fetchChild() { if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { @@ -272,13 +296,13 @@ class CoreObject extends CommonObject { } - public function update() { - + public function update(User &$user) { + if(empty($this->id )) return $this->create($user); } - public function create() { - + public function create(User &$user) { + if($this->id>0) return $this->update($user); } @@ -287,10 +311,46 @@ class CoreObject extends CommonObject { if(empty($this->{$field})) return ''; elseif($this->{$field}<=strtotime('1000-01-01 00:00:00')) return ''; else { + return dol_print_date($this->{$field}, $format); } } + public function set_date($field,$date){ + + if(empty($date)) { + $this->{$field} = 0; + } + else { + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + + $this->{$field} = dol_stringtotime($date); + } + + return $this->{$field}; + } + + public function set_values(&$Tab) { + foreach ($Tab as $key=>$value) { + + if($this->checkFieldType($key,'date')) { + $this->set_date($key, $value); + } + else if( $this->checkFieldType($key,'array')){ + $this->{$key} = $value; + } + else if( $this->checkFieldType($key,'float') ) { + $this->{$key} = (double)price2num($value); + } + else if( $this->checkFieldType($key,'int') ) { + $this->{$key} = (int)price2num($value); + } + else { + $this->{$key} = @stripslashes($value); + } + + } + } } diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index 2a485d24a0a..f2ff6484c64 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -147,15 +147,16 @@ class Inventory extends CoreObject } - function update() + function update(User &$user) { + //si on valide l'inventaire on sauvegarde le stock à cette instant if ($this->status) { $this->regulate(); } - parent::update(); + parent::update($user); } function set_values($Tab) @@ -209,7 +210,7 @@ class Inventory extends CoreObject $det->load_product(); $date = $this->get_date('date_inventory', 'Y-m-d'); - if(empty($date))$date = $this->get_date('date_cre', 'Y-m-d'); + if(empty($date))$date = $this->get_date('datec', 'Y-m-d'); $det->setStockDate( $date , $fk_entrepot); } @@ -416,9 +417,9 @@ class Inventorydet extends CoreObject return true; } - function setStockDate(&$PDOdb, $date, $fk_warehouse) { + function setStockDate($date, $fk_warehouse) { - list($pmp,$stock) = $this->getPmpStockFromDate($PDOdb, $date, $fk_warehouse); + list($pmp,$stock) = $this->getPmpStockFromDate($date, $fk_warehouse); $this->qty_stock = $stock; $this->pmp = $pmp; @@ -432,18 +433,17 @@ class Inventorydet extends CoreObject AND datem<='".$date." 23:59:59' ORDER BY datem DESC LIMIT 1"; - $res = $db->query($sql); + $res = $this->db->query($sql); - if($obj = $db->fetch_object($res)) { + if($res && $obj = $this->db->fetch_object($res)) { $last_pa = $obj->price; } $this->pa = $last_pa; - /* var_dump($fk_warehouse,$this->product->stock_warehouse,$this->pmp, $this->pa, $this->qty_stock); - exit;*/ + } - function getPmpStockFromDate(&$PDOdb, $date, $fk_warehouse){ + function getPmpStockFromDate( $date, $fk_warehouse){ $res = $this->product->load_stock(); @@ -459,7 +459,7 @@ class Inventorydet extends CoreObject } - //On récupère tous les mouvements de stocks du produit entre aujourd'hui et la date de l'inventaire + //All Stock mouvement between now and inventory date $sql = "SELECT value, price FROM ".MAIN_DB_PREFIX."stock_mouvement WHERE fk_product = ".$this->product->id." @@ -467,31 +467,25 @@ class Inventorydet extends CoreObject AND datem > '".date('Y-m-d 23:59:59',strtotime($date))."' ORDER BY datem DESC"; - //echo $sql.'
    '; - $db->query($sql); - $TMouvementStock = $PDOdb->Get_All(); + + $res = $this->db->query($sql); + $laststock = $stock; $lastpmp = $pmp; - //Pour chacun des mouvements on recalcule le PMP et le stock physique - foreach($TMouvementStock as $mouvement){ - - //150 - //if($this->product->id==394) echo 'laststock = '.$stock.'
    '; - - //9.33 - //if($this->product->id==394) echo 'lastpmp = '.$pmp.'
    '; - $price = ($mouvement->price>0 && $mouvement->value>0) ? $mouvement->price : $lastpmp; + + if($res) { + while($mouvement = $this->db->fetch_object($res)) { + $price = ($mouvement->price>0 && $mouvement->value>0) ? $mouvement->price : $lastpmp; - $stock_value = $laststock * $lastpmp; + $stock_value = $laststock * $lastpmp; + + $laststock -= $mouvement->value; + + $last_stock_value = $stock_value - ($mouvement->value * $price); + + $lastpmp = ($laststock != 0) ? $last_stock_value / $laststock : $lastpmp; + } - $laststock -= $mouvement->value; - - $last_stock_value = $stock_value - ($mouvement->value * $price); - - $lastpmp = ($laststock != 0) ? $last_stock_value / $laststock : $lastpmp; - - - } return array($lastpmp,$laststock); diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index d46f05059b4..4e70ee1b4cc 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -66,18 +66,17 @@ function _action() $inventory = new Inventory($db); - _fiche_warehouse($user, $db, $conf, $langs, $inventory); + _card_warehouse( $inventory); break; case 'confirmCreate': if (!$user->rights->inventory->create) accessforbidden(); - - + $inventory = new Inventory($db); - $inventory->set_values($_REQUEST); + $inventory->set_values($_POST); - $fk_inventory = $inventory->save(); + $fk_inventory = $inventory->create($user); $fk_category = (int)GETPOST('fk_category'); $fk_supplier = (int)GETPOST('fk_supplier'); $fk_warehouse = (int)GETPOST('fk_warehouse'); @@ -86,7 +85,7 @@ function _action() $e = new Entrepot($db); $e->fetch($fk_warehouse); $TChildWarehouses = array($fk_warehouse); - if(method_exists($e, 'get_children_warehouses')) $e->get_children_warehouses($fk_warehouse, $TChildWarehouses); + $e->get_children_warehouses($fk_warehouse, $TChildWarehouses); $sql = 'SELECT ps.fk_product, ps.fk_entrepot FROM '.MAIN_DB_PREFIX.'product_stock ps @@ -103,27 +102,27 @@ function _action() ORDER BY p.ref ASC,p.label ASC'; - $Tab = $PDOdb->ExecuteAsArray($sql); - - foreach($Tab as &$row) { - - $inventory->add_product($PDOdb, $row->fk_product, $row->fk_entrepot); + $res = $db->query($sql); + if($res) { + while($obj = $db->fetch_object($res)){ + + $inventory->add_product($obj->fk_product, $obj->fk_entrepot); + } } - $inventory->save($PDOdb); + $inventory->update($user); + + header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->id.'&action=edit', 1)); + break; - header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->getId().'&action=edit', 1)); - case 'edit': if (!$user->rights->inventory->write) accessforbidden(); - $id = __get('id', 0, 'int'); - $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch(GETPOST('id')); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, __get('action', 'edit', 'string')); + _card($inventory, GETPOST('action')); break; @@ -389,29 +388,29 @@ function _list() llxFooter(''); } -function _fiche_warehouse(&$PDOdb, &$user, &$db, &$conf, $langs, $inventory) +function _card_warehouse(&$inventory) { + global $langs,$conf,$db, $user, $form; + dol_include_once('/categories/class/categorie.class.php'); llxHeader('',$langs->trans('inventorySelectWarehouse'),'',''); print dol_get_fiche_head(inventoryPrepareHead($inventory)); - $form=new TFormCore('inventory.php', 'confirmCreate'); - print $form->hidden('action', 'confirmCreate'); - $form->Set_typeaff('edit'); + echo '
    '; + echo ''; $formproduct = new FormProduct($db); - $formDoli = new Form($db); ?> - + - + @@ -421,11 +420,11 @@ function _fiche_warehouse(&$PDOdb, &$user, &$db, &$conf, $langs, $inventory) - + - + @@ -439,7 +438,8 @@ function _fiche_warehouse(&$PDOdb, &$user, &$db, &$conf, $langs, $inventory) print ''; print ''; - print $form->end_form(); + echo ''; + llxFooter(''); } @@ -455,7 +455,7 @@ function _card(&$inventory, $mode='edit') print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), '&action='.$mode)); $lines = array(); - _card_line($inventory, $lines, $form); + _card_line($inventory, $lines, $mode); print ''.$langs->trans('inventoryOnDate')." ".$inventory->get_date('date_inventory').'

    '; @@ -488,7 +488,7 @@ function _card(&$inventory, $mode='edit') } -function _card_line(&$inventory, &$lines, &$form) +function _card_line(&$inventory, &$lines, $mode) { global $db; $inventory->amount_actual = 0; @@ -512,21 +512,23 @@ function _card_line(&$inventory, &$lines, &$form) if(!empty($TCacheEntrepot[$Inventorydet->fk_warehouse])) $e = $TCacheEntrepot[$Inventorydet->fk_warehouse]; elseif($e->fetch($Inventorydet->fk_warehouse) > 0) $TCacheEntrepot[$e->id] = $e; + $qty = (float)GETPOST('qty_to_add')[$k]; + $lines[]=array( 'produit' => $product->getNomUrl(1).' - '.$product->label ,'entrepot'=>$e->getNomUrl(1) ,'barcode' => $product->barcode - /*,'qty' => $form->texte('', 'qty_to_add['.$k.']', (isset($_REQUEST['qty_to_add'][$k]) ? $_REQUEST['qty_to_add'][$k] : 0), 8, 0, "style='text-align:center;'") - .($form->type_aff!='view' ? ''.img_picto('Ajouter', 'plus16@inventory').'' : '') + ,'qty' =>($mode == 'edit' ? '' : $qty ) + .($mode =='edit' ? ''.img_picto($langs->trans('Add'), 'plus16@inventory').'' : '') ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 ,'qty_stock' => $stock ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 - ,'action' => $user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '' + ,'action' => ($user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') ,'pmp_stock'=>round($pmp_actual,2) ,'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2) - ,'pmp_new'=>(!empty($user->rights->inventory->changePMP) ? $form->texte('', 'new_pmp['.$k.']',$Inventorydet->new_pmp, 8, 0, "style='text-align:right;'") - .($form->type_aff!='view' ? ''.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : '') : '' ) - */,'pa_stock'=>round($last_pa * $stock,2) + ,'pmp_new'=>(!empty($user->rights->inventory->changePMP) ? '' + .($mode =='edit' ? ''.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : '') : '') + ,'pa_stock'=>round($last_pa * $stock,2) ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2) ,'current_pa_stock'=>round($current_pa * $stock,2) ,'current_pa_actual'=>round($current_pa * $Inventorydet->qty_view,2) @@ -610,80 +612,9 @@ function exportCSV(&$inventory) { exit; } -function generateODT(&$PDOdb, &$db, &$conf, &$langs, &$inventory) -{ - $TBS=new TTemplateTBS(); - - $InventoryPrint = array(); // Tableau envoyé à la fonction render contenant les informations concernant l'inventaire - - foreach($inventory->Inventorydet as $k => $v) - { - $prod = new Product($db); - $prod->fetch($v->fk_product); - //$prod->fetch_optionals($prod->id); - - $InventoryPrint[] = array( - 'product' => $prod->ref.' - '.$prod->label - , 'qty_view' => $v->qty_view - ); - } - - $warehouse = new Entrepot($db); - $warehouse->fetch($inventory->fk_warehouse); - - $dirName = 'INVENTORY'.$inventory->getId().'('.date("d_m_Y").')'; - $dir = DOL_DATA_ROOT.'/inventory/'.$dirName.'/'; - - @mkdir($dir, 0777, true); - - $template = "templateINVENTORY.odt"; - //$template = "templateOF.doc"; - - $file_gen = $TBS->render(dol_buildpath('inventory/exempleTemplate/'.$template) - ,array( - 'InventoryPrint'=>$InventoryPrint - ) - ,array( - 'date_cre'=>$inventory->get_date('date_cre', 'd/m/Y') - ,'date_maj'=>$inventory->get_date('date_maj', 'd/m/Y H:i') - ,'date_inv'=>$inventory->get_date('date_inventory', 'd/m/Y') - ,'numero'=>empty($inventory->title) ? 'Inventaire n°'.$inventory->getId() : $inventory->title - ,'warehouse'=>$warehouse->libelle - ,'status'=>($inventory->status ? $langs->transnoentitiesnoconv('inventoryValidate') : $langs->transnoentitiesnoconv('inventoryDraft')) - ,'logo'=>DOL_DATA_ROOT."/mycompany/logos/".MAIN_INFO_SOCIETE_LOGO - ) - ,array() - ,array( - 'outFile'=>$dir.$inventory->getId().".odt" - ,"convertToPDF"=>(!empty($conf->global->INVENTORY_GEN_PDF) ? true : false) - ,'charset'=>OPENTBS_ALREADY_UTF8 - - ) - - ); - - header("Location: ".DOL_URL_ROOT."/document.php?modulepart=inventory&entity=".$conf->entity."&file=".$dirName."/".$inventory->getId(). (!empty($conf->global->INVENTORY_GEN_PDF) ? '.pdf' : '.odt') ); - - /* - $size = filesize("./" . basename($file_gen)); - header("Content-Type: application/force-download; name=\"" . basename($file_gen) . "\""); - header("Content-Transfer-Encoding: binary"); - header("Content-Length: $size"); - header("Content-Disposition: attachment; filename=\"" . basename($file_gen) . "\""); - header("Expires: 0"); - header("Cache-Control: no-cache, must-revalidate"); - header("Pragma: no-cache"); - - readfile($file_gen); - */ - - //header("Location: ".DOL_URL_ROOT."/document.php?modulepart=asset&entity=1&file=".$dirName."/".$assetOf->numero.".doc"); - -} function _footerList($view,$total_pmp,$total_pmp_actual,$total_pa,$total_pa_actual, $total_current_pa,$total_current_pa_actual) { global $conf,$user,$langs; - if ($view['can_validate'] == 1) { ?> diff --git a/htdocs/inventory/tpl/inventory.tpl.php b/htdocs/inventory/tpl/inventory.tpl.php index d7022245f5b..8a3bfd0f2a6 100644 --- a/htdocs/inventory/tpl/inventory.tpl.php +++ b/htdocs/inventory/tpl/inventory.tpl.php @@ -154,9 +154,9 @@ - - - @@ -168,18 +168,17 @@
    - trans('Print') ?> trans('ExportCSV') ?> trans('Modify') ?> rights->inventory->changePMP)) { - echo ''.$langs->trans('ApplyPMP').''; } if ($can_validate == 1) { ?> - Réguler le stock + Réguler le stock @@ -196,7 +195,6 @@
    - trans('Print') ?> trans('ExportCSV') ?> trans('Delete') ?> From a463759ba3b88cdcc97a263c2cd6e42d5944aaf7 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Wed, 14 Dec 2016 16:54:05 +0100 Subject: [PATCH 08/41] init query builder into db --- htdocs/core/class/coreobject.class.php | 98 +++++++++++++++++++++- htdocs/core/db/DoliDB.class.php | 108 +++++++++++++++++++++++++ 2 files changed, 203 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index f5e5b0e79a1..8f55a5bf458 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -150,7 +150,7 @@ class CoreObject extends CommonObject { foreach ($this->__fields as $field=>$info) { - if($this->_is_date($info)){ + if($this->is_date($info)){ if(empty($this->{$field})){ $query[$field] = $this->date_0; } @@ -166,11 +166,11 @@ class CoreObject extends CommonObject { $query[$field] = (int)price2num($this->{$field}); } - else if($this->_is_float($info)){ + else if($this->is_float($info)){ $query[$field] = (double)price2num($this->{$field}); } - elseif($this->_is_null($info)) { + elseif($this->is_null($info)) { $query[$field] = (is_null($this->{$field}) || (empty($this->{$field}) && $this->{$field}!==0 && $this->{$field}!=='0')?null:$this->{$field}); } else{ @@ -264,6 +264,20 @@ class CoreObject extends CommonObject { return $k; } + + public function removeChild($tabName, $id, $key='id') { + foreach($this->{$tabName} as &$object) { + + if($object->{$key} == $id) { + $object->to_delete = true; + return true; + } + + + } + return false; + } + public function fetchChild() { if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { @@ -295,18 +309,96 @@ class CoreObject extends CommonObject { } + public function saveChild(User &$user) { + if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { + foreach($this->childtables as &$childTable) { + + $className = ucfirst($childTable); + + foreach($this->{$className} as $i => &$object) { + + $object->{$this->fk_element} = $this->id; + + $object->update($user); + if($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete==true) unset($this->{$className}[$i]); + } + + } + } + } public function update(User &$user) { if(empty($this->id )) return $this->create($user); + if(isset($this->to_delete) && $this->to_delete==true) { + $this->delete(); + } + else { + + $query = array(); + + $query['id']=$this->id; + if(!isset($this->no_dt_maj))$query['tms'] = date('Y-m-d H:i:s'); + $this->set_save_query($query); + + $this->db->update($this->table_element,$query,array('id')); + + $this->id = $this->db->last_insert_id($this->table_element); + + $result = $this->call_trigger(strtoupper($this->element). '_UPDATE', $user); + + $this->saveChild($user); + + } + return $this->id; + } public function create(User &$user) { if($this->id>0) return $this->update($user); + $query = array(); + $query['datec'] = date("Y-m-d H:i:s",$this->datec); + if(!isset($this->no_dt_maj))$query['tms'] = date('Y-m-d H:i:s'); + $this->set_save_query($query); + + $this->db->insert($this->table_element,$query); + + $this->id = $this->db->last_insert_id($this->table_element); + + $result = $this->call_trigger(strtoupper($this->element). '_CREATE', $user); + + $this->saveChild($user); + + + return $this->id; } + public function delete(){ + if($this->id>0){ + $this->call_trigger(strtoupper($this->element). '_DELETE', $user); + $this->db->delete($this->table_element,array('id'=>$this->id),array(0=>'id')); + + if($this->withChild) { + foreach($this->childtables as &$childTable) { + + $className = ucfirst($childTable); + foreach($this->{$className} as &$object) { + + $object->delete(); + + } + + } + } + + + + } + + + } public function get_date($field,$format='') { if(empty($this->{$field})) return ''; elseif($this->{$field}<=strtotime('1000-01-01 00:00:00')) return ''; diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index c63227e1601..395f6009169 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -288,5 +288,113 @@ abstract class DoliDB implements Database { return $this->lastqueryerror; } + + /** + * Generate and execute Update SQL commande + * + * @param string $table table to update + * @param array $values array of values to update + * @param int|string|array $key key of value to select row to update + * @return bool|result false or boolean + */ + function update($table,$values,$key){ + + foreach ($value as $k => $v) { + if(is_string($v)) $v=stripslashes($v); + + if (is_array($key)){ + $i=array_search($k , $key ); + if ( $i !== false) { + $where[] = $key[$i]."=" . $this->escape( $v ) ; + continue; + } + } else { + if ( $k == $key) { + $where[] = "$k=" .$this->escape( $v ) ; + continue; + } + } + + if(is_null($v)) $val = 'NULL'; + else if(is_int($v) || is_double($v)) $val=$v; + else $val = $this->escape( $v ); + + $tmp[] = "$k=$val"; + } + $sql = sprintf( "UPDATE $table SET %s WHERE %s" , implode( ",", $tmp ) , implode(" AND ",$where) ); + + $res = $this->query( $sql ); + + if($res===false) { + //error + return false; + } + + return true; + } + + /** + * Generate and execute Insert SQL commande + * + * @param string $table table to update + * @param array $values array of values to update + * @return bool|result false or boolean + */ + function insert($table,$values){ + + foreach ($values as $k => $v) { + + $fields[] = $k; + if(is_null($v)){ + $values[] = 'NULL'; + }else{ + $v=stripslashes($v); + $values[] =$this->escape( $v ); + } + } + $sql = sprintf( 'INSERT INTO '.$table.' ( %s ) values( %s ) ', implode( ",", $fields ) , implode( ",", $values ) ); + + $res = $this->query($sql); + + if($res===false) { + + return false; + } + + return true; + } + + /** + * Generate and execute Delete SQL commande + * + * @param string $table table for the delete + * @param array $values array of values to delete + * @param int|string|array $key key of value to select row to update + * @return bool|result false or boolean + */ + function delete($table,$values,$key){ + foreach ($values as $k => $v) { + if(is_string($v)) $v=stripslashes($v); + + if (is_array($key)){ + $i=array_search($k , $key ); + if ( $i !== false) { + $where[] = $key[$i]."=" . $this->escape( $v ) ; + continue; + } + } else { + if ( $k == $key) { + $where[] = "$k=" .$this->escape( $v ) ; + continue; + } + } + + } + + $sql = sprintf( 'DELETE FROM '.$table.' WHERE '.implode(" AND ",$where)); + + return $this->query( $sql ); + } + } From 703b8708e3702b21cf4027e2ad0d5c071298dfab Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 10:39:59 +0100 Subject: [PATCH 09/41] fix create --- htdocs/core/class/coreobject.class.php | 66 +++-- htdocs/core/db/DoliDB.class.php | 55 ++-- htdocs/core/modules/modinventory.class.php | 329 +++++++++++++++++++++ htdocs/inventory/class/inventory.class.php | 4 +- htdocs/inventory/img/bt-save.png | Bin 0 -> 493 bytes htdocs/inventory/inventory.php | 5 +- 6 files changed, 401 insertions(+), 58 deletions(-) create mode 100644 htdocs/core/modules/modinventory.class.php create mode 100644 htdocs/inventory/img/bt-save.png diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 8f55a5bf458..7613a556092 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -31,7 +31,14 @@ class CoreObject extends CommonObject { public $withChild = true; - protected $__fields=array(); + public $no_update_tms = false; + + public $date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? + + /* + * @var Array $_fields Fields to synchronize with Database + */ + protected $__fields=array(); /** * Constructor * @@ -39,7 +46,7 @@ class CoreObject extends CommonObject { */ function __construct(DoliDB &$db) { - $this->date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? + } protected function init() { @@ -142,11 +149,7 @@ class CoreObject extends CommonObject { private function set_save_query(){ - $query=array( - 'rowid'=>$this->id - ,'datec'=>($this->id>0 ? $this->db->jdate($this->datec) : time()) - ,'tms'=>time() - ); + $query=array(); foreach ($this->__fields as $field=>$info) { @@ -315,20 +318,21 @@ class CoreObject extends CommonObject { foreach($this->childtables as &$childTable) { $className = ucfirst($childTable); - - foreach($this->{$className} as $i => &$object) { - - $object->{$this->fk_element} = $this->id; - - $object->update($user); - if($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete==true) unset($this->{$className}[$i]); + if(!empty($this->{$className})) { + foreach($this->{$className} as $i => &$object) { + + $object->{$this->fk_element} = $this->id; + + $object->update($user); + if($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete==true) unset($this->{$className}[$i]); + } } } } } public function update(User &$user) { - if(empty($this->id )) return $this->create($user); + if(empty($this->id )) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed if(isset($this->to_delete) && $this->to_delete==true) { $this->delete(); @@ -337,10 +341,10 @@ class CoreObject extends CommonObject { $query = array(); + $query = $this->set_save_query(); $query['id']=$this->id; - if(!isset($this->no_dt_maj))$query['tms'] = date('Y-m-d H:i:s'); - $this->set_save_query($query); - + if(empty($this->no_update_tms))$query['tms'] = date('Y-m-d H:i:s'); + $this->db->update($this->table_element,$query,array('id')); $this->id = $this->db->last_insert_id($this->table_element); @@ -358,21 +362,25 @@ class CoreObject extends CommonObject { if($this->id>0) return $this->update($user); $query = array(); + $query = $this->set_save_query(); $query['datec'] = date("Y-m-d H:i:s",$this->datec); - if(!isset($this->no_dt_maj))$query['tms'] = date('Y-m-d H:i:s'); - $this->set_save_query($query); - - $this->db->insert($this->table_element,$query); - - $this->id = $this->db->last_insert_id($this->table_element); + if(empty($this->no_update_tms))$query['tms'] = date('Y-m-d H:i:s'); - $result = $this->call_trigger(strtoupper($this->element). '_CREATE', $user); - - $this->saveChild($user); + $res = $this->db->insert($this->table_element,$query); + if($res) { + $this->id = $this->db->last_insert_id($this->table_element); + + $result = $this->call_trigger(strtoupper($this->element). '_CREATE', $user); + + $this->saveChild($user); + + return $this->id; + } + else{ + return false; + } - return $this->id; - } public function delete(){ if($this->id>0){ diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index 395f6009169..85766c31949 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -288,6 +288,19 @@ abstract class DoliDB implements Database { return $this->lastqueryerror; } + /* + * Add quote to field value if necessary + * + * @param string|int $value value to protect + * @return string|int + */ + function quote($value) { + + if(is_null($value)) return 'NULL'; + else if(is_numeric($value)) return $value; + else return "'".$this->escape( $value )."'"; + + } /** * Generate and execute Update SQL commande @@ -297,31 +310,27 @@ abstract class DoliDB implements Database * @param int|string|array $key key of value to select row to update * @return bool|result false or boolean */ - function update($table,$values,$key){ + function update($table,$fields,$key){ - foreach ($value as $k => $v) { + foreach ($fields as $k => $v) { if(is_string($v)) $v=stripslashes($v); if (is_array($key)){ $i=array_search($k , $key ); if ( $i !== false) { - $where[] = $key[$i]."=" . $this->escape( $v ) ; + $where[] = $key[$i].'=' . $this->quote( $v ) ; continue; } } else { if ( $k == $key) { - $where[] = "$k=" .$this->escape( $v ) ; + $where[] = $k.'=' .$this->quote( $v ) ; continue; } } - if(is_null($v)) $val = 'NULL'; - else if(is_int($v) || is_double($v)) $val=$v; - else $val = $this->escape( $v ); - - $tmp[] = "$k=$val"; + $tmp[] = $k.'='.$this->quote($val); } - $sql = sprintf( "UPDATE $table SET %s WHERE %s" , implode( ",", $tmp ) , implode(" AND ",$where) ); + $sql = sprintf( 'UPDATE '.MAIN_DB_PREFIX.$table.' SET %s WHERE %s' , implode( ',', $tmp ) , implode(' AND ',$where) ); $res = $this->query( $sql ); @@ -340,22 +349,18 @@ abstract class DoliDB implements Database * @param array $values array of values to update * @return bool|result false or boolean */ - function insert($table,$values){ + function insert($table,$fields){ - foreach ($values as $k => $v) { + foreach ($fields as $k => $v) { - $fields[] = $k; - if(is_null($v)){ - $values[] = 'NULL'; - }else{ - $v=stripslashes($v); - $values[] =$this->escape( $v ); - } + $keys[] = $k; + $values[] = $this->quote($v); + } - $sql = sprintf( 'INSERT INTO '.$table.' ( %s ) values( %s ) ', implode( ",", $fields ) , implode( ",", $values ) ); - - $res = $this->query($sql); + $sql = sprintf( 'INSERT INTO '.MAIN_DB_PREFIX.$table.' ( %s ) values( %s ) ', implode( ",", $keys ) , implode( ",", $values ) ); + + $res = $this->query($sql); if($res===false) { return false; @@ -372,8 +377,8 @@ abstract class DoliDB implements Database * @param int|string|array $key key of value to select row to update * @return bool|result false or boolean */ - function delete($table,$values,$key){ - foreach ($values as $k => $v) { + function delete($table,$fields,$key){ + foreach ($fields as $k => $v) { if(is_string($v)) $v=stripslashes($v); if (is_array($key)){ @@ -391,7 +396,7 @@ abstract class DoliDB implements Database } - $sql = sprintf( 'DELETE FROM '.$table.' WHERE '.implode(" AND ",$where)); + $sql = sprintf( 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.implode(' AND ',$where)); return $this->query( $sql ); } diff --git a/htdocs/core/modules/modinventory.class.php b/htdocs/core/modules/modinventory.class.php new file mode 100644 index 00000000000..10fb1cc477e --- /dev/null +++ b/htdocs/core/modules/modinventory.class.php @@ -0,0 +1,329 @@ + + * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \defgroup inventory Module inventory + * \brief Example of a module descriptor. + * Such a file must be copied into htdocs/inventory/core/modules directory. + * \file htdocs/inventory/core/modules/modinventory.class.php + * \ingroup inventory + * \brief Description and activation file for module inventory + */ +include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; + + +/** + * Description and activation class for module inventory + */ +class modinventory extends DolibarrModules +{ + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + global $langs,$conf; + + $this->db = $db; + + // Id for module (must be unique). + // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 104420; // 104000 to 104999 for ATM CONSULTING + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'inventory'; + + // Family can be 'crm','financial','hr','projects','products','ecm','technic','other' + // It is used to group modules in module setup page + $this->family = "products"; + // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) + $this->name = preg_replace('/^mod/i','',get_class($this)); + // Module description, used if translation string 'ModuleXXXDesc' not found (where XXX is value of numeric property 'numero' of module) + $this->description = "Description of module inventory"; + // Possible values for version are: 'development', 'experimental', 'dolibarr' or version + $this->version = 'dolibarr'; + // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Where to store the module in setup page (0=common,1=interface,2=others,3=very specific) + $this->special = 0; + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' + $this->picto='inventory@inventory'; + + // Defined all module parts (triggers, login, substitutions, menus, css, etc...) + // for default path (eg: /inventory/core/xxxxx) (0=disable, 1=enable) + // for specific path of parts (eg: /inventory/core/modules/barcode) + // for specific css file (eg: /inventory/css/inventory.css.php) + //$this->module_parts = array( + // 'triggers' => 0, // Set this to 1 if module has its own trigger directory (core/triggers) + // 'login' => 0, // Set this to 1 if module has its own login method directory (core/login) + // 'substitutions' => 0, // Set this to 1 if module has its own substitution function file (core/substitutions) + // 'menus' => 0, // Set this to 1 if module has its own menus handler directory (core/menus) + // 'theme' => 0, // Set this to 1 if module has its own theme directory (theme) + // 'tpl' => 0, // Set this to 1 if module overwrite template dir (core/tpl) + // 'barcode' => 0, // Set this to 1 if module has its own barcode directory (core/modules/barcode) + // 'models' => 0, // Set this to 1 if module has its own models directory (core/modules/xxx) + // 'css' => array('/inventory/css/inventory.css.php'), // Set this to relative path of css file if module has its own css file + // 'js' => array('/inventory/js/inventory.js'), // Set this to relative path of js file if module must load a js on all pages + // 'hooks' => array('hookcontext1','hookcontext2') // Set here all hooks context managed by module + // 'dir' => array('output' => 'othermodulename'), // To force the default directories names + // 'workflow' => array('WORKFLOW_MODULE1_YOURACTIONTYPE_MODULE2'=>array('enabled'=>'! empty($conf->module1->enabled) && ! empty($conf->module2->enabled)', 'picto'=>'yourpicto@inventory')) // Set here all workflow context managed by module + // ); + $this->module_parts = array(); + + // Data directories to create when module is enabled. + // Example: this->dirs = array("/inventory/temp"); + $this->dirs = array(); + + // Config pages. Put here list of php page, stored into inventory/admin directory, to use to setup module. + $this->config_page_url = array("inventory_setup.php@inventory"); + + // Dependencies + $this->hidden = false; // A condition to hide module + $this->depends = array('modStock'); // List of modules id that must be enabled if this module is enabled + $this->requiredby = array(); // List of modules id to disable if this one is disabled + $this->conflictwith = array(); // List of modules id this module is in conflict with + $this->phpmin = array(5,0); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(3,0); // Minimum version of Dolibarr required by module + $this->langfiles = array("inventory@inventory"); + + // Constants + // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: $this->const=array(0=>array('MYMODULE_MYNEWCONST1','chaine','myvalue','This is a constant to add',1), + // 1=>array('MYMODULE_MYNEWCONST2','chaine','myvalue','This is another constant to add',0, 'current', 1) + // ); + $this->const = array(); + + // Array to add new pages in new tabs + // Example: $this->tabs = array('objecttype:+tabname1:Title1:mylangfile@inventory:$user->rights->inventory->read:/inventory/mynewtab1.php?id=__ID__', // To add a new tab identified by code tabname1 + // 'objecttype:+tabname2:Title2:mylangfile@inventory:$user->rights->othermodule->read:/inventory/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2 + // 'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname + // where objecttype can be + // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) + // 'contact' to add a tab in contact view + // 'contract' to add a tab in contract view + // 'group' to add a tab in group view + // 'intervention' to add a tab in intervention view + // 'invoice' to add a tab in customer invoice view + // 'invoice_supplier' to add a tab in supplier invoice view + // 'member' to add a tab in fundation member view + // 'opensurveypoll' to add a tab in opensurvey poll view + // 'order' to add a tab in customer order view + // 'order_supplier' to add a tab in supplier order view + // 'payment' to add a tab in payment view + // 'payment_supplier' to add a tab in supplier payment view + // 'product' to add a tab in product view + // 'propal' to add a tab in propal view + // 'project' to add a tab in project view + // 'stock' to add a tab in stock view + // 'thirdparty' to add a tab in third party view + // 'user' to add a tab in user view + $this->tabs = array(); + + // Dictionaries + if (! isset($conf->inventory->enabled)) + { + $conf->inventory=new stdClass(); + $conf->inventory->enabled=0; + } + $this->dictionaries=array(); + /* Example: + if (! isset($conf->inventory->enabled)) $conf->inventory->enabled=0; // This is to avoid warnings + $this->dictionaries=array( + 'langs'=>'mylangfile@inventory', + 'tabname'=>array(MAIN_DB_PREFIX."table1",MAIN_DB_PREFIX."table2",MAIN_DB_PREFIX."table3"), // List of tables we want to see into dictonnary editor + 'tablib'=>array("Table1","Table2","Table3"), // Label of tables + 'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'), // Request to select fields + 'tabsqlsort'=>array("label ASC","label ASC","label ASC"), // Sort order + 'tabfield'=>array("code,label","code,label","code,label"), // List of fields (result of select to show dictionary) + 'tabfieldvalue'=>array("code,label","code,label","code,label"), // List of fields (list of fields to edit a record) + 'tabfieldinsert'=>array("code,label","code,label","code,label"), // List of fields (list of fields for insert) + 'tabrowid'=>array("rowid","rowid","rowid"), // Name of columns with primary key (try to always name it 'rowid') + 'tabcond'=>array($conf->inventory->enabled,$conf->inventory->enabled,$conf->inventory->enabled) // Condition to show each dictionary + ); + */ + + // Boxes + // Add here list of php file(s) stored in core/boxes that contains class to show a box. + $this->boxes = array(); // List of boxes + // Example: + //$this->boxes=array(array(0=>array('file'=>'myboxa.php','note'=>'','enabledbydefaulton'=>'Home'),1=>array('file'=>'myboxb.php','note'=>''),2=>array('file'=>'myboxc.php','note'=>''));); + + $langs->load('inventory@inventory'); + + // Permissions + $this->rights = array(); // Permission array used by this module + $r=0; + + // Add here list of permission defined by an id, a label, a boolean and two constant strings. + // Example: + // $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + // $this->rights[$r][1] = 'Permision label'; // Permission label + // $this->rights[$r][3] = 1; // Permission by default for new user (0/1) + // $this->rights[$r][4] = 'level1'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + // $this->rights[$r][5] = 'level2'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + // $r++; + + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'inventoryReadPermission'; // Permission label + $this->rights[$r][3] = 1; // Permission by default for new user (0/1) + $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $r++; + + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'inventoryCreatePermission'; // Permission label + $this->rights[$r][3] = 0; // Permission by default for new user (0/1) + $this->rights[$r][4] = 'create'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $r++; + + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'inventoryWritePermission'; // Permission label + $this->rights[$r][3] = 0; // Permission by default for new user (0/1) + $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $r++; + + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'inventoryValidatePermission'; // Permission label + $this->rights[$r][3] = 0; // Permission by default for new user (0/1) + $this->rights[$r][4] = 'validate'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $r++; + + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'inventoryChangePMPPermission'; // Permission label + $this->rights[$r][3] = 0; // Permission by default for new user (0/1) + $this->rights[$r][4] = 'changePMP'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $r++; + + // Main menu entries + $this->menu = array(); // List of menus to add + $r=0; + + // Add here entries to declare new menus + // + // Example to declare a new Top Menu entry and its Left menu entry: + // $this->menu[$r]=array( 'fk_menu'=>0, // Put 0 if this is a top menu + // 'type'=>'top', // This is a Top menu entry + // 'titre'=>'inventory top menu', + // 'mainmenu'=>'inventory', + // 'leftmenu'=>'inventory', + // 'url'=>'/inventory/pagetop.php', + // 'langs'=>'mylangfile@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + // 'position'=>100, + // 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. + // 'perms'=>'1', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules + // 'target'=>'', + // 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both + // $r++; + // + // Example to declare a Left Menu entry into an existing Top menu entry: + // $this->menu[$r]=array( 'fk_menu'=>'fk_mainmenu=xxx', // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + // 'type'=>'left', // This is a Left menu entry + // 'titre'=>'inventory left menu', + // 'mainmenu'=>'xxx', + // 'leftmenu'=>'inventory', + // 'url'=>'/inventory/pagelevel2.php', + // 'langs'=>'mylangfile@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + // 'position'=>100, + // 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + // 'perms'=>'1', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules + // 'target'=>'', + // 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both + // $r++; + $this->menu[$r]=array( 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', // Put 0 if this is a top menu + 'type'=>'left', // This is a Top menu entry + 'titre'=>'Liste des inventaires', + 'mainmenu'=>'inventory', + 'leftmenu'=>'inventory', + 'url'=>'/inventory/inventory.php?action=list', + 'langs'=>'inventory@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>100, + 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->inventory->read', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both + $r++; + + $this->menu[$r]=array( 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', // Put 0 if this is a top menu + 'type'=>'left', // This is a Top menu entry + 'titre'=>'Nouvel inventaire', + 'mainmenu'=>'inventory', + 'leftmenu'=>'inventory', + 'url'=>'/inventory/inventory.php?action=create', + 'langs'=>'inventory@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>100, + 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->inventory->create', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both + $r++; + + // Exports + $r=1; + + // Example: + // $this->export_code[$r]=$this->rights_class.'_'.$r; + // $this->export_label[$r]='CustomersInvoicesAndInvoiceLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + // $this->export_enabled[$r]='1'; // Condition to show export in list (ie: '$user->id==3'). Set to 1 to always show when module is enabled. + // $this->export_permission[$r]=array(array("facture","facture","export")); + // $this->export_fields_array[$r]=array('s.rowid'=>"IdCompany",'s.nom'=>'CompanyName','s.address'=>'Address','s.zip'=>'Zip','s.town'=>'Town','s.fk_pays'=>'Country','s.phone'=>'Phone','s.siren'=>'ProfId1','s.siret'=>'ProfId2','s.ape'=>'ProfId3','s.idprof4'=>'ProfId4','s.code_compta'=>'CustomerAccountancyCode','s.code_compta_fournisseur'=>'SupplierAccountancyCode','f.rowid'=>"InvoiceId",'f.facnumber'=>"InvoiceRef",'f.datec'=>"InvoiceDateCreation",'f.datef'=>"DateInvoice",'f.total'=>"TotalHT",'f.total_ttc'=>"TotalTTC",'f.tva'=>"TotalVAT",'f.paye'=>"InvoicePaid",'f.fk_statut'=>'InvoiceStatus','f.note'=>"InvoiceNote",'fd.rowid'=>'LineId','fd.description'=>"LineDescription",'fd.price'=>"LineUnitPrice",'fd.tva_tx'=>"LineVATRate",'fd.qty'=>"LineQty",'fd.total_ht'=>"LineTotalHT",'fd.total_tva'=>"LineTotalTVA",'fd.total_ttc'=>"LineTotalTTC",'fd.date_start'=>"DateStart",'fd.date_end'=>"DateEnd",'fd.fk_product'=>'ProductId','p.ref'=>'ProductRef'); + // $this->export_entities_array[$r]=array('s.rowid'=>"company",'s.nom'=>'company','s.address'=>'company','s.zip'=>'company','s.town'=>'company','s.fk_pays'=>'company','s.phone'=>'company','s.siren'=>'company','s.siret'=>'company','s.ape'=>'company','s.idprof4'=>'company','s.code_compta'=>'company','s.code_compta_fournisseur'=>'company','f.rowid'=>"invoice",'f.facnumber'=>"invoice",'f.datec'=>"invoice",'f.datef'=>"invoice",'f.total'=>"invoice",'f.total_ttc'=>"invoice",'f.tva'=>"invoice",'f.paye'=>"invoice",'f.fk_statut'=>'invoice','f.note'=>"invoice",'fd.rowid'=>'invoice_line','fd.description'=>"invoice_line",'fd.price'=>"invoice_line",'fd.total_ht'=>"invoice_line",'fd.total_tva'=>"invoice_line",'fd.total_ttc'=>"invoice_line",'fd.tva_tx'=>"invoice_line",'fd.qty'=>"invoice_line",'fd.date_start'=>"invoice_line",'fd.date_end'=>"invoice_line",'fd.fk_product'=>'product','p.ref'=>'product'); + // $this->export_sql_start[$r]='SELECT DISTINCT '; + // $this->export_sql_end[$r] =' FROM ('.MAIN_DB_PREFIX.'facture as f, '.MAIN_DB_PREFIX.'facturedet as fd, '.MAIN_DB_PREFIX.'societe as s)'; + // $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'product as p on (fd.fk_product = p.rowid)'; + // $this->export_sql_end[$r] .=' WHERE f.fk_soc = s.rowid AND f.rowid = fd.fk_facture'; + // $this->export_sql_order[$r] .=' ORDER BY s.nom'; + // $r++; + } + + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + function init($options='') + { + $sql = array(); + define('INC_FROM_DOLIBARR', true); + dol_include_once('/inventory/config.php'); + dol_include_once("/inventory/script/create-maj-base.php"); + + return $this->_init($sql, $options); + } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + function remove($options='') + { + $sql = array(); + + return $this->_remove($sql, $options); + } + +} diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index f2ff6484c64..76ed46c4aa8 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -159,7 +159,7 @@ class Inventory extends CoreObject parent::update($user); } - function set_values($Tab) + function set_values(&$Tab) { global $db,$langs; @@ -183,7 +183,7 @@ class Inventory extends CoreObject } } - return parent::set_values($Tab); + parent::set_values($Tab); } function deleteAllLine() { diff --git a/htdocs/inventory/img/bt-save.png b/htdocs/inventory/img/bt-save.png new file mode 100644 index 0000000000000000000000000000000000000000..f20d292ca91805ab875cbb48391cba2e94e3f194 GIT binary patch literal 493 zcmV;DB6!8NR z1gjKw5($c?FkoS2VIkVsX<-$VG!`O)SSTs9h<{)au@C}cZ*M*ziUuSX&F#!aXZG$i zF&9m6;4!yzJ8$32ENkWSdHAnIZeIpIwANtTHV_dIA}9tb14(>v14}z6zFdUW+_4$A*W93~2-T2sq_LIMs7|t<;^mkZ8tnBIC^H<%a2WSO j#)$U$lt^ynQ-A>gD&Upv=pk<>00000NkvXXu0mjflc~?j literal 0 HcmV?d00001 diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index 4e70ee1b4cc..1d9ec174257 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -77,6 +77,7 @@ function _action() $inventory->set_values($_POST); $fk_inventory = $inventory->create($user); + $fk_category = (int)GETPOST('fk_category'); $fk_supplier = (int)GETPOST('fk_supplier'); $fk_warehouse = (int)GETPOST('fk_warehouse'); @@ -490,7 +491,7 @@ function _card(&$inventory, $mode='edit') function _card_line(&$inventory, &$lines, $mode) { - global $db; + global $db,$langs,$user,$conf; $inventory->amount_actual = 0; $TCacheEntrepot = array(); @@ -523,7 +524,7 @@ function _card_line(&$inventory, &$lines, $mode) ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 ,'qty_stock' => $stock ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 - ,'action' => ($user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') + ,'action' => ($user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') ,'pmp_stock'=>round($pmp_actual,2) ,'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2) ,'pmp_new'=>(!empty($user->rights->inventory->changePMP) ? '' From 81b01cd05529218ac7dda3a7ad7c55b1fca6d268 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 11:23:13 +0100 Subject: [PATCH 10/41] fix --- htdocs/core/class/coreobject.class.php | 21 +-- htdocs/core/db/DoliDB.class.php | 26 ++-- htdocs/inventory/admin/inventory_setup.php | 168 +++++++++++++++++++++ htdocs/inventory/ajax/ajax.inventory.php | 19 +-- htdocs/inventory/img/plus.png | Bin 0 -> 1299 bytes htdocs/inventory/img/plus16.png | Bin 0 -> 665 bytes htdocs/inventory/inventory.php | 68 ++++----- htdocs/inventory/tpl/inventory.tpl.php | 6 +- 8 files changed, 239 insertions(+), 69 deletions(-) create mode 100644 htdocs/inventory/admin/inventory_setup.php create mode 100644 htdocs/inventory/img/plus.png create mode 100644 htdocs/inventory/img/plus16.png diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 7613a556092..75706403069 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -342,10 +342,10 @@ class CoreObject extends CommonObject { $query = array(); $query = $this->set_save_query(); - $query['id']=$this->id; + $query['rowid']=$this->id; if(empty($this->no_update_tms))$query['tms'] = date('Y-m-d H:i:s'); - $this->db->update($this->table_element,$query,array('id')); + $this->db->update($this->table_element,$query,array('rowid')); $this->id = $this->db->last_insert_id($this->table_element); @@ -382,19 +382,22 @@ class CoreObject extends CommonObject { } } - public function delete(){ + public function delete(User &$user){ if($this->id>0){ $this->call_trigger(strtoupper($this->element). '_DELETE', $user); - $this->db->delete($this->table_element,array('id'=>$this->id),array(0=>'id')); - if($this->withChild) { + $this->db->delete($this->table_element,array('rowid'=>$this->id),array('rowid')); + + if($this->withChild && !empty($this->childtables)) { foreach($this->childtables as &$childTable) { $className = ucfirst($childTable); - foreach($this->{$className} as &$object) { - - $object->delete(); - + if(!empty($this->{$className})) { + foreach($this->{$className} as &$object) { + + $object->delete($user); + + } } } diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index 85766c31949..da0717e665b 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -313,7 +313,6 @@ abstract class DoliDB implements Database function update($table,$fields,$key){ foreach ($fields as $k => $v) { - if(is_string($v)) $v=stripslashes($v); if (is_array($key)){ $i=array_search($k , $key ); @@ -328,10 +327,9 @@ abstract class DoliDB implements Database } } - $tmp[] = $k.'='.$this->quote($val); + $tmp[] = $k.'='.$this->quote($v); } - $sql = sprintf( 'UPDATE '.MAIN_DB_PREFIX.$table.' SET %s WHERE %s' , implode( ',', $tmp ) , implode(' AND ',$where) ); - + $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET '.implode( ',', $tmp ).' WHERE ' . implode(' AND ',$where) ; $res = $this->query( $sql ); if($res===false) { @@ -358,7 +356,9 @@ abstract class DoliDB implements Database } - $sql = sprintf( 'INSERT INTO '.MAIN_DB_PREFIX.$table.' ( %s ) values( %s ) ', implode( ",", $keys ) , implode( ",", $values ) ); + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$table.' + ( '.implode( ",", $keys ).' ) + VALUES ( '.implode( ",", $values ).' ) '; $res = $this->query($sql); if($res===false) { @@ -379,26 +379,30 @@ abstract class DoliDB implements Database */ function delete($table,$fields,$key){ foreach ($fields as $k => $v) { - if(is_string($v)) $v=stripslashes($v); - if (is_array($key)){ $i=array_search($k , $key ); if ( $i !== false) { - $where[] = $key[$i]."=" . $this->escape( $v ) ; + $where[] = $key[$i].'=' . $this->quote( $v ) ; continue; } } else { if ( $k == $key) { - $where[] = "$k=" .$this->escape( $v ) ; + $where[] = $k.'='.$this->quote( $v ) ; continue; } } } - $sql = sprintf( 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.implode(' AND ',$where)); + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.implode(' AND ',$where); - return $this->query( $sql ); + $res = $this->query( $sql ); + if($res===false) { + return false; + } + + return true; + } } diff --git a/htdocs/inventory/admin/inventory_setup.php b/htdocs/inventory/admin/inventory_setup.php new file mode 100644 index 00000000000..f55bc092517 --- /dev/null +++ b/htdocs/inventory/admin/inventory_setup.php @@ -0,0 +1,168 @@ + + * Copyright (C) 2015 ATM Consulting + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file admin/inventory.php + * \ingroup inventory + * \brief This file is an example module setup page + * Put some comments here + */ +// Dolibarr environment +$res = @include("../../main.inc.php"); // From htdocs directory +if (! $res) { + $res = @include("../../../main.inc.php"); // From "custom" directory +} + +// Libraries +require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; +require_once '../lib/inventory.lib.php'; + +// Translations +$langs->load("inventory@inventory"); + +// Access control +if (! $user->admin) { + accessforbidden(); +} + +// Parameters +$action = GETPOST('action', 'alpha'); + +/* + * Actions + */ +if (preg_match('/set_(.*)/',$action,$reg)) +{ + $code=$reg[1]; + if (dolibarr_set_const($db, $code, GETPOST($code), 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + dol_print_error($db); + } +} + +if (preg_match('/del_(.*)/',$action,$reg)) +{ + $code=$reg[1]; + if (dolibarr_del_const($db, $code, 0) > 0) + { + Header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + dol_print_error($db); + } +} + +/* + * View + */ +$page_name = "inventorySetup"; +llxHeader('', $langs->trans($page_name)); + +// Subheader +$linkback = '' + . $langs->trans("BackToModuleList") . ''; +print_fiche_titre($langs->trans($page_name), $linkback); + +// Configuration header +$head = inventoryAdminPrepareHead(); +dol_fiche_head( + $head, + 'settings', + $langs->trans("Module104420Name"), + 0, + "inventory@inventory" +); + +// Setup page goes here +$form=new Form($db); +$var=false; +print '
    trans('Title') ?>texte('', 'title', '',50,255) ?>
    trans('Date') ?>calendrier('', 'date_inventory',time()) ?>select_date(time(),'date_inventory'); ?>
    trans('SelectCategory') ?>select_all_categories(0,'', 'fk_category') ?>select_all_categories(0,'', 'fk_category') ?>
    trans('SelectFournisseur') ?>select_thirdparty('','fk_supplier','s.fournisseur = 1') ?>select_thirdparty('','fk_supplier','s.fournisseur = 1') ?>
    trans('OnlyProdsInStock') ?>
     
    '; +print ''; +print ''."\n"; +print ''; +print ''."\n"; + + +// Example with a yes / no select +$var=!$var; +print ''; +print ''; +print ''; +print ''; + +// Example with a yes / no select +$var=!$var; +print ''; +print ''; +print ''; +print ''; + +// Example with a yes / no select +$var=!$var; +print ''; +print ''; +print ''; +print ''; + +// Example with a yes / no select +$var=!$var; +print ''; +print ''; +print ''; +print ''; + +print '
    '.$langs->trans("Parameters").' '.$langs->trans("Value").'
    '.$langs->trans("INVENTORY_GEN_PDF").' '; +print '
    '; +print ''; +print ''; +print $form->selectyesno("INVENTORY_GEN_PDF",$conf->global->INVENTORY_GEN_PDF,1); +print ''; +print '
    '; +print '
    '.$langs->trans("INVENTORY_DISABLE_VIRTUAL").' '; +print '
    '; +print ''; +print ''; +print $form->selectyesno("INVENTORY_DISABLE_VIRTUAL",$conf->global->INVENTORY_DISABLE_VIRTUAL,1); +print ''; +print '
    '; +print '
    '.$langs->trans("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA").' '; +print '
    '; +print ''; +print ''; +print $form->selectyesno("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA",$conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA,1); +print ''; +print '
    '; +print '
    '.$langs->trans("INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT").' '; +print '
    '; +print ''; +print ''; +print $form->selectyesno("INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT",$conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT,1); +print ''; +print '
    '; +print '
    '; + +llxFooter(); + +$db->close(); \ No newline at end of file diff --git a/htdocs/inventory/ajax/ajax.inventory.php b/htdocs/inventory/ajax/ajax.inventory.php index 34efecfab8f..f2f5ef54903 100644 --- a/htdocs/inventory/ajax/ajax.inventory.php +++ b/htdocs/inventory/ajax/ajax.inventory.php @@ -1,24 +1,21 @@ rights->inventory->write) { echo -1; exit; } $fk_det_inventory = GETPOST('fk_det_inventory'); - $det = new Inventorydet; - if( $det->load($PDOdb, $fk_det_inventory)) { + $det = new Inventorydet($db); + if( $det->fetch( $fk_det_inventory)) { $det->qty_view+=GETPOST('qty'); - $det->save($PDOdb); + $det->update($user); echo $det->qty_view; } @@ -33,10 +30,10 @@ $fk_det_inventory = GETPOST('fk_det_inventory'); - $det = new Inventorydet; - if( $det->load($PDOdb, $fk_det_inventory)) { + $det = new Inventorydet($db); + if( $det->fetch( $fk_det_inventory)) { $det->new_pmp=price2num(GETPOST('pmp')); - $det->save($PDOdb); + $det->update($user); echo $det->new_pmp; } diff --git a/htdocs/inventory/img/plus.png b/htdocs/inventory/img/plus.png new file mode 100644 index 0000000000000000000000000000000000000000..b7072a96960e30374c5d4f6a5e9bfc374e7a532a GIT binary patch literal 1299 zcmV+u1?>8XP)?02y>e zSad^gZEa<4bO1wgWnpw>WFU8GbZ8()Nlj2!fese{00etUL_t(o!?l;qYaC@9$3Hun z-R>r7NwP^cY02AGDU_xVmNpiZDhL+DlP!XX2QLa1CD6aXqaGA`Q1IZ{Lr;QO>Ol{R zp2WMMHcbebDalT=vzd8bJ!ED(nQqc;n|$G6W}auB-}m?a%oI2Pqobn$Jb3URohsGq z^^t0|Is^<^Yb(YWwAO7YWe^0x*4o~|lP4?HYW4b=GiSc2)oMt& zOQw`UDb=}`Qlhm+2+>&!g24E`zZ3+)w{aYcxw$!3R#wnjAFM#FR%2shgHxwYU0PgR zyg5ET-Y66b8FGzMa*qP}d!-b{7=#eCTCG3V*VjLeqUfI|dSHBf9MAJOckbMk3l}cj zs#GfddkHjJ?>-A5&|2>y*IIYHk&fiu*!TUnTdmd|$8j*mbU6F63WQGFf=qov)N=~VxqFRxcK|%=;%V$eR($vA@F_w zmJp(4j3FsQ3k>#G`mbuUyEk1k#&nd>S`$Ul-_2(8)wDv~YPFgwaASCQcp+;^-a08I zJ3BiBL9lf1-o5)-@0CiWsp;wItLd|~mMDq{!;mP7I!ak<7l03dZvfn+QH;#a&VFu; z=^DqpLXP9O`D}Jw*G*l$y}eDd*?g?zGWZ(!4p1&YqtRFz7#Q4B$Jr3%vpk!{DU?!p zp2yD4PS^DuO288Er2~}5#>U=AJ6bl=(~+G^70E*gK^TU;kf(Sbz&(5RY_+eiZ?2p5 zLI|QLVz=e)mQ)ftIJk1TgKEN~K|?)EMwsBiY*8`oZ(OPm9H3(OQeO79oU< zqR8taa21%!DPn-HfOor{FTjLrtsODOIN9V&6%ay%zVCZITBH&s@@Vh#{xM+Kl~SI_ zHjJzS#+U-nkNspgK*deFS{j0UH#=&$g+d`vN_9#pOKyy@hrqF)3mTQhJW#Od4%Sd%2Vn&-1PU*Sc)3 z19x+CQ^3DZ;hAk<-C12--IPM!)mo!6r{3Dy8dA!m4F5W?>KJ38`Lm>YJc;Q)VwFGe zSad^gZEa<4bO1wgWnpw>WFU8GbZ8()Nlj2!fese{00IF?L_t(I%YBf)Yg17i#Xm23 zFPK1Dy0mf1E9sDe1d2mr5Hg8_7!f0Mh@0T9ga1V9(A9sSgE-YX3I4#X2pz;BSuD}m z)YeCH-@WhNyq7wd7oH*QfdgOoo^$wqk3|9-8yoEG>`<%K8ihik7KYKH)&WYXqh7D~ zx!rE>uB@!k>2xL@D;co9zFsYrN_%s2a|^!jqm-IZYmMi5zmJcPZ}>b5A}Ne zQKeFO17v;QM@os5^1qNMigLDXKd~(9n^Nj4K)Tgxk$J`r&9adTWgNVF5IoO)rzl%xkR)f*?Nk#s2>OGXU3hw=Bzg zdU|?_5P~R*0FHoyU9DE{JB~B&`#xH0;*cN+ocO(Nx9fyq$P|`4-O8V$HrVPhm;cF^_T#SL_on- zN}Z=tsmbX{jLnzAR!aR!rBaxoK?t!3YylbI1Mq6BYXbH03rh+APu!w=uUsylyRLf< zB)OdsZcpuE-T|OkES@-yGrinQ1Z>VQcL7*lUdFcV>oWvr!1poFX6)Cd`*?7{nX`EJ zqEgp@-X+FE;9AmPT@Z8&xCvaHv<;ttchkbZ0%0!T4SB2a00000NkvXXu0mjfN$Dr+ literal 0 HcmV?d00001 diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index 1d9ec174257..ccda1b37c0e 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -131,7 +131,7 @@ function _action() if (!$user->rights->inventory->write) accessforbidden(); - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); $inventory->load($PDOdb, $id); @@ -153,7 +153,7 @@ function _action() case 'regulate': - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); $inventory->load($PDOdb, $id); @@ -174,10 +174,10 @@ function _action() case 'changePMP': - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch( $id ); $inventory->changePMP($PDOdb); @@ -188,12 +188,11 @@ function _action() case 'add_line': if (!$user->rights->inventory->write) accessforbidden(); - - $id = __get('id', 0, 'int'); - $fk_warehouse = __get('fk_warehouse', 0, 'int'); + $id = GETPOST('id'); + $fk_warehouse = GETPOST('fk_warehouse'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch( $id ); $type = (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT) ? 'string' : 'int'); //AA heu ? @@ -245,16 +244,17 @@ function _action() //Cette action devrais se faire uniquement si le status de l'inventaire est à 0 mais aucune vérif - $rowid = __get('rowid', 0, 'int'); - $Inventorydet = new Inventory($db); - $Inventorydet->load($PDOdb, $rowid); - $Inventorydet->delete($PDOdb); - - $id = __get('id', 0, 'int'); + $rowid = GETPOST('rowid'); + $Inventorydet = new Inventorydet($db); + if($Inventorydet->fetch($rowid)>0) { + $Inventorydet->delete($user); + setEventMessage("ProductDeletedFromInventory"); + } + $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch( $id); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + _card($inventory, 'edit'); break; case 'flush': @@ -519,16 +519,14 @@ function _card_line(&$inventory, &$lines, $mode) 'produit' => $product->getNomUrl(1).' - '.$product->label ,'entrepot'=>$e->getNomUrl(1) ,'barcode' => $product->barcode - ,'qty' =>($mode == 'edit' ? '' : $qty ) - .($mode =='edit' ? ''.img_picto($langs->trans('Add'), 'plus16@inventory').'' : '') + ,'qty' =>($mode == 'edit' ? ' '.img_picto($langs->trans('Add'), 'plus16@inventory').'' : '' ) ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 ,'qty_stock' => $stock ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 ,'action' => ($user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') ,'pmp_stock'=>round($pmp_actual,2) ,'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2) - ,'pmp_new'=>(!empty($user->rights->inventory->changePMP) ? '' - .($mode =='edit' ? ''.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : '') : '') + ,'pmp_new'=>(!empty($user->rights->inventory->changePMP && $mode =='edit') ? ' '.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : price($Inventorydet->new_pmp)) ,'pa_stock'=>round($last_pa * $stock,2) ,'pa_actual'=>round($last_pa * $Inventorydet->qty_view,2) ,'current_pa_stock'=>round($current_pa * $stock,2) @@ -656,24 +654,24 @@ function _headerList($view) { ?>   Produit - Entrepôt + trans('Warehouse'); ?> barcode->enabled)) { ?> - Code-barre + trans('Barcode'); ?> - Quantité théorique + trans('TheoricalQty'); ?> global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ - echo 'Valeur théorique'; + echo ''.$langs->trans('TheoricalValue').''; } else { - echo 'Valeur théorique'; + echo ''.$langs->trans('TheoricalValue').''; } ?> - Quantité réelle + trans('RealQty'); ?> global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++; if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)) $colspan++; - echo 'Valeur réelle'; + echo ''.$langs->trans('RealValue').''; ?> - Quantité régulée + trans('RegulatedQty'); ?> # - +   - PMP - Dernier PA + trans('PMP'); ?> + trans('LastPA'); ?> global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ - echo 'PA courant'; + echo ''.$langs->trans('CurrentPA').''; } ?>   - PMP + trans('PMP'); ?> rights->inventory->changePMP)) { echo ''.$langs->trans('ColumnNewPMP').''; } ?> - Dernier PA + trans('LastPA'); ?> global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ - echo 'PA courant'; + echo ''.$langs->trans('CurrentPA').''; } ?> diff --git a/htdocs/inventory/tpl/inventory.tpl.php b/htdocs/inventory/tpl/inventory.tpl.php index 8a3bfd0f2a6..c3c1347446b 100644 --- a/htdocs/inventory/tpl/inventory.tpl.php +++ b/htdocs/inventory/tpl/inventory.tpl.php @@ -8,7 +8,7 @@ $('#a_save_qty_'+k).hide(); $.ajax({ - url:"script/interface.php" + url:"ajax/ajax.inventory.php" ,data:{ 'fk_det_inventory' : fk_det_inventory ,'qty': qty @@ -37,7 +37,7 @@ $('#a_save_new_pmp_'+k).hide(); $.ajax({ - url:"script/interface.php" + url:"ajax/ajax.inventory.php" ,data:{ 'fk_det_inventory' : fk_det_inventory ,'pmp': pmp @@ -137,7 +137,7 @@ rights->inventory->changePMP)) { - echo ''.$row['pmp_new'].''; + echo ''.$row['pmp_new'].''; } ?> From 9f6f87465503e57e757b46b4de0c783a510f17b8 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 12:33:26 +0100 Subject: [PATCH 11/41] fix --- htdocs/core/class/coreobject.class.php | 4 +- htdocs/core/db/DoliDB.class.php | 2 +- htdocs/inventory/class/inventory.class.php | 55 ++++++++++++---- htdocs/inventory/inventory.php | 73 ++++++---------------- 4 files changed, 64 insertions(+), 70 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 75706403069..50b59761b1d 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -158,7 +158,7 @@ class CoreObject extends CommonObject { $query[$field] = $this->date_0; } else{ - $query[$field] = $this->db->jdate($this->{$field}); + $query[$field] = $this->db->idate($this->{$field}); } } else if($this->is_array($info)){ @@ -427,7 +427,6 @@ class CoreObject extends CommonObject { } else { require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $this->{$field} = dol_stringtotime($date); } @@ -435,6 +434,7 @@ class CoreObject extends CommonObject { } public function set_values(&$Tab) { + foreach ($Tab as $key=>$value) { if($this->checkFieldType($key,'date')) { diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index da0717e665b..230572050b5 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -355,7 +355,7 @@ abstract class DoliDB implements Database $values[] = $this->quote($v); } - + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$table.' ( '.implode( ",", $keys ).' ) VALUES ( '.implode( ",", $values ).' ) '; diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index 76ed46c4aa8..b02d601854d 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -71,8 +71,9 @@ class Inventory extends CoreObject public $db; - function __construct(DoliDB &$db) + public function __construct(DoliDB &$db) { + global $conf; $this->db = &$db; @@ -85,13 +86,13 @@ class Inventory extends CoreObject } - function sort_det() + private function sort_det() { if(!empty($this->Inventorydet)) usort($this->Inventorydet, array('Inventory', 'customSort')); } - function fetch($id,$annexe = true) + public function fetch($id,$annexe = true) { if(!$annexe) $this->withChild = false; @@ -115,7 +116,7 @@ class Inventory extends CoreObject } - function customSort(&$objA, &$objB) + private function customSort(&$objA, &$objB) { global $db; @@ -128,7 +129,7 @@ class Inventory extends CoreObject return $r; } - function changePMP() { + public function changePMP() { foreach ($this->Inventorydet as $k => &$Inventorydet) { @@ -147,7 +148,7 @@ class Inventory extends CoreObject } - function update(User &$user) + public function update(User &$user) { //si on valide l'inventaire on sauvegarde le stock à cette instant @@ -159,7 +160,7 @@ class Inventory extends CoreObject parent::update($user); } - function set_values(&$Tab) + public function set_values(&$Tab) { global $db,$langs; @@ -186,19 +187,19 @@ class Inventory extends CoreObject parent::set_values($Tab); } - function deleteAllLine() { + public function deleteAllLine(User &$user) { foreach($this->Inventorydet as &$det) { $det->to_delete = true; } - $this->update(); + $this->update($user); $this->Inventorydet=array(); } - function add_product($fk_product, $fk_entrepot='') { + public function add_product($fk_product, $fk_entrepot='') { $k = $this->addChild('Inventorydet'); $det = &$this->Inventorydet[$k]; @@ -215,7 +216,7 @@ class Inventory extends CoreObject } - function correct_stock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='') + public function correct_stock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='') { global $conf, $db, $langs, $user; @@ -250,7 +251,7 @@ class Inventory extends CoreObject } } - function regulate() + public function regulate() { global $db,$user,$langs,$conf; @@ -312,6 +313,36 @@ class Inventory extends CoreObject } + public function add_products_for($fk_warehouse,$fk_category=0,$fk_supplier=0,$only_prods_in_stock=0) { + $e = new Entrepot($this->db); + $e->fetch($fk_warehouse); + $TChildWarehouses = array($fk_warehouse); + $e->get_children_warehouses($fk_warehouse, $TChildWarehouses); + + $sql = 'SELECT ps.fk_product, ps.fk_entrepot + FROM '.MAIN_DB_PREFIX.'product_stock ps + INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = ps.fk_product) + LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product cp ON (cp.fk_product = p.rowid) + LEFT JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid) + WHERE ps.fk_entrepot IN ('.implode(', ', $TChildWarehouses).')'; + + if($fk_category>0) $sql.= " AND cp.fk_categorie=".$fk_category; + if($fk_supplier>0) $sql.= " AND pfp.fk_soc=".$fk_supplier; + if(!empty($only_prods_in_stock)) $sql.= ' AND ps.reel > 0'; + + $sql.=' GROUP BY ps.fk_product, ps.fk_entrepot + ORDER BY p.ref ASC,p.label ASC'; + + $res = $this->db->query($sql); + if($res) { + while($obj = $this->db->fetch_object($res)){ + $this->add_product($obj->fk_product, $obj->fk_entrepot); + } + } + + + } + static function getLink($id) { global $langs,$db; diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index ccda1b37c0e..b03627d326a 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -83,34 +83,7 @@ function _action() $fk_warehouse = (int)GETPOST('fk_warehouse'); $only_prods_in_stock = (int)GETPOST('OnlyProdsInStock'); - $e = new Entrepot($db); - $e->fetch($fk_warehouse); - $TChildWarehouses = array($fk_warehouse); - $e->get_children_warehouses($fk_warehouse, $TChildWarehouses); - - $sql = 'SELECT ps.fk_product, ps.fk_entrepot - FROM '.MAIN_DB_PREFIX.'product_stock ps - INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = ps.fk_product) - LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product cp ON (cp.fk_product = p.rowid) - LEFT JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid) - WHERE ps.fk_entrepot IN ('.implode(', ', $TChildWarehouses).')'; - - if($fk_category>0) $sql.= " AND cp.fk_categorie=".$fk_category; - if($fk_supplier>0) $sql.= " AND pfp.fk_soc=".$fk_supplier; - if($only_prods_in_stock>0) $sql.= ' AND ps.reel > 0'; - - $sql.=' GROUP BY ps.fk_product, ps.fk_entrepot - ORDER BY p.ref ASC,p.label ASC'; - - - $res = $db->query($sql); - if($res) { - while($obj = $db->fetch_object($res)){ - - $inventory->add_product($obj->fk_product, $obj->fk_entrepot); - } - } - + $inventory->add_products_for($fk_warehouse,$fk_category,$fk_supplier,$only_prods_in_stock); $inventory->update($user); header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->id.'&action=edit', 1)); @@ -134,14 +107,14 @@ function _action() $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch($id); $inventory->set_values($_REQUEST); if ($inventory->errors) { setEventMessage($inventory->errors, 'errors'); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + _card( $inventory, 'edit'); } else { @@ -156,18 +129,18 @@ function _action() $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch($id); if($inventory->status == 0) { $inventory->status = 1; - $inventory->save($PDOdb); + $inventory->update($user); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + _card( $inventory, 'view'); } else { - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + _card( $inventory, 'view'); } break; @@ -181,7 +154,7 @@ function _action() $inventory->changePMP($PDOdb); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'view'); + _card( $inventory, 'view'); break; @@ -235,7 +208,7 @@ function _action() $inventory->sort_det(); } - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + _card( $inventory, 'edit'); break; @@ -261,16 +234,16 @@ function _action() if (!$user->rights->inventory->create) accessforbidden(); - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch($id); $inventory->deleteAllLine($PDOdb); setEventMessage('Inventaire vidé'); - _fiche($PDOdb, $user, $db, $conf, $langs, $inventory, 'edit'); + _card( $inventory, 'edit'); break; @@ -278,33 +251,23 @@ function _action() if (!$user->rights->inventory->create) accessforbidden(); - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch($id); - $inventory->delete($PDOdb); + $inventory->delete($user); header('Location: '.dol_buildpath('/inventory/inventory.php', 1)); exit; //_list(); - case 'printDoc': - - $id = __get('id', 0, 'int'); - - $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); - - generateODT($PDOdb, $db, $conf, $langs, $inventory); - break; - case 'exportCSV': - $id = __get('id', 0, 'int'); + $id = GETPOST('id'); $inventory = new Inventory($db); - $inventory->load($PDOdb, $id); + $inventory->fetch($id); exportCSV($inventory); @@ -453,7 +416,7 @@ function _card(&$inventory, $mode='edit') $warehouse = new Entrepot($db); $warehouse->fetch($inventory->fk_warehouse); - print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), '&action='.$mode)); + print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), empty($mode) ? '': '&action='.$mode)); $lines = array(); _card_line($inventory, $lines, $mode); From 1596760d21211d562717467d5043e96d9eda3245 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 17:02:20 +0100 Subject: [PATCH 12/41] fix regulate / apply new PMP / add or remove line --- htdocs/core/class/coreobject.class.php | 24 +++- htdocs/inventory/class/inventory.class.php | 47 ++++---- htdocs/inventory/inventory.php | 129 ++++++++++++++------- htdocs/inventory/tpl/inventory.tpl.php | 26 ++--- 4 files changed, 142 insertions(+), 84 deletions(-) diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 50b59761b1d..2022844d6fe 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -35,6 +35,7 @@ class CoreObject extends CommonObject { public $date_0 = '1001-01-01 00:00:00'; //TODO there is a solution for this ? + public $error = ''; /* * @var Array $_fields Fields to synchronize with Database */ @@ -244,6 +245,8 @@ class CoreObject extends CommonObject { return $this->id; } else { + $this->error = $this->db->lasterror(); + return false; } @@ -335,7 +338,7 @@ class CoreObject extends CommonObject { if(empty($this->id )) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed if(isset($this->to_delete) && $this->to_delete==true) { - $this->delete(); + $this->delete($user); } else { @@ -345,13 +348,21 @@ class CoreObject extends CommonObject { $query['rowid']=$this->id; if(empty($this->no_update_tms))$query['tms'] = date('Y-m-d H:i:s'); - $this->db->update($this->table_element,$query,array('rowid')); + $res = $this->db->update($this->table_element,$query,array('rowid')); - $this->id = $this->db->last_insert_id($this->table_element); + if($res) { + + $result = $this->call_trigger(strtoupper($this->element). '_UPDATE', $user); - $result = $this->call_trigger(strtoupper($this->element). '_UPDATE', $user); + $this->saveChild($user); + + return true; + } + else{ + $this->error = $this->db->lasterror(); - $this->saveChild($user); + return false; + } } return $this->id; @@ -378,6 +389,9 @@ class CoreObject extends CommonObject { return $this->id; } else{ + + $this->error = $this->db->lasterror(); + return false; } diff --git a/htdocs/inventory/class/inventory.class.php b/htdocs/inventory/class/inventory.class.php index b02d601854d..b39445807e9 100644 --- a/htdocs/inventory/class/inventory.class.php +++ b/htdocs/inventory/class/inventory.class.php @@ -86,7 +86,7 @@ class Inventory extends CoreObject } - private function sort_det() + public function sort_det() { if(!empty($this->Inventorydet)) usort($this->Inventorydet, array('Inventory', 'customSort')); @@ -129,22 +129,23 @@ class Inventory extends CoreObject return $r; } - public function changePMP() { - - foreach ($this->Inventorydet as $k => &$Inventorydet) - { - - if($Inventorydet->new_pmp>0) { - $Inventorydet->pmp = $Inventorydet->new_pmp; - $Inventorydet->new_pmp = 0; - - $db->query("UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$Inventorydet->pmp." - WHERE rowid = ".$Inventorydet->fk_product ); + public function changePMP(User &$user) { + if(!empty($this->Inventorydet)) { + foreach ($this->Inventorydet as $k => &$Inventorydet) + { + if($Inventorydet->new_pmp>0) { + $Inventorydet->pmp = $Inventorydet->new_pmp; + $Inventorydet->new_pmp = 0; + + $this->db->query("UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$Inventorydet->pmp." + WHERE rowid = ".$Inventorydet->fk_product ); + + } } } - parent::save($PDOdb); + return parent::update($user); } @@ -214,6 +215,7 @@ class Inventory extends CoreObject if(empty($date))$date = $this->get_date('datec', 'Y-m-d'); $det->setStockDate( $date , $fk_entrepot); + return true; } public function correct_stock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='') @@ -233,6 +235,9 @@ class Inventory extends CoreObject $datem = empty($conf->global->INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT) ? dol_now() : $this->date_inventory; $movementstock=new MouvementStock($db); + $movementstock->origin = new stdClass(); + $movementstock->origin->element = 'inventory'; + $movementstock->origin->id = $this->id; $result=$movementstock->_create($user,$fk_product,$fk_warehouse,$op[$movement],$movement,$price,$label,$inventorycode, $datem); if ($result >= 0) @@ -289,10 +294,7 @@ class Inventory extends CoreObject $href = dol_buildpath('/inventory/inventory.php?id='.$this->id.'&action=view', 1); - if(empty($this->title)) - $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock', $href, $this->id)); - else - $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStockWithNomInventaire', $href, $this->title)); + $this->correct_stock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock')); } } @@ -304,12 +306,15 @@ class Inventory extends CoreObject return 1; } - public function getNomUrl($picto = 1) { + public function getTitle() { global $langs; - $title = !empty($this->title) ? $this->title : $langs->trans('inventoryTitle').' '.$this->id; - - return ''.($picto ? img_picto('','object_list.png','',0).' ' : '').$title.''; + return !empty($this->title) ? $this->title : $langs->trans('inventoryTitle').' '.$this->id; + } + + public function getNomUrl($picto = 1) { + + return ''.($picto ? img_picto('','object_list.png','',0).' ' : '').$this->getTitle().''; } diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index b03627d326a..5a87eb94ceb 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -77,16 +77,25 @@ function _action() $inventory->set_values($_POST); $fk_inventory = $inventory->create($user); - - $fk_category = (int)GETPOST('fk_category'); - $fk_supplier = (int)GETPOST('fk_supplier'); - $fk_warehouse = (int)GETPOST('fk_warehouse'); - $only_prods_in_stock = (int)GETPOST('OnlyProdsInStock'); + if($fk_inventory>0) { + + $fk_category = (int)GETPOST('fk_category'); + $fk_supplier = (int)GETPOST('fk_supplier'); + $fk_warehouse = (int)GETPOST('fk_warehouse'); + $only_prods_in_stock = (int)GETPOST('OnlyProdsInStock'); + + $inventory->add_products_for($fk_warehouse,$fk_category,$fk_supplier,$only_prods_in_stock); + $inventory->update($user); + + header('Location: '.dol_buildpath('/inventory/inventory.php?id='.$inventory->id.'&action=edit', 1)); + + } + else{ + + setEventMessage($inventory->error,'errors'); + header('Location: '.dol_buildpath('/inventory/inventory.php?action=create', 1)); + } - $inventory->add_products_for($fk_warehouse,$fk_category,$fk_supplier,$only_prods_in_stock); - $inventory->update($user); - - header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->id.'&action=edit', 1)); break; case 'edit': @@ -118,14 +127,14 @@ function _action() } else { - $inventory->save($PDOdb); + $inventory->udpate($user); header('Location: '.dol_buildpath('inventory/inventory.php?id='.$inventory->getId().'&action=view', 1)); } break; - case 'regulate': - + case 'confirm_regulate': + if (!$user->rights->inventory->write) accessforbidden(); $id = GETPOST('id'); $inventory = new Inventory($db); @@ -145,14 +154,14 @@ function _action() break; - case 'changePMP': + case 'confirm_changePMP': $id = GETPOST('id'); $inventory = new Inventory($db); $inventory->fetch( $id ); - $inventory->changePMP($PDOdb); + $inventory->changePMP($user); _card( $inventory, 'view'); @@ -167,35 +176,33 @@ function _action() $inventory = new Inventory($db); $inventory->fetch( $id ); - $type = (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT) ? 'string' : 'int'); //AA heu ? - - $fk_product = __get('fk_product', 0, $type); - - if ($fk_product) + $fk_product = GETPOST('fk_product'); + if ($fk_product>0) { $product = new Product($db); - $product->fetch($fk_product); // ! ref TODO vérifier quand même - if($product->type != 0) { + if($product->fetch($fk_product)<=0 || $product->type != 0) { setEventMessage($langs->trans('ThisIsNotAProduct'),'errors'); } else{ //Check product not already exists $alreadyExists = false; - foreach ($inventory->Inventorydet as $invdet) - { - if ($invdet->fk_product == $product->id - && $invdet->fk_warehouse == $fk_warehouse) + if(!empty($inventory->Inventorydet)) { + foreach ($inventory->Inventorydet as $invdet) { - $alreadyExists = true; - break; + if ($invdet->fk_product == $product->id + && $invdet->fk_warehouse == $fk_warehouse) + { + $alreadyExists = true; + break; + } } } - if (!$alreadyExists) { - $inventory->add_product($PDOdb, $product->id, $fk_warehouse); - + if($inventory->add_product($product->id, $fk_warehouse)) { + setEventMessage($langs->trans('ProductAdded')); + } } else { @@ -204,7 +211,7 @@ function _action() } - $inventory->save($PDOdb); + $inventory->update($user); $inventory->sort_det(); } @@ -212,7 +219,7 @@ function _action() break; - case 'delete_line': + case 'confirm_delete_line': if (!$user->rights->inventory->write) accessforbidden(); @@ -230,7 +237,7 @@ function _action() _card($inventory, 'edit'); break; - case 'flush': + case 'confirm_flush': if (!$user->rights->inventory->create) accessforbidden(); @@ -239,15 +246,15 @@ function _action() $inventory = new Inventory($db); $inventory->fetch($id); - $inventory->deleteAllLine($PDOdb); + $inventory->deleteAllLine($user); - setEventMessage('Inventaire vidé'); + setEventMessage($langs->trans('InventoryFlushed')); _card( $inventory, 'edit'); break; - case 'delete': + case 'confirm_delete': if (!$user->rights->inventory->create) accessforbidden(); @@ -258,7 +265,9 @@ function _action() $inventory->delete($user); - header('Location: '.dol_buildpath('/inventory/inventory.php', 1)); + setEventMessage($langs->trans('InventoryDeleted')); + + header('Location: '.dol_buildpath('/inventory/inventory.php?action=list', 1)); exit; //_list(); @@ -407,19 +416,53 @@ function _card_warehouse(&$inventory) llxFooter(''); } -function _card(&$inventory, $mode='edit') +function _card(&$inventory, $action='edit') { - global $langs, $conf, $db, $user; + global $langs, $conf, $db, $user,$form; llxHeader('',$langs->trans('inventoryEdit'),'',''); + if($action == 'changePMP') { + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$inventory->id,$langs->trans('ApplyNewPMP') + ,$langs->trans('ConfirmApplyNewPMP',$inventory->getTitle()),'confirm_changePMP' + ,array(),'no',1); + + } + else if($action == 'flush') { + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$inventory->id,$langs->trans('FlushInventory') + ,$langs->trans('ConfirmFlushInventory',$inventory->getTitle()),'confirm_flush' + ,array(),'no',1); + + } + else if($action == 'delete') { + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$inventory->id,$langs->trans('Delete') + ,$langs->trans('ConfirmDelete',$inventory->getTitle()),'confirm_delete' + ,array(),'no',1); + + } + else if($action == 'delete_line') { + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$inventory->id.'&rowid='.GETPOST('rowid'),$langs->trans('DeleteLine') + ,$langs->trans('ConfirmDeleteLine',$inventory->getTitle()),'confirm_delete_line' + ,array(),'no',1); + + } + else if($action == 'regulate') { + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$inventory->id,$langs->trans('RegulateStock') + ,$langs->trans('ConfirmRegulateStock',$inventory->getTitle()),'confirm_regulate' + ,array(),'no',1); + + } + $warehouse = new Entrepot($db); $warehouse->fetch($inventory->fk_warehouse); - print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), empty($mode) ? '': '&action='.$mode)); + print dol_get_fiche_head(inventoryPrepareHead($inventory, $langs->trans('inventoryOfWarehouse', $warehouse->libelle), empty($action) ? '': '&action='.$action)); $lines = array(); - _card_line($inventory, $lines, $mode); + _card_line($inventory, $lines, $action); print ''.$langs->trans('inventoryOnDate')." ".$inventory->get_date('date_inventory').'

    '; @@ -439,7 +482,7 @@ function _card(&$inventory, $mode='edit') $view_url = dol_buildpath('/inventory/inventory.php', 1); $view = array( - 'mode' => $mode + 'mode' => $action ,'url' => dol_buildpath('/inventory/inventory.php', 1) ,'can_validate' => (int) $user->rights->inventory->validate ,'is_already_validate' => (int) $inventory->status @@ -486,7 +529,7 @@ function _card_line(&$inventory, &$lines, $mode) ,'qty_view' => $Inventorydet->qty_view ? $Inventorydet->qty_view : 0 ,'qty_stock' => $stock ,'qty_regulated' => $Inventorydet->qty_regulated ? $Inventorydet->qty_regulated : 0 - ,'action' => ($user->rights->inventory->write ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') + ,'action' => ($user->rights->inventory->write && $mode=='edit' ? ''.img_picto($langs->trans('inventoryDeleteLine'), 'delete').'' : '') ,'pmp_stock'=>round($pmp_actual,2) ,'pmp_actual'=> round($pmp * $Inventorydet->qty_view,2) ,'pmp_new'=>(!empty($user->rights->inventory->changePMP && $mode =='edit') ? ' '.img_picto($langs->trans('Save'), 'bt-save.png@inventory').'' : price($Inventorydet->new_pmp)) diff --git a/htdocs/inventory/tpl/inventory.tpl.php b/htdocs/inventory/tpl/inventory.tpl.php index c3c1347446b..d707ec581b1 100644 --- a/htdocs/inventory/tpl/inventory.tpl.php +++ b/htdocs/inventory/tpl/inventory.tpl.php @@ -159,44 +159,40 @@ } _footerList($view,$total_pmp,$total_pmp_actual,$total_pa,$total_pa_actual, $total_current_pa,$total_current_pa_actual); - ?> - - + ?> - + status != 1) { ?>
    - + trans('ExportCSV') ?> trans('Modify') ?> rights->inventory->changePMP)) { - echo ''.$langs->trans('ApplyPMP').''; + echo ''.$langs->trans('ApplyPMP').''; } if ($can_validate == 1) { ?> - Réguler le stock + trans('RegulateStock') ?> - - + + - Vider + trans('Flush'); ?>     - Supprimer + trans('Delete') ?>
    - + status == 1) { ?> From b7a6a71dff921c7bca72fcca7c964fd7b2c0b7a5 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 17:20:46 +0100 Subject: [PATCH 13/41] move file to core --- .../inventory.php} | 26 +-- ...ntory.class.php => modInventory.class.php} | 4 +- htdocs/inventory/lib/inventory.lib.php | 161 +----------------- 3 files changed, 15 insertions(+), 176 deletions(-) rename htdocs/{inventory/admin/inventory_setup.php => admin/inventory.php} (84%) rename htdocs/core/modules/{modinventory.class.php => modInventory.class.php} (99%) diff --git a/htdocs/inventory/admin/inventory_setup.php b/htdocs/admin/inventory.php similarity index 84% rename from htdocs/inventory/admin/inventory_setup.php rename to htdocs/admin/inventory.php index f55bc092517..2548494fc79 100644 --- a/htdocs/inventory/admin/inventory_setup.php +++ b/htdocs/admin/inventory.php @@ -23,17 +23,16 @@ * Put some comments here */ // Dolibarr environment -$res = @include("../../main.inc.php"); // From htdocs directory -if (! $res) { - $res = @include("../../../main.inc.php"); // From "custom" directory -} +require '../main.inc.php'; + // Libraries require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; -require_once '../lib/inventory.lib.php'; +require_once DOL_DOCUMENT_ROOT .'/inventory/lib/inventory.lib.php'; // Translations -$langs->load("inventory@inventory"); +$langs->load("stock"); +$langs->load("inventory"); // Access control if (! $user->admin) { @@ -104,21 +103,6 @@ print ''.$langs->trans("Parameters").''."\n"; print ' '; print ''.$langs->trans("Value").''."\n"; - -// Example with a yes / no select -$var=!$var; -print ''; -print ''.$langs->trans("INVENTORY_GEN_PDF").''; -print ' '; -print ''; -print '
    '; -print ''; -print ''; -print $form->selectyesno("INVENTORY_GEN_PDF",$conf->global->INVENTORY_GEN_PDF,1); -print ''; -print '
    '; -print ''; - // Example with a yes / no select $var=!$var; print ''; diff --git a/htdocs/core/modules/modinventory.class.php b/htdocs/core/modules/modInventory.class.php similarity index 99% rename from htdocs/core/modules/modinventory.class.php rename to htdocs/core/modules/modInventory.class.php index 10fb1cc477e..31170375752 100644 --- a/htdocs/core/modules/modinventory.class.php +++ b/htdocs/core/modules/modInventory.class.php @@ -94,7 +94,7 @@ class modinventory extends DolibarrModules $this->dirs = array(); // Config pages. Put here list of php page, stored into inventory/admin directory, to use to setup module. - $this->config_page_url = array("inventory_setup.php@inventory"); + $this->config_page_url = array("inventory.php"); // Dependencies $this->hidden = false; // A condition to hide module @@ -103,7 +103,7 @@ class modinventory extends DolibarrModules $this->conflictwith = array(); // List of modules id this module is in conflict with $this->phpmin = array(5,0); // Minimum version of PHP required by module $this->need_dolibarr_version = array(3,0); // Minimum version of Dolibarr required by module - $this->langfiles = array("inventory@inventory"); + $this->langfiles = array("inventory"); // Constants // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) diff --git a/htdocs/inventory/lib/inventory.lib.php b/htdocs/inventory/lib/inventory.lib.php index fd60d631a58..3cbf03a67c7 100644 --- a/htdocs/inventory/lib/inventory.lib.php +++ b/htdocs/inventory/lib/inventory.lib.php @@ -32,14 +32,11 @@ function inventoryAdminPrepareHead() $h = 0; $head = array(); - $head[$h][0] = dol_buildpath("/inventory/admin/inventory_setup.php", 1); + $head[$h][0] = dol_buildpath("/admin/inventory.php", 1); $head[$h][1] = $langs->trans("Parameters"); $head[$h][2] = 'settings'; $h++; - $head[$h][0] = dol_buildpath("/inventory/admin/inventory_about.php", 1); - $head[$h][1] = $langs->trans("About"); - $head[$h][2] = 'about'; - $h++; + // Show more tabs from modules // Entries must be declared in modules descriptor with line @@ -54,10 +51,12 @@ function inventoryAdminPrepareHead() return $head; } -function inventoryPrepareHead(&$inventory, $title='Inventaire', $get='') +function inventoryPrepareHead(&$inventory, $title='Inventory', $get='') { + global $langs; + return array( - array(dol_buildpath('/inventory/inventory.php?id='.$inventory->id.$get, 1), $title,'inventaire') + array(dol_buildpath('/inventory/inventory.php?id='.$inventory->id.$get, 1), $langs->trans($title),'inventory') ); } @@ -65,7 +64,7 @@ function inventoryPrepareHead(&$inventory, $title='Inventaire', $get='') function inventorySelectProducts(&$inventory) { - global $conf,$db; + global $conf,$db,$langs; $except_product_id = array(); @@ -78,7 +77,6 @@ function inventorySelectProducts(&$inventory) $form = new Form($db); $form->select_produits(-1, 'fk_product'); - // Il nous faut impérativement une liste custom car il ne faut que les entrepôts de la famille de celui qu'on inventorie $TChildWarehouses = array($inventory->fk_warehouse); $e = new Entrepot($db); $e->fetch($inventory->fk_warehouse); @@ -93,153 +91,10 @@ function inventorySelectProducts(&$inventory) $Tab[$res->rowid] = $res->label; } print '   '; - print 'Entrepôt : '.$form::selectarray('fk_warehouse', $Tab); + print $langs->trans('Warehouse').' : '.$form::selectarray('fk_warehouse', $Tab); $select_html = ob_get_clean(); return $select_html; } -function ajaxAutocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array()) -{ - if (empty($minLength)) $minLength=1; - - $script = ''; - - $script.= ''; - - return $script; -} From e65ae08e5cbf926a16ee75c655dc50fe4e955ac0 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Thu, 15 Dec 2016 17:42:14 +0100 Subject: [PATCH 14/41] langs --- htdocs/inventory/inventory.php | 7 ++--- htdocs/langs/en_US/inventory.lang | 52 +++++++++++++++++++++++++++++++ htdocs/langs/fr_FR/inventory.lang | 50 +++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 htdocs/langs/en_US/inventory.lang create mode 100644 htdocs/langs/fr_FR/inventory.lang diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index 5a87eb94ceb..d0ca303c239 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -23,8 +23,6 @@ require_once '../main.inc.php'; -ini_set('memory_limit', '512M'); - require_once DOL_DOCUMENT_ROOT.'/core/class/listview.class.php'; require_once DOL_DOCUMENT_ROOT.'/inventory/class/inventory.class.php'; require_once DOL_DOCUMENT_ROOT.'/inventory/lib/inventory.lib.php'; @@ -35,12 +33,11 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; -set_time_limit(0); +$langs->load("stock"); +$langs->load("inventory"); if(!$user->rights->inventory->read) accessforbidden(); -$langs->load("inventory"); - _action(); function _action() diff --git a/htdocs/langs/en_US/inventory.lang b/htdocs/langs/en_US/inventory.lang new file mode 100644 index 00000000000..ba947f09d77 --- /dev/null +++ b/htdocs/langs/en_US/inventory.lang @@ -0,0 +1,52 @@ +# Dolibarr language file - Source file is en_US - inventory + +Module104420Name = Inventory +Module104420Desc = Create and manage your inventory + +inventorySetup = Inventory Setup + +inventoryCreatePermission=Create new inventory +inventoryReadPermission=View inventories +inventoryWritePermission=Update inventories +inventoryValidatePermission=Validate inventory + +inventoryTitle=Inventory +inventoryListTitle=List +inventoryListEmpty=No inventory in progress + +inventoryCreateDelete=Create/Delete inventory +inventoryCreate=Create new +inventoryEdit=Edit +inventoryValidate=Validated +inventoryDraft=Running +inventorySelectWarehouse=Warehouse choice +inventoryConfirmCreate=Create +inventoryOfWarehouse=Inventory for warehouse : %s +inventoryErrorQtyAdd=Error : one quantity is leaser than zero +inventoryMvtStock=By inventory +inventoryWarningProductAlreadyExists=This product is already into list +SelectCategory=Category filter +SelectFournisseur=Supplier filter +inventoryOnDate=Inventory +INVENTORY_DISABLE_VIRTUAL=Allow to not destock child product from a kit on inventory +INVENTORY_USE_MIN_PA_IF_NO_LAST_PA=Use the buy price if no last buy price can be found +INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT=Stock mouvment have date of inventory +inventoryChangePMPPermission=Allow to change PMP value for a product +ColumnNewPMP=New unit PMP +OnlyProdsInStock=Do not add product without stock +TheoricalQty=Theorique qty +TheoricalValue=Theorique qty +LastPA=Last BP +CurrentPA=Curent BP +RealQty=Real Qty +RealValue=Real Value +RegulatedQty=Regulated Qty +AddInventoryProduct=Add product to inventory +AddProduct=Add +ApplyPMP=Apply PMP +FlushInventory=Flush inventory +ConfirmFlushInventory=Do you confirm this action ? +InventoryFlushed=Inventory flushed +ExitEditMode=Exit edition +inventoryDeleteLine=Delete line +RegulateStock=Regulate Stock \ No newline at end of file diff --git a/htdocs/langs/fr_FR/inventory.lang b/htdocs/langs/fr_FR/inventory.lang new file mode 100644 index 00000000000..85fdf3112dc --- /dev/null +++ b/htdocs/langs/fr_FR/inventory.lang @@ -0,0 +1,50 @@ +Module104420Name = Inventory +Module104420Desc = Create and manage your inventory + +inventorySetup = Inventory Setup + +inventoryCreatePermission=Create new inventory +inventoryReadPermission=View inventories +inventoryWritePermission=Update inventories +inventoryValidatePermission=Validate inventory + +inventoryTitle=Inventory +inventoryListTitle=List +inventoryListEmpty=No inventory in progress + +inventoryCreateDelete=Create/Delete inventory +inventoryCreate=Create new +inventoryEdit=Edit +inventoryValidate=Validated +inventoryDraft=Running +inventorySelectWarehouse=Warehouse choice +inventoryConfirmCreate=Create +inventoryOfWarehouse=Inventory for warehouse : %s +inventoryErrorQtyAdd=Error : one quantity is leaser than zero +inventoryMvtStock=By inventory +inventoryWarningProductAlreadyExists=This product is already into list +SelectCategory=Category filter +SelectFournisseur=Supplier filter +inventoryOnDate=Inventory +INVENTORY_DISABLE_VIRTUAL=Allow to not destock child product from a kit on inventory +INVENTORY_USE_MIN_PA_IF_NO_LAST_PA=Use the buy price if no last buy price can be found +INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT=Stock mouvment have date of inventory +inventoryChangePMPPermission=Allow to change PMP value for a product +ColumnNewPMP=New unit PMP +OnlyProdsInStock=Do not add product without stock +TheoricalQty=Theorique qty +TheoricalValue=Theorique qty +LastPA=Last BP +CurrentPA=Curent BP +RealQty=Real Qty +RealValue=Real Value +RegulatedQty=Regulated Qty +AddInventoryProduct=Add product to inventory +AddProduct=Add +ApplyPMP=Apply PMP +FlushInventory=Flush inventory +ConfirmFlushInventory=Do you confirm this action ? +InventoryFlushed=Inventory flushed +ExitEditMode=Exit edition +inventoryDeleteLine=Delete line +RegulateStock=Regulate Stock \ No newline at end of file From 4d375bcf958bed8cffe9b4b56f9fa58f3f669472 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 16 Dec 2016 11:31:14 +0100 Subject: [PATCH 15/41] debug translate --- htdocs/core/class/listview.class.php | 95 +++++++--------------- htdocs/core/js/listview.js | 56 ++++++------- htdocs/core/modules/modInventory.class.php | 11 +-- htdocs/inventory/inventory.php | 17 ++-- htdocs/langs/en_US/inventory.lang | 4 +- htdocs/langs/fr_FR/inventory.lang | 4 +- 6 files changed, 75 insertions(+), 112 deletions(-) diff --git a/htdocs/core/class/listview.class.php b/htdocs/core/class/listview.class.php index e94a648ec27..d276853a362 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/core/class/listview.class.php @@ -68,7 +68,6 @@ class Listview { $TParam['orderBy'] = $POSTList[$this->id]['orderBy']; } - // print_r($TParam); } private function getSearchNull($key, &$TParam) { return !empty($TParam['search'][$key]['allow_is_null']); @@ -80,7 +79,7 @@ class Listview { if (!is_array($TParam['search'][$key]['table'])) $TParam['search'][$key]['table'] = array($TParam['search'][$key]['table']); foreach ($TParam['search'][$key]['table'] as $prefix_table) { - $TPrefixe[] = '`'.$prefix_table.'`.'; + $TPrefixe[] = $prefix_table.'.'; } } @@ -90,27 +89,18 @@ class Listview { foreach ($TParam['search'][$key]['field'] as $i => $field) { $prefixe = !empty($TPrefixe[$i]) ? $TPrefixe[$i] : $TPrefixe[0]; - $TKey[] = $prefixe.'`'. $field .'`'; + $TKey[] = $prefixe. $field ; } } else { - $TKey[] =$TPrefixe[0].'`'. strtr($key,';','*').'`'; + $TKey[] =$TPrefixe[0].$key; } return $TKey; } - private function getSearchValue($value) { - $value = strtr(trim($value),';','*'); - - return $value; - } private function dateToSQLDate($date) { - list($dd,$mm,$aaaa) = explode('/', substr($date,0,10)); - - $value = date('Y-m-d', mktime(0,0,0,$mm,$dd,$aaaa)); - - return $value; + return $this->db->jdate($date); } private function addSqlFromTypeDate(&$TSQLMore, &$value, $sKey, $sBindKey) @@ -118,19 +108,10 @@ class Listview { if(is_array($value)) { - unset($this->TBind[$sBindKey]); - // Si le type de "recherche" est "calendars" on a 2 champs de transmis, [début et fin] ou [que début] ou [que fin] => un BETWEEN Sql serait utile que dans le 1er cas - // donc l'utilisation des opérateur >= et <= permettent un fonctionnement générique $TSQLDate=array(); if(!empty($value['start'])) { $valueDeb = $this->dateToSQLDate($value['start']); - - if(isset($this->TBind[$sBindKey.'_start'])) // TODO can't use this in query case - { - $this->TBind[$sBindKey.'_start'] = $valueDeb; - } - $TSQLDate[]=$sKey." >= '".$valueDeb." 00:00:00'" ; } @@ -138,10 +119,6 @@ class Listview { if(!empty($value['end'])) { $valueFin = $this->dateToSQLDate($value['end']); - if(isset($this->TBind[$sBindKey.'_end'])) { // TODO can't use this in query case - $this->TBind[$sBindKey.'_end'] = $valueFin; - } - $TSQLDate[]=$sKey." <= '".$valueFin." 23:59:59'" ; } @@ -150,25 +127,15 @@ class Listview { } else { - // Sinon je communique une date directement au format d/m/Y et la méthode du dessous reformat en Y-m-d $value = $this->dateToSQLDate($value); - if(isset($this->TBind[$sBindKey])) - { - $this->TBind[$sBindKey] = $value; - } - else - { - // Le % en fin de chaine permet de trouver un resultat si le contenu est au format Y-m-d H:i:s et non en Y-m-d - $TSQLMore[]=$sKey." LIKE '".$value."%'" ; - } + $TSQLMore[]=$sKey." LIKE '".$value."%'" ; + } } private function addSqlFromOther(&$TSQLMore, &$value, &$TParam, $sKey, $sBindKey, $key) { - $value = $this->getSearchValue($value); - if(isset($TParam['operator'][$key])) { if($TParam['operator'][$key] == '<' || $TParam['operator'][$key] == '>' || $TParam['operator'][$key]=='=') @@ -207,7 +174,6 @@ class Listview { foreach($_REQUEST['Listview'][$this->id]['search'] as $key=>$value) { $TsKey = $this->getSearchKey($key, $TParam); - $TsBindKey = $this->getTsBindKey($TsKey); //if (!empty($value)) var_dump($TsKey, $TsBindKey, '=================================='); $TSQLMore = array(); @@ -217,38 +183,32 @@ class Listview { foreach ($TsKey as $i => &$sKey) { - //if (!empty($value)) var_dump($sKey); - $sBindKey = $TsBindKey[$i]; - if($allow_is_null && !empty($_REQUEST['Listview'][$this->id]['search_on_null'][$key])) { - $this->TBind[$sBindKey.'_null'] = $sKey.' IS NULL '; $TSQLMore[] = $sKey.' IS NULL '; $search_on_null = true; - if(isset($this->TBind[$sBindKey])) $this->TBind[$sBindKey]= ''; $value = ''; } elseif($allow_is_null) { - $this->TBind[$sBindKey.'_null'] =0; // $sKey.' IS NOT NULL '; - //$TSQLMore[] = $sKey.' IS NOT NULL '; + null; } if($value!='') { // pas empty car biensûr le statut = 0 existe dans de nombreux cas if(isset($TParam['type'][$key]) && ($TParam['type'][$key]==='date' || $TParam['type'][$key]==='datetime')) { - $this->addSqlFromTypeDate($TSQLMore, $value, $sKey, $sBindKey); + $this->addSqlFromTypeDate($TSQLMore, $value, $sKey); } else { - $this->addSqlFromOther($TSQLMore, $value, $TParam, $sKey, $sBindKey, $key); + $this->addSqlFromOther($TSQLMore, $value, $TParam, $sKey, $key); } } } - if(!isset($this->TBind[$sBindKey]) && !empty($TSQLMore)) + if(!empty($TSQLMore)) { $sql.=' AND ( '.implode(' OR ',$TSQLMore).' ) '; } @@ -282,13 +242,11 @@ class Listview { } private function setSearch(&$THeader, &$TParam) { - global $langs; + global $langs, $form; if(empty($TParam['search'])) return array(); $TSearch=array(); - $form=new TFormCore; - $form->strict_string_compare = true; $nb_search_in_bar = 0; @@ -296,20 +254,22 @@ class Listview { foreach($THeader as $key=>$libelle) { // init if(empty($TSearch[$key]))$TSearch[$key]=''; } - } + } + + $ListPOST = GETPOST('Listview'); + foreach($TParam['search'] as $key=>$param_search) { - - $value = isset($_REQUEST['Listview'][$this->id]['search'][$key]) ? $_REQUEST['Listview'][$this->id]['search'][$key] : ''; + $value = isset($ListPOST[$this->id]['search'][$key]) ? $ListPOST[$this->id]['search'][$key] : ''; $typeRecherche = (is_array($param_search) && isset($param_search['recherche'])) ? $param_search['recherche'] : $param_search; if(is_array($typeRecherche)) { - $typeRecherche = array(''=>' ') + $typeRecherche; - $fsearch=$form->combo('','Listview['.$this->id.'][search]['.$key.']', $typeRecherche,$value,0,'',' listviewtbs="combo" init-value="'.$value.'" '); + $fsearch=$form->selectarray('Listview['.$this->id.'][search]['.$key.']', $typeRecherche,$value,1); } else if($typeRecherche==='calendar') { - $fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); + $fsearch = $form->select_date($value, 'Listview['.$this->id.'][search]['.$key.']',0, 0, 1, "", 1, 0, 1); + //$fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); } else if($typeRecherche==='calendars') { $fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.'][start]',isset($value['start'])?$value['start']:'',10,10,' listviewtbs="calendars" ') @@ -340,7 +300,7 @@ class Listview { } - $search_button = ' '.$TParam['liste']['picto_search'].''; + $search_button = ' '.$TParam['liste']['picto_search'].''; if(!empty($TParam['liste']['head_search'])) { $TParam['liste']['head_search'].='
    '.$langs->trans('Search').' '.$search_button.'
    '; @@ -406,8 +366,8 @@ class Listview { private function getJS(&$TParam) { $javaScript = ''; @@ -542,10 +502,13 @@ class Listview { $out.=''; - if(!empty($TParam['liste']['nbSearch'])) { - $out.=' - '.img_search().' - '; + if(count($TSearch)>0) { + $out.=''; + foreach($TSearch as $field=>$search) { + $out.=''.$search.''; + + } + $out.=''; } $out.=''; diff --git a/htdocs/core/js/listview.js b/htdocs/core/js/listview.js index 1157c2ef4b8..03ca7f72508 100644 --- a/htdocs/core/js/listview.js +++ b/htdocs/core/js/listview.js @@ -1,27 +1,27 @@ -var TListTBS_include = true; +var Listview_include = true; -function TListTBS_OrderDown(idListe, column) { +function Listview_OrderDown(idListe, column) { var base_url = document.location.href; - base_url = TListTBS_recup_form_param(idListe,base_url); - base_url = TListTBS_removeParam(base_url,'TListTBS['+encodeURIComponent(idListe)+'][orderBy]'); + base_url = Listview_recup_form_param(idListe,base_url); + base_url = Listview_removeParam(base_url,'Listview['+encodeURIComponent(idListe)+'][orderBy]'); - base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + base_url = Listview_removeParam(base_url,'get-all-for-export'); - document.location.href=TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","DESC"); + document.location.href=Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","DESC"); } -function TListTBS_OrderUp(idListe, column) { +function Listview_OrderUp(idListe, column) { var base_url = document.location.href; - base_url = TListTBS_recup_form_param(idListe,base_url); - base_url = TListTBS_removeParam(base_url,'TListTBS['+encodeURIComponent(idListe)+'][orderBy]'); + base_url = Listview_recup_form_param(idListe,base_url); + base_url = Listview_removeParam(base_url,'Listview['+encodeURIComponent(idListe)+'][orderBy]'); - base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + base_url = Listview_removeParam(base_url,'get-all-for-export'); - document.location.href=TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","ASC"); + document.location.href=Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][orderBy]["+encodeURIComponent(column)+"]","ASC"); } -function TListTBS_modifyUrl(strURL,paramName,paramNewValue){ +function Listview_modifyUrl(strURL,paramName,paramNewValue){ if (strURL.indexOf(paramName+'=')!=-1){ var strFirstPart=strURL.substring(0,strURL.indexOf(paramName+'=',0))+paramName+'='; @@ -39,7 +39,7 @@ function TListTBS_modifyUrl(strURL,paramName,paramNewValue){ return strURL; } -function TListTBS_removeParam(strURL, paramMask) { +function Listview_removeParam(strURL, paramMask) { var cpt=0; var url = ''; @@ -60,11 +60,11 @@ function TListTBS_removeParam(strURL, paramMask) { return url; } -function TListTBS_recup_form_param(idListe,base_url) { +function Listview_recup_form_param(idListe,base_url) { $('#'+idListe+' tr.barre-recherche [listviewtbs],#'+idListe+' tr.barre-recherche-head input,#'+idListe+' tr.barre-recherche-head select,#'+idListe+' div.tabsAction input[listviewtbs]').each(function(i,item) { if($(item).attr("name")) { - base_url = TListTBS_modifyUrl(base_url, $(item).attr("name") , $(item).val()); + base_url = Listview_modifyUrl(base_url, $(item).attr("name") , $(item).val()); } }); @@ -72,37 +72,37 @@ function TListTBS_recup_form_param(idListe,base_url) { return base_url; } -function TListTBS_GoToPage(idListe,pageNumber){ +function Listview_GoToPage(idListe,pageNumber){ var base_url = document.location.href; - base_url = TListTBS_recup_form_param(idListe,base_url); - base_url =TListTBS_modifyUrl(base_url,"TListTBS["+encodeURIComponent(idListe)+"][page]",pageNumber); + base_url = Listview_recup_form_param(idListe,base_url); + base_url =Listview_modifyUrl(base_url,"Listview["+encodeURIComponent(idListe)+"][page]",pageNumber); - base_url = TListTBS_removeParam(base_url,'get-all-for-export'); + base_url = Listview_removeParam(base_url,'get-all-for-export'); document.location.href=base_url; } -function TListTBS_submitSearch(obj) { +function Listview_submitSearch(obj) { $(obj).closest('form').submit(); - //console.log($(obj).closest('form')); + } -function TListTBS_launch_downloadAs(mode,url,token,session_name) { - $('#listTBSdAS_export_form').remove(); +function Listview_launch_downloadAs(mode,url,token,session_name) { + $('#listviewdAS_export_form').remove(); - $form = $('
    '); + $form = $('
    '); $form.append(''); $form.append(''); $form.append(''); $('body').append($form); - $('#listTBSdAS_export_form').submit(); + $('#listviewdAS_export_form').submit(); } -function TListTBS_downloadAs(obj, mode,url,token,session_name) { +function Listview_downloadAs(obj, mode,url,token,session_name) { $form = $(obj).closest('form'); $div = $form.find('div.tabsAction'); @@ -112,7 +112,7 @@ function TListTBS_downloadAs(obj, mode,url,token,session_name) { $div.append(''); $div.append(''); - TListTBS_submitSearch(obj); + Listview_submitSearch(obj); } $(document).ready(function() { @@ -137,7 +137,7 @@ $(document).ready(function() { }); if(typeof $_GET["get-all-for-export"] != "undefined") { - TListTBS_launch_downloadAs($_GET["mode"],$_GET["url"],$_GET["token"],$_GET["session_name"]); + Listview_launch_downloadAs($_GET["mode"],$_GET["url"],$_GET["token"],$_GET["session_name"]); } }); diff --git a/htdocs/core/modules/modInventory.class.php b/htdocs/core/modules/modInventory.class.php index 31170375752..abe65b65647 100644 --- a/htdocs/core/modules/modInventory.class.php +++ b/htdocs/core/modules/modInventory.class.php @@ -66,7 +66,7 @@ class modinventory extends DolibarrModules // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' - $this->picto='inventory@inventory'; + $this->picto='inventory'; // Defined all module parts (triggers, login, substitutions, menus, css, etc...) // for default path (eg: /inventory/core/xxxxx) (0=disable, 1=enable) @@ -167,8 +167,6 @@ class modinventory extends DolibarrModules // Example: //$this->boxes=array(array(0=>array('file'=>'myboxa.php','note'=>'','enabledbydefaulton'=>'Home'),1=>array('file'=>'myboxb.php','note'=>''),2=>array('file'=>'myboxc.php','note'=>''));); - $langs->load('inventory@inventory'); - // Permissions $this->rights = array(); // Permission array used by this module $r=0; @@ -249,11 +247,11 @@ class modinventory extends DolibarrModules // $r++; $this->menu[$r]=array( 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', // Put 0 if this is a top menu 'type'=>'left', // This is a Top menu entry - 'titre'=>'Liste des inventaires', + 'titre'=>'ListInventory', 'mainmenu'=>'inventory', 'leftmenu'=>'inventory', 'url'=>'/inventory/inventory.php?action=list', - 'langs'=>'inventory@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>100, 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. 'perms'=>'$user->rights->inventory->read', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules @@ -263,11 +261,10 @@ class modinventory extends DolibarrModules $this->menu[$r]=array( 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', // Put 0 if this is a top menu 'type'=>'left', // This is a Top menu entry - 'titre'=>'Nouvel inventaire', + 'titre'=>'NewInventory', 'mainmenu'=>'inventory', 'leftmenu'=>'inventory', 'url'=>'/inventory/inventory.php?action=create', - 'langs'=>'inventory@inventory', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>100, 'enabled'=>'$conf->inventory->enabled', // Define condition to show or hide menu entry. Use '$conf->inventory->enabled' if entry must be visible if module is enabled. 'perms'=>'$user->rights->inventory->create', // Use 'perms'=>'$user->rights->inventory->level1->level2' if you want your menu with a permission rules diff --git a/htdocs/inventory/inventory.php b/htdocs/inventory/inventory.php index d0ca303c239..f0a0d073a27 100644 --- a/htdocs/inventory/inventory.php +++ b/htdocs/inventory/inventory.php @@ -266,8 +266,8 @@ function _action() header('Location: '.dol_buildpath('/inventory/inventory.php?action=list', 1)); exit; - //_list(); + break; case 'exportCSV': $id = GETPOST('id'); @@ -309,18 +309,14 @@ function _list() $THide = array('label'); echo $l->render(Inventory::getSQL('All'), array( - 'limit'=>array( - 'nbLine'=>'30' - ) - ,'subQuery'=>array() - ,'link'=>array( + 'link'=>array( 'fk_warehouse'=>''.img_picto('','object_stock.png','',0).' @label@' ) ,'translate'=>array() ,'hide'=>$THide ,'type'=>array( - 'date_cre'=>'date' - ,'date_maj'=>'datetime' + 'datec'=>'date' + ,'tms'=>'datetime' ,'date_inventory'=>'date' ) ,'liste'=>array( @@ -343,7 +339,10 @@ function _list() ,'eval'=>array( 'status' => '(@val@ ? img_picto("'.$langs->trans("inventoryValidate").'", "statut4") : img_picto("'.$langs->trans("inventoryDraft").'", "statut3"))' ,'rowid'=>'Inventory::getLink(@val@)' - + ) + ,'search'=>array( + 'date_inventory'=>'calendar' + ) )); diff --git a/htdocs/langs/en_US/inventory.lang b/htdocs/langs/en_US/inventory.lang index ba947f09d77..152aceed862 100644 --- a/htdocs/langs/en_US/inventory.lang +++ b/htdocs/langs/en_US/inventory.lang @@ -49,4 +49,6 @@ ConfirmFlushInventory=Do you confirm this action ? InventoryFlushed=Inventory flushed ExitEditMode=Exit edition inventoryDeleteLine=Delete line -RegulateStock=Regulate Stock \ No newline at end of file +RegulateStock=Regulate Stock +ListInventory=Inventories list +NewInventory=New inventory \ No newline at end of file diff --git a/htdocs/langs/fr_FR/inventory.lang b/htdocs/langs/fr_FR/inventory.lang index 85fdf3112dc..546a5202976 100644 --- a/htdocs/langs/fr_FR/inventory.lang +++ b/htdocs/langs/fr_FR/inventory.lang @@ -47,4 +47,6 @@ ConfirmFlushInventory=Do you confirm this action ? InventoryFlushed=Inventory flushed ExitEditMode=Exit edition inventoryDeleteLine=Delete line -RegulateStock=Regulate Stock \ No newline at end of file +RegulateStock=Regulate Stock +InventoryDate=Inventory date +DateUpdate=Last update \ No newline at end of file From 79867a85d05d6730eaa88951c7ab149745efa89e Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 16 Dec 2016 16:09:02 +0100 Subject: [PATCH 16/41] fix list issue --- htdocs/core/class/listview.class.php | 74 +++++++-------- htdocs/core/js/listview.js | 10 +- htdocs/core/modules/modInventory.class.php | 2 +- htdocs/inventory/class/inventory.class.php | 2 +- htdocs/inventory/inventory.php | 68 +------------- htdocs/inventory/list.php | 103 +++++++++++++++++++++ 6 files changed, 152 insertions(+), 107 deletions(-) create mode 100644 htdocs/inventory/list.php diff --git a/htdocs/core/class/listview.class.php b/htdocs/core/class/listview.class.php index d276853a362..6b57fd36a21 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/core/class/listview.class.php @@ -40,7 +40,7 @@ class Listview { if(!isset($TParam['link']))$TParam['link']=array(); if(!isset($TParam['type']))$TParam['type']=array(); if(!isset($TParam['orderby']['noOrder']))$TParam['orderby']['noOrder']=array(); - if(!isset($TParam['no-select'])) $TParam['no-select'] = 1; + if(!isset($TParam['allow-fields-select'])) $TParam['allow-fields-select'] = 0; if(!isset($TParam['list']))$TParam['list']=array(); $TParam['list'] = array_merge(array( @@ -53,7 +53,7 @@ class Listview { ,'orderUp'=>'' ,'id'=>$this->id ,'head_search'=>'' - ,'export'=>array() + ,'export'=>array() //TODO include native export ,'view_type'=>'' //TODO to include graph or kanban instead of list ),$TParam['list']); @@ -133,7 +133,7 @@ class Listview { } } - private function addSqlFromOther(&$TSQLMore, &$value, &$TParam, $sKey, $sBindKey, $key) + private function addSqlFromOther(&$TSQLMore, &$value, &$TParam, $sKey, $key) { if(isset($TParam['operator'][$key])) @@ -272,38 +272,40 @@ class Listview { //$fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.']',$value,10,10,' listviewtbs="calendar" '); } else if($typeRecherche==='calendars') { - $fsearch=$form->calendrier('','Listview['.$this->id.'][search]['.$key.'][start]',isset($value['start'])?$value['start']:'',10,10,' listviewtbs="calendars" ') - .' '.$form->calendrier('','Listview['.$this->id.'][search]['.$key.'][end]',isset($value['end'])?$value['end']:'',10,10,' listviewtbs="calendars" '); + + $fsearch = $form->select_date(isset($value['start'])?$value['start']:'', 'Listview['.$this->id.'][search]['.$key.'][start]',0, 0, 1, "", 1, 0, 1) + . $form->select_date(isset($value['end'])?$value['end']:'', 'Listview['.$this->id.'][search]['.$key.'][end]',0, 0, 1, "", 1, 0, 1); + } else if(is_string($typeRecherche)) { $fsearch=$TParam['search'][$key]; } else { - $fsearch=$form->texte('','Listview['.$this->id.'][search]['.$key.']',$value,15,255,' listviewtbs="input" '); + $fsearch=''; } if(!empty($param_search['allow_is_null'])) { - $valueNull = isset($_REQUEST['Listview'][$this->id]['search_on_null'][$key]) ? 1 : 0; + $valueNull = isset($ListPOST[$this->id]['search_on_null'][$key]) ? 1 : 0; $fsearch.=' '.$form->checkbox1('', 'Listview['.$this->id.'][search_on_null]['.$key.']',1, $valueNull,' onclick=" if($(this).is(\':checked\')){ $(this).prev().val(\'\'); }" ').img_help(1, $langs->trans('SearchOnNUllValue')); } - if(!empty($THeader[$key]) || $this->getViewType($TParam) == 'chart') { + if(!empty($THeader[$key])) { $TSearch[$key] = $fsearch; $nb_search_in_bar++; } else { - $libelle = !empty($TParam['title'][$key]) ? $TParam['title'][$key] : $key ; - $TParam['liste']['head_search'].='
    '.$libelle.' '.$fsearch.'
    '; + $label = !empty($TParam['title'][$key]) ? $TParam['title'][$key] : $key ; + $TParam['list']['head_search'].='
    '.$libelle.' '.$fsearch.'
    '; } } - $search_button = ' '.$TParam['liste']['picto_search'].''; + $search_button = ' '.img_search().''; - if(!empty($TParam['liste']['head_search'])) { - $TParam['liste']['head_search'].='
    '.$langs->trans('Search').' '.$search_button.'
    '; + if(!empty($TParam['list']['head_search'])) { + $TParam['list']['head_search']='
    '.$search_button.'
    '.$TParam['list']['head_search']; } if($nb_search_in_bar>0) { @@ -364,7 +366,7 @@ class Listview { return array($TTotal,$TTotalGroup); } - private function getJS(&$TParam) { + private function getJS() { $javaScript = '