From a7813c37a1dee3b5ba8d2e4da451e0f16e96f519 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Mon, 12 Dec 2016 12:36:00 +0100 Subject: [PATCH 001/116] 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 002/116] 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 003/116] 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 004/116] 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 005/116] 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 006/116] 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 007/116] 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 008/116] 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 009/116] 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 010/116] 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 011/116] 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 012/116] 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 013/116] 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 014/116] 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 015/116] 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 016/116] 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 = ' -status != 1) { ?> +status != 1) { ?> trans('AddInventoryProduct'); ?> :
    - + - + - +
    @@ -90,7 +90,7 @@ - +
    - status != 1) { ?> + status != 1) { ?> - status == 1) { ?> + status == 1) { ?> -

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

    +

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

    From b57bf6460bd6f73339030ad83ed35de6d6843056 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 02:34:00 +0200 Subject: [PATCH 094/116] Start debug inventory --- .../install/mysql/migration/5.0.0-6.0.0.sql | 2 +- .../install/mysql/tables/llx_inventorydet.sql | 2 +- htdocs/product/inventory/card.php | 19 ++++++++----------- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 4a383fcb505..b20da8b9b89 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -204,7 +204,7 @@ tms timestamp, fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, -entity integer DEFAULT 0, +batch varchar(30) DEFAULT NULL, qty_view double DEFAULT 0, qty_stock double DEFAULT 0, qty_regulated double DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_inventorydet.sql b/htdocs/install/mysql/tables/llx_inventorydet.sql index 20e48b877b5..2b203e0c58b 100644 --- a/htdocs/install/mysql/tables/llx_inventorydet.sql +++ b/htdocs/install/mysql/tables/llx_inventorydet.sql @@ -25,7 +25,7 @@ tms timestamp, fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, -entity integer DEFAULT 0, +batch varchar(30) DEFAULT NULL, -- Lot or serial number qty_view double DEFAULT 0, qty_stock double DEFAULT 0, qty_regulated double DEFAULT 0, diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index e89a59bb505..f7e4cbecb0a 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -146,12 +146,13 @@ if (empty($reshook)) if ($object->errors) { setEventMessage($object->errors, 'errors'); - card( $object, 'edit'); + $action = 'edit'; } else { $object->udpate($user); header('Location: '.dol_buildpath('/product/inventory/card.php?id='.$object->getId().'&action=view', 1)); + exit; } break; @@ -167,12 +168,10 @@ if (empty($reshook)) $object->status = 1; $object->update($user); - card( $object, 'view'); - - + $action='view'; } else { - card( $object, 'view'); + $action='view'; } break; @@ -186,7 +185,7 @@ if (empty($reshook)) $object->changePMP($user); - card( $object, 'view'); + $action='view'; break; @@ -238,7 +237,7 @@ if (empty($reshook)) $object->sortDet(); } - card( $object, 'edit'); + $action='edit'; break; @@ -257,7 +256,7 @@ if (empty($reshook)) $object = new Inventory($db); $object->fetch( $id); - card($object, 'edit'); + $action='edit'; break; case 'confirm_flush': @@ -273,14 +272,12 @@ if (empty($reshook)) setEventMessage($langs->trans('InventoryFlushed')); - card( $object, 'edit'); - + $action='edit'; break; case 'confirm_delete': if (!$user->rights->stock->supprimer) accessforbidden(); - $id = GETPOST('id'); $object = new Inventory($db); From 865c8140d1bf0900d59906de1b01f4416d360b1b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 03:18:49 +0200 Subject: [PATCH 095/116] Clean code --- ChangeLog | 4 +- htdocs/comm/propal/contact.php | 4 +- htdocs/commande/contact.php | 5 +- htdocs/core/class/commonobject.class.php | 119 +++++++++--------- htdocs/core/lib/company.lib.php | 49 ++++++++ htdocs/expedition/contact.php | 4 +- htdocs/expedition/shipment.php | 4 +- .../skeletons/skeleton_class.class.php | 49 +++++--- htdocs/product/card.php | 77 ++++++------ htdocs/societe/class/societe.class.php | 12 -- htdocs/societe/societecontact.php | 5 +- 11 files changed, 197 insertions(+), 135 deletions(-) diff --git a/ChangeLog b/ChangeLog index 31ddbd56bdd..3eb284ccc80 100644 --- a/ChangeLog +++ b/ChangeLog @@ -13,7 +13,9 @@ Following changes may create regression for some external modules, but were nece * The page compta/facture.php was renamed into compta/facture/card.php to match page naming conventions. * The signature of method ->delete() of class Product and PriceExpression was changed from ->delete($id, notrigger) to ->delete(User, notrigger) to match standard dev rules. - +* Removed CommonObject::displayMarginInfos (was deprecated in 3.8). Use same method into + html.formmargin.class.php +* Removed Societe::set_commnucation_level (was deprecated in 4.0). Was not used. ***** ChangeLog for 5.0.1 compared to 5.0.0 ***** FIX: #6503: SQL error in "Last pending payment invoices" diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 3c3aa6aef88..3e9e5a1205d 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -130,12 +130,12 @@ else if ($action == 'deletecontact' && $user->rights->propale->creer) dol_print_error($db); } } - +/* else if ($action == 'setaddress' && $user->rights->propale->creer) { $result=$object->setDeliveryAddress($_POST['fk_address']); if ($result < 0) dol_print_error($db,$object->error); -} +}*/ /* diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index bc257f3ac05..fe37a630c5d 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -107,13 +107,14 @@ else if ($action == 'deletecontact' && $user->rights->commande->creer) dol_print_error($db); } } - +/* else if ($action == 'setaddress' && $user->rights->commande->creer) { $object->fetch($id); $result=$object->setDeliveryAddress($_POST['fk_address']); if ($result < 0) dol_print_error($db,$object->error); -} +}*/ + /* * View diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index e03db1b4773..2526638cee5 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -238,6 +238,7 @@ abstract class CommonObject /** * @var int Delivery address ID + * @deprecated * @see setDeliveryAddress() */ public $fk_delivery_address; @@ -1623,7 +1624,8 @@ abstract class CommonObject /** * Define delivery address - * + * @deprecated + * * @param int $id Address id * @return int <0 si ko, >0 si ok */ @@ -3223,51 +3225,14 @@ abstract class CommonObject /** * Return if a country is inside the EEC (European Economic Community) - * TODO Add a field into dictionary + * @deprecated * * @return boolean true = country inside EEC, false = country outside EEC */ function isInEEC() { - // List of all country codes that are in europe for european vat rules - // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9 - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta - //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom - //'CH', // Switzerland - No. Swizerland in not in EEC - ); - //print "dd".$this->country_code; - return in_array($this->country_code,$country_code_in_EEC); + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + return isInEEC($this); } @@ -3754,21 +3719,6 @@ abstract class CommonObject } - /** - * Show the array with all margin infos - * - * @param bool $force_price Force price - * @return void - * @deprecated 3.8 Load FormMargin class and make a direct call to displayMarginInfos - */ - function displayMarginInfos($force_price=false) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; - $formmargin=new FormMargin($this->db); - $formmargin->displayMarginInfos($this, $force_price); - } - - /** * Add resources to the current object : add entry into llx_element_resources * Need $this->element & $this->id @@ -4711,4 +4661,61 @@ abstract class CommonObject } return $buyPrice; } + + + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * + * @return int <0 if KO, Id of created object if OK + */ + public function createCommon(User $user, $notrigger = false) + { + + } + + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchCommon($id, $ref = null) + { + + } + + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * + * @return int <0 if KO, >0 if OK + */ + public function updateCommon(User $user, $notrigger = false) + { + + } + + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * + * @return int <0 if KO, >0 if OK + */ + public function deleteCommon(User $user, $notrigger = false) + { + + } } diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 809a045bacf..6847cd7b9c2 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -496,6 +496,55 @@ function getFormeJuridiqueLabel($code) } } +/** + * Return if a country is inside the EEC (European Economic Community) + * TODO Add a field into country dictionary. + * + * @param Object $object Object + * @return boolean true = country inside EEC, false = country outside EEC + */ +function isInEEC($object) +{ + // List of all country codes that are in europe for european vat rules + // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9 + $country_code_in_EEC=array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta + //'NO', // Norway + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom + //'CH', // Switzerland - No. Swizerland in not in EEC + ); + //print "dd".$this->country_code; + return in_array($object->country_code, $country_code_in_EEC); +} /** diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php index 1354b3d49f1..7c721d7cf47 100644 --- a/htdocs/expedition/contact.php +++ b/htdocs/expedition/contact.php @@ -123,13 +123,13 @@ else if ($action == 'deletecontact' && $user->rights->expedition->creer) dol_print_error($db); } } - +/* else if ($action == 'setaddress' && $user->rights->expedition->creer) { $object->fetch($id); $result=$object->setDeliveryAddress($_POST['fk_address']); if ($result < 0) dol_print_error($db,$object->error); -} +}*/ /* diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index 57ad04a8a1a..ede1cc6bec9 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -113,7 +113,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + /* if ($action == 'setdeliveryaddress' && $user->rights->commande->creer) { $object = new Commande($db); @@ -122,7 +122,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + */ if ($action == 'setmode' && $user->rights->commande->creer) { $object = new Commande($db); diff --git a/htdocs/modulebuilder/skeletons/skeleton_class.class.php b/htdocs/modulebuilder/skeletons/skeleton_class.class.php index 01b48c35f75..6805a697043 100644 --- a/htdocs/modulebuilder/skeletons/skeleton_class.class.php +++ b/htdocs/modulebuilder/skeletons/skeleton_class.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2007-2017 Laurent Destailleur * Copyright (C) 2014-2016 Juanjo Menent * Copyright (C) 2015 Florian Henry * Copyright (C) 2015 Raphaël Doursenaud @@ -20,10 +20,9 @@ */ /** - * \file dev/skeletons/skeleton_class.class.php - * \ingroup mymodule othermodule1 othermodule2 - * \brief This file is an example for a CRUD class file (Create/Read/Update/Delete) - * Put some comments here + * \file modulebuilder/skeletons/skeleton_class.class.php + * \ingroup mymodule othermodule1 othermodule2 + * \brief This file is an example for a CRUD class file (Create/Read/Update/Delete) */ // Put here all includes required by your class file @@ -34,26 +33,27 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; /** * Class Skeleton_Class * - * Put here description of your class - * - * @see CommonObject + * Put here description of your class. */ class Skeleton_Class extends CommonObject { /** - * @var string Id to identify managed objects + * @var string Id to identify managed object */ public $element = 'skeleton'; /** * @var string Name of table without prefix where object is stored */ public $table_element = 'skeleton'; - - /** - * @var Skeleton_ClassLine[] Lines - */ - public $lines = array(); - + /** + * @var array Array with all fields and their property + */ + public $picto = 'generic'; + /** + * @var array Array with all fields and their property + */ + public $fields; + /** * @var mixed Sample property 1 */ @@ -62,8 +62,21 @@ class Skeleton_Class extends CommonObject * @var mixed Sample property 2 */ public $prop2; + //... - + + protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + + public $table_element_line = 'skeletondet'; + public $class_element_line = 'SkeletonLine'; + public $fk_element = 'fk_skeleton'; + /** + * @var Skeleton_ClassLine[] Lines + */ + public $lines = array(); + + + /** * Constructor * @@ -289,10 +302,10 @@ class Skeleton_Class extends CommonObject */ public function update(User $user, $notrigger = false) { - $error = 0; - dol_syslog(__METHOD__, LOG_DEBUG); + $error = 0; + // Clean parameters if (isset($this->prop1)) { $this->prop1 = trim($this->prop1); diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 536bcece10f..71f7cd8e7f6 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -1801,60 +1801,61 @@ if (($action == 'clone' && (empty($conf->use_javascript_ajax) || ! empty($conf-> /* Barre d'action */ /* */ /* ************************************************************************** */ - -print "\n".'
    '."\n"; - -$parameters=array(); -$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook -if (empty($reshook)) +if ($action != 'create' && $action != 'edit') { - if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer ) || - ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)) + print "\n".'
    '."\n"; + + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { - if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print ''; - - if (! isset($object->no_button_copy) || $object->no_button_copy <> 1) + if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer ) || + ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)) { - if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print ''; + + if (! isset($object->no_button_copy) || $object->no_button_copy <> 1) { - print '
    '.$langs->trans('ToClone').'
    '."\n"; - } - else - { - print ''; + if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + { + print '
    '.$langs->trans('ToClone').'
    '."\n"; + } + else + { + print ''; + } } } - } - $object_is_used = $object->isObjectUsed($object->id); - - if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) - || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer)) - { - if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1)) + $object_is_used = $object->isObjectUsed($object->id); + + if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) + || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer)) { - if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1)) { - print '
    '.$langs->trans('Delete').'
    '."\n"; + if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + { + print '
    '.$langs->trans('Delete').'
    '."\n"; + } + else + { + print ''; + } } else - { - print ''; + { + print ''; } } else - { - print ''; + { + print ''; } } - else - { - print ''; - } + + print "\n
    \n"; } -print "\n
    \n"; - - /* * All the "Add to" areas */ @@ -1974,7 +1975,7 @@ if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action = * Documents generes */ -if ($action != 'edit' && $action != 'delete') +if ($action != 'create' && $action != 'edit' && $action != 'delete') { print '
    '; print ''; // ancre diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 74aef09e7a9..0581ed1960e 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -3326,18 +3326,6 @@ class Societe extends CommonObject return "Error, mode/status not found"; } - /** - * Set commnunication level - * - * @param User $user User making change - * @return int <0 if KO, >0 if OK - * @deprecated Use update function instead - */ - function set_commnucation_level($user) - { - return $this->update($this->id, $user); - } - /** * Set outstanding value * diff --git a/htdocs/societe/societecontact.php b/htdocs/societe/societecontact.php index 2bda75867dc..b5ffc87517f 100644 --- a/htdocs/societe/societecontact.php +++ b/htdocs/societe/societecontact.php @@ -107,13 +107,14 @@ else if ($action == 'deletecontact' && $user->rights->societe->creer) dol_print_error($db); } } - +/* else if ($action == 'setaddress' && $user->rights->societe->creer) { $object->fetch($id); $result=$object->setDeliveryAddress($_POST['fk_address']); if ($result < 0) dol_print_error($db,$object->error); -} +}*/ + /* * View From 60951cf30743e0fb12a1991aae063b6eeba8c7b2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 04:09:50 +0200 Subject: [PATCH 096/116] Less data example --- htdocs/admin/dict.php | 7 ++++--- htdocs/core/menus/standard/eldy.lib.php | 2 +- .../mysql/data/llx_c_hrm_department.sql | 18 +++++++----------- htdocs/langs/en_US/admin.lang | 2 +- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index 125f913eb8d..d4aa0ce6989 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -1073,7 +1073,7 @@ if ($id) print ''; // Line to enter new values - print ''; + print ''; $obj = new stdClass(); // If data was already input, we define them in obj to populate input fields. @@ -1814,13 +1814,14 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') if ($fieldlist[$field]=='affect') $class='maxwidth50'; if ($fieldlist[$field]=='delay') $class='maxwidth50'; if ($fieldlist[$field]=='position') $class='maxwidth50'; - if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent'; + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $class='quatrevingtpercent'; if ($fieldlist[$field]=='tracking') $class='quatrevingtpercent'; if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $class='maxwidth50'; print ''; $transfound=0; if (in_array($fieldlist[$field], array('label','libelle'))) { + $transkey=''; // Special case for labels if ($tabname == MAIN_DB_PREFIX.'c_civility') { $transkey="Civility".strtoupper($obj->code); @@ -1829,7 +1830,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') $langs->load("bills"); $transkey="PaymentCondition".strtoupper($obj->code); } - if ($langs->trans($transkey) != $transkey) + if ($transkey && $langs->trans($transkey) != $transkey) { $transfound=1; print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 1e88601604f..dffc5f9af1b 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -545,7 +545,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu $newmenu->add("/admin/ihm.php?mainmenu=home", $langs->trans("GUISetup"),1); $newmenu->add("/admin/translation.php?mainmenu=home", $langs->trans("Translation"),1); - $newmenu->add("/admin/defaultvalues.php?mainmenu=home", $langs->trans("DefaultValues"),1, $conf->global->MAIN_FEATURES_LEVEL); + $newmenu->add("/admin/defaultvalues.php?mainmenu=home", $langs->trans("DefaultValues"),1); $newmenu->add("/admin/boxes.php?mainmenu=home", $langs->trans("Boxes"),1); $newmenu->add("/admin/delais.php?mainmenu=home",$langs->trans("MenuWarnings"),1); $newmenu->add("/admin/security_other.php?mainmenu=home", $langs->trans("Security"),1); diff --git a/htdocs/install/mysql/data/llx_c_hrm_department.sql b/htdocs/install/mysql/data/llx_c_hrm_department.sql index e6e4921f372..c4865ad9e30 100644 --- a/htdocs/install/mysql/data/llx_c_hrm_department.sql +++ b/htdocs/install/mysql/data/llx_c_hrm_department.sql @@ -24,20 +24,16 @@ -- INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(1, 5,'MANAGEMENT', 'Management', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(2, 10,'GESTION', 'Gestion', 1); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(3, 15,'TRAINING', 'Training', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(4, 20,'IT', 'Inform. Technology (IT)', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(5, 25,'MARKETING', 'Marketing', 1); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(4, 20,'IT', 'Inform. Technology (IT)', 0); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(5, 25,'MARKETING', 'Marketing', 0); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(6, 30,'SALES', 'Sales', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(7, 35,'LEGAL', 'Legal', 1); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(7, 35,'LEGAL', 'Legal', 0); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(8, 40,'FINANCIAL', 'Financial accounting', 1); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(9, 45,'HUMANRES', 'Human resources', 1); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(10, 50,'PURCHASING', 'Purchasing', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(11, 55,'SERVICES', 'Services', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(12, 60,'CUSTOMSERV', 'Customer service', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(13, 65,'CONSULTING', 'Consulting', 1); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(12, 60,'CUSTOMSERV', 'Customer service', 0); INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(14, 70,'LOGISTIC', 'Logistics', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(15, 75,'CONSTRUCT', 'Engineering/design', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(16, 80,'PRODUCTION', 'Manufacturing', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(17, 85,'QUALITY', 'Quality assurance', 1); -INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(18, 85,'MAINT', 'Plant assurance', 1); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(15, 75,'CONSTRUCT', 'Engineering/design', 0); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(16, 80,'PRODUCTION', 'Production', 1); +INSERT INTO llx_c_hrm_department (rowid, pos, code, label, active) VALUES(17, 85,'QUALITY', 'Quality assurance', 0); \ No newline at end of file diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 69c72fc7aad..02ff5740986 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -432,7 +432,7 @@ PageUrlForDefaultValues=You must enter here the relative url of the page. If you PageUrlForDefaultValuesCreate=
    For form to create a new thirdparty, it is %s PageUrlForDefaultValuesList=
    For page that list thirdparties, it is %s GoIntoTranslationMenuToChangeThis=A translation has been found for the key with this code, so to change this value, you must edit it fom Home-Setup-translation. -WarningSettingSortOrder=Warning, setting a default sort order may result in a technical error when going on the list page if field is an unknown field. If you experience such an error, come back to this page to remove the default sort order to retreive default behavior. +WarningSettingSortOrder=Warning, setting a default sort order may result in a technical error when going on the list page if field is an unknown field. If you experience such an error, come back to this page to remove the default sort order and restore default behavior. Field=Field # Modules Module0Name=Users & groups From a9eeb823bd25d81f1979db1a99f92fd16328b522 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 04:32:03 +0200 Subject: [PATCH 097/116] Fix browser notif --- htdocs/admin/agenda.php | 2 +- htdocs/admin/agenda_extrafields.php | 2 +- htdocs/admin/agenda_extsites.php | 2 +- htdocs/admin/agenda_other.php | 2 +- htdocs/admin/agenda_xcal.php | 2 +- htdocs/core/ajax/check_notifications.php | 7 ++++++- htdocs/core/js/lib_notification.js.php | 12 +++++++----- 7 files changed, 18 insertions(+), 11 deletions(-) diff --git a/htdocs/admin/agenda.php b/htdocs/admin/agenda.php index d076fcf7e26..c5fc1c55793 100644 --- a/htdocs/admin/agenda.php +++ b/htdocs/admin/agenda.php @@ -144,7 +144,7 @@ print ''; $head=agenda_prepare_head(); -dol_fiche_head($head, 'autoactions', $langs->trans("Agenda"), 0, 'action'); +dol_fiche_head($head, 'autoactions', $langs->trans("Agenda"), -1, 'action'); print $langs->trans("AgendaAutoActionDesc")."
    \n"; print $langs->trans("OnlyActiveElementsAreShown").'
    '; diff --git a/htdocs/admin/agenda_extrafields.php b/htdocs/admin/agenda_extrafields.php index 2cf3a323c21..74ae6cb2d95 100644 --- a/htdocs/admin/agenda_extrafields.php +++ b/htdocs/admin/agenda_extrafields.php @@ -75,7 +75,7 @@ print "
    \n"; $head=agenda_prepare_head(); -dol_fiche_head($head, 'attributes', $langs->trans("Agenda"), 0, 'action'); +dol_fiche_head($head, 'attributes', $langs->trans("Agenda"), -1, 'action'); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; diff --git a/htdocs/admin/agenda_extsites.php b/htdocs/admin/agenda_extsites.php index 1e595b5088e..0b69b947a38 100644 --- a/htdocs/admin/agenda_extsites.php +++ b/htdocs/admin/agenda_extsites.php @@ -137,7 +137,7 @@ print ''; $head=agenda_prepare_head(); -dol_fiche_head($head, 'extsites', $langs->trans("Agenda"), 0, 'action'); +dol_fiche_head($head, 'extsites', $langs->trans("Agenda"), -1, 'action'); print $langs->trans("AgendaExtSitesDesc")."
    \n"; print "
    \n"; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index 6e0a62610aa..f652829a80c 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -196,7 +196,7 @@ print "
    \n"; $head=agenda_prepare_head(); -dol_fiche_head($head, 'other', $langs->trans("Agenda"), 0, 'action'); +dol_fiche_head($head, 'other', $langs->trans("Agenda"), -1, 'action'); /* diff --git a/htdocs/admin/agenda_xcal.php b/htdocs/admin/agenda_xcal.php index cd2406e6fdc..0e66125ba7c 100644 --- a/htdocs/admin/agenda_xcal.php +++ b/htdocs/admin/agenda_xcal.php @@ -83,7 +83,7 @@ print ''; $head=agenda_prepare_head(); -dol_fiche_head($head, 'xcal', $langs->trans("Agenda"), 0, 'action'); +dol_fiche_head($head, 'xcal', $langs->trans("Agenda"), -1, 'action'); print $langs->trans("AgendaSetupOtherDesc")."
    \n"; print "
    \n"; diff --git a/htdocs/core/ajax/check_notifications.php b/htdocs/core/ajax/check_notifications.php index 4db67aef939..fa3edd7a4be 100644 --- a/htdocs/core/ajax/check_notifications.php +++ b/htdocs/core/ajax/check_notifications.php @@ -21,7 +21,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; @@ -88,9 +87,11 @@ if ($time >= $_SESSION['auto_check_events_not_before']) while ($obj = $db->fetch_object($resql)) { $langs->load("agenda"); + $langs->load("commercial"); $actionmod->fetch($obj->id); + // Message must be formated and translated to be used with javascript directly $event = array(); $event['type'] = 'agenda'; $event['id'] = $actionmod->id; @@ -101,6 +102,10 @@ if ($time >= $_SESSION['auto_check_events_not_before']) $eventfound[] = $event; } } + else + { + dol_syslog("Error sql = ".$db->lasterror(), LOG_ERR); + } } diff --git a/htdocs/core/js/lib_notification.js.php b/htdocs/core/js/lib_notification.js.php index af4452dfb39..a3b90a35db6 100644 --- a/htdocs/core/js/lib_notification.js.php +++ b/htdocs/core/js/lib_notification.js.php @@ -65,7 +65,7 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H // We set a delay before launching first test so next check will arrive after the time_auto_update compared to previous one. var time_first_execution = (time_auto_update - (nowtime - time_js_next_test)) * 1000; //need milliseconds if (login != '') { - console.log("Launch browser notif check: setTimeout to wait time_first_execution="+time_first_execution+" before first check - nowtime = "+nowtime+" auto_check_events_not_before = "+auto_check_events_not_before+" time_js_next_test = "+time_js_next_test+" time_auto_update="+time_auto_update); + console.log("Launch browser notif check: setTimeout is set to launch 'first_execution' function after a wait of time_first_execution="+time_first_execution+". nowtime (time php page generation) = "+nowtime+" auto_check_events_not_before (val in session)= "+auto_check_events_not_before+" time_js_next_test (max now,auto_check_events_not_before) = "+time_js_next_test+" time_auto_update="+time_auto_update); setTimeout(first_execution, time_first_execution); } //first run auto check @@ -79,17 +79,18 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H function check_events() { if (Notification.permission === "granted") { - console.log("Call check_events time_js_next_test="+time_js_next_test); - $.ajax("", { - type: "post", // Usually post o get + console.log("Call check_events time_js_next_test = date we are looking for event after ="+time_js_next_test); + $.ajax("", { + type: "post", // Usually post or get async: true, data: {time: time_js_next_test}, success: function (result) { var arr = JSON.parse(result); if (arr.length > 0) { + var audio = null; global->AGENDA_NOTIFICATION_SOUND)) { - print 'var audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');'; + print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');'; } ?> @@ -136,6 +137,7 @@ if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['H } time_js_next_test += time_auto_update; + console.log('Updated time_js_next_test. New value is '+time_js_next_test); } Date: Sun, 30 Apr 2017 12:55:11 +0200 Subject: [PATCH 098/116] NEW When down payment is entered, discount to reuse into final invoice is automatically created. This save one click into invoice workflow. --- htdocs/compta/facture/card.php | 18 +++--- htdocs/compta/paiement.php | 38 ++++++------ .../compta/paiement/class/paiement.class.php | 60 +++++++++++++++++-- htdocs/langs/en_US/bills.lang | 2 +- 4 files changed, 85 insertions(+), 33 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 70eea532a79..6f5ef85310d 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -611,7 +611,9 @@ if (empty($reshook)) { $db->begin(); - // Boucle sur chaque taux de tva + $amount_ht = $amount_tva = $amount_ttc = array(); + + // Loop on each vat rate $i = 0; foreach ($object->lines as $line) { @@ -630,20 +632,19 @@ if (empty($reshook)) $discount->description = '(CREDIT_NOTE)'; elseif ($object->type == Facture::TYPE_DEPOSIT) $discount->description = '(DEPOSIT)'; - elseif ($object->type == Facture::TYPE_STANDARD) + elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) $discount->description = '(EXCESS RECEIVED)'; else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } - $discount->tva_tx = abs($object->total_ttc); $discount->fk_soc = $object->socid; $discount->fk_facture_source = $object->id; $error = 0; - if ($object->type == Facture::TYPE_STANDARD) { - - // If we're on a standard invoice, we have to get excess received to create it in TTC wuthout VAT + if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) + { + // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT $sql = 'SELECT SUM(pf.amount) as total_paiements FROM llx_c_paiement as c, llx_paiement_facture as pf, llx_paiement as p @@ -663,8 +664,9 @@ if (empty($reshook)) $error++; } - } else { - + } + if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) + { foreach ($amount_ht as $tva_tx => $xxx) { $discount->amount_ht = abs($amount_ht[$tva_tx]); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 96f77e85758..8cd924a0df8 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke @@ -221,7 +221,7 @@ if (empty($reshook)) $db->begin(); // Clean parameters amount if payment is for a credit note - if (GETPOST('type') == 2) + if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) { foreach ($amounts as $key => $value) // How payment is dispatch { @@ -249,7 +249,7 @@ if (empty($reshook)) // Creation of payment line $paiement = new Paiement($db); $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement'); $paiement->num_paiement = GETPOST('num_paiement'); @@ -257,7 +257,7 @@ if (empty($reshook)) if (! $error) { - $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0)); + $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0)); // This include closing invoices if ($paiement_id < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); @@ -268,7 +268,7 @@ if (empty($reshook)) if (! $error) { $label='(CustomerInvoicePayment)'; - if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)'; + if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note $result=$paiement->addPaymentToBank($user,'payment',$label,GETPOST('accountid'),GETPOST('chqemetteur'),GETPOST('chqbank')); if ($result < 0) { @@ -281,7 +281,7 @@ if (empty($reshook)) { $db->commit(); - // If payment dispatching on more than one invoice, we keep on summary page, otherwise go on invoice card + // If payment dispatching on more than one invoice, we keep on summary page, otherwise jump on invoice card $invoiceid=0; foreach ($paiement->amounts as $key => $amount) { @@ -309,7 +309,7 @@ if (empty($reshook)) * View */ -llxHeader(); +llxHeader('', $langs->trans("Payment")); $form=new Form($db); @@ -324,8 +324,8 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $facture->fetch_thirdparty(); $title=''; - if ($facture->type != 2) $title.=$langs->trans("EnterPaymentReceivedFromCustomer"); - if ($facture->type == 2) $title.=$langs->trans("EnterPaymentDueToCustomer"); + if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentReceivedFromCustomer"); + if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentDueToCustomer"); print load_fiche_titre($title); // Initialize data for confirmation (this is used because data can be change during confirmation) @@ -347,7 +347,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Add realtime total information - if ($conf->use_javascript_ajax) + if (! empty($conf->use_javascript_ajax)) { print "\n".''."\n"; } diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 53035dca96f..03a7759e52c 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -255,7 +255,7 @@ class Paiement extends CommonObject { if (! empty($conf->prelevement->enabled)) { - // TODO Check if this payment has a withdraw request + // FIXME Check if this invoice has a withdraw request // if not, $mustwait++; // This will disable automatic close on invoice to allow to process } } @@ -275,11 +275,61 @@ class Paiement extends CommonObject else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more."); else { - $result=$invoice->set_paid($user,'',''); - if ($result<0) + // If invoice is a down payment, we also convert down payment to discount + if ($invoice->type == Facture::TYPE_DEPOSIT) { - $this->error=$invoice->error; - $error++; + $amount_ht = $amount_tva = $amount_ttc = array(); + + // Loop on each vat rate + $i = 0; + foreach ($invoice->lines as $line) + { + if ($line->total_ht!=0) + { // no need to create discount if amount is null + $amount_ht[$line->tva_tx] += $line->total_ht; + $amount_tva[$line->tva_tx] += $line->total_tva; + $amount_ttc[$line->tva_tx] += $line->total_ttc; + $i ++; + } + } + + // Insert one discount by VAT rate category + $discount = new DiscountAbsolute($this->db); + $discount->description = '(DEPOSIT)'; + $discount->fk_soc = $invoice->socid; + $discount->fk_facture_source = $invoice->id; + + foreach ($amount_ht as $tva_tx => $xxx) + { + $discount->amount_ht = abs($amount_ht[$tva_tx]); + $discount->amount_tva = abs($amount_tva[$tva_tx]); + $discount->amount_ttc = abs($amount_ttc[$tva_tx]); + $discount->tva_tx = abs($tva_tx); + + $result = $discount->create($user); + if ($result < 0) + { + $error++; + break; + } + } + + if ($error) + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + } + } + + // Set invoice to paid + if (! $error) + { + $result=$invoice->set_paid($user,'',''); + if ($result<0) + { + $this->error=$invoice->error; + $error++; + } } } } diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 7432f0e2412..189ef5c1fe2 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -447,7 +447,7 @@ CantRemovePaymentWithOneInvoicePaid=Can't remove payment since there is at least ExpectedToPay=Expected payment CantRemoveConciliatedPayment=Can't remove conciliated payment PayedByThisPayment=Paid by this payment -ClosePaidInvoicesAutomatically=Classify "Paid" all standard, situation or replacement invoices entirely paid. +ClosePaidInvoicesAutomatically=Classify "Paid" all standard, down payment or replacement invoices entirely paid. ClosePaidCreditNotesAutomatically=Classify "Paid" all credit notes entirely paid back. ClosePaidContributionsAutomatically=Classify "Paid" all social or fiscal contributions entirely paid. AllCompletelyPayedInvoiceWillBeClosed=All invoice with no remain to pay will be automatically closed to status "Paid". From 58e2b49b1c2c59392e0453f479a9af43b95d6f5b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 13:49:06 +0200 Subject: [PATCH 099/116] Clean code --- htdocs/compta/facture/card.php | 13 ------------- htdocs/core/class/commoninvoice.class.php | 3 ++- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 6f5ef85310d..7e08bdc7fae 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -873,19 +873,6 @@ if (empty($reshook)) $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); } } - - // Add predefined lines - /* - TODO delete - for($i = 1; $i <= $NBLINES; $i ++) { - if ($_POST['idprod' . $i]) { - $product = new Product($db); - $product->fetch($_POST['idprod' . $i]); - $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']); - $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']); - $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type); - } - }*/ } } diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 3e9d56f8f8c..4d9fa7a72af 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -51,7 +51,8 @@ abstract class CommonInvoice extends CommonObject const TYPE_DEPOSIT = 3; /** - * Proforma invoice + * Proforma invoice. + * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice ! */ const TYPE_PROFORMA = 4; From 072eb740c713bef7210a5474409b274a175f6a22 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 13:57:13 +0200 Subject: [PATCH 100/116] Fix php compatibility --- htdocs/product/inventory/card.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index f7e4cbecb0a..026bd37e743 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -463,7 +463,8 @@ function card_line(&$inventory, &$lines, $mode) 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]; + $qtytoadd = GETPOST('qty_to_add', 'array'); + $qty = (float) $qtytoadd[$k]; $lines[]=array( 'produit' => $product->getNomUrl(1).' - '.$product->label, From 1e3384a842d11f490ca81654e608d629229911bd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 14:04:01 +0200 Subject: [PATCH 101/116] Fix travis --- htdocs/core/class/commonobject.class.php | 64 +++++++++- htdocs/core/db/DoliDB.class.php | 117 ------------------ htdocs/product/inventory/card.php | 2 +- htdocs/product/inventory/list.php | 2 +- .../inventory}/listview.class.php | 80 ++++++------ 5 files changed, 104 insertions(+), 161 deletions(-) rename htdocs/{core/class => product/inventory}/listview.class.php (93%) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 2526638cee5..5e5c13056e7 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -4674,7 +4674,26 @@ abstract class CommonObject */ public function createCommon(User $user, $notrigger = false) { + foreach ($this->fields as $k => $v) { + $keys[] = $k; + $values[] = $this->quote($v); + + } + + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$table.' + ( '.implode( ",", $keys ).' ) + VALUES ( '.implode( ",", $values ).' ) '; + + $res = $this->query($sql); + if($res===false) { + + return false; + } + + // TODO Add triggers + + return true; } @@ -4690,7 +4709,6 @@ abstract class CommonObject { } - /** * Update object into database @@ -4702,10 +4720,36 @@ abstract class CommonObject */ public function updateCommon(User $user, $notrigger = false) { + foreach ($this->fields as $k => $v) { + if (is_array($key)){ + $i=array_search($k, $key); + if ( $i !== false) { + $where[] = $key[$i].'=' . $this->quote( $v ) ; + continue; + } + } else { + if ( $k == $key) { + $where[] = $k.'=' .$this->quote( $v ) ; + continue; + } + } + + $tmp[] = $k.'='.$this->quote($v); + } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET '.implode( ',', $tmp ).' WHERE ' . implode(' AND ',$where) ; + $res = $this->query( $sql ); + + if($res===false) { + //error + return false; + } + + // TODO Add triggers + + return true; } - /** * Delete object in database * @@ -4718,4 +4762,20 @@ abstract class CommonObject { } + + /** + * 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 )."'"; + + } + } + diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index fb398270fa6..9fc1739334c 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -295,122 +295,5 @@ 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 - * - * @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,$fields,$key){ - - foreach ($fields as $k => $v) { - - if (is_array($key)){ - $i=array_search($k , $key ); - if ( $i !== false) { - $where[] = $key[$i].'=' . $this->quote( $v ) ; - continue; - } - } else { - if ( $k == $key) { - $where[] = $k.'=' .$this->quote( $v ) ; - continue; - } - } - - $tmp[] = $k.'='.$this->quote($v); - } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET '.implode( ',', $tmp ).' WHERE ' . 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,$fields){ - - foreach ($fields as $k => $v) { - - $keys[] = $k; - $values[] = $this->quote($v); - - } - - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$table.' - ( '.implode( ",", $keys ).' ) - VALUES ( '.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,$fields,$key){ - foreach ($fields as $k => $v) { - if (is_array($key)){ - $i=array_search($k , $key ); - if ( $i !== false) { - $where[] = $key[$i].'=' . $this->quote( $v ) ; - continue; - } - } else { - if ( $k == $key) { - $where[] = $k.'='.$this->quote( $v ) ; - continue; - } - } - - } - - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.implode(' AND ',$where); - - $res = $this->query( $sql ); - if($res===false) { - return false; - } - - return true; - - } - } diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 026bd37e743..dc279cc0929 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -23,7 +23,7 @@ require_once '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/listview.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/inventory/listview.class.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'; diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index 36a185d7fd1..57545b07948 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -23,7 +23,7 @@ require_once '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/listview.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/inventory/listview.class.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'; diff --git a/htdocs/core/class/listview.class.php b/htdocs/product/inventory/listview.class.php similarity index 93% rename from htdocs/core/class/listview.class.php rename to htdocs/product/inventory/listview.class.php index 91dd182fc56..51855629686 100644 --- a/htdocs/core/class/listview.class.php +++ b/htdocs/product/inventory/listview.class.php @@ -103,7 +103,7 @@ class Listview /** * @param string $key field name - * @param array $TParam array of configuration + * @param string $TParam array of configuration * @return array */ private function getSearchKey($key, &$TParam) @@ -149,7 +149,7 @@ class Listview /** - * @param array $TSQLMore contain some additional sql instructions + * @param string $TSQLMore contain some additional sql instructions * @param string $value date with read format * @param string $sKey field name */ @@ -181,9 +181,9 @@ class Listview /** - * @param array $TSQLMore contain some additional sql instructions + * @param string $TSQLMore contain some additional sql instructions * @param string $value value to filter - * @param array $TParam array of configuration + * @param string $TParam array of configuration * @param string $sKey field name * @param string $key reference of sKey to find value into TParam * @return bool @@ -222,7 +222,7 @@ class Listview /** * @param string $sql standard select sql - * @param array $TParam array of configuration + * @param string $TParam array of configuration * @return string */ private function search($sql, &$TParam) @@ -289,7 +289,7 @@ class Listview /** * @param string $sql standard select sql - * @param array $TParam array of configuration + * @param string $TParam array of configuration * @return string */ public function render($sql, $TParam=array()) @@ -321,8 +321,8 @@ class Listview } /** - * @param array $THeader the configuration of header - * @param array $TParam array of configuration + * @param string $THeader the configuration of header + * @param string $TParam array of configuration * @return array */ private function setSearch(&$THeader, &$TParam) @@ -427,8 +427,8 @@ class Listview /** * Function to analyse and calculate the total from a column * - * @param $TField - * @param $TParam + * @param string $TField TField + * @param string $TParam TParam * @return array */ private function get_total(&$TField, &$TParam) @@ -495,9 +495,9 @@ class Listview */ /** - * @param $TParam - * @param $TField - * @param $THeader + * @param string $TParam TParam + * @param string $TField TField + * @param string $THeader THeader * @return array */ private function setExport(&$TParam, $TField, $THeader) @@ -535,8 +535,8 @@ class Listview } /** - * @param $TField - * @param $TTotalGroup + * @param string $TField TField + * @param string $TTotalGroup TTotalGroup * @return array */ private function addTotalGroup($TField, $TTotalGroup) @@ -594,11 +594,11 @@ class Listview } /** - * @param $THeader - * @param $TField - * @param $TTotal - * @param $TTotalGroup - * @param $TParam + * @param string $THeader THeader + * @param string $TField TField + * @param string $TTotal TTotal + * @param string $TTotalGroup TTotalGroup + * @param string $TParam TParam * @return string */ private function renderList(&$THeader, &$TField, &$TTotal, &$TTotalGroup, &$TParam) @@ -723,9 +723,9 @@ class Listview } /** - * @param $db - * @param $TField - * @param array $TParam + * @param string $db Db + * @param string $TField TField + * @param string $TParam TParam */ public function renderArray(&$db, $TField, $TParam=array()) { @@ -744,9 +744,9 @@ class Listview /** - * @param $THeader - * @param $TField - * @param $TParam + * @param string $THeader THeader + * @param string $TField TField + * @param string $TParam TParam * @return bool */ private function parse_array(&$THeader, &$TField, &$TParam) @@ -853,8 +853,8 @@ class Listview } /** - * @param $TParam - * @param $line_number + * @param string $TParam TParam + * @param string $line_number aaa * @return bool */ private function in_view(&$TParam, $line_number) @@ -874,9 +874,9 @@ class Listview } /** - * @param $TField - * @param $TParam - * @param $currentLine + * @param string $TField TField + * @param string $TParam TParam + * @param string $currentLine aaa */ private function set_line(&$TField, &$TParam, $currentLine) { @@ -910,7 +910,7 @@ class Listview if(isset($TParam['eval'][$field]) && in_array($field,array_keys($row))) { - $strToEval = 'return '.strtr( $TParam['eval'][$field] , array_merge( $trans, array('@val@'=>$row[$field]) )).';'; + $strToEval = 'return '.strtr( $TParam['eval'][$field], array_merge( $trans, array('@val@'=>$row[$field]) )).';'; $row[$field] = eval($strToEval); } @@ -932,7 +932,7 @@ class Listview 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($TParam['type'][$field]=='integer') { $row[$field] = '
    '.((int) $row[$field]).'
    '; } } if(isset($TParam['link'][$field])) @@ -945,7 +945,7 @@ class Listview { if(isset($TParam['translate'][$field][''])) unset($TParam['translate'][$field]['']); - $row[$field] = strtr( $row[$field] , $TParam['translate'][$field]); + $row[$field] = strtr( $row[$field], $TParam['translate'][$field]); } } } @@ -986,8 +986,8 @@ class Listview } /** - * @param $sql - * @param $TParam + * @param string $sql sql + * @param string $TParam TParam * @return string */ private function limitSQL($sql, &$TParam) @@ -1001,10 +1001,10 @@ class Listview } /** - * @param $THeader - * @param $TField - * @param $TParam - * @param $sql + * @param string $THeader THeader + * @param string $TField TField + * @param string $TParam TParam + * @param string $sql sql */ private function parse_sql(&$THeader, &$TField, &$TParam, $sql) { From 1dd462d94783bc972ba8fc08daf80db5b49dc5dd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 30 Apr 2017 23:39:35 +0200 Subject: [PATCH 102/116] Fix disable notification on smartphone --- htdocs/main.inc.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 6a92e0f4eed..ab92df9ca12 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -1271,9 +1271,10 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs { $enablebrowsernotif=false; if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_NOTIFICATION)) $enablebrowsernotif=true; + if ($conf->browser->layout == 'phone') $enablebrowsernotif=false; if ($enablebrowsernotif) { - print ''."\n"; + print ''."\n"; print ''."\n"; } } From 5af5c23a987f9d0025653da691120c6e8e3516e5 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 1 May 2017 12:46:40 +0200 Subject: [PATCH 103/116] Look and feel v6 --- .../core/tpl/admin_extrafields_view.tpl.php | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index c14927ec048..3242a388a3d 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2010-2017 Laurent Destailleur * Copyright (C) 2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -49,23 +49,36 @@ if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ' '; print "\n"; -$var=True; -foreach($extrafields->attribute_type as $key => $value) +if (count($extrafields->attribute_type)) { + foreach($extrafields->attribute_type as $key => $value) + { + + print ''; + print "".$extrafields->attribute_pos[$key]."\n"; + print "".$extrafields->attribute_label[$key]."\n"; + print "".$key."\n"; + print "".$type2label[$extrafields->attribute_type[$key]]."\n"; + print ''.$extrafields->attribute_size[$key]."\n"; + print ''.yn($extrafields->attribute_unique[$key])."\n"; + print ''.yn($extrafields->attribute_required[$key])."\n"; + print ''.yn($extrafields->attribute_alwayseditable[$key])."\n"; + if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.yn($extrafields->attribute_hidden[$key])."\n"; // Add hidden option on not working feature. Why hide if user can't see it. + print ''.img_edit().''; + print "  ".img_delete()."\n"; + print ""; + } +} +else +{ + $colspan=9; + if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) $colspan++; print ''; - print "".$extrafields->attribute_pos[$key]."\n"; - print "".$extrafields->attribute_label[$key]."\n"; - print "".$key."\n"; - print "".$type2label[$extrafields->attribute_type[$key]]."\n"; - print ''.$extrafields->attribute_size[$key]."\n"; - print ''.yn($extrafields->attribute_unique[$key])."\n"; - print ''.yn($extrafields->attribute_required[$key])."\n"; - print ''.yn($extrafields->attribute_alwayseditable[$key])."\n"; - if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.yn($extrafields->attribute_hidden[$key])."\n"; // Add hidden option on not working feature. Why hide if user can't see it. - print ''.img_edit().''; - print "  ".img_delete()."\n"; - print ""; + print ''; + print $langs->trans("None"); + print ''; + print ''; } print ""; From 6e1f82519020ac0a38532438df32a8481eb63f1c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 1 May 2017 13:01:05 +0200 Subject: [PATCH 104/116] Look and feel v6 --- htdocs/admin/clicktodial.php | 3 ++- htdocs/core/lib/ajax.lib.php | 2 +- htdocs/langs/en_US/admin.lang | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/htdocs/admin/clicktodial.php b/htdocs/admin/clicktodial.php index 060c910753a..86b94d8ecf0 100644 --- a/htdocs/admin/clicktodial.php +++ b/htdocs/admin/clicktodial.php @@ -91,7 +91,8 @@ print ''; print ''; print $langs->trans("DefaultLink").''; -print 'global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS?' disabled="disabled"':'').' value="'.$conf->global->CLICKTODIAL_URL.'">
    '; +print 'global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS?' disabled="disabled"':'').' value="'.$conf->global->CLICKTODIAL_URL.'">
    '; +print ajax_autoselect('CLICKTODIAL_URL'); print '
    '; print $langs->trans("ClickToDialUrlDesc").'
    '; print $langs->trans("Example").':
    http://myphoneserver/mypage?login=__LOGIN__&password=__PASS__&caller=__PHONEFROM__&called=__PHONETO__'; diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 942c17f5df9..49218ddf141 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -349,7 +349,7 @@ function ajax_dialog($title,$message,$w=350,$h=150) /** - * Make a input box content all selected + * Make content of an input box selected when we click into input field. * * @param string $htmlname Id of html object * @param int $addlink Add a link to after diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 02ff5740986..35037387c1f 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -1501,7 +1501,7 @@ AGENDA_NOTIFICATION=Enable event notification on user browsers when event date i AGENDA_NOTIFICATION_SOUND=Enable sound notification ##### Clicktodial ##### ClickToDialSetup=Click To Dial module setup -ClickToDialUrlDesc=Url called when a click on phone picto is done. In URL, you can use tags
    __PHONETO__ that will be replaced with the phone number of person to call
    __PHONEFROM__ that will be replaced with phone number of calling person (yours)
    __LOGIN__ that will be replaced with your clicktodial login (defined on your user card)
    __PASS__ that will be replaced with your clicktodial password (defined on your user card). +ClickToDialUrlDesc=Url called when a click on phone picto is done. In URL, you can use tags
    __PHONETO__ that will be replaced with the phone number of person to call
    __PHONEFROM__ that will be replaced with phone number of calling person (yours)
    __LOGIN__ that will be replaced with clicktodial login (defined on user card)
    __PASS__ that will be replaced with clicktodial password (defined on user card). ClickToDialDesc=This module allows to make phone numbers clickable. A click on this icon will call make your phone to call the phone number. This can be used to call a call center system from Dolibarr that can call the phone number on a SIP system for example. ClickToDialUseTelLink=Use just a link "tel:" on phone numbers ClickToDialUseTelLinkDesc=Use this method if your users have a softphone or a software interface installed on same computer than the browser, and called when you click on a link in your browser that start with "tel:". If you need a full server solution (no need of local software installation), you must set this to "No" and fill next field. From 8730add15f70eab2a1f458f047f4f2df7c797358 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 1 May 2017 16:01:39 +0200 Subject: [PATCH 105/116] Better message for api key return --- build/debian/README.howto | 29 +++++++++++++++++++++------- htdocs/api/class/api_login.class.php | 2 +- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/build/debian/README.howto b/build/debian/README.howto index 705899d47c4..399c4f07a1f 100644 --- a/build/debian/README.howto +++ b/build/debian/README.howto @@ -385,13 +385,14 @@ http://packages.qa.debian.org * Package will be into release when test will be moved as stable. -##### Send an unblock request + +##### Send an unblock request to make a full update of a stable package Use this to move from unstable to testing. reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls Choose package "release.debian.org" -Then "unblock" +Then usertag "unblock" Then name of package "dolibarr" Fill message, for example: "Please unblock package dolibarr @@ -400,12 +401,11 @@ Note that package 3.5.7 contains not only fixed for bugs reported to debian. It so it is a better solution to validate this maintenance release than applying a patch of the only CVE-2015-3935. After discussion with ..., it appears that security holes are enough to request this unblock request." - -Use this to request an update of a stable package +Use this to request an full update of a stable package reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls Choose package "release.debian.org" -Then "unblock" +Then usertag "unblock" Then name of package "dolibarr" Fill message, for example: " @@ -417,11 +417,26 @@ Pro are: - It fixes also stability bugs - Patches were already tested because deployed and used by several thousands of users. - It is easier for package maintener to include this official set of fixes than applying one patch after one patch for each debian report or backported each patch into a dedicated version. -- Debian maintenance version matches with official project maintenance version (better when all fixes are not related to the way the software is packaged) +- Debian maintenance version is inline with official project maintenance version (better when all fixes are not related to the way the software is packaged) Cons are: -- The patch include more than the only one security reported fxes +- The patch include more than the only one security reported fixes So I just need to know if it's ok to push such a version 3.5.7 (fixes for 3.5.* branch) instead of only one fix for only the few (the only) reported debian bugs, since it provides more stability and is for me a more secured process. " +##### Send an request to ask a simple fix of a stable package + +Use this to ask to apply patches on a stable version. + +reportbug -B debian --smtphost=smtp.gmail.com:587 --smtpuser=xxxx --smtppasswd=yyyy --tls +Choose package "release.debian.org" +Then usertag "jessie-pu" +Then name of package "dolibarr" +Fill message, for example: +"Please unblock package dolibarr +A security error CVE-2015-3935 was reported and is fixed into package 3.5.7. +Note that package 3.5.7 contains not only fixed for bugs reported to debian. It includes other fixes, but they are all related to stability or security, +so it is a better solution to validate this maintenance release than applying a patch of the only CVE-2015-3935. +After discussion with ..., it appears that security holes are enough to request this unblock request." + diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 704ec1b6874..76a9befebc9 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -102,7 +102,7 @@ class Login 'success' => array( 'code' => 200, 'token' => $token, - 'message' => 'Welcome ' . $login.($reset?' - Token is new':' - This is your token (generated by a previous call)') + 'message' => 'Welcome ' . $login.($reset?' - Token is new':' - This is your token (generated by a previous call). You can use it to make any REST API call, or enter it into the DOLAPIKEY field to use the Dolibarr API explorer.') ) ); } From 9641a240ead9a444c6555b3f807736980315ac5f Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 11:27:35 +0200 Subject: [PATCH 106/116] Complete vat dictionnary --- htdocs/admin/dict.php | 19 ++++++++++--------- htdocs/install/mysql/data/llx_c_tva.sql | 6 ++++-- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index d4aa0ce6989..c2730e6c034 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -918,10 +918,19 @@ if (empty($id)) print "
    \n"; +$param = '&id='.$id; +if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; +if ($search_code != '') $param.= '&search_code='.urlencode($search_country_id); +$paramwithsearch = $param; +if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; +if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; +if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); + + // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.urlencode($_GET["code"]).'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'rowid='.$rowid.'&code='.urlencode($_GET["code"]).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -1134,14 +1143,6 @@ if ($id) $num = $db->num_rows($resql); $i = 0; - $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; - if ($search_code != '') $param.= '&search_code='.urlencode($search_country_id); - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); - // There is several pages if ($num > $listlimit) { diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 81c72eccb8f..34842ed324e 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -96,12 +96,14 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (80 -- FRANCE (id country=1) insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 11, 1, '20','0','VAT standard rate (France hors DOM-TOM)',1); -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 12, 1, '8.5','0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0); -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 13, 1, '8.5','1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0); +insert into llx_c_tva(rowid,fk_pays,taux,code,recuperableonly,note,active) values ( 12, 1, '8.5', '8.5', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 14, 1, '5.5','0','VAT reduced rate (France hors DOM-TOM)',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 15, 1, '0','0','VAT Rate 0 ou non applicable',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 16, 1, '2.1','0','VAT super-reduced rate',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 17, 1, '10','0','VAT reduced rate',1); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active) values (1, '8.5', '85NPR', '1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,note,active) values (1, '8.5', '85NPROM', '1', 2, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer',0); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values (1, '8.5', '85NPROMOMR', '1', 2, 3, 2.5, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer et Octroi de Mer Regional',0); -- GERMANY (id country=5) insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 51, 5, '19.0','0','allgemeine Ust.',1); From 31d99bbfe6c0956c4b9633e2f4127808602366ff Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 11:28:40 +0200 Subject: [PATCH 107/116] Complete event tracked automatically --- ...terface_50_modAgenda_ActionsAuto.class.php | 73 +-- htdocs/expensereport/card.php | 478 ++++++++++-------- .../mysql/data/llx_c_action_trigger.sql | 4 + .../install/mysql/migration/5.0.0-6.0.0.sql | 22 + htdocs/install/mysql/tables/llx_holiday.sql | 4 +- 5 files changed, 304 insertions(+), 277 deletions(-) diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index 84517e36c08..bce6d69b2fa 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -87,7 +87,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("NewCompanyToDolibarr",$object->name); $object->actionmsg=$langs->transnoentities("NewCompanyToDolibarr",$object->name); if (! empty($object->prefix)) $object->actionmsg.=" (".$object->prefix.")"; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->socid=$object->id; @@ -100,7 +99,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actiontypecode)) $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) dol_syslog('Trigger called with property actionmsg2 on object not defined', LOG_ERR); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; @@ -114,7 +112,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -127,7 +124,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -142,7 +138,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("ProposalSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -157,7 +152,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedSignedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("PropalClosedSignedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -170,7 +164,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -183,7 +176,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedRefusedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("PropalClosedRefusedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -195,7 +187,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -208,7 +199,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderDeliveredInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("OrderDeliveredInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -221,7 +211,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderBilledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("OrderBilledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -234,7 +223,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderCanceledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("OrderCanceledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -249,7 +237,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("OrderSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -264,7 +251,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -277,7 +263,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -292,7 +277,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("InvoiceSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -308,7 +292,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; $object->actionmsg2=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -321,7 +304,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -334,7 +316,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->fk_element=0; @@ -349,7 +330,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->fk_element=0; @@ -364,7 +344,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->fk_element=0; @@ -379,7 +358,7 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionSentByEMail",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; } @@ -392,7 +371,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -405,7 +383,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -418,7 +395,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->fk_element=0; @@ -435,7 +411,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("ShippingValidated",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -452,7 +427,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("ShippingSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -467,7 +441,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderCreatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("OrderCreatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -480,7 +453,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -493,7 +465,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderApprovedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("OrderApprovedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -506,7 +477,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderRefusedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("OrderRefusedInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -519,7 +489,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("SupplierOrderSubmitedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("SupplierOrderSubmitedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -532,7 +501,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("SupplierOrderReceivedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("SupplierOrderReceivedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -548,7 +516,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("SupplierOrderSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -566,7 +533,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("SupplierOrderClassifiedBilled",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } $object->sendtoid=0; @@ -580,7 +546,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -593,7 +558,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -609,7 +573,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg)) { $object->actionmsg=$langs->transnoentities("SupplierInvoiceSentByEMail",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller @@ -624,7 +587,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -637,7 +599,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -654,7 +615,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -669,7 +629,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actionmsg=$langs->transnoentities("MemberModifiedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -686,7 +645,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; $object->actionmsg.="\n".$langs->transnoentities("Amount").': '.$object->last_subscription_amount; $object->actionmsg.="\n".$langs->transnoentities("Period").': '.dol_print_date($object->last_subscription_date_start,'day').' - '.dol_print_date($object->last_subscription_date_end,'day'); - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -701,7 +659,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actionmsg=$langs->transnoentities("MemberResiliatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -716,7 +673,6 @@ class InterfaceActionsAuto extends DolibarrTriggers $object->actionmsg=$langs->transnoentities("MemberDeletedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -732,7 +688,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Project").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -746,7 +701,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectValidatedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("ProjectValidatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Project").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -759,7 +713,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectModifiedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("ProjectModifieddInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -775,7 +728,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskCreatedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("TaskCreatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -789,7 +741,6 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskModifiedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("TaskModifieddInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } @@ -803,18 +754,24 @@ class InterfaceActionsAuto extends DolibarrTriggers if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskDeletedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("TaskDeletedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; - $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; } - - // The trigger was enabled but we are missing the implementation, let the log know - else - { - dol_syslog("Trigger '".$this->name."' for action '$action' was ran by ".__FILE__." but no handler found for this action.", LOG_WARNING); - return 0; + // TODO Merge all previous cases into this generic one + else { + // Note: We are here only if $conf->global->MAIN_AGENDA_ACTIONAUTO_action is on (tested at begining of this function) + $langs->load("agenda"); + $langs->load("other"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities($action."InDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities($action."InDolibarr",$object->ref); + + $object->sendtoid=0; } - + + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); // Add entry in event table diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index db2328cdfb4..9a2433994bd 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -444,14 +444,16 @@ if (empty($reshook)) $destinataire->fetch($object->fk_user_validator); $emailTo = $destinataire->email; - if ($emailTo) - { - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_author); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_author); + $emailFrom = $expediteur->email; - // SUBJECT + if ($emailFrom && $emailTo) + { + $filename=array(); $filedir=array(); $mimetype=array(); + + // SUBJECT $subject = $langs->transnoentities("ExpenseReportWaitingForReApproval"); // CONTENT @@ -561,73 +563,83 @@ if (empty($reshook)) // CC $emailCC = $conf->global->NDF_CC_EMAILS; + if (empty($emailTo)) $emailTo=$emailCC; // FROM $expediteur = new User($db); $expediteur->fetch($object->fk_user_valid); $emailFrom = $expediteur->email; - // SUBJECT - $subject = $langs->transnoentities("ExpenseReportApproved"); - - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - - // Rebuilt pdf - /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - - if($resultPDF - { - // ATTACHMENT + if ($emailFrom && $emailTo) + { $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ + + // SUBJECT + $subject = $langs->transnoentities("ExpenseReportApproved"); + + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + + // Rebuilt pdf + /* + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + + if($resultPDF + { + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); + } + */ - // PREPARE SEND - $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); - - if ($mailfile) - { - // SEND - $result=$mailfile->sendfile(); - if ($result) - { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg=''; - $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg.='
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } - else - { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } + $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); + + if ($mailfile) + { + // SEND + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg=''; + $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg.='
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } + else + { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } + else + { + setEventMessages($mailfile->error,$mailfile->errors,'errors'); + $action=''; + } } - else - { - setEventMessages($mailfile->error,$mailfile->errors,'errors'); - $action=''; - } - } + else + { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action=''; + } + } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings'); $action=''; } } @@ -677,68 +689,78 @@ if (empty($reshook)) $expediteur->fetch($object->fk_user_refuse); $emailFrom = $expediteur->email; - // SUBJECT - $subject = $langs->transnoentities("ExpenseReportRefused"); - - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_refuse'], $link); - - // Rebuilt pdf - /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - - if($resultPDF - { - // ATTACHMENT + if ($emailFrom && $emailTo) + { $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ + + // SUBJECT + $subject = $langs->transnoentities("ExpenseReportRefused"); - // PREPARE SEND - $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_refuse'], $link); - if ($mailfile) - { - // SEND - $result=$mailfile->sendfile(); - if ($result) + // Rebuilt pdf + /* + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + + if($resultPDF { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg=''; - $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg.='
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } - else - { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } - else - { - setEventMessages($mailfile->error,$mailfile->errors,'errors'); - $action=''; - } + */ + + // PREPARE SEND + $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); + + if ($mailfile) + { + // SEND + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg=''; + $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg.='
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } + else + { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } + else + { + setEventMessages($mailfile->error,$mailfile->errors,'errors'); + $action=''; + } + } + else + { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action=''; + } } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action=''; + setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings'); + $action=''; } } else @@ -790,67 +812,77 @@ if (empty($reshook)) $expediteur->fetch($object->fk_user_cancel); $emailFrom = $expediteur->email; - // SUBJECT - $subject = $langs->transnoentities("ExpenseReportCanceled"); - - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_cancel'], $link); - - // Rebuilt pdf - /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - - if($resultPDF - { - // ATTACHMENT - $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ - - // PREPARE SEND - $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); - - if ($mailfile) + if ($emailFrom && $emailTo) { - // SEND - $result=$mailfile->sendfile(); - if ($result) + $filename=array(); $filedir=array(); $mimetype=array(); + + // SUBJECT + $subject = $langs->transnoentities("ExpenseReportCanceled"); + + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $_POST['detail_cancel'], $link); + + // Rebuilt pdf + /* + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + + if($resultPDF { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg=''; - $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg.='
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } - else - { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); } + */ + + // PREPARE SEND + $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); + + if ($mailfile) + { + // SEND + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg=''; + $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg.='
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } + else + { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } + else + { + setEventMessages($mailfile->error,$mailfile->errors,'errors'); + $action=''; + } } else { - setEventMessages($mailfile->error,$mailfile->errors,'errors'); - $action=''; - } + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action=''; + } } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings'); $action=''; } } @@ -945,63 +977,73 @@ if (empty($reshook)) $expediteur->fetch($user->id); $emailFrom = $expediteur->email; - // SUBJECT - $subject = $langs->transnoentities("ExpenseReportPaid"); - - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - - // CONTENT - $message = "Bonjour {$destinataire->firstname},\n\n"; - $message.= "Votre note de frais \"{$object->ref}\" vient d'être payée.\n"; - $message.= "- Payeur : {$expediteur->firstname} {$expediteur->lastname}\n"; - $message.= "- Lien : {$dolibarr_main_url_root}/expensereport/card.php?id={$object->id}\n\n"; - $message.= "Bien cordialement,\n' SI"; - - // Generate pdf before attachment - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - - // PREPARE SEND - $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); - - if ($mailfile) + if ($emailFrom && $emailTo) { - // SEND - $result=$mailfile->sendfile(); - if ($result) - { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg=''; - $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg.='
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } - else - { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } + $filename=array(); $filedir=array(); $mimetype=array(); + + // SUBJECT + $subject = $langs->transnoentities("ExpenseReportPaid"); + + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + + // CONTENT + $message = "Bonjour {$destinataire->firstname},\n\n"; + $message.= "Votre note de frais \"{$object->ref}\" vient d'être payée.\n"; + $message.= "- Payeur : {$expediteur->firstname} {$expediteur->lastname}\n"; + $message.= "- Lien : {$dolibarr_main_url_root}/expensereport/card.php?id={$object->id}\n\n"; + $message.= "Bien cordialement,\n' SI"; + + // Generate pdf before attachment + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + + // PREPARE SEND + $mailfile = new CMailFile($subject,$emailTo,$emailFrom,$message,$filedir,$mimetype,$filename); + + if ($mailfile) + { + // SEND + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($emailFrom,2),$mailfile->getValidAddress($emailTo,2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg=''; + $mesg.=$langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg.='
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } + else + { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } + else + { + setEventMessages($mailfile->error,$mailfile->errors,'errors'); + $action=''; + } } else { - setEventMessages($mailfile->error,$mailfile->errors,'errors'); - $action=''; + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action=''; } } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings'); $action=''; } } diff --git a/htdocs/install/mysql/data/llx_c_action_trigger.sql b/htdocs/install/mysql/data/llx_c_action_trigger.sql index 9aadb0c083e..d25963e8c3a 100644 --- a/htdocs/install/mysql/data/llx_c_action_trigger.sql +++ b/htdocs/install/mysql/data/llx_c_action_trigger.sql @@ -78,6 +78,10 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('FICHINTER_SENTBYMAIL','Intervention sent by mail','Executed when a intervention is sent by mail','ficheinter',35); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_CREATE','Product or service created','Executed when a product or sevice is created','product',40); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_DELETE','Product or service deleted','Executed when a product or sevice is deleted','product',42); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expensereport',201); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expensereport',202); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expensereport',203); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expensereport',204); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_VALIDATE','Project validation','Executed when a project is validated','project',141); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_DELETE','Project deleted','Executed when a project is deleted','project',143); -- actions not enabled by default (no constant created for that) when we enable module agenda diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index b20da8b9b89..71f9a17273c 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -42,10 +42,22 @@ ALTER TABLE llx_ecm_files ADD UNIQUE INDEX uk_ecm_files (filepath, filename, ent ALTER TABLE llx_ecm_files ADD INDEX idx_ecm_files_label (label); +ALTER TABLE llx_holiday ADD COLUMN import_key varchar(14); +ALTER TABLE llx_holiday ADD COLUMN extraparams varchar(255); + +ALTER TABLE llx_expensereport ADD COLUMN import_key varchar(14); +ALTER TABLE llx_expensereport ADD COLUMN extraparams varchar(255); + + insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_CREATE','Product or service created','Executed when a product or sevice is created','product',30); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_MODIFY','Product or service modified','Executed when a product or sevice is modified','product',30); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_DELETE','Product or service deleted','Executed when a product or sevice is deleted','product',30); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expense_report',201); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expense_report',202); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expense_report',203); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expense_report',204); + ALTER TABLE llx_c_email_templates ADD COLUMN content_lines text; ALTER TABLE llx_loan ADD COLUMN fk_projet integer DEFAULT NULL; @@ -111,6 +123,16 @@ INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES ( ALTER TABLE llx_paiementfourn ADD COLUMN model_pdf varchar(255); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_CREATE','Expense report created','Executed when an expense report is created','expensereport',201); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_VALIDATE','Expense report validated','Executed when an expense report is validated','expensereport',202); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_APPROVE','Expense report approved','Executed when an expense report is approved','expensereport',203); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('EXPENSE_REPORT_PAYED','Expense report billed','Executed when an expense report is set as billed','expensereport',204); + +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_CREATE' ,'Leave request created','Executed when a leave request is created','holiday',221); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_VALIDATE','Leave request validated','Executed when a leave request is validated','holiday',222); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('HOLIDAY_APPROVE' ,'Leave request approved','Executed when a leave request is approved','holiday',223); + + ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier_line integer; ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier integer; ALTER TABLE llx_societe_remise_except ADD COLUMN fk_invoice_supplier_source integer; diff --git a/htdocs/install/mysql/tables/llx_holiday.sql b/htdocs/install/mysql/tables/llx_holiday.sql index 2a981444df3..2091dea9541 100644 --- a/htdocs/install/mysql/tables/llx_holiday.sql +++ b/htdocs/install/mysql/tables/llx_holiday.sql @@ -40,6 +40,8 @@ fk_user_cancel integer DEFAULT NULL, detail_refuse varchar( 250 ) DEFAULT NULL, note_private text, note_public text, -tms timestamp +tms timestamp, +import_key varchar(14), +extraparams varchar(255) -- for other parameters with json format ) ENGINE=innodb; From ad095d7fb24752c60085f54c44ce9604545970bd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 14:26:51 +0200 Subject: [PATCH 108/116] NEW Can set margins of PDFs --- htdocs/admin/pdf.php | 45 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index b0c32a344ff..2e650c75696 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -42,15 +42,25 @@ $langs->load("members"); if (! $user->admin) accessforbidden(); $action = GETPOST('action','alpha'); +$cancel = GETPOST('cancel','alpha'); + /* * Actions */ +if ($cancel) { + $action=''; +} + if ($action == 'update') { dolibarr_set_const($db, "MAIN_PDF_FORMAT", $_POST["MAIN_PDF_FORMAT"],'chaine',0,'',$conf->entity); - + + dolibarr_set_const($db, "MAIN_PDF_MARGIN_LEFT", $_POST["MAIN_PDF_MARGIN_LEFT"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_PDF_MARGIN_RIGHT", $_POST["MAIN_PDF_MARGIN_RIGHT"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_PDF_MARGIN_TOP", $_POST["MAIN_PDF_MARGIN_TOP"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_PDF_MARGIN_BOTTOM", $_POST["MAIN_PDF_MARGIN_BOTTOM"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_PROFID1_IN_ADDRESS", $_POST["MAIN_PROFID1_IN_ADDRESS"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_PROFID2_IN_ADDRESS", $_POST["MAIN_PROFID2_IN_ADDRESS"],'chaine',0,'',$conf->entity); @@ -133,7 +143,20 @@ if ($action == 'edit') // Edit print $formadmin->select_paper_format($selected,'MAIN_PDF_FORMAT'); print ''; - print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_LEFT").''; + print ''; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_RIGHT").''; + print ''; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_TOP").''; + print ''; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_BOTTOM").''; + print ''; + print ''; + + print ''; print '
    '; @@ -270,7 +293,9 @@ if ($action == 'edit') // Edit print ''; print '
    '; - print ''; + print ''; + print '   '; + print ''; print '
    '; print ''; @@ -314,6 +339,20 @@ else // Show print $pdfformatlabel; print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_LEFT").''; + print empty($conf->global->MAIN_PDF_MARGIN_LEFT)?10:$conf->global->MAIN_PDF_MARGIN_LEFT; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_RIGHT").''; + print empty($conf->global->MAIN_PDF_MARGIN_RIGHT)?10:$conf->global->MAIN_PDF_MARGIN_RIGHT; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_TOP").''; + print empty($conf->global->MAIN_PDF_MARGIN_TOP)?10:$conf->global->MAIN_PDF_MARGIN_TOP; + print ''; + print ''.$langs->trans("MAIN_PDF_MARGIN_BOTTOM").''; + print empty($conf->global->MAIN_PDF_MARGIN_BOTTOM)?10:$conf->global->MAIN_PDF_MARGIN_BOTTOM; + print ''; + + print ''; print '
    '; From c673d283e01e41a6292875dce4b9a8bb07bcf817 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 18:21:50 +0200 Subject: [PATCH 109/116] Fix script to send emailings --- ...terface_50_modAgenda_ActionsAuto.class.php | 2 +- scripts/emailings/mailing-send.php | 41 ++++++++++++++----- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index bce6d69b2fa..9da1ada59ad 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -48,7 +48,7 @@ class InterfaceActionsAuto extends DolibarrTriggers * $object->actionmsg (note, long text) * $object->actionmsg2 (label, short text) * $object->sendtoid (id of contact or array of ids) - * $object->socid + * $object->socid (id of thirdparty) * $object->fk_project * $object->fk_element * $object->elementtype diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php index 27cc22448e6..6465e765cfe 100755 --- a/scripts/emailings/mailing-send.php +++ b/scripts/emailings/mailing-send.php @@ -41,11 +41,12 @@ if (! isset($argv[1]) || ! $argv[1]) { exit(-1); } $id=$argv[1]; -if (! isset($argv[2]) || !empty($argv[2])) $login = $argv[2]; +if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2]; else $login = ''; require_once ($path."../../htdocs/master.inc.php"); require_once (DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php"); +require_once (DOL_DOCUMENT_ROOT."/comm/mailing/class/mailing.class.php"); // Global variables @@ -70,9 +71,8 @@ $user = new User($db); // for signature, we use user send as parameter if (! empty($login)) $user->fetch('',$login); -// We get list of emailing to process -$sql = "SELECT m.rowid, m.titre, m.sujet, m.body,"; -$sql.= " m.email_from, m.email_replyto, m.email_errorsto"; +// We get list of emailing id to process +$sql = "SELECT m.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."mailing as m"; $sql.= " WHERE m.statut IN (1,2)"; if ($id != 'all') @@ -96,12 +96,15 @@ if ($resql) dol_syslog("Process mailing with id ".$obj->rowid); print "Process mailing with id ".$obj->rowid."\n"; - $id = $obj->rowid; - $subject = $obj->sujet; - $message = $obj->body; - $from = $obj->email_from; - $replyto = $obj->email_replyto; - $errorsto = $obj->email_errorsto; + $emailing = new Mailing($db); + $emailing->fetch($obj->rowid); + + $id = $emailing->id; + $subject = $emailing->sujet; + $message = $emailing->body; + $from = $emailing->email_from; + $replyto = $emailing->email_replyto; + $errorsto = $emailing->email_errorsto; // Le message est-il en html $msgishtml=-1; // Unknown by default if (preg_match('/[\s\t]*/i',$message)) $msgishtml=1; @@ -232,6 +235,24 @@ if ($resql) dol_syslog("ok for emailing id ".$id." #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); + // Note: If emailing is 100 000 targets, 100 000 entries are added, so we don't enter events for each target here + // We must union table llx_mailing_taget for event tab OR enter 1 event with a special table link (id of email in event) + // Run trigger + /* + if ($obj2->source_type == 'contact') + { + $emailing->sendtoid = $obj2->source_id; + } + if ($obj2->source_type == 'thirdparty') + { + $emailing->socid = $obj2->source_id; + } + // Call trigger + $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user); + if ($result < 0) $error++; + // End call triggers + */ + $sqlok ="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sqlok.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj2->rowid; $resqlok=$db->query($sqlok); From 0bc46facd75af8117780da5e4b30af9011645bd1 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 21:24:18 +0200 Subject: [PATCH 110/116] Add missing vat_src_code on recurring invoices --- htdocs/install/mysql/migration/5.0.0-6.0.0.sql | 2 ++ htdocs/install/mysql/tables/llx_facture_rec.sql | 1 + 2 files changed, 3 insertions(+) diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 71f9a17273c..991381cb432 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -141,6 +141,8 @@ ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_soc_remise_fk_invoice_su ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_invoice_supplier FOREIGN KEY (fk_invoice_supplier) REFERENCES llx_facture_fourn (rowid); ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_invoice_supplier_source FOREIGN KEY (fk_invoice_supplier) REFERENCES llx_facture_fourn (rowid); +ALTER TABLE llx_facture_rec ADD COLUMN vat_src_code varchar(10) DEFAULT ''; + UPDATE llx_const set value='moono-lisa' where value = 'moono' AND name = 'FCKEDITOR_SKIN'; ALTER TABLE llx_product_price ADD COLUMN default_vat_code varchar(10) after tva_tx; diff --git a/htdocs/install/mysql/tables/llx_facture_rec.sql b/htdocs/install/mysql/tables/llx_facture_rec.sql index d0d79ef57dc..0e25100386b 100644 --- a/htdocs/install/mysql/tables/llx_facture_rec.sql +++ b/htdocs/install/mysql/tables/llx_facture_rec.sql @@ -32,6 +32,7 @@ create table llx_facture_rec remise_percent real DEFAULT 0, remise_absolue real DEFAULT 0, + vat_src_code varchar(10) DEFAULT '', -- Vat code used as source of vat fields. Not strict foreign key here. tva double(24,8) DEFAULT 0, localtax1 double(24,8) DEFAULT 0, -- amount localtax1 localtax2 double(24,8) DEFAULT 0, -- amount localtax2 From b8f5e93ab0b56157dbfa83d95da42df84ff57487 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 21:40:18 +0200 Subject: [PATCH 111/116] Debug inventory data model --- htdocs/install/mysql/data/llx_c_tva.sql | 2 +- htdocs/install/mysql/migration/5.0.0-6.0.0.sql | 13 +++++++++---- htdocs/install/mysql/tables/llx_inventorydet.sql | 8 ++++---- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 34842ed324e..3b401abd37d 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -96,11 +96,11 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (80 -- FRANCE (id country=1) insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 11, 1, '20','0','VAT standard rate (France hors DOM-TOM)',1); -insert into llx_c_tva(rowid,fk_pays,taux,code,recuperableonly,note,active) values ( 12, 1, '8.5', '8.5', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 14, 1, '5.5','0','VAT reduced rate (France hors DOM-TOM)',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 15, 1, '0','0','VAT Rate 0 ou non applicable',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 16, 1, '2.1','0','VAT super-reduced rate',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 17, 1, '10','0','VAT reduced rate',1); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active) values (1, '8.5', '85', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0); insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active) values (1, '8.5', '85NPR', '1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0); insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,note,active) values (1, '8.5', '85NPROM', '1', 2, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer',0); insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values (1, '8.5', '85NPROMOMR', '1', 2, 3, 2.5, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer et Octroi de Mer Regional',0); diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 991381cb432..1982ef6aff8 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -229,9 +229,9 @@ fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, batch varchar(30) DEFAULT NULL, -qty_view double DEFAULT 0, -qty_stock double DEFAULT 0, -qty_regulated double DEFAULT 0, +qty_view double DEFAULT NULL, +qty_stock double DEFAULT NULL, +qty_regulated double DEFAULT NULL, pmp double DEFAULT 0, pa double DEFAULT 0, new_pmp double DEFAULT 0 @@ -242,4 +242,9 @@ ALTER TABLE llx_inventory ADD INDEX idx_inventory_tms (tms); ALTER TABLE llx_inventory ADD INDEX idx_inventory_datec (datec); ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_tms (tms); ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_datec (datec); -ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_fk_inventory (fk_inventory); \ No newline at end of file +ALTER TABLE llx_inventorydet ADD INDEX idx_inventorydet_fk_inventory (fk_inventory); + +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active) values (1, '8.5', '85', '0','VAT standard rate (DOM sauf Guyane et Saint-Martin)',0); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,note,active) values (1, '8.5', '85NPR', '1','VAT standard rate (DOM sauf Guyane et Saint-Martin), non perçu par le vendeur mais récupérable par acheteur',0); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,note,active) values (1, '8.5', '85NPROM', '1', 2, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer',0); +insert into llx_c_tva(fk_pays,taux,code,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values (1, '8.5', '85NPROMOMR', '1', 2, 3, 2.5, 3, 'VAT standard rate (DOM sauf Guyane et Saint-Martin), NPR, Octroi de Mer et Octroi de Mer Regional',0); diff --git a/htdocs/install/mysql/tables/llx_inventorydet.sql b/htdocs/install/mysql/tables/llx_inventorydet.sql index 2b203e0c58b..ce40d03939c 100644 --- a/htdocs/install/mysql/tables/llx_inventorydet.sql +++ b/htdocs/install/mysql/tables/llx_inventorydet.sql @@ -25,10 +25,10 @@ tms timestamp, fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, -batch varchar(30) DEFAULT NULL, -- Lot or serial number -qty_view double DEFAULT 0, -qty_stock double DEFAULT 0, -qty_regulated double DEFAULT 0, +batch varchar(30) DEFAULT NULL, -- Lot or serial number +qty_view double DEFAULT NULL, -- must be filled once regulation is done +qty_stock double DEFAULT NULL, -- can be filled during draft edition +qty_regulated double DEFAULT NULL, -- must be filled once regulation is done pmp double DEFAULT 0, pa double DEFAULT 0, new_pmp double DEFAULT 0 From a115d4877b9903dfb137e9ecb2d0cd2fb03db4c7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 2 May 2017 22:37:23 +0200 Subject: [PATCH 112/116] Fix for new property array fields --- htdocs/api/class/api.class.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 7aef2671c8d..9228c71ccbf 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -90,6 +90,8 @@ class DolibarrApi // Remove linkedObjects. We should already have linkedObjectIds that avoid huge responses unset($object->linkedObjects); + unset($object->fields); + unset($object->oldline); unset($object->error); From f543461e9b084de70e84ba06a5ed15c4f2943394 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 4 May 2017 11:21:28 +0200 Subject: [PATCH 113/116] Complete the substitution array with substitution array with all possible keys --- htdocs/core/class/html.formmail.class.php | 3 +++ htdocs/core/lib/functions.lib.php | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index d7ab17e60c4..6c411b60e66 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -1133,6 +1133,9 @@ class FormMail extends Form $vars['__SECUREKEYPAYPAL_MEMBER__']=''; } } + + $vars=complete_substitutions_array($vars, $langs, null, null); + return $vars; } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 857ddc6eec2..b6cf92aa81d 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -4953,7 +4953,8 @@ function make_substitutions($text, $substitutionarray, $outputlangs=null) } /** - * Complete the $substitutionarray with more entries + * Complete the $substitutionarray with more entries. + * Can also add substitution keys coming from external module that had set the "substitutions=1" into module_part array. In this case, method completesubstitutionarray provided by module is called. * * @param array $substitutionarray Array substitution old value => new value value * @param Translate $outputlangs Output language From 7ec46b3bd6ace90a7e91e51198d874f484ff1e0b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 4 May 2017 12:35:45 +0200 Subject: [PATCH 114/116] Finished work to have substitution keys code mutualized. --- htdocs/accountancy/admin/accountmodel.php | 3 +-- htdocs/admin/mails_templates.php | 22 +++++++++++++++------- htdocs/core/class/html.formmail.class.php | 18 ++++++++++++------ 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 0b4aa70e548..55c194cd416 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -757,8 +757,7 @@ if ($id) { print '* '.$langs->trans("AvailableVariables").": "; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail=new FormMail($db); - $tmp=$formmail->getAvailableSubstitKey('form'); + $tmp=FormMail::getAvailableSubstitKey('formemail'); print implode(', ', $tmp); print ''; } diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index f0bf5609adf..08ba76dca99 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -118,17 +118,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail=new FormMail($db); if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { - $tmp=$formmail->getAvailableSubstitKey('form'); + $tmp=FormMail::getAvailableSubstitKey('formemail'); $tmp['__(AnyTransKey)__']='__(AnyTransKey)__'; $helpsubstit = $langs->trans("AvailableVariables").':
    '.implode('
    ', $tmp); $helpsubstitforlines = $langs->trans("AvailableVariables").':
    '.implode('
    ', $tmp); } else { - $tmp=$formmail->getAvailableSubstitKey('formwithlines'); + $tmp=FormMail::getAvailableSubstitKey('formemailwithlines'); $tmp['__(AnyTransKey)__']='__(AnyTransKey)__'; $helpsubstit = $langs->trans("AvailableVariables").':
    '.implode('
    ', $tmp); - $tmp=$formmail->getAvailableSubstitKey('formforlines'); + $tmp=FormMail::getAvailableSubstitKey('formemailforlines'); $helpsubstitforlines = $langs->trans("AvailableVariables").':
    '.implode('
    ', $tmp); } @@ -484,7 +484,11 @@ if ($action != 'edit') { print ''; if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else if (! empty($tabhelp[$id][$value])) + { + if (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value); // Tooltip on click + else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover + } else print $valuetoshow; print ''; } @@ -539,8 +543,8 @@ if ($action != 'edit') foreach ($fieldsforcontent as $tmpfieldlist) { print ''; - if ($tmpfieldlist == 'content') print ''.$form->textwithpicto($langs->trans("Content"),$tabhelp[$id][$tmpfieldlist]).'
    '; - if ($tmpfieldlist == 'content_lines') print ''.$form->textwithpicto($langs->trans("ContentForLines"),$tabhelp[$id][$tmpfieldlist]).'
    '; + if ($tmpfieldlist == 'content') print ''.$form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
    '; + if ($tmpfieldlist == 'content_lines') print ''.$form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
    '; if ($context != 'hide') { @@ -624,7 +628,11 @@ if ($resql) // Affiche nom du champ if ($showfield) { - if (! empty($tabhelp[$id][$value])) $valuetoshow = $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + if (! empty($tabhelp[$id][$value])) + { + if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover + else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover + } print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); } } diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 6c411b60e66..6988fb4b992 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -1059,18 +1059,18 @@ class FormMail extends Form } /** - * Set substit array from object + * Get list of substition keys available. * - * @param string $mode 'form', 'formwithlines', 'formforlines' or 'emailing' + * @param string $mode 'formemail', 'formemailwithlines', 'formemailforlines', 'emailing', ... * @return void */ - function getAvailableSubstitKey($mode='form') + static function getAvailableSubstitKey($mode='formemail') { - global $conf; + global $conf, $langs; $vars=array(); - if ($mode == 'form' || $mode == 'formwithlines' || $mode == 'formforlines') + if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines') { $vars=array( '__REF__', @@ -1134,7 +1134,13 @@ class FormMail extends Form } } - $vars=complete_substitutions_array($vars, $langs, null, null); + $tmparray=array(); + $parameters=array('mode'=>$mode); + complete_substitutions_array($tmparray, $langs, null, $parameters); + foreach($tmparray as $key => $val) + { + $vars[]=$key; + } return $vars; } From 1a6c118a5dfa001a8dd5cda90402d543cd067902 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 4 May 2017 12:41:29 +0200 Subject: [PATCH 115/116] Fix travis warning --- htdocs/product/inventory/card.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index dc279cc0929..827354b864c 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -127,8 +127,6 @@ if (empty($reshook)) header('Location: '.dol_buildpath('/product/inventory/card.php?action=create', 1)); exit; } - - break; } switch($action) { From 7d5b5cf86a1da58fad3a006cdee9f2ec079d2eb9 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 4 May 2017 13:09:42 +0200 Subject: [PATCH 116/116] Better behavior for tooltip on click --- htdocs/core/class/html.form.class.php | 5 +++-- htdocs/langs/en_US/main.lang | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 3275ee0f303..cab420fe888 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -492,10 +492,11 @@ class Form */ function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='') { - global $conf; + global $conf, $langs; $alt = ''; - + if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp"); + //For backwards compatibility if ($type == '0') $type = 'info'; elseif ($type == '1') $type = 'help'; diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 1a3eea413df..c567890730a 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -766,6 +766,9 @@ Download=Download ActualizeCurrency=Update currency rate Fiscalyear=Fiscal year ModuleBuilder=Module Builder +SetMultiCurrencyCode=Set currency +BulkActions=Bulk actions +ClickToShowHelp=Click to show tooltip help # Week day Monday=Monday Tuesday=Tuesday @@ -822,6 +825,4 @@ SearchIntoInterventions=Interventions SearchIntoContracts=Contracts SearchIntoCustomerShipments=Customer shipments SearchIntoExpenseReports=Expense reports -SearchIntoLeaves=Leaves -SetMultiCurrencyCode=Set currency -BulkActions=Bulk actions \ No newline at end of file +SearchIntoLeaves=Leaves \ No newline at end of file