productlot.class.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. <?php
  2. /* Copyright (C) 2007-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
  4. * Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
  5. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  6. * Copyright (C) 2018-2022 Frédéric France <frederic.france@netlogic.fr>
  7. * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file product/stock/class/productlot.class.php
  24. * \ingroup stock
  25. * \brief This is CRUD class file to manage table productlot (Create/Read/Update/Delete)
  26. */
  27. // Put here all includes required by your class file
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  29. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  30. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  31. /**
  32. * Class with list of lots and properties
  33. */
  34. class Productlot extends CommonObject
  35. {
  36. /**
  37. * @var string Id to identify managed objects
  38. */
  39. public $element = 'productlot';
  40. /**
  41. * @var string Name of table without prefix where object is stored
  42. */
  43. public $table_element = 'product_lot';
  44. /**
  45. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  46. */
  47. public $picto = 'lot';
  48. /**
  49. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  50. * @var int
  51. */
  52. public $ismultientitymanaged = 1;
  53. public $stats_propale;
  54. public $stats_commande;
  55. public $stats_contrat;
  56. public $stats_facture;
  57. public $stats_commande_fournisseur;
  58. public $stats_expedition;
  59. public $stats_reception;
  60. public $stats_mo;
  61. public $stats_bom;
  62. public $stats_mrptoconsume;
  63. public $stats_mrptoproduce;
  64. public $stats_facturerec;
  65. public $stats_facture_fournisseur;
  66. /**
  67. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  68. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  69. * 'label' the translation key.
  70. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  71. * 'position' is the sort order of field.
  72. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  73. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  74. * 'noteditable' says if field is not editable (1 or 0)
  75. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  76. * 'index' if we want an index in database.
  77. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  78. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  79. * '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).
  80. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  81. * 'help' is a string visible as a tooltip on field
  82. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  83. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  84. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  85. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  86. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  87. *
  88. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  89. */
  90. /**
  91. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  92. */
  93. public $fields = array(
  94. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
  95. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>5, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'picto' => 'product', 'css'=>'maxwidth500 widthcentpercentminusxx', 'csslist'=>'maxwidth150'),
  96. 'batch' => array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'comment'=>'Batch', 'searchall'=>1, 'picto'=>'lot'),
  97. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
  98. 'sellby' => array('type'=>'date', 'label'=>'SellByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_SELLBY)?1:0', 'visible'=>1, 'notnull'=>0, 'position'=>60),
  99. 'eatby' => array('type'=>'date', 'label'=>'EatByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_EATBY)?1:0', 'visible'=>1, 'notnull'=>0, 'position'=>62),
  100. 'eol_date' => array('type'=>'date', 'label'=>'EndOfLife', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?1:0', 'visible'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?5:0', 'position'=>70),
  101. 'manufacturing_date' => array('type'=>'date', 'label'=>'ManufacturingDate', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_TRACEABILITY")?1:0', 'visible'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_TRACEABILITY")?5:0', 'position'=>80),
  102. 'scrapping_date' => array('type'=>'date', 'label'=>'DestructionDate', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_TRACEABILITY")?1:0', 'visible'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_TRACEABILITY")?5:0', 'position'=>90),
  103. //'commissionning_date' => array('type'=>'date', 'label'=>'FirstUseDate', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_TRACEABILITY", 0)', 'visible'=>5, 'position'=>100),
  104. 'qc_frequency' => array('type'=>'integer', 'label'=>'QCFrequency', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?1:0', 'visible'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?5:0', 'position'=>110),
  105. 'lifetime' => array('type'=>'integer', 'label'=>'Lifetime', 'enabled'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?1:0', 'visible'=>'getDolGlobalInt("PRODUCT_LOT_ENABLE_QUALITY_CONTROL")?5:0', 'position'=>110),
  106. 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
  107. 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -2, 'position' => 310),
  108. 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>500),
  109. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
  110. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
  111. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
  112. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000)
  113. );
  114. /**
  115. * @var int Entity
  116. */
  117. public $entity;
  118. /**
  119. * @var int Product ID
  120. */
  121. public $fk_product;
  122. /**
  123. * @var string batch ref
  124. */
  125. public $batch;
  126. public $eatby = '';
  127. public $sellby = '';
  128. public $eol_date = '';
  129. public $manufacturing_date = '';
  130. public $scrapping_date = '';
  131. //public $commissionning_date = '';
  132. public $qc_frequency = '';
  133. public $lifetime = '';
  134. public $datec = '';
  135. public $tms = '';
  136. /**
  137. * @var int user ID
  138. */
  139. public $fk_user_creat;
  140. /**
  141. * @var int user ID
  142. */
  143. public $fk_user_modif;
  144. /**
  145. * @var string import key
  146. */
  147. public $import_key;
  148. public $stats_supplier_order=array();
  149. /**
  150. * Constructor
  151. *
  152. * @param DoliDb $db Database handler
  153. */
  154. public function __construct(DoliDB $db)
  155. {
  156. $this->db = $db;
  157. }
  158. /**
  159. * Check sell or eat by date is mandatory
  160. *
  161. * @param string $onlyFieldName [=''] check all fields by default or only one field name ("sellby", "eatby")
  162. * @return int Return integer <0 if KO, 0 nothing done, >0 if OK
  163. */
  164. public function checkSellOrEatByMandatory($onlyFieldName = '')
  165. {
  166. if (getDolGlobalString('PRODUCT_DISABLE_SELLBY') && getDolGlobalString('PRODUCT_DISABLE_EATBY')) {
  167. return 0;
  168. }
  169. $errorMsgArr = array();
  170. if ($this->fk_product > 0) {
  171. $res = $this->fetch_product();
  172. $product = $this->product;
  173. if ($res <= 0) {
  174. $errorMsgArr[] = $product->errorsToString();
  175. }
  176. if (empty($errorMsgArr)) {
  177. $errorMsgArr = self::checkSellOrEatByMandatoryFromProductAndDates($product, $this->sellby, $this->eatby, $onlyFieldName, true);
  178. }
  179. }
  180. if (!empty($errorMsgArr)) {
  181. $this->errors = array_merge($this->errors, $errorMsgArr);
  182. return -1;
  183. } else {
  184. return 1;
  185. }
  186. }
  187. /**
  188. * Check sell or eat by date is mandatory from product id and sell-by and eat-by dates
  189. *
  190. * @param int $productId Product id
  191. * @param int $sellBy Sell by date
  192. * @param int $eatBy Eat by date
  193. * @param string $onlyFieldName [=''] check all fields by default or only one field name ("sellby", "eatby")
  194. * @return array|null Array of errors or null if nothing done
  195. */
  196. public static function checkSellOrEatByMandatoryFromProductIdAndDates($productId, $sellBy, $eatBy, $onlyFieldName = '')
  197. {
  198. global $db;
  199. if (getDolGlobalString('PRODUCT_DISABLE_SELLBY') && getDolGlobalString('PRODUCT_DISABLE_EATBY')) {
  200. return null;
  201. }
  202. $errorMsgArr = array();
  203. if ($productId > 0) {
  204. $product = new Product($db);
  205. $res = $product->fetch($productId);
  206. if ($res <= 0) {
  207. $errorMsgArr[] = $product->errorsToString();
  208. }
  209. if (empty($errorMsgArr)) {
  210. $errorMsgArr = self::checkSellOrEatByMandatoryFromProductAndDates($product, $sellBy, $eatBy, $onlyFieldName, true);
  211. }
  212. }
  213. return $errorMsgArr;
  214. }
  215. /**
  216. * Check sell or eat by date is mandatory from product and sell-by and eat-by dates
  217. *
  218. * @param Product $product Product object
  219. * @param int $sellBy Sell by date
  220. * @param int $eatBy Eat by date
  221. * @param string $onlyFieldName [=''] check all fields by default or only one field name ("sellby", "eatby")
  222. * @param bool $alreadyCheckConf [=false] conf hasn't been already checked by default or true not to check conf
  223. * @return array|null Array of errors or null if nothing done
  224. */
  225. public static function checkSellOrEatByMandatoryFromProductAndDates($product, $sellBy, $eatBy, $onlyFieldName = '', $alreadyCheckConf = false)
  226. {
  227. global $langs;
  228. if ($alreadyCheckConf === false && getDolGlobalString('PRODUCT_DISABLE_SELLBY') && getDolGlobalString('PRODUCT_DISABLE_EATBY')) {
  229. return null;
  230. }
  231. $errorMsgArr = array();
  232. $checkSellByMandatory = false;
  233. $checkEatByMandatory = false;
  234. $sellOrEatByMandatoryId = $product->sell_or_eat_by_mandatory;
  235. if (!getDolGlobalString('PRODUCT_DISABLE_SELLBY') && $sellOrEatByMandatoryId == Product::SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY && ($onlyFieldName == '' || $onlyFieldName == 'sellby')) {
  236. $checkSellByMandatory = true;
  237. } elseif (!getDolGlobalString('PRODUCT_DISABLE_EATBY') && $sellOrEatByMandatoryId == Product::SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY && ($onlyFieldName == '' || $onlyFieldName == 'eatby')) {
  238. $checkEatByMandatory = true;
  239. } elseif ($sellOrEatByMandatoryId == Product::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT) {
  240. if (!getDolGlobalString('PRODUCT_DISABLE_SELLBY') && ($onlyFieldName == '' || $onlyFieldName == 'sellby')) {
  241. $checkSellByMandatory = true;
  242. }
  243. if (!getDolGlobalString('PRODUCT_DISABLE_EATBY') && ($onlyFieldName == '' || $onlyFieldName == 'eatby')) {
  244. $checkEatByMandatory = true;
  245. }
  246. }
  247. if ($checkSellByMandatory === true) {
  248. if (!isset($sellBy) || dol_strlen($sellBy) == 0) {
  249. // error : sell by is mandatory
  250. $errorMsgArr[] = $langs->trans('ErrorFieldRequired', $langs->transnoentities('SellByDate'));
  251. }
  252. }
  253. if ($checkEatByMandatory === true) {
  254. if (!isset($eatBy) || dol_strlen($eatBy) == 0) {
  255. // error : eat by is mandatory
  256. $errorMsgArr[] = $langs->trans('ErrorFieldRequired', $langs->transnoentities('EatByDate'));
  257. }
  258. }
  259. return $errorMsgArr;
  260. }
  261. /**
  262. * Create object into database
  263. *
  264. * @param User $user User that creates
  265. * @param bool $notrigger false=launch triggers after, true=disable triggers
  266. *
  267. * @return int Return integer <0 if KO, Id of created object if OK
  268. */
  269. public function create(User $user, $notrigger = false)
  270. {
  271. global $conf, $langs;
  272. dol_syslog(__METHOD__, LOG_DEBUG);
  273. $error = 0;
  274. // Clean parameters
  275. if (isset($this->entity)) {
  276. $this->entity = (int) $this->entity;
  277. }
  278. if (isset($this->fk_product)) {
  279. $this->fk_product = (int) $this->fk_product;
  280. }
  281. if (isset($this->batch)) {
  282. $this->batch = trim($this->batch);
  283. }
  284. if (isset($this->fk_user_creat)) {
  285. $this->fk_user_creat = (int) $this->fk_user_creat;
  286. }
  287. if (isset($this->fk_user_modif)) {
  288. $this->fk_user_modif = (int) $this->fk_user_modif;
  289. }
  290. if (isset($this->import_key)) {
  291. $this->import_key = trim($this->import_key);
  292. }
  293. // Check parameters
  294. if ($this->batch === '') {
  295. $this->errors[] = $langs->trans("ErrorBadValueForBatch");
  296. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  297. return -1;
  298. }
  299. // Put here code to add control on parameters values
  300. // Insert request
  301. $sql = 'INSERT INTO '.$this->db->prefix().$this->table_element.'(';
  302. $sql .= 'entity,';
  303. $sql .= 'fk_product,';
  304. $sql .= 'batch,';
  305. $sql .= 'eatby,';
  306. $sql .= 'sellby,';
  307. $sql .= 'eol_date,';
  308. $sql .= 'manufacturing_date,';
  309. $sql .= 'scrapping_date,';
  310. //$sql .= 'commissionning_date,';
  311. $sql .= 'qc_frequency,';
  312. $sql .= 'lifetime,';
  313. $sql .= 'datec,';
  314. $sql .= 'fk_user_creat,';
  315. $sql .= 'fk_user_modif,';
  316. $sql .= 'import_key';
  317. $sql .= ') VALUES (';
  318. $sql .= ' '.(!isset($this->entity) ? $conf->entity : $this->entity).',';
  319. $sql .= ' '.(!isset($this->fk_product) ? 'NULL' : $this->fk_product).',';
  320. $sql .= ' '.(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").',';
  321. $sql .= ' '.(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").',';
  322. $sql .= ' '.(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").',';
  323. $sql .= ' '.(!isset($this->eol_date) || dol_strlen($this->eol_date) == 0 ? 'NULL' : "'".$this->db->idate($this->eol_date)."'").',';
  324. $sql .= ' '.(!isset($this->manufacturing_date) || dol_strlen($this->manufacturing_date) == 0 ? 'NULL' : "'".$this->db->idate($this->manufacturing_date)."'").',';
  325. $sql .= ' '.(!isset($this->scrapping_date) || dol_strlen($this->scrapping_date) == 0 ? 'NULL' : "'".$this->db->idate($this->scrapping_date)."'").',';
  326. //$sql .= ' '.(!isset($this->commissionning_date) || dol_strlen($this->commissionning_date) == 0 ? 'NULL' : "'".$this->db->idate($this->commissionning_date)."'").',';
  327. $sql .= ' '.(empty($this->qc_frequency) ? 'NULL' : $this->qc_frequency).',';
  328. $sql .= ' '.(empty($this->lifetime) ? 'NULL' : $this->lifetime).',';
  329. $sql .= ' '."'".$this->db->idate(dol_now())."'".',';
  330. $sql .= ' '.(!isset($this->fk_user_creat) ? 'NULL' : $this->fk_user_creat).',';
  331. $sql .= ' '.(!isset($this->fk_user_modif) ? 'NULL' : $this->fk_user_modif).',';
  332. $sql .= ' '.(!isset($this->import_key) ? 'NULL' : $this->import_key);
  333. $sql .= ')';
  334. $this->db->begin();
  335. $resql = $this->db->query($sql);
  336. if (!$resql) {
  337. $error++;
  338. $this->errors[] = 'Error '.$this->db->lasterror();
  339. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  340. }
  341. if (!$error) {
  342. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  343. // Actions on extra fields
  344. if (!$error) {
  345. $result = $this->insertExtraFields();
  346. if ($result < 0) {
  347. $error++;
  348. }
  349. }
  350. if (!$error && !$notrigger) {
  351. // Call triggers
  352. $result = $this->call_trigger('PRODUCTLOT_CREATE', $user);
  353. if ($result < 0) {
  354. $error++;
  355. }
  356. // End call triggers
  357. }
  358. }
  359. // Commit or rollback
  360. if ($error) {
  361. $this->db->rollback();
  362. return -1 * $error;
  363. } else {
  364. $this->db->commit();
  365. return $this->id;
  366. }
  367. }
  368. /**
  369. * Load object in memory from the database
  370. *
  371. * @param int $id Id of lot/batch
  372. * @param int $product_id Id of product, batch number parameter required
  373. * @param string $batch batch number
  374. *
  375. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  376. */
  377. public function fetch($id = 0, $product_id = 0, $batch = '')
  378. {
  379. global $conf;
  380. dol_syslog(__METHOD__, LOG_DEBUG);
  381. $sql = "SELECT";
  382. $sql .= " t.rowid,";
  383. $sql .= " t.entity,";
  384. $sql .= " t.fk_product,";
  385. $sql .= " t.batch,";
  386. $sql .= " t.eatby,";
  387. $sql .= " t.sellby,";
  388. $sql .= " t.eol_date,";
  389. $sql .= " t.manufacturing_date,";
  390. $sql .= " t.scrapping_date,";
  391. //$sql .= " t.commissionning_date,";
  392. $sql .= " t.qc_frequency,";
  393. $sql .= " t.lifetime,";
  394. $sql .= " t.model_pdf,";
  395. $sql .= " t.last_main_doc,";
  396. $sql .= " t.datec,";
  397. $sql .= " t.tms,";
  398. $sql .= " t.fk_user_creat,";
  399. $sql .= " t.fk_user_modif,";
  400. $sql .= " t.import_key,";
  401. $sql .= " t.note_public,";
  402. $sql .= " t.note_private";
  403. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  404. if ($product_id > 0 && $batch != '') {
  405. $sql .= " WHERE t.batch = '".$this->db->escape($batch)."' AND t.fk_product = ".((int) $product_id);
  406. } else {
  407. $sql .= " WHERE t.rowid = ".((int) $id);
  408. }
  409. $resql = $this->db->query($sql);
  410. if ($resql) {
  411. $numrows = $this->db->num_rows($resql);
  412. if ($numrows) {
  413. $obj = $this->db->fetch_object($resql);
  414. $this->id = $obj->rowid;
  415. $this->ref = $obj->rowid;
  416. //$this->ref = $obj->fk_product.'_'.$obj->batch;
  417. $this->batch = $obj->batch;
  418. $this->entity = (!empty($obj->entity) ? $obj->entity : $conf->entity); // Prevent "null" entity
  419. $this->fk_product = $obj->fk_product;
  420. $this->eatby = $this->db->jdate($obj->eatby);
  421. $this->sellby = $this->db->jdate($obj->sellby);
  422. $this->eol_date = $this->db->jdate($obj->eol_date);
  423. $this->manufacturing_date = $this->db->jdate($obj->manufacturing_date);
  424. $this->scrapping_date = $this->db->jdate($obj->scrapping_date);
  425. //$this->commissionning_date = $this->db->jdate($obj->commissionning_date);
  426. $this->qc_frequency = $obj->qc_frequency;
  427. $this->lifetime = $obj->lifetime;
  428. $this->model_pdf = $obj->model_pdf;
  429. $this->last_main_doc = $obj->last_main_doc;
  430. $this->datec = $this->db->jdate($obj->datec);
  431. $this->tms = $this->db->jdate($obj->tms);
  432. $this->fk_user_creat = $obj->fk_user_creat;
  433. $this->fk_user_modif = $obj->fk_user_modif;
  434. $this->import_key = $obj->import_key;
  435. $this->note_public = $obj->note_public;
  436. $this->note_private = $obj->note_private;
  437. // Retrieve all extrafield
  438. // fetch optionals attributes and labels
  439. $this->fetch_optionals();
  440. }
  441. $this->db->free($resql);
  442. if ($numrows) {
  443. return 1;
  444. } else {
  445. return 0;
  446. }
  447. } else {
  448. $this->errors[] = 'Error '.$this->db->lasterror();
  449. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  450. return -1;
  451. }
  452. }
  453. /**
  454. * Update object into database
  455. *
  456. * @param User $user User that modifies
  457. * @param bool $notrigger false=launch triggers after, true=disable triggers
  458. *
  459. * @return int Return integer <0 if KO, >0 if OK
  460. */
  461. public function update(User $user, $notrigger = false)
  462. {
  463. $error = 0;
  464. dol_syslog(__METHOD__, LOG_DEBUG);
  465. // Clean parameters
  466. if (isset($this->entity)) {
  467. $this->entity = (int) $this->entity;
  468. }
  469. if (isset($this->fk_product)) {
  470. $this->fk_product = (int) $this->fk_product;
  471. }
  472. if (isset($this->batch)) {
  473. $this->batch = trim($this->batch);
  474. }
  475. if (isset($this->fk_user_creat)) {
  476. $this->fk_user_creat = (int) $this->fk_user_creat;
  477. }
  478. if (isset($this->fk_user_modif)) {
  479. $this->fk_user_modif = (int) $this->fk_user_modif;
  480. }
  481. if (isset($this->import_key)) {
  482. $this->import_key = trim($this->import_key);
  483. }
  484. // $this->oldcopy should have been set by the caller of update (here properties were already modified)
  485. if (empty($this->oldcopy)) {
  486. $this->oldcopy = dol_clone($this);
  487. }
  488. // Update request
  489. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET';
  490. $sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
  491. $sql .= ' fk_product = '.(isset($this->fk_product) ? $this->fk_product : "null").',';
  492. $sql .= ' batch = '.(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").',';
  493. $sql .= ' eatby = '.(!isset($this->eatby) || dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').',';
  494. $sql .= ' sellby = '.(!isset($this->sellby) || dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').',';
  495. $sql .= ' eol_date = '.(!isset($this->eol_date) || dol_strlen($this->eol_date) != 0 ? "'".$this->db->idate($this->eol_date)."'" : 'null').',';
  496. $sql .= ' manufacturing_date = '.(!isset($this->manufacturing_date) || dol_strlen($this->manufacturing_date) != 0 ? "'".$this->db->idate($this->manufacturing_date)."'" : 'null').',';
  497. $sql .= ' scrapping_date = '.(!isset($this->scrapping_date) || dol_strlen($this->scrapping_date) != 0 ? "'".$this->db->idate($this->scrapping_date)."'" : 'null').',';
  498. //$sql .= ' commissionning_date = '.(!isset($this->first_use_date) || dol_strlen($this->first_use_date) != 0 ? "'".$this->db->idate($this->first_use_date)."'" : 'null').',';
  499. $sql .= ' qc_frequency = '.(!empty($this->qc_frequency) ? (int) $this->qc_frequency : 'null').',';
  500. $sql .= ' lifetime = '.(!empty($this->lifetime) ? (int) $this->lifetime : 'null').',';
  501. $sql .= ' datec = '.(!isset($this->datec) || dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').',';
  502. $sql .= ' tms = '.(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : "'".$this->db->idate(dol_now())."'").',';
  503. $sql .= ' fk_user_creat = '.(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").',';
  504. $sql .= ' fk_user_modif = '.(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").',';
  505. $sql .= ' import_key = '.(isset($this->import_key) ? $this->import_key : "null");
  506. $sql .= ' WHERE rowid='.((int) $this->id);
  507. $this->db->begin();
  508. $resql = $this->db->query($sql);
  509. if (!$resql) {
  510. $error++;
  511. $this->errors[] = 'Error '.$this->db->lasterror();
  512. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  513. }
  514. // Actions on extra fields
  515. if (!$error) {
  516. $result = $this->insertExtraFields();
  517. if ($result < 0) {
  518. $error++;
  519. }
  520. }
  521. if (!$error && !$notrigger) {
  522. // Call triggers
  523. $result = $this->call_trigger('PRODUCTLOT_MODIFY', $user);
  524. if ($result < 0) {
  525. $error++;
  526. }
  527. // End call triggers
  528. }
  529. // Commit or rollback
  530. if ($error) {
  531. $this->db->rollback();
  532. return -1 * $error;
  533. } else {
  534. $this->db->commit();
  535. return 1;
  536. }
  537. }
  538. /**
  539. * Delete object in database
  540. *
  541. * @param User $user User that deletes
  542. * @param bool $notrigger false=launch triggers after, true=disable triggers
  543. *
  544. * @return int Return integer <0 if KO, >0 if OK
  545. */
  546. public function delete(User $user, $notrigger = false)
  547. {
  548. dol_syslog(__METHOD__, LOG_DEBUG);
  549. $error = 0;
  550. $this->db->begin();
  551. // Check there is no stock for this lot
  552. $sql = "SELECT pb.rowid FROM ".$this->db->prefix()."product_batch as pb, ".$this->db->prefix()."product_stock as ps";
  553. $sql .= " WHERE pb.fk_product_stock = ps.rowid AND pb.batch = '".$this->db->escape($this->batch)."'";
  554. $sql .= " AND ps.fk_product = ".((int) $this->fk_product);
  555. $sql .= $this->db->plimit(1);
  556. $resql = $this->db->query($sql);
  557. if ($resql) {
  558. $obj = $this->db->fetch_object($resql);
  559. if ($obj) {
  560. $error++;
  561. $this->errors[] = 'Error Lot is used in stock (ID = '.$obj->rowid.'). Deletion not possible.';
  562. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  563. }
  564. } else {
  565. $error++;
  566. $this->errors[] = 'Error '.$this->db->lasterror();
  567. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  568. }
  569. // Check there is no movement for this lot
  570. $sql = "SELECT sm.rowid FROM ".$this->db->prefix()."stock_mouvement as sm";
  571. $sql .= " WHERE sm.batch = '".$this->db->escape($this->batch)."'";
  572. $sql .= " AND sm.fk_product = ".((int) $this->fk_product);
  573. $sql .= $this->db->plimit(1);
  574. $resql = $this->db->query($sql);
  575. if ($resql) {
  576. $obj = $this->db->fetch_object($resql);
  577. if ($obj) {
  578. $error++;
  579. $this->errors[] = 'Error Lot was used in a stock movement (ID '.$obj->rowid.'). Deletion not possible.';
  580. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  581. }
  582. } else {
  583. $error++;
  584. $this->errors[] = 'Error '.$this->db->lasterror();
  585. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  586. }
  587. // TODO
  588. //if (!$error) {
  589. //if (!$notrigger) {
  590. // Uncomment this and change PRODUCTLOT to your own tag if you
  591. // want this action calls a trigger.
  592. //// Call triggers
  593. //$result=$this->call_trigger('PRODUCTLOT_DELETE',$user);
  594. //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
  595. //// End call triggers
  596. //}
  597. //}
  598. if (!$error) {
  599. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element;
  600. $sql .= ' WHERE rowid='.((int) $this->id);
  601. $resql = $this->db->query($sql);
  602. if (!$resql) {
  603. $error++;
  604. $this->errors[] = 'Error '.$this->db->lasterror();
  605. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  606. }
  607. }
  608. // Commit or rollback
  609. if ($error) {
  610. $this->db->rollback();
  611. return -1 * $error;
  612. } else {
  613. $this->db->commit();
  614. return 1;
  615. }
  616. }
  617. /**
  618. * Load an object from its id and create a new one in database
  619. *
  620. * @param User $user User making the clone
  621. * @param int $fromid Id of object to clone
  622. * @return int New id of clone
  623. */
  624. public function createFromClone(User $user, $fromid)
  625. {
  626. dol_syslog(__METHOD__, LOG_DEBUG);
  627. $error = 0;
  628. $object = new Productlot($this->db);
  629. $this->db->begin();
  630. // Load source object
  631. $object->fetch($fromid);
  632. // Reset object
  633. $object->id = 0;
  634. // Clear fields
  635. // ...
  636. // Create clone
  637. $object->context['createfromclone'] = 'createfromclone';
  638. $result = $object->create($user);
  639. // Other options
  640. if ($result < 0) {
  641. $error++;
  642. $this->errors = $object->errors;
  643. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  644. }
  645. unset($object->context['createfromclone']);
  646. // End
  647. if (!$error) {
  648. $this->db->commit();
  649. return $object->id;
  650. } else {
  651. $this->db->rollback();
  652. return -1;
  653. }
  654. }
  655. /**
  656. * Charge tableau des stats expedition pour le lot/numéro de série
  657. *
  658. * @param int $socid Id societe
  659. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  660. */
  661. public function loadStatsExpedition($socid = 0)
  662. {
  663. // phpcs:enable
  664. global $db, $conf, $user, $hookmanager, $action;
  665. $sql = "SELECT COUNT(DISTINCT exp.fk_soc) as nb_customers, COUNT(DISTINCT exp.rowid) as nb,";
  666. $sql .= " COUNT(ed.rowid) as nb_rows, SUM(edb.qty) as qty";
  667. $sql .= " FROM ".$this->db->prefix()."expeditiondet_batch as edb";
  668. $sql .= " INNER JOIN ".$this->db->prefix()."expeditiondet as ed ON (ed.rowid = edb.fk_expeditiondet)";
  669. $sql .= " INNER JOIN ".$this->db->prefix()."expedition as exp ON (exp.rowid = ed.fk_expedition)";
  670. // $sql .= ", ".$this->db->prefix()."societe as s";
  671. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  672. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  673. }
  674. $sql .= " WHERE exp.entity IN (".getEntity('expedition').")";
  675. $sql .= " AND edb.batch = '".($this->db->escape($this->batch))."'";
  676. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  677. $sql .= " AND exp.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  678. }
  679. //$sql.= " AND exp.fk_statut != 0";
  680. if ($socid > 0) {
  681. $sql .= " AND exp.fk_soc = ".((int) $socid);
  682. }
  683. $result = $this->db->query($sql);
  684. if ($result) {
  685. $obj = $this->db->fetch_object($result);
  686. $this->stats_expedition['customers'] = $obj->nb_customers;
  687. $this->stats_expedition['nb'] = $obj->nb;
  688. $this->stats_expedition['rows'] = $obj->nb_rows;
  689. $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
  690. // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
  691. // if it's a virtual product, maybe it is in invoice by extension
  692. // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  693. // $TFather = $this->getFather();
  694. // if (is_array($TFather) && !empty($TFather)) {
  695. // foreach ($TFather as &$fatherData) {
  696. // $pFather = new Product($this->db);
  697. // $pFather->id = $fatherData['id'];
  698. // $qtyCoef = $fatherData['qty'];
  699. //
  700. // if ($fatherData['incdec']) {
  701. // $pFather->loadStatsExpedition($socid);
  702. //
  703. // $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
  704. // $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
  705. // $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
  706. // $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
  707. // }
  708. // }
  709. // }
  710. // }
  711. $parameters = array('socid' => $socid);
  712. $reshook = $hookmanager->executeHooks('loadStatsLotExpedition', $parameters, $this, $action);
  713. if ($reshook > 0) {
  714. $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
  715. }
  716. return 1;
  717. } else {
  718. $this->error = $this->db->error();
  719. return -1;
  720. }
  721. }
  722. /**
  723. * Charge tableau des stats commande fournisseur pour le lot/numéro de série
  724. *
  725. * @param int $socid Id societe
  726. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  727. */
  728. public function loadStatsSupplierOrder($socid = 0)
  729. {
  730. // phpcs:enable
  731. global $db, $conf, $user, $hookmanager, $action;
  732. $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_customers, COUNT(DISTINCT cf.rowid) as nb,";
  733. $sql .= " COUNT(cfd.rowid) as nb_rows, SUM(cfdi.qty) as qty";
  734. $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as cfdi";
  735. $sql .= " INNER JOIN ".$this->db->prefix()."commande_fournisseurdet as cfd ON (cfd.rowid = cfdi.fk_commandefourndet)";
  736. $sql .= " INNER JOIN ".$this->db->prefix()."commande_fournisseur as cf ON (cf.rowid = cfd.fk_commande)";
  737. // $sql .= ", ".$this->db->prefix()."societe as s";
  738. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  739. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  740. }
  741. $sql .= " WHERE cf.entity IN (".getEntity('expedition').")";
  742. $sql .= " AND cfdi.batch = '".($this->db->escape($this->batch))."'";
  743. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  744. $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  745. }
  746. //$sql.= " AND cf.fk_statut != 0";
  747. if ($socid > 0) {
  748. $sql .= " AND cf.fk_soc = ".((int) $socid);
  749. }
  750. $result = $this->db->query($sql);
  751. if ($result) {
  752. $obj = $this->db->fetch_object($result);
  753. $this->stats_supplier_order['customers'] = $obj->nb_customers;
  754. $this->stats_supplier_order['nb'] = $obj->nb;
  755. $this->stats_supplier_order['rows'] = $obj->nb_rows;
  756. $this->stats_supplier_order['qty'] = $obj->qty ? $obj->qty : 0;
  757. // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
  758. // if it's a virtual product, maybe it is in invoice by extension
  759. // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  760. // $TFather = $this->getFather();
  761. // if (is_array($TFather) && !empty($TFather)) {
  762. // foreach ($TFather as &$fatherData) {
  763. // $pFather = new Product($this->db);
  764. // $pFather->id = $fatherData['id'];
  765. // $qtyCoef = $fatherData['qty'];
  766. //
  767. // if ($fatherData['incdec']) {
  768. // $pFather->stats_supplier_order($socid);
  769. //
  770. // $this->stats_supplier_order['customers'] += $pFather->stats_supplier_order['customers'];
  771. // $this->stats_supplier_order['nb'] += $pFather->stats_supplier_order['nb'];
  772. // $this->stats_supplier_order['rows'] += $pFather->stats_supplier_order['rows'];
  773. // $this->stats_supplier_order['qty'] += $pFather->stats_supplier_order['qty'] * $qtyCoef;
  774. // }
  775. // }
  776. // }
  777. // }
  778. $parameters = array('socid' => $socid);
  779. $reshook = $hookmanager->executeHooks('loadStatsLotSupplierOrder', $parameters, $this, $action);
  780. if ($reshook > 0) {
  781. $this->stats_supplier_order = $hookmanager->resArray['stats_supplier_order'];
  782. }
  783. return 1;
  784. } else {
  785. $this->error = $this->db->error();
  786. return -1;
  787. }
  788. }
  789. /**
  790. * Charge tableau des stats expedition pour le lot/numéro de série
  791. *
  792. * @param int $socid Id societe
  793. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  794. */
  795. public function loadStatsReception($socid = 0)
  796. {
  797. // phpcs:enable
  798. global $db, $conf, $user, $hookmanager, $action;
  799. $sql = "SELECT COUNT(DISTINCT recep.fk_soc) as nb_customers, COUNT(DISTINCT recep.rowid) as nb,";
  800. $sql .= " COUNT(cfdi.rowid) as nb_rows, SUM(cfdi.qty) as qty";
  801. $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as cfdi";
  802. $sql .= " INNER JOIN ".$this->db->prefix()."reception as recep ON (recep.rowid = cfdi.fk_reception)";
  803. // $sql .= ", ".$this->db->prefix()."societe as s";
  804. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  805. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  806. }
  807. $sql .= " WHERE recep.entity IN (".getEntity('reception').")";
  808. $sql .= " AND cfdi.batch = '".($this->db->escape($this->batch))."'";
  809. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  810. $sql .= " AND recep.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  811. }
  812. //$sql.= " AND exp.fk_statut != 0";
  813. if ($socid > 0) {
  814. $sql .= " AND recep.fk_soc = ".((int) $socid);
  815. }
  816. $result = $this->db->query($sql);
  817. if ($result) {
  818. $obj = $this->db->fetch_object($result);
  819. $this->stats_reception['customers'] = $obj->nb_customers;
  820. $this->stats_reception['nb'] = $obj->nb;
  821. $this->stats_reception['rows'] = $obj->nb_rows;
  822. $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
  823. // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
  824. // if it's a virtual product, maybe it is in invoice by extension
  825. // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  826. // $TFather = $this->getFather();
  827. // if (is_array($TFather) && !empty($TFather)) {
  828. // foreach ($TFather as &$fatherData) {
  829. // $pFather = new Product($this->db);
  830. // $pFather->id = $fatherData['id'];
  831. // $qtyCoef = $fatherData['qty'];
  832. //
  833. // if ($fatherData['incdec']) {
  834. // $pFather->loadStatsReception($socid);
  835. //
  836. // $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
  837. // $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
  838. // $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
  839. // $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
  840. // }
  841. // }
  842. // }
  843. // }
  844. $parameters = array('socid' => $socid);
  845. $reshook = $hookmanager->executeHooks('loadStatsLotReception', $parameters, $this, $action);
  846. if ($reshook > 0) {
  847. $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
  848. }
  849. return 1;
  850. } else {
  851. $this->error = $this->db->error();
  852. return -1;
  853. }
  854. }
  855. /**
  856. * Charge tableau des stats expedition pour le lot/numéro de série
  857. *
  858. * @param int $socid Id societe
  859. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  860. */
  861. public function loadStatsMo($socid = 0)
  862. {
  863. // phpcs:enable
  864. global $user, $hookmanager, $action;
  865. $error = 0;
  866. foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
  867. $this->stats_mo['customers_'.$role] = 0;
  868. $this->stats_mo['nb_'.$role] = 0;
  869. $this->stats_mo['qty_'.$role] = 0;
  870. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  871. $sql .= " SUM(mp.qty) as qty";
  872. $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
  873. $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
  874. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  875. $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
  876. }
  877. $sql .= " WHERE ";
  878. $sql .= " c.entity IN (".getEntity('mo').")";
  879. $sql .= " AND mp.batch = '".($this->db->escape($this->batch))."'";
  880. $sql .= " AND mp.role ='".$this->db->escape($role)."'";
  881. if ($socid > 0) {
  882. $sql .= " AND c.fk_soc = ".((int) $socid);
  883. }
  884. $result = $this->db->query($sql);
  885. if ($result) {
  886. $obj = $this->db->fetch_object($result);
  887. $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
  888. $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
  889. $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
  890. } else {
  891. $this->error = $this->db->error();
  892. $error++;
  893. }
  894. }
  895. if (!empty($error)) {
  896. return -1;
  897. }
  898. $parameters = array('socid' => $socid);
  899. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  900. if ($reshook > 0) {
  901. $this->stats_mo = $hookmanager->resArray['stats_mo'];
  902. }
  903. return 1;
  904. }
  905. /**
  906. * Return label of status of object
  907. *
  908. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  909. * @return string Label of status
  910. */
  911. public function getLibStatut($mode = 0)
  912. {
  913. return $this->LibStatut(0, $mode);
  914. }
  915. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  916. /**
  917. * Return label of a given status
  918. *
  919. * @param int $status Status
  920. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  921. * @return string Label of status
  922. */
  923. public function LibStatut($status, $mode = 0)
  924. {
  925. // phpcs:enable
  926. global $langs;
  927. //$langs->load('stocks');
  928. return '';
  929. }
  930. /**
  931. * getTooltipContentArray
  932. *
  933. * @param array $params Params to construct tooltip data
  934. * @since v18
  935. * @return array
  936. */
  937. public function getTooltipContentArray($params)
  938. {
  939. global $conf, $langs, $user;
  940. $langs->loadLangs(['stocks', 'productbatch']);
  941. $option = $params['option'] ?? '';
  942. $datas = [];
  943. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Batch").'</u>';
  944. //$datas['divopen'] = '<div width="100%">';
  945. $datas['batch'] = '<br><b>'.$langs->trans('Batch').':</b> '.$this->batch;
  946. if ($this->eatby && !getDolGlobalString('PRODUCT_DISABLE_EATBY')) {
  947. $datas['eatby'] = '<br><b>'.$langs->trans('EatByDate').':</b> '.dol_print_date($this->db->jdate($this->eatby), 'day');
  948. }
  949. if ($this->sellby && !getDolGlobalString('PRODUCT_DISABLE_SELLBY')) {
  950. $datas['sellby'] = '<br><b>'.$langs->trans('SellByDate').':</b> '.dol_print_date($this->db->jdate($this->sellby), 'day');
  951. }
  952. //$datas['divclose'] = '</div>';
  953. return $datas;
  954. }
  955. /**
  956. * Return a link to the a lot card (with optionaly the picto)
  957. * Use this->id,this->lastname, this->firstname
  958. *
  959. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  960. * @param string $option On what the link point to
  961. * @param integer $notooltip 1=Disable tooltip
  962. * @param int $maxlen Max length of visible user name
  963. * @param string $morecss Add more css on link
  964. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  965. * @return string String with URL
  966. */
  967. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '', $save_lastsearch_value = -1)
  968. {
  969. global $langs, $conf, $hookmanager;
  970. $result = '';
  971. $params = [
  972. 'id' => $this->id,
  973. 'objecttype' => $this->element,
  974. 'option' => $option,
  975. ];
  976. $classfortooltip = 'classfortooltip';
  977. $dataparams = '';
  978. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  979. $classfortooltip = 'classforajaxtooltip';
  980. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  981. $label = '';
  982. } else {
  983. $label = implode($this->getTooltipContentArray($params));
  984. }
  985. $url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id;
  986. if ($option != 'nolink') {
  987. // Add param to save lastsearch_values or not
  988. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  989. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  990. $add_save_lastsearch_values = 1;
  991. }
  992. if ($add_save_lastsearch_values) {
  993. $url .= '&save_lastsearch_values=1';
  994. }
  995. }
  996. $linkclose = '';
  997. if (empty($notooltip)) {
  998. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  999. $label = $langs->trans("ShowMyObject");
  1000. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1001. }
  1002. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1003. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  1004. } else {
  1005. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1006. }
  1007. if ($option == 'nolink') {
  1008. $linkstart = '<span';
  1009. } else {
  1010. $linkstart = '<a href="'.$url.'"';
  1011. }
  1012. $linkstart .= $linkclose.'>';
  1013. if ($option == 'nolink') {
  1014. $linkend = '</span>';
  1015. } else {
  1016. $linkend = '</a>';
  1017. }
  1018. $result .= $linkstart;
  1019. if ($withpicto) {
  1020. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  1021. }
  1022. if ($withpicto != 2) {
  1023. $result .= $this->batch;
  1024. }
  1025. $result .= $linkend;
  1026. global $action;
  1027. $hookmanager->initHooks(array('productlotdao'));
  1028. $parameters = array('id' => $this->id, 'getnomurl' => $result);
  1029. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1030. if ($reshook > 0) {
  1031. $result = $hookmanager->resPrint;
  1032. } else {
  1033. $result .= $hookmanager->resPrint;
  1034. }
  1035. return $result;
  1036. }
  1037. /**
  1038. * Initialise object with example values
  1039. * Id must be 0 if object instance is a specimen
  1040. *
  1041. * @return void
  1042. */
  1043. public function initAsSpecimen()
  1044. {
  1045. global $conf;
  1046. // Initialise parametres
  1047. $this->id = 0;
  1048. $this->ref = 'SPECIMEN';
  1049. $this->specimen = 1;
  1050. $this->entity = $conf->entity;
  1051. $this->fk_product = null;
  1052. $this->batch = '';
  1053. $this->eatby = '';
  1054. $this->sellby = '';
  1055. $this->datec = '';
  1056. $this->tms = '';
  1057. $this->fk_user_creat = null;
  1058. $this->fk_user_modif = null;
  1059. $this->import_key = '';
  1060. }
  1061. /**
  1062. * Create a document onto disk according to template module.
  1063. *
  1064. * @param string $modele Force model to use ('' to not force)
  1065. * @param Translate $outputlangs Object langs to use for output
  1066. * @param int $hidedetails Hide details of lines
  1067. * @param int $hidedesc Hide description
  1068. * @param int $hideref Hide ref
  1069. * @return int 0 if KO, 1 if OK
  1070. */
  1071. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1072. {
  1073. global $conf, $user, $langs;
  1074. $langs->loadLangs(array('stocks', 'productbatch', "products"));
  1075. $outputlangs->loadLangs(array('stocks', 'productbatch', "products"));
  1076. // Positionne le modele sur le nom du modele a utiliser
  1077. if (!dol_strlen($modele)) {
  1078. $modele = '';
  1079. if (!empty($this->model_pdf)) {
  1080. $modele = $this->model_pdf;
  1081. } elseif (getDolGlobalString('PRODUCT_BATCH_ADDON_PDF')) {
  1082. $modele = $conf->global->PRODUCT_BATCH_ADDON_PDF;
  1083. }
  1084. }
  1085. $modelpath = "core/modules/product_batch/doc/";
  1086. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1087. }
  1088. }