Fix new generic classes system

This commit is contained in:
Laurent Destailleur 2017-07-25 01:21:20 +02:00
parent 307b8ef4f6
commit aff61fad7d
6 changed files with 1391 additions and 2459 deletions

View File

@ -18,9 +18,8 @@
/**
* \file htdocs/modulebuilder/template/myobject_card.php
* \ingroup mymodule othermodule1 othermodule2
* \brief This file is an example of a php page
* Put here some comments
* \ingroup mymodule
* \brief Page to create/edit/view myobject
*/
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');

View File

@ -19,7 +19,7 @@
/**
* \file htdocs/modulebuilder/template/myobject_list.php
* \ingroup mymodule
* \brief List page for monmodule
* \brief List page for myobject
*/
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,9 @@
<?php
/* Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr>
/* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2014-2016 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
@ -16,698 +20,271 @@
*/
/**
* \file htdocs/inventory/class/product.class.php
* \ingroup product
* \brief File of class to manage predefined products stock
* \file product/inventory/class/inventory.class.php
* \ingroup inventory
* \brief This file is a CRUD class file for Inventory (Create/Read/Update/Delete)
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
// Put here all includes required by your class file
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
/**
* Class to manage inventories
* Class for Inventory
*/
class Inventory extends CoreObject
class Inventory extends CommonObject
{
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
* @var string ID to identify managed object
*/
public $fk_warehouse;
public $element = 'inventory';
/**
* Entity Id
* @var int
* @var string Name of table without prefix where object is stored
*/
public $table_element = 'inventory';
/**
* @var array Does this field is linked to a thirdparty ?
*/
protected $isnolinkedbythird = 1;
/**
* @var array Does inventory support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
*/
protected $ismultientitymanaged = 1;
/**
* @var string String with name of icon for inventory
*/
public $picto = 'inventory';
/**
* 'type' if the field format, 'label' the translation key, 'enabled' is a condition when the filed must be managed,
* 'visible' says if field is visible in list (-1 means not shown by default but can be aded into list to be viewed)
* 'notnull' if not null in database
* 'index' if we want an index in database
* 'position' is the sort order of field
* 'searchall' is 1 if we want to search in this field when making a search from the quick search button
* 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
* 'comment' is not used. You can store here any text of your choice.
*/
// BEGIN MODULEBUILDER PROPERTIES
/**
* @var array Array with all fields and their property
*/
public $fields=array(
'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
'ref' => array('type'=>'varchar(64)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Reference of object',),
'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
'fk_warehouse' => array('type'=>'integer', 'label'=>'', 'visible'=>1, 'enabled'=>1, 'index'=>1,),
'date_inventory' => array('type'=>'date', 'label'=>'', 'visible'=>1, 'enabled'=>1,),
'title' => array('type'=>'varchar(255)', 'label'=>'', 'visible'=>1, 'enabled'=>1,),
'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'index'=>1,),
'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500,),
'date_validation' => array('type'=>'datetime', 'label'=>'DateValidation', 'visible'=>-1, 'enabled'=>1, 'position'=>500,),
'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500,),
'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500,),
'fk_user_valid' => array('type'=>'integer', 'label'=>'UserValid', 'visible'=>-1, 'enabled'=>1, 'position'=>500,),
'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'index'=>1,),
);
public $rowid;
public $ref;
public $entity;
/**
* Status
* @var int
*/
public $status;
/**
* Inventory Date
* @var date
*/
public $fk_warehouse;
public $date_inventory;
/**
* Inventory Title
* @var string
*/
public $title;
public $status;
public $date_creation;
public $date_validation;
public $tms;
public $fk_user_creat;
public $fk_user_modif;
public $fk_user_valid;
public $import_key;
// END MODULEBUILDER PROPERTIES
/**
* Attribute object linked with database
* @var array
*/
protected $fields=array(
'fk_warehouse'=>array('type'=>'integer','index'=>true)
,'ref'=>array('type'=>'string','index'=>true)
,'entity'=>array('type'=>'integer','index'=>true)
,'status'=>array('type'=>'integer','index'=>true)
,'date_inventory'=>array('type'=>'date')
,'title'=>array('type'=>'string')
);
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct(DoliDB &$db)
// If this object has a subtable with lines
/**
* @var int Name of subtable line
*/
//public $table_element_line = 'inventorydet';
/**
* @var int Field with ID of parent key if this field has a parent
*/
//public $fk_element = 'fk_inventory';
/**
* @var int Name of subtable class that manage subtable lines
*/
//public $class_element_line = 'Inventoryline';
/**
* @var array Array of child tables (child tables to delete before deleting a record)
*/
//protected $childtables=array('inventorydet');
/**
* @var InventoryLine[] Array of subtable lines
*/
//public $lines = array();
/**
* Constructor
*
* @param DoliDb $db Database handler
*/
public function __construct(DoliDB $db)
{
global $conf;
parent::__construct($db);
parent::init();
$this->status = 0;
$this->entity = $conf->entity;
$this->errors = array();
$this->amount = 0;
$this->db = $db;
}
/**
* Function to sort children object
*/
public function sortDet()
/**
* Return a link to the object card (with optionaly the picto)
*
* @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
* @param string $option On what the link point to
* @param int $notooltip 1=Disable tooltip
* @param string $morecss Add more css on link
* @return string String with URL
*/
function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='')
{
if(!empty($this->Inventorydet)) usort($this->Inventorydet, array('Inventory', 'customSort'));
}
global $db, $conf, $langs;
global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager;
/**
* Get object and children from database
*
* @param int $id Id of object to load
* @param bool $loadChild used to load children from database
* @return int >0 if OK, <0 if KO, 0 if not found
*/
public function fetch($id, $loadChild = true)
{
if(!$loadChild) $this->withChild = false;
$res = parent::fetch($id, $loadChild);
if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
if ($res > 0)
{
$this->sortDet();
$this->amount = 0;
if(!empty($this->Inventorydet ))
{
foreach($this->Inventorydet as &$det)
{
$this->amount += $det->qty_view * $det->pmp;
}
}
}
return $res;
}
$result = '';
$companylink = '';
/**
* Custom function call by usort
*
* @param Inventorydet $objA first Inventorydet object
* @param Inventorydet $objB second Inventorydet object
* @return int
*/
private function customSort(&$objA, &$objB)
{
$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;
}
$label = '<u>' . $langs->trans("Inventory") . '</u>';
$label.= '<br>';
$label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
/**
* @param User $user user object
* @return int
*/
public function changePMP(User &$user)
{
$error = 0;
$this->db->begin();
$url = $url = dol_buildpath('/inventory/m_card.php',1).'?id='.$this->id;
if(!empty($this->Inventorydet))
{
foreach ($this->Inventorydet as $k => &$Inventorydet)
{
if($Inventorydet->new_pmp>0)
{
$Inventorydet->pmp = $Inventorydet->new_pmp;
$Inventorydet->new_pmp = 0;
$res = $this->db->query('UPDATE '.MAIN_DB_PREFIX.'product as p SET pmp = '.$Inventorydet->pmp.' WHERE rowid = '.$Inventorydet->fk_product );
if (!$res)
{
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->db->lasterror();
}
}
}
}
$res = parent::update($user);
if (!$res)
$linkclose='';
if (empty($notooltip))
{
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->db->lasterror();
}
if (!$error)
{
$this->db->commit();
return 1;
}
else
{
$this->db->rollback();
return -1;
}
}
/**
* Function to update object or create or delete if needed
*
* @param User $user user object
* @return < 0 if ko, > 0 if ok
*/
public function update(User &$user)
{
$error = 0;
$this->db->begin();
// if we valid the inventory we save the stock at the same time
if ($this->status)
{
$res = $this->regulate();
if ($res < 0)
if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->db->lasterror();
$label=$langs->trans("ShowInventory");
$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
}
$linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
}
else $linkclose = ($morecss?' class="'.$morecss.'"':'');
$linkstart = '<a href="'.$url.'"';
$linkstart.=$linkclose.'>';
$linkend='</a>';
if ($withpicto)
{
$result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend);
if ($withpicto != 2) $result.=' ';
}
$res = parent::update($user);
if (!$res)
{
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->db->lasterror();
}
if (!$error)
{
$this->db->commit();
return $this->id;
}
else
{
$this->db->rollback();
return -1;
}
$result.= $linkstart . $this->ref . $linkend;
return $result;
}
/**
* Function to update current object
*
* @param array $Tab Array of values
* @return int
*/
public function setValues(&$Tab)
/**
* Retourne le libelle du status d'un user (actif, inactif)
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
* @return string Label of status
*/
function getLibStatut($mode=0)
{
return $this->LibStatut($this->status,$mode);
}
/**
* Return the status
*
* @param int $status Id status
* @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto
* @return string Label of status
*/
static function LibStatut($status,$mode=0)
{
global $langs;
if (isset($Tab['qty_to_add']))
if ($mode == 0)
{
foreach ($Tab['qty_to_add'] as $k => $qty)
{
$qty = (float) price2num($qty);
if ($qty < 0)
{
$this->errors[] = $langs->trans('inventoryErrorQtyAdd');
return -1;
}
$product = new Product($this->db);
$product->fetch($this->Inventorydet[$k]->fk_product);
$this->Inventorydet[$k]->pmp = $product->pmp;
$this->Inventorydet[$k]->qty_view += $qty;
}
$prefix='';
if ($status == 1) return $langs->trans('Enabled');
if ($status == 0) return $langs->trans('Disabled');
}
if ($mode == 1)
{
if ($status == 1) return $langs->trans('Enabled');
if ($status == 0) return $langs->trans('Disabled');
}
if ($mode == 2)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
}
if ($mode == 3)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
}
if ($mode == 4)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
}
if ($mode == 5)
{
if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
}
if ($mode == 6)
{
if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
}
return parent::setValues($Tab);
}
/**
* Function to delete all Inventorydet
*
* @param User $user user object
* @return < 0 if ko, > 0 if ok
*/
public function deleteAllLine(User &$user)
{
foreach($this->Inventorydet as &$det)
{
$det->to_delete = true;
}
$res = $this->update($user);
if ($res > 0) $this->Inventorydet = array();
else return -1;
}
/**
* Function to add Inventorydet
*
* @param int $fk_product fk_product of Inventorydet
* @param int $fk_warehouse fk_warehouse target
* @return bool
*/
public function addProduct($fk_product, $fk_warehouse=0)
{
$k = $this->addChild('Inventorydet');
$det = &$this->Inventorydet[$k];
$det->fk_inventory = $this->id;
$det->fk_product = $fk_product;
$det->fk_warehouse = empty($fk_warehouse) ? $this->fk_warehouse : $fk_warehouse;
$det->load_product();
$date = $this->getDate('date_inventory', 'Y-m-d');
if(empty($date)) $date = $this->getDate('datec', 'Y-m-d');
$det->setStockDate($date, $fk_warehouse);
return true;
}
/**
* Duplication method product to add datem
* Adjust stock in a warehouse for product
*
* @param int $fk_product id of product
* @param int $fk_warehouse id of warehouse
* @param double $nbpiece nb of units
* @param int $movement 0 = add, 1 = remove
* @param string $label Label of stock movement
* @param double $price Unit price HT of product, used to calculate average weighted price (PMP in french). If 0, average weighted price is not changed.
* @param string $inventorycode Inventory code
* @return int <0 if KO, >0 if OK
*/
public function correctStock($fk_product, $fk_warehouse, $nbpiece, $movement, $label='', $price=0, $inventorycode='')
/**
* Initialise object with example values
* Id must be 0 if object instance is a specimen
*
* @return void
*/
public function initAsSpecimen()
{
global $conf, $user;
if ($fk_warehouse)
{
$this->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($this->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)
{
$this->db->commit();
return 1;
}
else
{
$this->error=$movementstock->error;
$this->errors=$movementstock->errors;
$this->db->rollback();
return -1;
}
}
$this->initAsSpecimenCommon();
}
/**
* Function to regulate stock
*
* @return int
*/
public function regulate()
{
global $langs,$conf;
if($conf->global->INVENTORY_DISABLE_VIRTUAL)
{
$pdt_virtuel = false;
// Test if virtual product is enabled
if($conf->global->PRODUIT_SOUSPRODUITS)
{
$pdt_virtuel = true;
$conf->global->PRODUIT_SOUSPRODUITS = 0;
}
}
foreach ($this->Inventorydet as $k => $Inventorydet)
{
$product = new Product($this->db);
$product->fetch($Inventorydet->fk_product);
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->id.'&action=view', 1);
$res = $this->correctStock($product->id, $Inventorydet->fk_warehouse, $nbpiece, $movement, $langs->trans('inventoryMvtStock'));
if ($res < 0) return -1;
}
}
if($conf->global->INVENTORY_DISABLE_VIRTUAL)
{
// Test if virtual product was enabled before regulate
if($pdt_virtuel) $conf->global->PRODUIT_SOUSPRODUITS = 1;
}
return 1;
}
/**
* Get the title
* @return string
*/
public function getTitle()
{
global $langs;
return !empty($this->title) ? $this->title : $langs->trans('inventoryTitle').' '.$this->id;
}
/**
* Return clicable link of object (with eventually picto)
*
* @param int $withpicto Add picto into link
* @return string
*/
public function getNomUrl($withpicto = 1)
{
return '<a href="'.DOL_URL_ROOT.'/product/inventory/card.php?id='.$this->id.'">'.($withpicto ? img_picto('','object_list.png','',0).' ' : '').$this->getTitle().'</a>';
}
/**
* Function to add products by default from warehouse and children
*
* @param int $fk_warehouse id of warehouse
* @param int $fk_category id of category
* @param int $fk_supplier id of supplier
* @param int $only_prods_in_stock only product with stock
*
* @return int
*/
public function addProductsFor($fk_warehouse,$fk_category=0,$fk_supplier=0,$only_prods_in_stock=0)
{
$warehouse = new Entrepot($this->db);
$warehouse->fetch($fk_warehouse);
$TChildWarehouses = array($fk_warehouse);
$warehouse->get_children_warehouses($fk_warehouse, $TChildWarehouses);
$sql = 'SELECT ps.fk_product, ps.fk_entrepot';
$sql.= ' FROM '.MAIN_DB_PREFIX.'product_stock ps';
$sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = ps.fk_product)';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product cp ON (cp.fk_product = p.rowid)';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid)';
$sql.= ' 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->addProduct($obj->fk_product, $obj->fk_entrepot);
}
return 1;
}
else
{
$this->error = $this->db->lasterror();
$this->errors[] = $this->db->lasterror();
return -1;
}
}
/**
* Return clicable link of inventory object
*
* @param int $id id of inventory
* @param int $withpicto Add picto into link
* @return string
*/
static function getLink($id, $withpicto=1)
{
global $langs,$db;
$inventory = new Inventory($db);
if($inventory->fetch($id, false) > 0) return $inventory->getNomUrl($withpicto);
else return $langs->trans('InventoryUnableToFetchObject');
}
/**
* Function to get the sql select of inventory
*
* @param string $type 'All' to get all data
* @return string
*/
static function getSQL($type)
{
global $conf;
$sql = '';
if($type == 'All')
{
$sql = 'SELECT i.rowid,i.title, e.label, i.date_inventory, i.fk_warehouse, i.datec, i.tms, i.status';
$sql.= ' FROM '.MAIN_DB_PREFIX.'inventory i';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot e ON (e.rowid = i.fk_warehouse)';
$sql.= ' WHERE i.entity IN ('.getEntity('inventory').')';
}
return $sql;
}
}
class Inventorydet extends CoreObject
/**
* Class InventoryObjectLine
*/
class InventoryObjectLine
{
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;
protected $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')
);
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
function __construct(DoliDB &$db)
{
global $conf;
parent::__construct($db);
parent::init();
$this->entity = $conf->entity;
$this->errors = array();
$this->product = null;
$this->current_pa = 0;
}
/**
* Get object and children from database
*
* @param int $id id of inventorydet object
* @param bool $loadChild load children
* @return int
*/
function fetch($id, $loadChild = true)
{
$res = parent::fetch($id);
$this->load_product();
$this->fetch_current_pa();
return $res;
}
/**
* Function to get the unit buy price
*
* @return bool
*/
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 to set pa attribute from date en fk_warehouse
*
* @param date $date date value
* @param int $fk_warehouse fk_warehouse target
*/
function setStockDate($date, $fk_warehouse)
{
list($pmp, $stock) = $this->getPmpStockFromDate($date, $fk_warehouse);
$this->qty_stock = $stock;
$this->pmp = $pmp;
$last_pa = 0;
$sql = 'SELECT price FROM '.MAIN_DB_PREFIX.'stock_mouvement';
$sql.= ' WHERE fk_entrepot = '.$fk_warehouse;
$sql.= ' AND fk_product = '.$this->fk_product;
$sql.= ' AND (origintype=\'order_supplier\' || origintype=\'invoice_supplier\')';
$sql.= ' AND price > 0';
$sql.= ' AND datem <= \''.$date.' 23:59:59\'';
$sql.= ' ORDER BY datem DESC LIMIT 1';
$res = $this->db->query($sql);
if($res && $obj = $this->db->fetch_object($res))
{
$last_pa = $obj->price;
}
$this->pa = $last_pa;
}
/**
* Get the last pmp and last stock from date and warehouse
*
* @param date $date date to check
* @param int $fk_warehouse id of warehouse
* @return array
*/
function getPmpStockFromDate($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;
$pmp = $this->product->pmp;
}
//All Stock mouvement between now and inventory date
$sql = 'SELECT value, price';
$sql.= ' FROM '.MAIN_DB_PREFIX.'stock_mouvement';
$sql.= ' WHERE fk_product = '.$this->product->id;
$sql.= ' AND fk_entrepot = '.$fk_warehouse;
$sql.= ' AND datem > \''.date('Y-m-d 23:59:59', strtotime($date)).'\'';
$sql.= ' ORDER BY datem DESC';
$res = $this->db->query($sql);
$laststock = $stock;
$lastpmp = $pmp;
if($res)
{
while($mouvement = $this->db->fetch_object($res))
{
$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);
}
/**
* Fetch the product linked with the line
* @return void
*/
function load_product()
{
global $db;
if($this->fk_product>0)
{
$this->product = new Product($db);
$this->product->fetch($this->fk_product);
}
}
/**
* @var int ID
*/
public $id;
/**
* @var mixed Sample line property 1
*/
public $prop1;
/**
* @var mixed Sample line property 2
*/
public $prop2;
}

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr>
/* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
@ -16,119 +17,623 @@
*/
/**
* \file htdocs/inventory/list.php
* \ingroup product
* \brief File of class to manage inventory
* \file product/inventory/list.php
* \ingroup inventory
* \brief List page for monmodule
*/
require_once '../../main.inc.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';
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';
require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php';
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1');
//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1');
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');
//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test
//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test
//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test
//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test
//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session)
$langs->load("stock");
$langs->load("inventory");
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php");
// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php");
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php");
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php");
if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php");
if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php");
if (! $res) die("Include of main fails");
require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php');
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
dol_include_once('/inventory/class/inventory.class.php');
// Load traductions files requiredby by page
$langs->loadLangs(array("inventory","other"));
$action = GETPOST('action','alpha');
$massaction = GETPOST('massaction','alpha');
$show_files = GETPOST('show_files','int');
$confirm = GETPOST('confirm','alpha');
$cancel = GETPOST('cancel', 'alpha');
$toselect = GETPOST('toselect', 'array');
$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'inventorylist'; // To manage different context of search
$id = GETPOST('id','int');
$backtopage = GETPOST('backtopage');
$optioncss = GETPOST('optioncss','alpha');
// Load variable for pagination
$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = (GETPOST("page",'int')?GETPOST("page", 'int'):0);
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortfield) $sortfield="i.title";
// Initialize technical objects
$object=new Inventory($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->inventory->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('inventorylist')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('inventory');
$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_');
// Default sort order (if not yet defined by previous GETPOST)
if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition.
if (! $sortorder) $sortorder="ASC";
if (empty($user->rights->stock->lire)) accessforbidden();
/*
* Actions
*/
// None
/*
* View
*/
llxHeader('',$langs->trans('inventoryListTitle'),'','');
echo '<form name="formListInvetory" action="'.$_SERVER['PHP_SELF'].'" method="post" >';
$inventory = new Inventory($db);
$list = new ListView($db, 'listInventory');
$THide = array('label','title');
echo $list->render(Inventory::getSQL('All'), array(
'param' => array(
'limit' => $limit,
'offset' => $offset,
'sortfield' => $sortfield,
'sortorder'=> $sortorder,
'page'=>$page
),
'limit' => array(
'nbLine' => $limit,
),
'allow-field-select' => true,
'link'=>array(
'fk_warehouse'=>'<a href="'.DOL_URL_ROOT.'/product/stock/card.php?id=@val@">'.img_picto('','object_stock.png','',0).' @label@</a>'
),
'translate'=>array(),
'hide'=>$THide,
'type'=>array(
'datec'=>'date',
'tms'=>'datetime',
'date_inventory'=>'date'
),
'list'=>array(
'title'=>$langs->trans('inventoryListTitle'),
'messageNothing'=>$langs->trans('inventoryListEmpty'),
'image' => 'title_products.png'
),
'title'=>array(
'rowid'=>$langs->trans('Title'),
'date_inventory'=>$langs->trans('InventoryDate'),
'fk_warehouse'=>$langs->trans('Warehouse'),
'datec'=>$langs->trans('DateCreation'),
'tms'=>$langs->trans('DateModification'),
'status'=>$langs->trans('Status')
),
'eval'=>array(
'status' => '(@val@ ? img_picto("'.$langs->trans("inventoryValidate").'", "statut4") : img_picto("'.$langs->trans("inventoryDraft").'", "statut3"))',
'rowid'=>'Inventory::getLink(@val@)'
),
'position' => array(
'text-align' => array('status' => 'right')
),
'search'=>array(
'rowid' => array('search_type' => true, 'table' => array('i'), 'field' => array('title')),
'date_inventory'=>array('search_type' => 'calendars', 'table' => array('i'), 'field' => array('date_inventory')),
'status'=>array('search_type' => array(1=>$langs->trans("inventoryValidate"), 0=>$langs->trans("inventoryDraft")))
)
));
/*if (!empty($user->rights->stock->create))
// Protection if external user
$socid=0;
if ($user->societe_id > 0)
{
print '<div class="tabsAction">';
print '<a class="butAction" href="inventory.php?action=create">'.$langs->trans('inventoryCreate').'</a>';
//$socid = $user->societe_id;
accessforbidden();
}
// Initialize array of search criterias
$search_all=trim(GETPOST("search_all",'alpha'));
$search=array();
foreach($object->fields as $key => $val)
{
if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha');
}
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array();
foreach($object->fields as $key => $val)
{
if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label'];
}
// Definition of fields for list
$arrayfields=array();
foreach($object->fields as $key => $val)
{
// If $val['visible']==0, then we never show the field
if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']);
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
foreach($extrafields->attribute_label as $key => $val)
{
$arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]);
}
}
/*
* ACTIONS
*
* Put here all code to do according to value of "$action" parameter
*/
if (GETPOST('cancel')) { $action='list'; $massaction=''; }
if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; }
$parameters=array();
$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
// Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria
if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers
{
foreach($object->fields as $key => $val)
{
$search[$key]='';
}
$toselect='';
$search_array_options=array();
}
if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')
|| GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha'))
{
$massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation
}
// Mass actions
$objectclass='Inventory';
$objectlabel='Inventory';
$permtoread = $user->rights->inventory->read;
$permtodelete = $user->rights->inventory->delete;
$uploaddir = $conf->inventory->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
/*
* VIEW
*
* Put here all code to build page
*/
$form=new Form($db);
$now=dol_now();
//$help_url="EN:Module_Inventory|FR:Module_Inventory_FR|ES:Módulo_Inventory";
$help_url='';
$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Inventorys"));
// Build and execute select
// --------------------------------------------------------------------
$sql = 'SELECT ';
foreach($object->fields as $key => $val)
{
$sql.='t.'.$key.', ';
}
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql=preg_replace('/, $/','', $sql);
$sql.= " FROM ".MAIN_DB_PREFIX."inventory as t";
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."inventory_extrafields as ef on (t.rowid = ef.fk_object)";
$sql.= " WHERE t.entity IN (".getEntity('inventory').")";
foreach($search as $key => $val)
{
if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:($object->fields[$key]['type'] == 'integer'?1:0)));
}
if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all);
// Add where from extra fields
foreach ($search_array_options as $key => $val)
{
$crit=$val;
$tmpkey=preg_replace('/search_options_/','',$key);
$typ=$extrafields->attribute_type[$tmpkey];
$mode=0;
if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric
if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit)))
{
$sql .= natural_search('ef.'.$tmpkey, $crit, $mode);
}
}
// Add where from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql.=$db->order($sortfield,$sortorder);
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->plimit($limit+1, $offset);
dol_syslog($script_file, LOG_DEBUG);
$resql=$db->query($sql);
if (! $resql)
{
dol_print_error($db);
exit;
}
$num = $db->num_rows($resql);
// Direct jump if only one record found
if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all)
{
$obj = $db->fetch_object($resql);
$id = $obj->rowid;
header("Location: ".DOL_URL_ROOT.'/inventory/inventory_card.php?id='.$id);
exit;
}
// Output page
// --------------------------------------------------------------------
llxHeader('', $title, $help_url);
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_myfunc()
{
jQuery("#myid").removeAttr(\'disabled\');
jQuery("#myid").attr(\'disabled\',\'disabled\');
}
init_myfunc();
jQuery("#mybutton").click(function() {
init_myfunc();
});
});
</script>';
$arrayofselected=is_array($toselect)?$toselect:array();
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
foreach($search as $key => $val)
{
$param.= '&search_'.$key.'='.urlencode($search[$key]);
}
if ($optioncss != '') $param.='&optioncss='.$optioncss;
// Add $param from extra fields
foreach ($search_array_options as $key => $val)
{
$crit=$val;
$tmpkey=preg_replace('/search_options_/','',$key);
if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val);
}
$arrayofmassactions = array(
'presend'=>$langs->trans("SendByMail"),
'builddoc'=>$langs->trans("PDFMerge"),
);
if ($user->rights->inventory->delete) $arrayofmassactions['delete']=$langs->trans("Delete");
if ($massaction == 'presend') $arrayofmassactions=array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit);
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
}
$moreforfilter = '';
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
$moreforfilter.= '</div>';
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint;
if (! empty($moreforfilter))
{
print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter;
print '</div>';
}*/
}
echo '</form>';
$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
$selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
llxFooter('');
$db->close();
print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach($object->fields as $key => $val)
{
if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
foreach($extrafields->attribute_label as $key => $val)
{
if (! empty($arrayfields["ef.".$key]['checked']))
{
$align=$extrafields->getAlignFlag($key);
$typeofextrafield=$extrafields->attribute_type[$key];
print '<td class="liste_titre'.($align?' '.$align:'').'">';
if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key]))
{
$crit=$val;
$tmpkey=preg_replace('/search_options_/','',$key);
$searchclass='';
if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring';
if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum';
print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">';
}
print '</td>';
}
}
}
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Rest of fields search
foreach($object->fields as $key => $val)
{
if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
}
// Action column
print '<td class="liste_titre" align="right">';
$searchpicto=$form->showFilterButtons();
print $searchpicto;
print '</td>';
print '</tr>'."\n";
// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach($object->fields as $key => $val)
{
if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.='nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n";
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
foreach($extrafields->attribute_label as $key => $val)
{
if (! empty($arrayfields["ef.".$key]['checked']))
{
$align=$extrafields->getAlignFlag($key);
$sortonfield = "ef.".$key;
if (! empty($extrafields->attribute_computed[$key])) $sortonfield='';
print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n";
}
}
}
// Hook fields
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Rest of fields title
foreach($object->fields as $key => $val)
{
if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n";
}
print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n";
print '</tr>'."\n";
// Detect if we need a fetch on each output line
$needToFetchEachLine=0;
foreach ($extrafields->attribute_computed as $key => $val)
{
if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object
}
// Loop on record
// --------------------------------------------------------------------
$i=0;
$totalarray=array();
while ($i < min($num, $limit))
{
$obj = $db->fetch_object($resql);
if ($obj)
{
// Store properties in $object
$object->id = $obj->rowid;
foreach($object->fields as $key => $val)
{
if (isset($obj->$key)) $object->$key = $obj->$key;
}
// Show here line of result
print '<tr class="oddeven">';
foreach($object->fields as $key => $val)
{
if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.='nowrap';
if ($key == 'status') $align.=($align?' ':'').'center';
if (! empty($arrayfields['t.'.$key]['checked']))
{
print '<td'.($align?' class="'.$align.'"':'').'>';
if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour');
elseif ($key == 'ref') print $object->getNomUrl(1);
elseif ($key == 'status') print $object->getLibStatut(3);
else print $obj->$key;
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (! empty($val['isameasure']))
{
if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key;
$totalarray['val']['t.'.$key] += $obj->$key;
}
}
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
foreach($extrafields->attribute_label as $key => $val)
{
if (! empty($arrayfields["ef.".$key]['checked']))
{
print '<td';
$align=$extrafields->getAlignFlag($key);
if ($align) print ' align="'.$align.'"';
print '>';
$tmpkey='options_'.$key;
print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1);
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (! empty($val['isameasure']))
{
if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey;
$totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey;
}
}
}
}
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
$reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Rest of fields
foreach($object->fields as $key => $val)
{
if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center';
if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap';
if ($key == 'status') $align.=($align?' ':'').'center';
if (! empty($arrayfields['t.'.$key]['checked']))
{
print '<td'.($align?' class="'.$align.'"':'').'>';
if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour');
elseif ($key == 'status') print $object->getLibStatut(3);
else print $obj->$key;
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (! empty($val['isameasure']))
{
if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key;
$totalarray['val']['t.'.$key] += $obj->$key;
}
}
}
// Action column
print '<td class="nowrap" align="center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected=0;
if (in_array($obj->rowid, $arrayofselected)) $selected=1;
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
}
print '</td>';
if (! $i) $totalarray['nbfield']++;
print '</tr>';
}
$i++;
}
// Show total line
if (isset($totalarray['pos']))
{
print '<tr class="liste_total">';
$i=0;
while ($i < $totalarray['nbfield'])
{
$i++;
if (! empty($totalarray['pos'][$i])) print '<td align="right">'.price($totalarray['val'][$totalarray['pos'][$i]]).'</td>';
else
{
if ($i == 1)
{
if ($num < $limit) print '<td align="left">'.$langs->trans("Total").'</td>';
else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td></td>';
}
}
print '</tr>';
}
// If no record found
if ($num == 0)
{
$colspan=1;
foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; }
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
}
$db->free($resql);
$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql);
$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '</table>'."\n";
print '</div>'."\n";
print '</form>'."\n";
if ($nbtotalofrecords === '' || $nbtotalofrecords)
{
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
{
require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php');
$formfile = new FormFile($db);
// Show list of available documents
$urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource.=str_replace('&amp;','&',$param);
$filedir=$diroutputmassaction;
$genallowed=$user->rights->inventory->read;
$delallowed=$user->rights->inventory->read;
print $formfile->showdocuments('massfilesarea_inventory','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'');
}
else
{
print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>';
}
}
// End of page
llxFooter();
$db->close();

File diff suppressed because it is too large Load Diff