dolibarr  19.0.0-dev
productlot.class.php
Go to the documentation of this file.
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 
29 // Put here all includes required by your class file
30 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
32 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
33 
37 class Productlot extends CommonObject
38 {
42  public $element = 'productlot';
43 
47  public $table_element = 'product_lot';
48 
52  public $picto = 'lot';
53 
58  public $ismultientitymanaged = 1;
59 
60  public $stats_propale;
61  public $stats_commande;
62  public $stats_contrat;
63  public $stats_facture;
64  public $stats_commande_fournisseur;
65  public $stats_expedition;
66  public $stats_reception;
67  public $stats_mo;
68  public $stats_bom;
69  public $stats_mrptoconsume;
70  public $stats_mrptoproduce;
71  public $stats_facturerec;
72  public $stats_facture_fournisseur;
73 
74 
103  public $fields = array(
104  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
105  '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'),
106  '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'),
107  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
108  'sellby' => array('type'=>'date', 'label'=>'SellByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_SELLBY)?1:0', 'visible'=>5, 'position'=>60),
109  'eol_date' => array('type'=>'date', 'label'=>'EndOfLife', 'enabled'=>'empty($conf->global->PRODUCT_ENABLE_TRACEABILITY)?0:1', 'visible'=>5, 'position'=>70),
110  'manufacturing_date' => array('type'=>'date', 'label'=>'ManufacturingDate', 'enabled'=>1, 'visible'=>1, 'position'=>80),
111  'scrapping_date' => array('type'=>'date', 'label'=>'DestructionDate', 'enabled'=>'getDolGlobalInt("PRODUCT_ENABLE_TRACEABILITY", 0)', 'visible'=>5, 'position'=>90),
112  //'commissionning_date' => array('type'=>'date', 'label'=>'FirstUseDate', 'enabled'=>'getDolGlobalInt("PRODUCT_ENABLE_TRACEABILITY", 0)', 'visible'=>5, 'position'=>100),
113  //'qc_frequency' => array('type'=>'varchar(6)', 'label'=>'QCFrequency', 'enabled'=>'empty($conf->global->PRODUCT_ENABLE_QUALITYCONTROL)?1:0', 'visible'=>5, 'position'=>110),
114  'eatby' => array('type'=>'date', 'label'=>'EatByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_EATBY)?1:0', 'visible'=>5, 'position'=>62),
115  'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
116  'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -2, 'position' => 310),
117  'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>500),
118  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
119  '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'),
120  'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
121  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000)
122  );
123 
127  public $entity;
128 
132  public $fk_product;
133 
137  public $batch;
138  public $eatby = '';
139  public $sellby = '';
140  public $eol_date = '';
141  public $manufacturing_date = '';
142  public $scrapping_date = '';
143  //public $commissionning_date = '';
144  //public $qc_frequency = '';
145  public $datec = '';
146  public $tms = '';
147 
151  public $fk_user_creat;
152 
156  public $fk_user_modif;
157 
161  public $import_key;
162 
163 
169  public function __construct(DoliDB $db)
170  {
171  $this->db = $db;
172  }
173 
182  public function create(User $user, $notrigger = false)
183  {
184  global $conf, $langs;
185 
186  dol_syslog(__METHOD__, LOG_DEBUG);
187 
188  $error = 0;
189 
190  // Clean parameters
191 
192  if (isset($this->entity)) {
193  $this->entity = (int) $this->entity;
194  }
195  if (isset($this->fk_product)) {
196  $this->fk_product = (int) $this->fk_product;
197  }
198  if (isset($this->batch)) {
199  $this->batch = trim($this->batch);
200  }
201  if (isset($this->fk_user_creat)) {
202  $this->fk_user_creat = (int) $this->fk_user_creat;
203  }
204  if (isset($this->fk_user_modif)) {
205  $this->fk_user_modif = (int) $this->fk_user_modif;
206  }
207  if (isset($this->import_key)) {
208  $this->import_key = trim($this->import_key);
209  }
210 
211  // Check parameters
212  if ($this->batch === '') {
213  $this->errors[] = $langs->trans("ErrorBadValueForBatch");
214  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
215  return -1;
216  }
217  // Put here code to add control on parameters values
218 
219  // Insert request
220  $sql = 'INSERT INTO '.$this->db->prefix().$this->table_element.'(';
221  $sql .= 'entity,';
222  $sql .= 'fk_product,';
223  $sql .= 'batch,';
224  $sql .= 'eatby,';
225  $sql .= 'sellby,';
226  $sql .= 'eol_date,';
227  $sql .= 'manufacturing_date,';
228  $sql .= 'scrapping_date,';
229  //$sql .= 'commissionning_date,';
230  //$sql .= 'qc_frequency,';
231  $sql .= 'datec,';
232  $sql .= 'fk_user_creat,';
233  $sql .= 'fk_user_modif,';
234  $sql .= 'import_key';
235  $sql .= ') VALUES (';
236  $sql .= ' '.(!isset($this->entity) ? $conf->entity : $this->entity).',';
237  $sql .= ' '.(!isset($this->fk_product) ? 'NULL' : $this->fk_product).',';
238  $sql .= ' '.(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").',';
239  $sql .= ' '.(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").',';
240  $sql .= ' '.(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").',';
241  $sql .= ' '.(!isset($this->eol_date) || dol_strlen($this->eol_date) == 0 ? 'NULL' : "'".$this->db->idate($this->eol_date)."'").',';
242  $sql .= ' '.(!isset($this->manufacturing_date) || dol_strlen($this->manufacturing_date) == 0 ? 'NULL' : "'".$this->db->idate($this->manufacturing_date)."'").',';
243  $sql .= ' '.(!isset($this->scrapping_date) || dol_strlen($this->scrapping_date) == 0 ? 'NULL' : "'".$this->db->idate($this->scrapping_date)."'").',';
244  //$sql .= ' '.(!isset($this->commissionning_date) || dol_strlen($this->commissionning_date) == 0 ? 'NULL' : "'".$this->db->idate($this->commissionning_date)."'").',';
245  //$sql .= ' '.(!isset($this->qc_frequency) ? 'NULL' : $this->qc_frequency).',';
246  $sql .= ' '."'".$this->db->idate(dol_now())."'".',';
247  $sql .= ' '.(!isset($this->fk_user_creat) ? 'NULL' : $this->fk_user_creat).',';
248  $sql .= ' '.(!isset($this->fk_user_modif) ? 'NULL' : $this->fk_user_modif).',';
249  $sql .= ' '.(!isset($this->import_key) ? 'NULL' : $this->import_key);
250  $sql .= ')';
251 
252  $this->db->begin();
253 
254  $resql = $this->db->query($sql);
255  if (!$resql) {
256  $error++;
257  $this->errors[] = 'Error '.$this->db->lasterror();
258  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
259  }
260 
261  if (!$error) {
262  $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
263 
264  // Actions on extra fields
265  if (!$error) {
266  $result = $this->insertExtraFields();
267  if ($result < 0) {
268  $error++;
269  }
270  }
271 
272  if (!$error && !$notrigger) {
273  // Call triggers
274  $result = $this->call_trigger('PRODUCTLOT_CREATE', $user);
275  if ($result < 0) {
276  $error++;
277  }
278  // End call triggers
279  }
280  }
281 
282  // Commit or rollback
283  if ($error) {
284  $this->db->rollback();
285 
286  return -1 * $error;
287  } else {
288  $this->db->commit();
289 
290  return $this->id;
291  }
292  }
293 
303  public function fetch($id = 0, $product_id = 0, $batch = '')
304  {
305  global $conf;
306  dol_syslog(__METHOD__, LOG_DEBUG);
307 
308  $sql = "SELECT";
309  $sql .= " t.rowid,";
310  $sql .= " t.entity,";
311  $sql .= " t.fk_product,";
312  $sql .= " t.batch,";
313  $sql .= " t.eatby,";
314  $sql .= " t.sellby,";
315  $sql .= " t.eol_date,";
316  $sql .= " t.manufacturing_date,";
317  $sql .= " t.scrapping_date,";
318  //$sql .= " t.commissionning_date,";
319  //$sql .= " t.qc_frequency,";
320  $sql .= " t.model_pdf,";
321  $sql .= " t.last_main_doc,";
322  $sql .= " t.datec,";
323  $sql .= " t.tms,";
324  $sql .= " t.fk_user_creat,";
325  $sql .= " t.fk_user_modif,";
326  $sql .= " t.import_key,";
327  $sql .= " t.note_public,";
328  $sql .= " t.note_private";
329  $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
330  if ($product_id > 0 && $batch != '') {
331  $sql .= " WHERE t.batch = '".$this->db->escape($batch)."' AND t.fk_product = ".((int) $product_id);
332  } else {
333  $sql .= " WHERE t.rowid = ".((int) $id);
334  }
335 
336  $resql = $this->db->query($sql);
337  if ($resql) {
338  $numrows = $this->db->num_rows($resql);
339  if ($numrows) {
340  $obj = $this->db->fetch_object($resql);
341 
342  $this->id = $obj->rowid;
343  $this->ref = $obj->rowid;
344  //$this->ref = $obj->fk_product.'_'.$obj->batch;
345 
346  $this->batch = $obj->batch;
347  $this->entity = (!empty($obj->entity) ? $obj->entity : $conf->entity); // Prevent "null" entity
348  $this->fk_product = $obj->fk_product;
349  $this->eatby = $this->db->jdate($obj->eatby);
350  $this->sellby = $this->db->jdate($obj->sellby);
351  $this->eol_date = $this->db->jdate($obj->eol_date);
352  $this->manufacturing_date = $this->db->jdate($obj->manufacturing_date);
353  $this->scrapping_date = $this->db->jdate($obj->scrapping_date);
354  //$this->commissionning_date = $this->db->jdate($obj->commissionning_date);
355  //$this->qc_frequency = $obj->qc_frequency;
356  $this->model_pdf = $obj->model_pdf;
357  $this->last_main_doc = $obj->last_main_doc;
358 
359  $this->datec = $this->db->jdate($obj->datec);
360  $this->tms = $this->db->jdate($obj->tms);
361  $this->fk_user_creat = $obj->fk_user_creat;
362  $this->fk_user_modif = $obj->fk_user_modif;
363  $this->import_key = $obj->import_key;
364  $this->note_public = $obj->note_public;
365  $this->note_private = $obj->note_private;
366 
367  // Retrieve all extrafield
368  // fetch optionals attributes and labels
369  $this->fetch_optionals();
370  }
371  $this->db->free($resql);
372 
373  if ($numrows) {
374  return 1;
375  } else {
376  return 0;
377  }
378  } else {
379  $this->errors[] = 'Error '.$this->db->lasterror();
380  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
381 
382  return -1;
383  }
384  }
385 
394  public function update(User $user, $notrigger = false)
395  {
396  $error = 0;
397 
398  dol_syslog(__METHOD__, LOG_DEBUG);
399 
400  // Clean parameters
401 
402  if (isset($this->entity)) {
403  $this->entity = (int) $this->entity;
404  }
405  if (isset($this->fk_product)) {
406  $this->fk_product = (int) $this->fk_product;
407  }
408  if (isset($this->batch)) {
409  $this->batch = trim($this->batch);
410  }
411  if (isset($this->fk_user_creat)) {
412  $this->fk_user_creat = (int) $this->fk_user_creat;
413  }
414  if (isset($this->fk_user_modif)) {
415  $this->fk_user_modif = (int) $this->fk_user_modif;
416  }
417  if (isset($this->import_key)) {
418  $this->import_key = trim($this->import_key);
419  }
420 
421  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
422  if (empty($this->oldcopy)) {
423  $this->oldcopy = dol_clone($this);
424  }
425 
426  // Update request
427  $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET';
428  $sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").',';
429  $sql .= ' fk_product = '.(isset($this->fk_product) ? $this->fk_product : "null").',';
430  $sql .= ' batch = '.(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").',';
431  $sql .= ' eatby = '.(!isset($this->eatby) || dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').',';
432  $sql .= ' sellby = '.(!isset($this->sellby) || dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').',';
433  $sql .= ' eol_date = '.(!isset($this->eol_date) || dol_strlen($this->eol_date) != 0 ? "'".$this->db->idate($this->eol_date)."'" : 'null').',';
434  $sql .= ' manufacturing_date = '.(!isset($this->manufacturing_date) || dol_strlen($this->manufacturing_date) != 0 ? "'".$this->db->idate($this->manufacturing_date)."'" : 'null').',';
435  $sql .= ' scrapping_date = '.(!isset($this->scrapping_date) || dol_strlen($this->scrapping_date) != 0 ? "'".$this->db->idate($this->scrapping_date)."'" : 'null').',';
436  //$sql .= ' commissionning_date = '.(!isset($this->first_use_date) || dol_strlen($this->first_use_date) != 0 ? "'".$this->db->idate($this->first_use_date)."'" : 'null').',';
437  //$sql .= ' qc_frequency = '.(!isset($this->qc_frequency) || dol_strlen($this->qc_frequency) != 0 ? "'".$this->db->escape($this->qc_frequency)."'" : 'null').',';
438  $sql .= ' datec = '.(!isset($this->datec) || dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').',';
439  $sql .= ' tms = '.(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : "'".$this->db->idate(dol_now())."'").',';
440  $sql .= ' fk_user_creat = '.(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").',';
441  $sql .= ' fk_user_modif = '.(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").',';
442  $sql .= ' import_key = '.(isset($this->import_key) ? $this->import_key : "null");
443  $sql .= ' WHERE rowid='.((int) $this->id);
444 
445  $this->db->begin();
446 
447  $resql = $this->db->query($sql);
448  if (!$resql) {
449  $error++;
450  $this->errors[] = 'Error '.$this->db->lasterror();
451  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
452  }
453 
454  // Actions on extra fields
455  if (!$error) {
456  $result = $this->insertExtraFields();
457  if ($result < 0) {
458  $error++;
459  }
460  }
461 
462  if (!$error && !$notrigger) {
463  // Call triggers
464  $result = $this->call_trigger('PRODUCTLOT_MODIFY', $user);
465  if ($result < 0) {
466  $error++;
467  }
468  // End call triggers
469  }
470 
471  // Commit or rollback
472  if ($error) {
473  $this->db->rollback();
474 
475  return -1 * $error;
476  } else {
477  $this->db->commit();
478 
479  return 1;
480  }
481  }
482 
491  public function delete(User $user, $notrigger = false)
492  {
493  dol_syslog(__METHOD__, LOG_DEBUG);
494 
495  $error = 0;
496 
497  $this->db->begin();
498 
499  // Check there is no stock for this lot
500  $sql = "SELECT pb.rowid FROM ".$this->db->prefix()."product_batch as pb, ".$this->db->prefix()."product_stock as ps";
501  $sql .= " WHERE pb.fk_product_stock = ps.rowid AND pb.batch = '".$this->db->escape($this->batch)."'";
502  $sql .= " AND ps.fk_product = ".((int) $this->fk_product);
503  $sql .= $this->db->plimit(1);
504 
505  $resql = $this->db->query($sql);
506  if ($resql) {
507  $obj = $this->db->fetch_object($resql);
508  if ($obj) {
509  $error++;
510  $this->errors[] = 'Error Lot is used in stock (ID = '.$obj->rowid.'). Deletion not possible.';
511  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
512  }
513  } else {
514  $error++;
515  $this->errors[] = 'Error '.$this->db->lasterror();
516  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
517  }
518 
519  // Check there is no movement for this lot
520  $sql = "SELECT sm.rowid FROM ".$this->db->prefix()."stock_mouvement as sm";
521  $sql .= " WHERE sm.batch = '".$this->db->escape($this->batch)."'";
522  $sql .= " AND sm.fk_product = ".((int) $this->fk_product);
523  $sql .= $this->db->plimit(1);
524 
525  $resql = $this->db->query($sql);
526  if ($resql) {
527  $obj = $this->db->fetch_object($resql);
528  if ($obj) {
529  $error++;
530  $this->errors[] = 'Error Lot was used in a stock movement (ID '.$obj->rowid.'). Deletion not possible.';
531  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
532  }
533  } else {
534  $error++;
535  $this->errors[] = 'Error '.$this->db->lasterror();
536  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
537  }
538 
539  // TODO
540  //if (!$error) {
541  //if (!$notrigger) {
542  // Uncomment this and change PRODUCTLOT to your own tag if you
543  // want this action calls a trigger.
544 
546  //$result=$this->call_trigger('PRODUCTLOT_DELETE',$user);
547  //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
549  //}
550  //}
551 
552  if (!$error) {
553  $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element;
554  $sql .= ' WHERE rowid='.((int) $this->id);
555 
556  $resql = $this->db->query($sql);
557  if (!$resql) {
558  $error++;
559  $this->errors[] = 'Error '.$this->db->lasterror();
560  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
561  }
562  }
563 
564  // Commit or rollback
565  if ($error) {
566  $this->db->rollback();
567 
568  return -1 * $error;
569  } else {
570  $this->db->commit();
571 
572  return 1;
573  }
574  }
575 
583  public function createFromClone(User $user, $fromid)
584  {
585  dol_syslog(__METHOD__, LOG_DEBUG);
586 
587  $error = 0;
588  $object = new Productlot($this->db);
589 
590  $this->db->begin();
591 
592  // Load source object
593  $object->fetch($fromid);
594  // Reset object
595  $object->id = 0;
596 
597  // Clear fields
598  // ...
599 
600  // Create clone
601  $object->context['createfromclone'] = 'createfromclone';
602  $result = $object->create($user);
603 
604  // Other options
605  if ($result < 0) {
606  $error++;
607  $this->errors = $object->errors;
608  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
609  }
610 
611  unset($object->context['createfromclone']);
612 
613  // End
614  if (!$error) {
615  $this->db->commit();
616 
617  return $object->id;
618  } else {
619  $this->db->rollback();
620 
621  return -1;
622  }
623  }
624 
631  public function loadStatsExpedition($socid = 0)
632  {
633  // phpcs:enable
634  global $db, $conf, $user, $hookmanager, $action;
635 
636  $sql = "SELECT COUNT(DISTINCT exp.fk_soc) as nb_customers, COUNT(DISTINCT exp.rowid) as nb,";
637  $sql .= " COUNT(ed.rowid) as nb_rows, SUM(edb.qty) as qty";
638  $sql .= " FROM ".$this->db->prefix()."expeditiondet_batch as edb";
639  $sql .= " INNER JOIN ".$this->db->prefix()."expeditiondet as ed ON (ed.rowid = edb.fk_expeditiondet)";
640  $sql .= " INNER JOIN ".$this->db->prefix()."expedition as exp ON (exp.rowid = ed.fk_expedition)";
641  // $sql .= ", ".$this->db->prefix()."societe as s";
642  if (empty($user->rights->societe->client->voir) && !$socid) {
643  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
644  }
645  $sql .= " WHERE exp.entity IN (".getEntity('expedition').")";
646  $sql .= " AND edb.batch = '".($this->db->escape($this->batch))."'";
647  if (empty($user->rights->societe->client->voir) && !$socid) {
648  $sql .= " AND exp.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
649  }
650  //$sql.= " AND exp.fk_statut != 0";
651  if ($socid > 0) {
652  $sql .= " AND exp.fk_soc = ".((int) $socid);
653  }
654 
655  $result = $this->db->query($sql);
656  if ($result) {
657  $obj = $this->db->fetch_object($result);
658  $this->stats_expedition['customers'] = $obj->nb_customers;
659  $this->stats_expedition['nb'] = $obj->nb;
660  $this->stats_expedition['rows'] = $obj->nb_rows;
661  $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
662 
663 
664  // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
665 
666  // if it's a virtual product, maybe it is in invoice by extension
667  // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
668  // $TFather = $this->getFather();
669  // if (is_array($TFather) && !empty($TFather)) {
670  // foreach ($TFather as &$fatherData) {
671  // $pFather = new Product($this->db);
672  // $pFather->id = $fatherData['id'];
673  // $qtyCoef = $fatherData['qty'];
674  //
675  // if ($fatherData['incdec']) {
676  // $pFather->loadStatsExpedition($socid);
677  //
678  // $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
679  // $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
680  // $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
681  // $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
682  // }
683  // }
684  // }
685  // }
686 
687  $parameters = array('socid' => $socid);
688  $reshook = $hookmanager->executeHooks('loadStatsLotExpedition', $parameters, $this, $action);
689  if ($reshook > 0) {
690  $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
691  }
692 
693  return 1;
694  } else {
695  $this->error = $this->db->error();
696  return -1;
697  }
698  }
699 
706  public function loadStatsSupplierOrder($socid = 0)
707  {
708  // phpcs:enable
709  global $db, $conf, $user, $hookmanager, $action;
710 
711  $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_customers, COUNT(DISTINCT cf.rowid) as nb,";
712  $sql .= " COUNT(cfd.rowid) as nb_rows, SUM(cfdi.qty) as qty";
713  $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as cfdi";
714  $sql .= " INNER JOIN ".$this->db->prefix()."commande_fournisseurdet as cfd ON (cfd.rowid = cfdi.fk_commandefourndet)";
715  $sql .= " INNER JOIN ".$this->db->prefix()."commande_fournisseur as cf ON (cf.rowid = cfd.fk_commande)";
716  // $sql .= ", ".$this->db->prefix()."societe as s";
717  if (empty($user->rights->societe->client->voir) && !$socid) {
718  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
719  }
720  $sql .= " WHERE cf.entity IN (".getEntity('expedition').")";
721  $sql .= " AND cfdi.batch = '".($this->db->escape($this->batch))."'";
722  if (empty($user->rights->societe->client->voir) && !$socid) {
723  $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
724  }
725  //$sql.= " AND cf.fk_statut != 0";
726  if ($socid > 0) {
727  $sql .= " AND cf.fk_soc = ".((int) $socid);
728  }
729 
730  $result = $this->db->query($sql);
731  if ($result) {
732  $obj = $this->db->fetch_object($result);
733  $this->stats_supplier_order['customers'] = $obj->nb_customers;
734  $this->stats_supplier_order['nb'] = $obj->nb;
735  $this->stats_supplier_order['rows'] = $obj->nb_rows;
736  $this->stats_supplier_order['qty'] = $obj->qty ? $obj->qty : 0;
737 
738 
739  // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
740 
741  // if it's a virtual product, maybe it is in invoice by extension
742  // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
743  // $TFather = $this->getFather();
744  // if (is_array($TFather) && !empty($TFather)) {
745  // foreach ($TFather as &$fatherData) {
746  // $pFather = new Product($this->db);
747  // $pFather->id = $fatherData['id'];
748  // $qtyCoef = $fatherData['qty'];
749  //
750  // if ($fatherData['incdec']) {
751  // $pFather->stats_supplier_order($socid);
752  //
753  // $this->stats_supplier_order['customers'] += $pFather->stats_supplier_order['customers'];
754  // $this->stats_supplier_order['nb'] += $pFather->stats_supplier_order['nb'];
755  // $this->stats_supplier_order['rows'] += $pFather->stats_supplier_order['rows'];
756  // $this->stats_supplier_order['qty'] += $pFather->stats_supplier_order['qty'] * $qtyCoef;
757  // }
758  // }
759  // }
760  // }
761 
762  $parameters = array('socid' => $socid);
763  $reshook = $hookmanager->executeHooks('loadStatsLotSupplierOrder', $parameters, $this, $action);
764  if ($reshook > 0) {
765  $this->stats_supplier_order = $hookmanager->resArray['stats_supplier_order'];
766  }
767 
768  return 1;
769  } else {
770  $this->error = $this->db->error();
771  return -1;
772  }
773  }
774 
781  public function loadStatsReception($socid = 0)
782  {
783  // phpcs:enable
784  global $db, $conf, $user, $hookmanager, $action;
785 
786  $sql = "SELECT COUNT(DISTINCT recep.fk_soc) as nb_customers, COUNT(DISTINCT recep.rowid) as nb,";
787  $sql .= " COUNT(cfdi.rowid) as nb_rows, SUM(cfdi.qty) as qty";
788  $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as cfdi";
789  $sql .= " INNER JOIN ".$this->db->prefix()."reception as recep ON (recep.rowid = cfdi.fk_reception)";
790  // $sql .= ", ".$this->db->prefix()."societe as s";
791  if (empty($user->rights->societe->client->voir) && !$socid) {
792  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
793  }
794  $sql .= " WHERE recep.entity IN (".getEntity('reception').")";
795  $sql .= " AND cfdi.batch = '".($this->db->escape($this->batch))."'";
796  if (empty($user->rights->societe->client->voir) && !$socid) {
797  $sql .= " AND recep.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
798  }
799  //$sql.= " AND exp.fk_statut != 0";
800  if ($socid > 0) {
801  $sql .= " AND recep.fk_soc = ".((int) $socid);
802  }
803 
804  $result = $this->db->query($sql);
805  if ($result) {
806  $obj = $this->db->fetch_object($result);
807  $this->stats_reception['customers'] = $obj->nb_customers;
808  $this->stats_reception['nb'] = $obj->nb;
809  $this->stats_reception['rows'] = $obj->nb_rows;
810  $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
811 
812 
813  // Virtual products can't be used with kits (see langs with key ErrorNoteAlsoThatSubProductCantBeFollowedByLot)
814 
815  // if it's a virtual product, maybe it is in invoice by extension
816  // if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
817  // $TFather = $this->getFather();
818  // if (is_array($TFather) && !empty($TFather)) {
819  // foreach ($TFather as &$fatherData) {
820  // $pFather = new Product($this->db);
821  // $pFather->id = $fatherData['id'];
822  // $qtyCoef = $fatherData['qty'];
823  //
824  // if ($fatherData['incdec']) {
825  // $pFather->loadStatsReception($socid);
826  //
827  // $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
828  // $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
829  // $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
830  // $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
831  // }
832  // }
833  // }
834  // }
835 
836  $parameters = array('socid' => $socid);
837  $reshook = $hookmanager->executeHooks('loadStatsLotReception', $parameters, $this, $action);
838  if ($reshook > 0) {
839  $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
840  }
841 
842  return 1;
843  } else {
844  $this->error = $this->db->error();
845  return -1;
846  }
847  }
848 
855  public function loadStatsMo($socid = 0)
856  {
857  // phpcs:enable
858  global $user, $hookmanager, $action;
859 
860  $error = 0;
861 
862  foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
863  $this->stats_mo['customers_'.$role] = 0;
864  $this->stats_mo['nb_'.$role] = 0;
865  $this->stats_mo['qty_'.$role] = 0;
866 
867  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
868  $sql .= " SUM(mp.qty) as qty";
869  $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
870  $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
871  if (empty($user->rights->societe->client->voir) && !$socid) {
872  $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
873  }
874  $sql .= " WHERE ";
875  $sql .= " c.entity IN (".getEntity('mo').")";
876 
877  $sql .= " AND mp.batch = '".($this->db->escape($this->batch))."'";
878  $sql .= " AND mp.role ='".$this->db->escape($role)."'";
879  if ($socid > 0) {
880  $sql .= " AND c.fk_soc = ".((int) $socid);
881  }
882 
883  $result = $this->db->query($sql);
884  if ($result) {
885  $obj = $this->db->fetch_object($result);
886  $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
887  $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
888  $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
889  } else {
890  $this->error = $this->db->error();
891  $error++;
892  }
893  }
894 
895  if (!empty($error)) {
896  return -1;
897  }
898 
899  $parameters = array('socid' => $socid);
900  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
901  if ($reshook > 0) {
902  $this->stats_mo = $hookmanager->resArray['stats_mo'];
903  }
904 
905  return 1;
906  }
907 
908 
915  public function getLibStatut($mode = 0)
916  {
917  return $this->LibStatut(0, $mode);
918  }
919 
920  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
928  public function LibStatut($status, $mode = 0)
929  {
930  // phpcs:enable
931  global $langs;
932 
933  //$langs->load('stocks');
934 
935  return '';
936  }
937 
938 
946  public function getTooltipContentArray($params)
947  {
948  global $conf, $langs, $user;
949 
950  $langs->loadLangs(['stocks', 'productbatch']);
951 
952  $option = $params['option'] ?? '';
953 
954  $datas = [];
955  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Batch").'</u>';
956  //$datas['divopen'] = '<div width="100%">';
957  $datas['batch'] = '<br><b>'.$langs->trans('Batch').':</b> '.$this->batch;
958  if ($this->eatby && empty($conf->global->PRODUCT_DISABLE_EATBY)) {
959  $datas['eatby'] = '<br><b>'.$langs->trans('EatByDate').':</b> '.dol_print_date($this->db->jdate($this->eatby), 'day');
960  }
961  if ($this->sellby && empty($conf->global->PRODUCT_DISABLE_SELLBY)) {
962  $datas['sellby'] = '<br><b>'.$langs->trans('SellByDate').':</b> '.dol_print_date($this->db->jdate($this->sellby), 'day');
963  }
964  //$datas['divclose'] = '</div>';
965 
966  return $datas;
967  }
968 
981  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '', $save_lastsearch_value = -1)
982  {
983  global $langs, $conf, $hookmanager, $db;
984  global $dolibarr_main_authentication, $dolibarr_main_demo;
985  global $menumanager;
986 
987  $result = '';
988  $params = [
989  'id' => $this->id,
990  'objecttype' => $this->element,
991  'option' => $option,
992  ];
993  $classfortooltip = 'classfortooltip';
994  $dataparams = '';
995  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
996  $classfortooltip = 'classforajaxtooltip';
997  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
998  $label = '';
999  } else {
1000  $label = implode($this->getTooltipContentArray($params));
1001  }
1002 
1003  $url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id;
1004 
1005  if ($option != 'nolink') {
1006  // Add param to save lastsearch_values or not
1007  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1008  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1009  $add_save_lastsearch_values = 1;
1010  }
1011  if ($add_save_lastsearch_values) {
1012  $url .= '&save_lastsearch_values=1';
1013  }
1014  }
1015 
1016  $linkclose = '';
1017  if (empty($notooltip)) {
1018  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1019  $label = $langs->trans("ShowMyObject");
1020  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1021  }
1022  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
1023  $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1024  } else {
1025  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1026  }
1027 
1028  if ($option == 'nolink') {
1029  $linkstart = '<span';
1030  } else {
1031  $linkstart = '<a href="'.$url.'"';
1032  }
1033  $linkstart .= $linkclose.'>';
1034  if ($option == 'nolink') {
1035  $linkend = '</span>';
1036  } else {
1037  $linkend = '</a>';
1038  }
1039 
1040  $result .= $linkstart;
1041  if ($withpicto) {
1042  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
1043  }
1044  if ($withpicto != 2) {
1045  $result .= $this->batch;
1046  }
1047  $result .= $linkend;
1048 
1049  global $action;
1050  $hookmanager->initHooks(array('productlotdao'));
1051  $parameters = array('id' => $this->id, 'getnomurl' => $result);
1052  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1053  if ($reshook > 0) {
1054  $result = $hookmanager->resPrint;
1055  } else {
1056  $result .= $hookmanager->resPrint;
1057  }
1058 
1059  return $result;
1060  }
1061 
1062 
1069  public function initAsSpecimen()
1070  {
1071  global $conf;
1072 
1073  // Initialise parametres
1074  $this->id = 0;
1075  $this->ref = 'SPECIMEN';
1076  $this->specimen = 1;
1077 
1078  $this->entity = $conf->entity;
1079  $this->fk_product = null;
1080  $this->batch = '';
1081  $this->eatby = '';
1082  $this->sellby = '';
1083  $this->datec = '';
1084  $this->tms = '';
1085  $this->fk_user_creat = null;
1086  $this->fk_user_modif = null;
1087  $this->import_key = '';
1088  }
1089 
1100  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1101  {
1102  global $conf, $user, $langs;
1103 
1104  $langs->loadLangs(array('stocks', 'productbatch', "products"));
1105  $outputlangs->loadLangs(array('stocks', 'productbatch', "products"));
1106 
1107  // Positionne le modele sur le nom du modele a utiliser
1108  if (!dol_strlen($modele)) {
1109  $modele = '';
1110 
1111  if (!empty($this->model_pdf)) {
1112  $modele = $this->model_pdf;
1113  } elseif (!empty($conf->global->PRODUCT_BATCH_ADDON_PDF)) {
1114  $modele = $conf->global->PRODUCT_BATCH_ADDON_PDF;
1115  }
1116  }
1117 
1118  $modelpath = "core/modules/product_batch/doc/";
1119 
1120  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1121  }
1122 }
$object ref
Definition: info.php:78
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class with list of lots and properties.
loadStatsReception($socid=0)
Charge tableau des stats expedition pour le lot/numéro de série.
getLibStatut($mode=0)
Return label of status of object.
getTooltipContentArray($params)
getTooltipContentArray
fetch($id=0, $product_id=0, $batch='')
Load object in memory from the database.
loadStatsExpedition($socid=0)
Charge tableau des stats expedition pour le lot/numéro de série.
LibStatut($status, $mode=0)
Return label of a given status.
getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='', $save_lastsearch_value=-1)
Return a link to the a lot card (with optionaly the picto) Use this->id,this->lastname,...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create a document onto disk according to template module.
loadStatsMo($socid=0)
Charge tableau des stats expedition pour le lot/numéro de série.
__construct(DoliDB $db)
Constructor.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
createFromClone(User $user, $fromid)
Load an object from its id and create a new one in database.
create(User $user, $notrigger=false)
Create object into database.
loadStatsSupplierOrder($socid=0)
Charge tableau des stats commande fournisseur pour le lot/numéro de série.
update(User $user, $notrigger=false)
Update object into database.
Class to manage Dolibarr users.
Definition: user.class.php:48
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.