dolibarr  19.0.0-dev
contrat.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2012 Destailleur Laurent <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6  * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
7  * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
8  * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
9  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
11  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
12  * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
13  * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 3 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program. If not, see <https://www.gnu.org/licenses/>.
27  */
28 
35 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
36 require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
37 require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
38 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
39 
43 class Contrat extends CommonObject
44 {
48  public $element = 'contrat';
49 
53  public $table_element = 'contrat';
54 
58  public $table_element_line = 'contratdet';
59 
63  public $fk_element = 'fk_contrat';
64 
68  public $picto = 'contract';
69 
74  public $ismultientitymanaged = 1;
75 
79  public $isextrafieldmanaged = 1;
80 
85  public $restrictiononfksoc = 1;
86 
90  protected $table_ref_field = 'ref';
91 
96  public $ref_customer;
97 
102  public $ref_supplier;
103 
108  public $entity;
109 
114  public $socid;
115 
116  public $societe; // Objet societe
117 
122  public $statut = 0; // 0=Draft,
123 
124  public $product;
125 
129  public $fk_user_author;
130 
136  public $user_author_id;
137 
141  public $user_creation;
142 
146  public $user_cloture;
147 
151  public $date_creation;
152 
156  public $date_modification;
157 
161  public $date_validation;
162 
166  public $date_contrat;
167 
168  public $commercial_signature_id;
169  public $commercial_suivi_id;
170 
175  public $fk_projet;
176 
177  public $extraparams = array();
178 
182  public $lines = array();
183 
184  public $nbofservices;
185  public $nbofserviceswait;
186  public $nbofservicesopened;
187  public $nbofservicesexpired;
188  public $nbofservicesclosed;
189  //public $lower_planned_end_date;
190  //public $higher_planner_end_date;
191 
196  protected $lines_id_index_mapper = array();
197 
198 
223  // BEGIN MODULEBUILDER PROPERTIES
227  public $fields = array(
228  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
229  'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>15, 'searchall'=>1),
230  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>20),
231  'ref_customer' =>array('type'=>'varchar(50)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>25, 'searchall'=>1),
232  'ref_supplier' =>array('type'=>'varchar(50)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>26, 'searchall'=>1),
233  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
234  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
235  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
236  'date_contrat' =>array('type'=>'datetime', 'label'=>'Date contrat', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
237  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'notnull'=>1, 'position'=>70),
238  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>75),
239  'fk_commercial_signature' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative Signature', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
240  'fk_commercial_suivi' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative follower', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
241  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
242  'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105, 'searchall'=>1),
243  'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110, 'searchall'=>1),
244  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
245  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
246  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
247  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
248  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
249  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'notnull'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed'))
250  );
251  // END MODULEBUILDER PROPERTIES
252 
253  const STATUS_DRAFT = 0;
254  const STATUS_VALIDATED = 1;
255  const STATUS_CLOSED = 2;
256 
257 
258 
264  public function __construct($db)
265  {
266  $this->db = $db;
267  }
268 
275  public function getNextNumRef($soc)
276  {
277  global $db, $langs, $conf;
278  $langs->load("contracts");
279 
280  if (!empty($conf->global->CONTRACT_ADDON)) {
281  $mybool = false;
282 
283  $file = $conf->global->CONTRACT_ADDON.".php";
284  $classname = $conf->global->CONTRACT_ADDON;
285 
286  // Include file with class
287  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
288 
289  foreach ($dirmodels as $reldir) {
290  $dir = dol_buildpath($reldir."core/modules/contract/");
291 
292  // Load file with numbering class (if found)
293  $mybool |= @include_once $dir.$file;
294  }
295 
296  if (!$mybool) {
297  dol_print_error('', "Failed to include file ".$file);
298  return '';
299  }
300 
301  $obj = new $classname();
302  $numref = $obj->getNextValue($soc, $this);
303 
304  if ($numref != "") {
305  return $numref;
306  } else {
307  $this->error = $obj->error;
308  dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
309  return "";
310  }
311  } else {
312  $langs->load("errors");
313  print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
314  return "";
315  }
316  }
317 
318  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
329  public function active_line($user, $line_id, $date_start, $date_end = '', $comment = '')
330  {
331  // phpcs:enable
332  $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
333  if ($result < 0) {
334  $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
335  $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
336  }
337  return $result;
338  }
339 
340 
341  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
351  public function close_line($user, $line_id, $date_end, $comment = '')
352  {
353  // phpcs:enable
354  $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
355  if ($result < 0) {
356  $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
357  $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
358  }
359  return $result;
360  }
361 
362 
374  public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
375  {
376  if (empty($date_start)) {
377  $date_start = dol_now();
378  }
379 
380  $this->db->begin();
381 
382  $error = 0;
383 
384  // Load lines
385  $this->fetch_lines();
386 
387  foreach ($this->lines as $contratline) {
388  // Open lines not already open
389  if ($contratline->statut != ContratLigne::STATUS_OPEN) {
390  $contratline->context = $this->context;
391 
392  $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
393  if ($result < 0) {
394  $error++;
395  $this->error = $contratline->error;
396  $this->errors = $contratline->errors;
397  break;
398  }
399  }
400  }
401 
402  if (!$error && $this->statut == 0) {
403  $result = $this->validate($user, '', $notrigger);
404  if ($result < 0) {
405  $error++;
406  }
407  }
408 
409  if (!$error) {
410  $this->db->commit();
411  return 1;
412  } else {
413  $this->db->rollback();
414  return -1;
415  }
416  }
417 
427  public function closeAll(User $user, $notrigger = 0, $comment = '')
428  {
429  $this->db->begin();
430 
431  // Load lines
432  $this->fetch_lines();
433 
434  $now = dol_now();
435 
436  $error = 0;
437 
438  foreach ($this->lines as $contratline) {
439  // Close lines not already closed
440  if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
441  $contratline->date_end_real = $now;
442  $contratline->date_cloture = $now; // For backward compatibility
443  $contratline->fk_user_cloture = $user->id;
444  $contratline->statut = ContratLigne::STATUS_CLOSED;
445  $result = $contratline->close_line($user, $now, $comment, $notrigger);
446  if ($result < 0) {
447  $error++;
448  $this->error = $contratline->error;
449  $this->errors = $contratline->errors;
450  break;
451  }
452  }
453  }
454 
455  if (!$error && $this->statut == 0) {
456  $result = $this->validate($user, '', $notrigger);
457  if ($result < 0) {
458  $error++;
459  }
460  }
461 
462  if (!$error) {
463  $this->db->commit();
464  return 1;
465  } else {
466  $this->db->rollback();
467  return -1;
468  }
469  }
470 
479  public function validate(User $user, $force_number = '', $notrigger = 0)
480  {
481  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
482  global $langs, $conf;
483 
484  $now = dol_now();
485 
486  $error = 0;
487  dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
488 
489 
490  $this->db->begin();
491 
492  $this->fetch_thirdparty();
493 
494  // A contract is validated so we can move thirdparty to status customer
495  if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) {
496  $result = $this->thirdparty->set_as_client();
497  }
498 
499  // Define new ref
500  if ($force_number) {
501  $num = $force_number;
502  } elseif (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
503  $num = $this->getNextNumRef($this->thirdparty);
504  } else {
505  $num = $this->ref;
506  }
507  $this->newref = dol_sanitizeFileName($num);
508 
509  if ($num) {
510  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
511  //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
512  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
513 
514  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
515  $resql = $this->db->query($sql);
516  if (!$resql) {
517  dol_print_error($this->db);
518  $error++;
519  $this->error = $this->db->lasterror();
520  }
521 
522  // Trigger calls
523  if (!$error && !$notrigger) {
524  // Call trigger
525  $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
526  if ($result < 0) {
527  $error++;
528  }
529  // End call triggers
530  }
531 
532  if (!$error) {
533  $this->oldref = $this->ref;
534 
535  // Rename directory if dir was a temporary ref
536  if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
537  // Now we rename also files into index
538  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'contract/".$this->db->escape($this->newref)."'";
539  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
540  $resql = $this->db->query($sql);
541  if (!$resql) {
542  $error++; $this->error = $this->db->lasterror();
543  }
544 
545  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
546  $oldref = dol_sanitizeFileName($this->ref);
547  $newref = dol_sanitizeFileName($num);
548  $dirsource = $conf->contract->dir_output.'/'.$oldref;
549  $dirdest = $conf->contract->dir_output.'/'.$newref;
550  if (!$error && file_exists($dirsource)) {
551  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
552 
553  if (@rename($dirsource, $dirdest)) {
554  dol_syslog("Rename ok");
555  // Rename docs starting with $oldref with $newref
556  $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
557  foreach ($listoffiles as $fileentry) {
558  $dirsource = $fileentry['name'];
559  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
560  $dirsource = $fileentry['path'].'/'.$dirsource;
561  $dirdest = $fileentry['path'].'/'.$dirdest;
562  @rename($dirsource, $dirdest);
563  }
564  }
565  }
566  }
567  }
568 
569  // Set new ref and define current statut
570  if (!$error) {
571  $this->ref = $num;
572  $this->statut = 1;
573  $this->brouillon = 0;
574  $this->date_validation = $now;
575  }
576  } else {
577  $error++;
578  }
579 
580  if (!$error) {
581  $this->db->commit();
582  return 1;
583  } else {
584  $this->db->rollback();
585  return -1;
586  }
587  }
588 
596  public function reopen($user, $notrigger = 0)
597  {
598  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
599  global $langs, $conf;
600 
601  $now = dol_now();
602 
603  $error = 0;
604  dol_syslog(get_class($this).'::reopen user='.$user->id);
605 
606  $this->db->begin();
607 
608  $this->fetch_thirdparty();
609 
610  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
611  //$sql.= ", fk_user_valid = null, date_valid = null";
612  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
613 
614  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
615  $resql = $this->db->query($sql);
616  if (!$resql) {
617  dol_print_error($this->db);
618  $error++;
619  $this->error = $this->db->lasterror();
620  }
621 
622  // Trigger calls
623  if (!$error && !$notrigger) {
624  // Call trigger
625  $result = $this->call_trigger('CONTRACT_REOPEN', $user);
626  if ($result < 0) {
627  $error++;
628  }
629  // End call triggers
630  }
631 
632  // Set new ref and define current status
633  if (!$error) {
634  $this->statut = 0;
635  $this->brouillon = 1;
636  $this->date_validation = $now;
637  }
638 
639  if (!$error) {
640  $this->db->commit();
641  return 1;
642  } else {
643  $this->db->rollback();
644  return -1;
645  }
646  }
647 
657  public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '')
658  {
659  $sql = "SELECT rowid, statut, ref, fk_soc,";
660  $sql .= " ref_supplier, ref_customer,";
661  $sql .= " ref_ext,";
662  $sql .= " entity,";
663  $sql .= " date_contrat as datecontrat,";
664  $sql .= " fk_user_author,";
665  $sql .= " fk_projet as fk_project,";
666  $sql .= " fk_commercial_signature, fk_commercial_suivi,";
667  $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
668  $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
669  if (!$id) {
670  $sql .= " WHERE entity IN (".getEntity('contract').")";
671  } else {
672  $sql .= " WHERE rowid = ".(int) $id;
673  }
674  if ($ref_customer) {
675  $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
676  }
677  if ($ref_supplier) {
678  $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
679  }
680  if ($ref) {
681  $sql .= " AND ref = '".$this->db->escape($ref)."'";
682  }
683 
684  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
685  $resql = $this->db->query($sql);
686  if ($resql) {
687  $num = $this->db->num_rows($resql);
688  if ($num > 1) {
689  $this->error = 'Fetch found several records.';
690  dol_syslog($this->error, LOG_ERR);
691  $result = -2;
692  return 0;
693  } elseif ($num) { // $num = 1
694  $obj = $this->db->fetch_object($resql);
695  if ($obj) {
696  $this->id = $obj->rowid;
697  $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
698  $this->ref_customer = $obj->ref_customer;
699  $this->ref_supplier = $obj->ref_supplier;
700  $this->ref_ext = $obj->ref_ext;
701  $this->entity = $obj->entity;
702  $this->statut = $obj->statut;
703 
704  $this->date_contrat = $this->db->jdate($obj->datecontrat);
705  $this->date_creation = $this->db->jdate($obj->datecontrat);
706 
707  $this->user_author_id = $obj->fk_user_author;
708 
709  $this->commercial_signature_id = $obj->fk_commercial_signature;
710  $this->commercial_suivi_id = $obj->fk_commercial_suivi;
711 
712  $this->note_private = $obj->note_private;
713  $this->note_public = $obj->note_public;
714  $this->model_pdf = $obj->model_pdf;
715  $this->modelpdf = $obj->model_pdf; // deprecated
716 
717  $this->fk_projet = $obj->fk_project; // deprecated
718  $this->fk_project = $obj->fk_project;
719 
720  $this->socid = $obj->fk_soc;
721  $this->fk_soc = $obj->fk_soc;
722  $this->last_main_doc = $obj->last_main_doc;
723  $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
724 
725  $this->db->free($resql);
726 
727  // Retrieve all extrafields
728  // fetch optionals attributes and labels
729  $result = $this->fetch_optionals();
730 
731  // Lines
732  if ($result >= 0 && !empty($this->table_element_line)) {
733  $result = $this->fetch_lines();
734  }
735 
736  if ($result < 0) {
737  $this->error = $this->db->lasterror();
738  return -3;
739  }
740 
741  return $this->id;
742  } else {
743  dol_syslog(get_class($this)."::fetch Contract failed");
744  $this->error = "Fetch contract failed";
745  return -1;
746  }
747  } else {
748  dol_syslog(get_class($this)."::fetch Contract not found");
749  $this->error = "Contract not found";
750  return 0;
751  }
752  } else {
753  dol_syslog(get_class($this)."::fetch Error searching contract");
754  $this->error = $this->db->error();
755  return -1;
756  }
757  }
758 
759  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
768  public function fetch_lines($only_services = 0, $loadalsotranslation = 0)
769  {
770  // phpcs:enable
771  global $langs, $conf;
772 
773  $this->nbofservices = 0;
774  $this->nbofserviceswait = 0;
775  $this->nbofservicesopened = 0;
776  $this->nbofservicesexpired = 0;
777  $this->nbofservicesclosed = 0;
778 
779  $total_ttc = 0;
780  $total_vat = 0;
781  $total_ht = 0;
782 
783  $now = dol_now();
784 
785  $this->lines = array();
786  $pos = 0;
787 
788  // Selects contract lines related to a product
789  $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
790  $sql .= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
791  $sql .= " d.total_ht,";
792  $sql .= " d.total_tva,";
793  $sql .= " d.total_localtax1,";
794  $sql .= " d.total_localtax2,";
795  $sql .= " d.total_ttc,";
796  $sql .= " d.info_bits, d.fk_product,";
797  $sql .= " d.date_ouverture_prevue as date_start,";
798  $sql .= " d.date_ouverture as date_start_real,";
799  $sql .= " d.date_fin_validite as date_end,";
800  $sql .= " d.date_cloture as date_end_real,";
801  $sql .= " d.fk_user_author,";
802  $sql .= " d.fk_user_ouverture,";
803  $sql .= " d.fk_user_cloture,";
804  $sql .= " d.fk_unit,";
805  $sql .= " d.product_type as type,";
806  $sql .= " d.rang";
807  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
808  $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
809  if ($only_services == 1) {
810  $sql .= " AND d.product_type = 1";
811  }
812  $sql .= " ORDER by d.rang ASC";
813 
814  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
815  $result = $this->db->query($sql);
816  if ($result) {
817  $num = $this->db->num_rows($result);
818  $i = 0;
819 
820  while ($i < $num) {
821  $objp = $this->db->fetch_object($result);
822 
823  $line = new ContratLigne($this->db);
824 
825  $line->id = $objp->rowid;
826  $line->ref = $objp->rowid;
827  $line->fk_contrat = $objp->fk_contrat;
828  $line->desc = $objp->description; // Description line
829  $line->qty = $objp->qty;
830  $line->vat_src_code = $objp->vat_src_code;
831  $line->tva_tx = $objp->tva_tx;
832  $line->localtax1_tx = $objp->localtax1_tx;
833  $line->localtax2_tx = $objp->localtax2_tx;
834  $line->localtax1_type = $objp->localtax1_type;
835  $line->localtax2_type = $objp->localtax2_type;
836  $line->subprice = $objp->subprice;
837  $line->statut = $objp->statut;
838  $line->remise_percent = $objp->remise_percent;
839  $line->price_ht = $objp->price_ht;
840  $line->price = $objp->price_ht; // For backward compatibility
841  $line->total_ht = $objp->total_ht;
842  $line->total_tva = $objp->total_tva;
843  $line->total_localtax1 = $objp->total_localtax1;
844  $line->total_localtax2 = $objp->total_localtax2;
845  $line->total_ttc = $objp->total_ttc;
846  $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
847  $line->info_bits = $objp->info_bits;
848  $line->type = $objp->type;
849 
850  $line->fk_fournprice = $objp->fk_fournprice;
851  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
852  $line->pa_ht = $marginInfos[0];
853 
854  $line->fk_user_author = $objp->fk_user_author;
855  $line->fk_user_ouverture = $objp->fk_user_ouverture;
856  $line->fk_user_cloture = $objp->fk_user_cloture;
857  $line->fk_unit = $objp->fk_unit;
858 
859  $line->ref = $objp->product_ref; // deprecated
860  $line->product_ref = $objp->product_ref; // Product Ref
861  $line->product_type = $objp->product_type; // Product Type
862  $line->product_desc = $objp->product_desc; // Product Description
863  $line->product_label = $objp->product_label; // Product Label
864 
865  $line->description = $objp->description;
866 
867  $line->date_start = $this->db->jdate($objp->date_start);
868  $line->date_start_real = $this->db->jdate($objp->date_start_real);
869  $line->date_end = $this->db->jdate($objp->date_end);
870  $line->date_end_real = $this->db->jdate($objp->date_end_real);
871  // For backward compatibility
872  //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
873  //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
874  //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
875  //$line->date_cloture = $this->db->jdate($objp->date_cloture);
876  //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
877  //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
878  //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
879  //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
880 
881  $line->rang = $objp->rang;
882 
883  // Retrieve all extrafields for contract line
884  // fetch optionals attributes and labels
885  $line->fetch_optionals();
886 
887  // multilangs
888  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
889  $tmpproduct = new Product($this->db);
890  $tmpproduct->fetch($objp->fk_product);
891  $tmpproduct->getMultiLangs();
892 
893  $line->multilangs = $tmpproduct->multilangs;
894  }
895 
896  $this->lines[$pos] = $line;
897 
898  $this->lines_id_index_mapper[$line->id] = $pos;
899 
900  //dol_syslog("1 ".$line->desc);
901  //dol_syslog("2 ".$line->product_desc);
902 
903  if ($line->statut == ContratLigne::STATUS_INITIAL) {
904  $this->nbofserviceswait++;
905  }
906  if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
907  $this->nbofservicesopened++;
908  }
909  if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
910  $this->nbofservicesexpired++;
911  }
912  if ($line->statut == ContratLigne::STATUS_CLOSED) {
913  $this->nbofservicesclosed++;
914  }
915 
916  $total_ttc += $objp->total_ttc; // TODO Not saved into database
917  $total_vat += $objp->total_tva;
918  $total_ht += $objp->total_ht;
919 
920  $i++;
921  $pos++;
922  }
923  $this->db->free($result);
924  } else {
925  dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
926  return -3;
927  }
928 
929  // Now set the global properties on contract not stored into database.
930  $this->nbofservices = count($this->lines);
931  $this->total_ttc = price2num($total_ttc);
932  $this->total_tva = price2num($total_vat);
933  $this->total_ht = price2num($total_ht);
934 
935  return $this->lines;
936  }
937 
944  public function create($user)
945  {
946  global $conf, $langs, $mysoc;
947 
948  // Check parameters
949  $paramsok = 1;
950  if ($this->commercial_signature_id <= 0) {
951  $langs->load("commercial");
952  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
953  $paramsok = 0;
954  }
955  if ($this->commercial_suivi_id <= 0) {
956  $langs->load("commercial");
957  $this->error .= ($this->error ? "<br>" : '');
958  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
959  $paramsok = 0;
960  }
961  if (!$paramsok) {
962  return -1;
963  }
964 
965 
966  $this->db->begin();
967 
968  $now = dol_now();
969 
970  // Insert contract
971  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
972  $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
973  $sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
974  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
975  $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
976  $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
977  $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
978  $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
979  $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
980  $sql .= ", ".((int) $conf->entity);
981  $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
982  $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
983  $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
984  $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
985  $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
986  $sql .= ")";
987  $resql = $this->db->query($sql);
988 
989  if ($resql) {
990  $error = 0;
991 
992  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
993 
994  // Load object modContract
995  $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
996  if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
997  $module = substr($module, 0, dol_strlen($module) - 4);
998  }
999  $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1000  if ($result > 0) {
1001  $modCodeContract = new $module();
1002 
1003  if (!empty($modCodeContract->code_auto)) {
1004  // Force the ref to a draft value if numbering module is an automatic numbering
1005  $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1006  if ($this->db->query($sql)) {
1007  if ($this->id) {
1008  $this->ref = "(PROV".$this->id.")";
1009  }
1010  }
1011  }
1012  }
1013 
1014  if (!$error) {
1015  $result = $this->insertExtraFields();
1016  if ($result < 0) {
1017  $error++;
1018  }
1019  }
1020 
1021  // Insert business contacts ('SALESREPSIGN','contrat')
1022  if (!$error) {
1023  $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1024  if ($result < 0) {
1025  $error++;
1026  }
1027  }
1028 
1029  // Insert business contacts ('SALESREPFOLL','contrat')
1030  if (!$error) {
1031  $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1032  if ($result < 0) {
1033  $error++;
1034  }
1035  }
1036 
1037  if (!$error) {
1038  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1039  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1040  }
1041 
1042  // Add object linked
1043  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1044  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1045  if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
1046  foreach ($tmp_origin_id as $origin_id) {
1047  $ret = $this->add_object_linked($origin, $origin_id);
1048  if (!$ret) {
1049  $this->error = $this->db->lasterror();
1050  $error++;
1051  }
1052  }
1053  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1054  {
1055  $origin_id = $tmp_origin_id;
1056  $ret = $this->add_object_linked($origin, $origin_id);
1057  if (!$ret) {
1058  $this->error = $this->db->lasterror();
1059  $error++;
1060  }
1061  }
1062  }
1063  }
1064 
1065  if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1066  $originforcontact = $this->origin;
1067  $originidforcontact = $this->origin_id;
1068  if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1069  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1070  $exp = new Expedition($this->db);
1071  $exp->fetch($this->origin_id);
1072  $exp->fetchObjectLinked();
1073  if (count($exp->linkedObjectsIds['commande']) > 0) {
1074  foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1075  $originforcontact = 'commande';
1076  $originidforcontact = $value;
1077  break; // We take first one
1078  }
1079  }
1080  }
1081 
1082  $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
1083  $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1084 
1085  $resqlcontact = $this->db->query($sqlcontact);
1086  if ($resqlcontact) {
1087  while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1088  if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1089  continue; // ignore this, already forced previously
1090  }
1091 
1092  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1093  $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
1094  }
1095  } else {
1096  dol_print_error($resqlcontact);
1097  }
1098  }
1099  }
1100 
1101  if (!$error) {
1102  // Call trigger
1103  $result = $this->call_trigger('CONTRACT_CREATE', $user);
1104  if ($result < 0) {
1105  $error++;
1106  }
1107  // End call triggers
1108 
1109  if (!$error) {
1110  $this->db->commit();
1111  return $this->id;
1112  } else {
1113  dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1114  $this->db->rollback();
1115  return -3;
1116  }
1117  } else {
1118  $this->error = "Failed to add contract";
1119  dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1120  $this->db->rollback();
1121  return -2;
1122  }
1123  } else {
1124  $this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1125 
1126  $this->db->rollback();
1127  return -1;
1128  }
1129  }
1130 
1131 
1138  public function delete($user)
1139  {
1140  global $conf, $langs;
1141  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1142 
1143  $error = 0;
1144 
1145  $this->db->begin();
1146 
1147  // Call trigger
1148  $result = $this->call_trigger('CONTRACT_DELETE', $user);
1149  if ($result < 0) {
1150  $error++;
1151  }
1152  // End call triggers
1153 
1154  if (!$error) {
1155  // Delete linked contacts
1156  $res = $this->delete_linked_contact();
1157  if ($res < 0) {
1158  dol_syslog(get_class($this)."::delete error", LOG_ERR);
1159  $error++;
1160  }
1161  }
1162 
1163  if (!$error) {
1164  // Delete linked object
1165  $res = $this->deleteObjectLinked();
1166  if ($res < 0) {
1167  $error++;
1168  }
1169  }
1170 
1171  if (!$error) {
1172  // Delete contratdet_log
1173  /*
1174  $sql = "DELETE cdl";
1175  $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1176  $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1177  */
1178  $sql = "SELECT cdl.rowid as cdlrowid ";
1179  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1180  $sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1181 
1182  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1183  $resql = $this->db->query($sql);
1184  if (!$resql) {
1185  $this->error = $this->db->error();
1186  $error++;
1187  }
1188  $numressql = $this->db->num_rows($resql);
1189  if (!$error && $numressql) {
1190  $tab_resql = array();
1191  for ($i = 0; $i < $numressql; $i++) {
1192  $objresql = $this->db->fetch_object($resql);
1193  $tab_resql[] = $objresql->cdlrowid;
1194  }
1195  $this->db->free($resql);
1196 
1197  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1198  $sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".$this->db->sanitize(implode(",", $tab_resql)).")";
1199 
1200  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1201  $resql = $this->db->query($sql);
1202  if (!$resql) {
1203  $this->error = $this->db->error();
1204  $error++;
1205  }
1206  }
1207  }
1208 
1209  // Delete lines
1210  if (!$error) {
1211  // Delete contratdet extrafields
1212  $main = MAIN_DB_PREFIX.'contratdet';
1213  $ef = $main."_extrafields";
1214  $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1215 
1216  dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1217  $resql = $this->db->query($sql);
1218  if (!$resql) {
1219  $this->error = $this->db->error();
1220  $error++;
1221  }
1222  }
1223 
1224  if (!$error) {
1225  // Delete contratdet
1226  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1227  $sql .= " WHERE fk_contrat=".((int) $this->id);
1228 
1229  dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1230  $resql = $this->db->query($sql);
1231  if (!$resql) {
1232  $this->error = $this->db->error();
1233  $error++;
1234  }
1235  }
1236 
1237  // Delete llx_ecm_files
1238  if (!$error) {
1239  $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
1240  $resql = $this->db->query($sql);
1241  if (!$resql) {
1242  $this->error = $this->db->lasterror();
1243  $this->errors[] = $this->error;
1244  $error++;
1245  }
1246  }
1247 
1248  // Delete contract
1249  if (!$error) {
1250  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1251  $sql .= " WHERE rowid=".((int) $this->id);
1252 
1253  dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1254  $resql = $this->db->query($sql);
1255  if (!$resql) {
1256  $this->error = $this->db->error();
1257  $error++;
1258  }
1259  }
1260 
1261  // Removed extrafields
1262  if (!$error) {
1263  $result = $this->deleteExtraFields();
1264  if ($result < 0) {
1265  $error++;
1266  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1267  }
1268  }
1269 
1270  if (!$error) {
1271  // We remove directory
1272  $ref = dol_sanitizeFileName($this->ref);
1273  if ($conf->contrat->dir_output) {
1274  $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1275  if (file_exists($dir)) {
1276  $res = @dol_delete_dir_recursive($dir);
1277  if (!$res) {
1278  $this->error = 'ErrorFailToDeleteDir';
1279  $error++;
1280  }
1281  }
1282  }
1283  }
1284 
1285  if (!$error) {
1286  $this->db->commit();
1287  return 1;
1288  } else {
1289  $this->error = $this->db->lasterror();
1290  $this->db->rollback();
1291  return -1;
1292  }
1293  }
1294 
1302  public function update($user, $notrigger = 0)
1303  {
1304  global $conf, $langs;
1305  $error = 0;
1306 
1307  // Clean parameters
1308  if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1309  $this->fk_commercial_signature = $this->commercial_signature_id;
1310  }
1311  if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1312  $this->fk_commercial_suivi = $this->commercial_suivi_id;
1313  }
1314  if (empty($this->fk_soc) && $this->socid > 0) {
1315  $this->fk_soc = (int) $this->socid;
1316  }
1317  if (empty($this->fk_project) && $this->projet > 0) {
1318  $this->fk_project = (int) $this->projet;
1319  }
1320 
1321  if (isset($this->ref)) {
1322  $this->ref = trim($this->ref);
1323  }
1324  if (isset($this->ref_customer)) {
1325  $this->ref_customer = trim($this->ref_customer);
1326  }
1327  if (isset($this->ref_supplier)) {
1328  $this->ref_supplier = trim($this->ref_supplier);
1329  }
1330  if (isset($this->ref_ext)) {
1331  $this->ref_ext = trim($this->ref_ext);
1332  }
1333  if (isset($this->entity)) {
1334  $this->entity = (int) $this->entity;
1335  }
1336  if (isset($this->statut)) {
1337  $this->statut = (int) $this->statut;
1338  }
1339  if (isset($this->fk_soc)) {
1340  $this->fk_soc = (int) $this->fk_soc;
1341  }
1342  if (isset($this->fk_commercial_signature)) {
1343  $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1344  }
1345  if (isset($this->fk_commercial_suivi)) {
1346  $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
1347  }
1348  if (isset($this->note_private)) {
1349  $this->note_private = trim($this->note_private);
1350  }
1351  if (isset($this->note_public)) {
1352  $this->note_public = trim($this->note_public);
1353  }
1354  if (isset($this->import_key)) {
1355  $this->import_key = trim($this->import_key);
1356  }
1357  //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1358 
1359  // Check parameters
1360  // Put here code to add a control on parameters values
1361 
1362  // Update request
1363  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1364  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1365  $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1366  $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1367  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1368  $sql .= " entity=".$conf->entity.",";
1369  $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1370  $sql .= " statut=".(isset($this->statut) ? $this->statut : "null").",";
1371  $sql .= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc : "null").",";
1372  $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1373  $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1374  $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1375  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1376  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1377  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1378  //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null");
1379  $sql .= " WHERE rowid=".((int) $this->id);
1380 
1381  $this->db->begin();
1382 
1383  $resql = $this->db->query($sql);
1384  if (!$resql) {
1385  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1386  }
1387 
1388  if (!$error) {
1389  $result = $this->insertExtraFields();
1390  if ($result < 0) {
1391  $error++;
1392  }
1393  }
1394 
1395  if (!$error && !$notrigger) {
1396  // Call triggers
1397  $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1398  if ($result < 0) {
1399  $error++;
1400  }
1401  // End call triggers
1402  }
1403 
1404  // Commit or rollback
1405  if ($error) {
1406  foreach ($this->errors as $errmsg) {
1407  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1408  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1409  }
1410  $this->db->rollback();
1411  return -1 * $error;
1412  } else {
1413  $this->db->commit();
1414  return 1;
1415  }
1416  }
1417 
1418 
1442  public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0)
1443  {
1444  global $user, $langs, $conf, $mysoc;
1445  $error = 0;
1446 
1447  dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1448 
1449  // Check parameters
1450  if ($fk_product <= 0 && empty($desc)) {
1451  $this->error = "ErrorDescRequiredForFreeProductLines";
1452  return -1;
1453  }
1454 
1455  if ($this->statut >= 0) {
1456  // Clean parameters
1457  $pu_ht = price2num($pu_ht);
1458  $pu_ttc = price2num($pu_ttc);
1459  $pa_ht = price2num($pa_ht);
1460 
1461  // Clean vat code
1462  $reg = array();
1463  $vat_src_code = '';
1464  if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1465  $vat_src_code = $reg[1];
1466  $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1467  }
1468  $txtva = price2num($txtva);
1469  $txlocaltax1 = price2num($txlocaltax1);
1470  $txlocaltax2 = price2num($txlocaltax2);
1471 
1472  $remise_percent = price2num($remise_percent);
1473  $qty = price2num($qty);
1474  if (empty($qty)) {
1475  $qty = 1;
1476  }
1477  if (empty($info_bits)) {
1478  $info_bits = 0;
1479  }
1480  if (empty($pu_ht) || !is_numeric($pu_ht)) {
1481  $pu_ht = 0;
1482  }
1483  if (empty($pu_ttc)) {
1484  $pu_ttc = 0;
1485  }
1486  if (empty($txtva) || !is_numeric($txtva)) {
1487  $txtva = 0;
1488  }
1489  if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1490  $txlocaltax1 = 0;
1491  }
1492  if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1493  $txlocaltax2 = 0;
1494  }
1495 
1496  if ($price_base_type == 'HT') {
1497  $pu = $pu_ht;
1498  } else {
1499  $pu = $pu_ttc;
1500  }
1501 
1502  // Check parameters
1503  if (empty($remise_percent)) {
1504  $remise_percent = 0;
1505  }
1506  if (empty($rang)) {
1507  $rang = 0;
1508  }
1509 
1510  if ($date_start && $date_end && $date_start > $date_end) {
1511  $langs->load("errors");
1512  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1513  return -1;
1514  }
1515 
1516  $this->db->begin();
1517 
1518  $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1519 
1520  // Calcul du total TTC et de la TVA pour la ligne a partir de
1521  // qty, pu, remise_percent et txtva
1522  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1523  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1524 
1525  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1526  $total_ht = $tabprice[0];
1527  $total_tva = $tabprice[1];
1528  $total_ttc = $tabprice[2];
1529  $total_localtax1 = $tabprice[9];
1530  $total_localtax2 = $tabprice[10];
1531 
1532  $localtax1_type = $localtaxes_type[0];
1533  $localtax2_type = $localtaxes_type[2];
1534 
1535  // TODO A virer
1536  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1537  $remise = 0;
1538  $price = price2num(round($pu_ht, 2));
1539  if (dol_strlen($remise_percent) > 0) {
1540  $remise = round(($pu_ht * $remise_percent / 100), 2);
1541  $price = $pu_ht - $remise;
1542  }
1543 
1544  if (empty($pa_ht)) {
1545  $pa_ht = 0;
1546  }
1547 
1548 
1549  // if buy price not defined, define buyprice as configured in margin admin
1550  if ($this->pa_ht == 0) {
1551  if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) {
1552  return $result;
1553  } else {
1554  $pa_ht = $result;
1555  }
1556  }
1557 
1558  // Insertion dans la base
1559  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1560  $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1561  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1562  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1563  $sql .= " info_bits,";
1564  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1565  if ($date_start > 0) {
1566  $sql .= ",date_ouverture_prevue";
1567  }
1568  if ($date_end > 0) {
1569  $sql .= ",date_fin_validite";
1570  }
1571  $sql .= ", fk_unit";
1572  $sql .= ", rang";
1573  $sql .= ") VALUES (";
1574  $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1575  $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1576  $sql .= " ".((float) $qty).",";
1577  $sql .= " ".((float) $txtva).",";
1578  $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1579  $sql .= " ".((float) $txlocaltax1).",";
1580  $sql .= " ".((float) $txlocaltax2).",";
1581  $sql .= " '".$this->db->escape($localtax1_type)."',";
1582  $sql .= " '".$this->db->escape($localtax2_type)."',";
1583  $sql .= " ".price2num($remise_percent).",";
1584  $sql .= " ".price2num($pu_ht).",";
1585  $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1586  $sql .= " '".$this->db->escape($info_bits)."',";
1587  $sql .= " ".price2num($price).",".price2num($remise).",";
1588  if (isset($fk_fournprice)) {
1589  $sql .= ' '.((int) $fk_fournprice).',';
1590  } else {
1591  $sql .= ' null,';
1592  }
1593  if (isset($pa_ht)) {
1594  $sql .= ' '.price2num($pa_ht);
1595  } else {
1596  $sql .= ' null';
1597  }
1598  if ($date_start > 0) {
1599  $sql .= ",'".$this->db->idate($date_start)."'";
1600  }
1601  if ($date_end > 0) {
1602  $sql .= ",'".$this->db->idate($date_end)."'";
1603  }
1604  $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1605  $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1606  $sql .= ")";
1607 
1608  $resql = $this->db->query($sql);
1609  if ($resql) {
1610  $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1611 
1612  if (!$error) {
1613  $contractline = new ContratLigne($this->db);
1614  $contractline->array_options = $array_options;
1615  $contractline->id = $contractlineid;
1616  $result = $contractline->insertExtraFields();
1617  if ($result < 0) {
1618  $this->error[] = $contractline->error;
1619  $error++;
1620  }
1621  }
1622 
1623  if (empty($error)) {
1624  // Call trigger
1625  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1626  if ($result < 0) {
1627  $error++;
1628  }
1629  // End call triggers
1630  }
1631 
1632  if ($error) {
1633  $this->db->rollback();
1634  return -1;
1635  } else {
1636  $this->db->commit();
1637  return $contractlineid;
1638  }
1639  } else {
1640  $this->db->rollback();
1641  $this->error = $this->db->error()." sql=".$sql;
1642  return -1;
1643  }
1644  } else {
1645  dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1646  return -2;
1647  }
1648  }
1649 
1674  public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_start_real = '', $date_end_real = '', $price_base_type = 'HT', $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0)
1675  {
1676  global $user, $conf, $langs, $mysoc;
1677 
1678  $error = 0;
1679 
1680  // Clean parameters
1681  $qty = trim($qty);
1682  $desc = trim($desc);
1683  $desc = trim($desc);
1684  $price = price2num($pu);
1685  $tvatx = price2num($tvatx);
1686  $localtax1tx = price2num($localtax1tx);
1687  $localtax2tx = price2num($localtax2tx);
1688  $pa_ht = price2num($pa_ht);
1689  if (empty($fk_fournprice)) {
1690  $fk_fournprice = 0;
1691  }
1692  if (empty($rang)) {
1693  $rang = 0;
1694  }
1695 
1696  $subprice = $price;
1697  $remise = 0;
1698  if (dol_strlen($remise_percent) > 0) {
1699  $remise = round(($pu * $remise_percent / 100), 2);
1700  $price = $pu - $remise;
1701  } else {
1702  $remise_percent = 0;
1703  }
1704 
1705  if ($date_start && $date_end && $date_start > $date_end) {
1706  $langs->load("errors");
1707  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1708  return -1;
1709  }
1710 
1711  dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_start_real, $date_end_real, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits, $rang");
1712 
1713  $this->db->begin();
1714 
1715  // Calcul du total TTC et de la TVA pour la ligne a partir de
1716  // qty, pu, remise_percent et tvatx
1717  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1718  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1719 
1720  $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1721  $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1722 
1723  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1724  $total_ht = $tabprice[0];
1725  $total_tva = $tabprice[1];
1726  $total_ttc = $tabprice[2];
1727  $total_localtax1 = $tabprice[9];
1728  $total_localtax2 = $tabprice[10];
1729 
1730  $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1731  $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1732 
1733  // TODO A virer
1734  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1735  $remise = 0;
1736  $price = price2num(round($pu, 2));
1737  if (dol_strlen($remise_percent) > 0) {
1738  $remise = round(($pu * $remise_percent / 100), 2);
1739  $price = $pu - $remise;
1740  }
1741 
1742  if (empty($pa_ht)) {
1743  $pa_ht = 0;
1744  }
1745 
1746  // if buy price not defined, define buyprice as configured in margin admin
1747  if ($this->pa_ht == 0) {
1748  if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
1749  return $result;
1750  } else {
1751  $pa_ht = $result;
1752  }
1753  }
1754 
1755  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1756  $sql .= ",price_ht = ".((float) price2num($price));
1757  $sql .= ",subprice = ".((float) price2num($subprice));
1758  $sql .= ",remise = ".((float) price2num($remise));
1759  $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1760  $sql .= ",qty = ".((float) $qty);
1761  $sql .= ",tva_tx = ".((float) price2num($tvatx));
1762  $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1763  $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1764  $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1765  $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1766  $sql .= ", total_ht = ".((float) price2num($total_ht));
1767  $sql .= ", total_tva = ".((float) price2num($total_tva));
1768  $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1769  $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1770  $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1771  $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1772  $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1773  if ($date_start > 0) {
1774  $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1775  } else {
1776  $sql .= ",date_ouverture_prevue = null";
1777  }
1778  if ($date_end > 0) {
1779  $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1780  } else {
1781  $sql .= ",date_fin_validite = null";
1782  }
1783  if ($date_start_real > 0) {
1784  $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1785  } else {
1786  $sql .= ",date_ouverture = null";
1787  }
1788  if ($date_end_real > 0) {
1789  $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1790  } else {
1791  $sql .= ",date_cloture = null";
1792  }
1793  $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1794  $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1795  $sql .= " WHERE rowid = ".((int) $rowid);
1796 
1797  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1798  $result = $this->db->query($sql);
1799  if ($result) {
1800  if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1801  $contractline = new ContratLigne($this->db);
1802  $contractline->fetch($rowid);
1803 
1804  // We replace values in $contractline->array_options only for entries defined into $array_options
1805  foreach ($array_options as $key => $value) {
1806  $contractline->array_options[$key] = $array_options[$key];
1807  }
1808 
1809  $result = $contractline->insertExtraFields();
1810  if ($result < 0) {
1811  $this->error[] = $contractline->error;
1812  $error++;
1813  }
1814  }
1815 
1816  if (empty($error)) {
1817  // Call trigger
1818  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1819  if ($result < 0) {
1820  $this->db->rollback();
1821  return -3;
1822  }
1823  // End call triggers
1824 
1825  $this->db->commit();
1826  return 1;
1827  } else {
1828  $this->db->rollback();
1829  return -1;
1830  }
1831  } else {
1832  $this->db->rollback();
1833  $this->error = $this->db->error();
1834  dol_syslog(get_class($this)."::updateline Erreur -1");
1835  return -1;
1836  }
1837  }
1838 
1846  public function deleteline($idline, User $user)
1847  {
1848  global $conf, $langs;
1849 
1850  $error = 0;
1851 
1852  if ($this->statut >= 0) {
1853  // Call trigger
1854  $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1855  if ($result < 0) {
1856  return -1;
1857  }
1858  // End call triggers
1859 
1860  $this->db->begin();
1861 
1862  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1863  $sql .= " WHERE rowid = ".((int) $idline);
1864 
1865  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1866  $resql = $this->db->query($sql);
1867  if (!$resql) {
1868  $this->error = "Error ".$this->db->lasterror();
1869  $error++;
1870  }
1871 
1872  if (!$error) {
1873  // Remove extrafields
1874  $contractline = new ContratLigne($this->db);
1875  $contractline->id = $idline;
1876  $result = $contractline->deleteExtraFields();
1877  if ($result < 0) {
1878  $error++;
1879  $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1880  }
1881  }
1882 
1883  if (empty($error)) {
1884  $this->db->commit();
1885  return 1;
1886  } else {
1887  dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1888  $this->db->rollback();
1889  return -1;
1890  }
1891  } else {
1892  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1893  return -2;
1894  }
1895  }
1896 
1897 
1898  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1906  public function update_statut($user)
1907  {
1908  // phpcs:enable
1909  dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1910 
1911  // If draft, we keep it (should not happen)
1912  if ($this->statut == 0) {
1913  return 1;
1914  }
1915 
1916  // Load $this->lines array
1917  // $this->fetch_lines();
1918 
1919  // $newstatut=1;
1920  // foreach($this->lines as $key => $contractline)
1921  // {
1922  // // if ($contractline) // Loop on each service
1923  // }
1924 
1925  return 1;
1926  }
1927 
1928 
1935  public function getLibStatut($mode)
1936  {
1937  return $this->LibStatut($this->statut, $mode);
1938  }
1939 
1940  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1948  public function LibStatut($status, $mode)
1949  {
1950  // phpcs:enable
1951  global $langs;
1952 
1953  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1954  global $langs;
1955  $langs->load("contracts");
1956  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1957  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1958  $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1959  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1960  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1961  $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1962  }
1963 
1964  $statusType = 'status'.$status;
1965  if ($status == self::STATUS_VALIDATED) {
1966  $statusType = 'status6';
1967  }
1968 
1969  if ($mode == 4 || $mode == 6 || $mode == 7) {
1970  $text = '';
1971  if ($mode == 4) {
1972  $text = '<span class="hideonsmartphone">';
1973  $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
1974  $text .= ' '.$langs->trans("Services");
1975  $text .= ': &nbsp; &nbsp; ';
1976  $text .= '</span>';
1977  }
1978  $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
1979  $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1980  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1981  $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1982  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1983  $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1984  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1985  $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
1986  $text .= ($mode == 7 ? '</span>' : '');
1987  return $text;
1988  } else {
1989  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1990  }
1991  }
1992 
1999  public function getTooltipContentArray($params)
2000  {
2001  global $conf, $langs, $user;
2002 
2003  $langs->load('contracts');
2004 
2005  $datas = [];
2006  $nofetch = !empty($params['nofetch']);
2007 
2008  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2009  return ['optimize' => $langs->trans("ShowContract")];
2010  }
2011  if ($user->hasRight('contrat', 'lire')) {
2012  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2013  /* Status of a contract is status of all services, so disabled
2014  if (isset($this->statut)) {
2015  $label .= ' '.$this->getLibStatut(5);
2016  }*/
2017  $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2018  if (!$nofetch) {
2019  $langs->load('companies');
2020  if (empty($this->thirdparty)) {
2021  $this->fetch_thirdparty();
2022  }
2023  $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2024  }
2025  $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2026  if (!$nofetch) {
2027  $langs->load('project');
2028  if (empty($this->project)) {
2029  $res = $this->fetch_project();
2030  if ($res > 0) {
2031  $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
2032  }
2033  }
2034  }
2035  $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2036  if (!empty($this->total_ht)) {
2037  $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2038  }
2039  if (!empty($this->total_tva)) {
2040  $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2041  }
2042  if (!empty($this->total_ttc)) {
2043  $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2044  }
2045  }
2046  return $datas;
2047  }
2048 
2058  public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2059  {
2060  global $conf, $langs, $user, $hookmanager;
2061 
2062  $result = '';
2063 
2064  $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2065 
2066  //if ($option !== 'nolink')
2067  //{
2068  // Add param to save lastsearch_values or not
2069  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2070  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2071  $add_save_lastsearch_values = 1;
2072  }
2073  if ($add_save_lastsearch_values) {
2074  $url .= '&save_lastsearch_values=1';
2075  }
2076  //}
2077  $params = [
2078  'id' => $this->id,
2079  'objecttype' => $this->element,
2080  'nofetch' => 1,
2081  ];
2082  $classfortooltip = 'classfortooltip';
2083  $dataparams = '';
2084  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2085  $classfortooltip = 'classforajaxtooltip';
2086  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2087  $label = '';
2088  } else {
2089  $label = implode($this->getTooltipContentArray($params));
2090  }
2091 
2092  $linkclose = '';
2093  if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2094  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2095  $label = $langs->trans("ShowContract");
2096  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2097  }
2098  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2099  $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2100  }
2101  $linkstart = '<a href="'.$url.'"';
2102  $linkstart .= $linkclose.'>';
2103  $linkend = '</a>';
2104 
2105  $result .= $linkstart;
2106  if ($withpicto) {
2107  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
2108  }
2109  if ($withpicto != 2) {
2110  $result .= ($this->ref ? $this->ref : $this->id);
2111  }
2112  $result .= $linkend;
2113 
2114  global $action;
2115  $hookmanager->initHooks(array('contractdao'));
2116  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2117  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2118  if ($reshook > 0) {
2119  $result = $hookmanager->resPrint;
2120  } else {
2121  $result .= $hookmanager->resPrint;
2122  }
2123 
2124  return $result;
2125  }
2126 
2133  public function info($id)
2134  {
2135  $sql = "SELECT c.rowid, c.ref, c.datec,";
2136  $sql .= " c.tms as date_modification,";
2137  $sql .= " fk_user_author";
2138  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2139  $sql .= " WHERE c.rowid = ".((int) $id);
2140 
2141  $result = $this->db->query($sql);
2142  if ($result) {
2143  if ($this->db->num_rows($result)) {
2144  $obj = $this->db->fetch_object($result);
2145 
2146  $this->id = $obj->rowid;
2147 
2148  if ($obj->fk_user_author) {
2149  $cuser = new User($this->db);
2150  $cuser->fetch($obj->fk_user_author);
2151  $this->user_creation = $cuser;
2152  }
2153 
2154  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2155  $this->date_creation = $this->db->jdate($obj->datec);
2156  $this->date_modification = $this->db->jdate($obj->date_modification);
2157  }
2158 
2159  $this->db->free($result);
2160  } else {
2161  dol_print_error($this->db);
2162  }
2163  }
2164 
2165  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2172  public function array_detail($status = -1)
2173  {
2174  // phpcs:enable
2175  $tab = array();
2176 
2177  $sql = "SELECT cd.rowid";
2178  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2179  $sql .= " WHERE fk_contrat =".((int) $this->id);
2180  if ($status >= 0) {
2181  $sql .= " AND statut = ".((int) $status);
2182  }
2183 
2184  dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2185  $resql = $this->db->query($sql);
2186  if ($resql) {
2187  $num = $this->db->num_rows($resql);
2188  $i = 0;
2189  while ($i < $num) {
2190  $obj = $this->db->fetch_object($resql);
2191  $tab[$i] = $obj->rowid;
2192  $i++;
2193  }
2194  return $tab;
2195  } else {
2196  $this->error = $this->db->error();
2197  return -1;
2198  }
2199  }
2200 
2210  public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2211  {
2212  $tab = array();
2213 
2214  $sql = "SELECT c.rowid";
2215  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2216  if (!empty($product_categories)) {
2217  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2218  $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = cd.fk_product AND cp.fk_categorie IN (".$this->db->sanitize(implode(', ', $product_categories)).")";
2219  }
2220  $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2221  $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2222  $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2223  $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2224  $sql .= " GROUP BY c.rowid";
2225 
2226  dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2227  $resql = $this->db->query($sql);
2228  if ($resql) {
2229  $num = $this->db->num_rows($resql);
2230  $i = 0;
2231  while ($i < $num) {
2232  $obj = $this->db->fetch_object($resql);
2233  $contrat = new Contrat($this->db);
2234  $contrat->fetch($obj->rowid);
2235  $tab[$contrat->id] = $contrat;
2236  $i++;
2237  }
2238  return $tab;
2239  } else {
2240  $this->error = $this->db->lasterror();
2241  return -1;
2242  }
2243  }
2244 
2245 
2246  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2254  public function load_board($user, $mode)
2255  {
2256  // phpcs:enable
2257  global $conf, $langs;
2258 
2259  $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2260  $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2261  $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2262  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2263  $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2264  }
2265 
2266  if ($mode == 'inactive') {
2267  $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2268  $sql .= $this->from;
2269  $sql .= " WHERE c.statut = 1";
2270  $sql .= " AND c.rowid = cd.fk_contrat";
2271  $sql .= " AND cd.statut = 0";
2272  } elseif ($mode == 'expired') {
2273  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2274  $sql .= $this->from;
2275  $sql .= " WHERE c.statut = 1";
2276  $sql .= " AND c.rowid = cd.fk_contrat";
2277  $sql .= " AND cd.statut = 4";
2278  $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2279  } elseif ($mode == 'active') {
2280  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2281  $sql .= $this->from;
2282  $sql .= " WHERE c.statut = 1";
2283  $sql .= " AND c.rowid = cd.fk_contrat";
2284  $sql .= " AND cd.statut = 4";
2285  //$datetouse = dol_now();
2286  //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2287  }
2288  $sql .= " AND c.fk_soc = s.rowid";
2289  $sql .= " AND c.entity = ".((int) $conf->entity);
2290  if ($user->socid) {
2291  $sql .= " AND c.fk_soc = ".((int) $user->socid);
2292  }
2293  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2294  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2295  }
2296 
2297  $resql = $this->db->query($sql);
2298  if ($resql) {
2299  $langs->load("contracts");
2300  $now = dol_now();
2301 
2302  if ($mode == 'inactive') {
2303  $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2304  $label = $langs->trans("BoardNotActivatedServices");
2305  $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2306  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2307  } elseif ($mode == 'expired') {
2308  $warning_delay = $conf->contrat->services->expires->warning_delay;
2309  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2310  $label = $langs->trans("BoardExpiredServices");
2311  $labelShort = $langs->trans("BoardExpiredServicesShort");
2312  } else {
2313  $warning_delay = $conf->contrat->services->expires->warning_delay;
2314  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2315  //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
2316  //if ($warning_delay >= 0) $url.='&amp;filter=expired';
2317  $label = $langs->trans("BoardRunningServices");
2318  $labelShort = $langs->trans("BoardRunningServicesShort");
2319  }
2320 
2321  $response = new WorkboardResponse();
2322  $response->warning_delay = $warning_delay / 60 / 60 / 24;
2323  $response->label = $label;
2324  $response->labelShort = $labelShort;
2325  $response->url = $url;
2326  $response->img = img_object('', "contract");
2327 
2328  while ($obj = $this->db->fetch_object($resql)) {
2329  $response->nbtodo++;
2330 
2331  if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2332  $response->nbtodolate++;
2333  }
2334  }
2335 
2336  return $response;
2337  } else {
2338  dol_print_error($this->db);
2339  $this->error = $this->db->error();
2340  return -1;
2341  }
2342  }
2343 
2344  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2350  public function load_state_board()
2351  {
2352  // phpcs:enable
2353  global $conf, $user;
2354 
2355  $this->nb = array();
2356  $clause = "WHERE";
2357 
2358  $sql = "SELECT count(c.rowid) as nb";
2359  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2360  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2361  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2362  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2363  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2364  $clause = "AND";
2365  }
2366  $sql .= " ".$clause." c.entity = ".$conf->entity;
2367 
2368  $resql = $this->db->query($sql);
2369  if ($resql) {
2370  while ($obj = $this->db->fetch_object($resql)) {
2371  $this->nb["contracts"] = $obj->nb;
2372  }
2373  $this->db->free($resql);
2374  return 1;
2375  } else {
2376  dol_print_error($this->db);
2377  $this->error = $this->db->error();
2378  return -1;
2379  }
2380  }
2381 
2382 
2383  /* gestion des contacts d'un contrat */
2384 
2390  public function getIdBillingContact()
2391  {
2392  return $this->getIdContact('external', 'BILLING');
2393  }
2394 
2400  public function getIdServiceContact()
2401  {
2402  return $this->getIdContact('external', 'SERVICE');
2403  }
2404 
2405 
2413  public function initAsSpecimen()
2414  {
2415  global $user, $langs, $conf;
2416 
2417  // Load array of products prodids
2418  $num_prods = 0;
2419  $prodids = array();
2420  $sql = "SELECT rowid";
2421  $sql .= " FROM ".MAIN_DB_PREFIX."product";
2422  $sql .= " WHERE entity IN (".getEntity('product').")";
2423  $sql .= " AND tosell = 1";
2424  $sql .= $this->db->plimit(100);
2425 
2426  $resql = $this->db->query($sql);
2427  if ($resql) {
2428  $num_prods = $this->db->num_rows($resql);
2429  $i = 0;
2430  while ($i < $num_prods) {
2431  $i++;
2432  $row = $this->db->fetch_row($resql);
2433  $prodids[$i] = $row[0];
2434  }
2435  }
2436 
2437  // Initialise parametres
2438  $this->id = 0;
2439  $this->specimen = 1;
2440 
2441  $this->ref = 'SPECIMEN';
2442  $this->ref_customer = 'SPECIMENCUST';
2443  $this->ref_supplier = 'SPECIMENSUPP';
2444  $this->socid = 1;
2445  $this->statut = 0;
2446  $this->date_creation = (dol_now() - 3600 * 24 * 7);
2447  $this->date_contrat = dol_now();
2448  $this->commercial_signature_id = 1;
2449  $this->commercial_suivi_id = 1;
2450  $this->note_private = 'This is a comment (private)';
2451  $this->note_public = 'This is a comment (public)';
2452  $this->fk_projet = 0;
2453  // Lines
2454  $nbp = 5;
2455  $xnbp = 0;
2456  while ($xnbp < $nbp) {
2457  $line = new ContratLigne($this->db);
2458  $line->qty = 1;
2459  $line->subprice = 100;
2460  $line->price = 100;
2461  $line->tva_tx = 19.6;
2462  $line->remise_percent = 10;
2463  $line->total_ht = 90;
2464  $line->total_ttc = 107.64; // 90 * 1.196
2465  $line->total_tva = 17.64;
2466  $line->date_start = dol_now() - 500000;
2467  $line->date_start_real = dol_now() - 200000;
2468  $line->date_end = dol_now() + 500000;
2469  $line->date_end_real = dol_now() - 100000;
2470  if ($num_prods > 0) {
2471  $prodid = mt_rand(1, $num_prods);
2472  $line->fk_product = $prodids[$prodid];
2473  }
2474  $this->lines[$xnbp] = $line;
2475  $xnbp++;
2476  }
2477  }
2478 
2484  public function getLinesArray()
2485  {
2486  return $this->fetch_lines();
2487  }
2488 
2489 
2501  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2502  {
2503  global $conf, $langs;
2504 
2505  if (!dol_strlen($modele)) {
2506  $modele = ''; // No doc template/generation by default
2507 
2508  if (!empty($this->model_pdf)) {
2509  $modele = $this->model_pdf;
2510  } elseif (!empty($this->modelpdf)) { // deprecated
2511  $modele = $this->modelpdf;
2512  } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
2513  $modele = $conf->global->CONTRACT_ADDON_PDF;
2514  }
2515  }
2516 
2517  if (empty($modele)) {
2518  return 0;
2519  } else {
2520  $langs->load("contracts");
2521  $outputlangs->load("products");
2522 
2523  $modelpath = "core/modules/contract/doc/";
2524  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2525  }
2526  }
2527 
2536  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2537  {
2538  $tables = array(
2539  'contrat'
2540  );
2541 
2542  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2543  }
2544 
2553  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2554  {
2555  $tables = array(
2556  'contratdet'
2557  );
2558 
2559  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2560  }
2561 
2570  public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2571  {
2572  global $db, $langs, $conf, $hookmanager, $extrafields;
2573 
2574  dol_include_once('/projet/class/project.class.php');
2575 
2576  $error = 0;
2577 
2578  $this->fetch($this->id);
2579 
2580  // Load dest object
2581  $clonedObj = clone $this;
2582  $clonedObj->socid = $socid;
2583 
2584  $this->db->begin();
2585 
2586  $objsoc = new Societe($this->db);
2587 
2588  $objsoc->fetch($clonedObj->socid);
2589 
2590  // Clean data
2591  $clonedObj->statut = 0;
2592  // Clean extrafields
2593  if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2594  $extrafields->fetch_name_optionals_label($this->table_element);
2595  foreach ($clonedObj->array_options as $key => $option) {
2596  $shortkey = preg_replace('/options_/', '', $key);
2597  //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2598  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2599  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2600  unset($clonedObj->array_options[$key]);
2601  }
2602  }
2603  }
2604 
2605  if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
2606  $this->error = 'ErrorSetupNotComplete';
2607  dol_syslog($this->error);
2608  return -1;
2609  }
2610 
2611  // Set ref
2612  require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
2613  $obj = $conf->global->CONTRACT_ADDON;
2614  $modContract = new $obj();
2615  $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2616 
2617  // get extrafields so they will be clone
2618  foreach ($this->lines as $line) {
2619  $line->fetch_optionals($line->id);
2620  }
2621 
2622  // Create clone
2623  $clonedObj->context['createfromclone'] = 'createfromclone';
2624  $result = $clonedObj->create($user);
2625  if ($result < 0) {
2626  $error++;
2627  $this->error = $clonedObj->error;
2628  $this->errors[] = $clonedObj->error;
2629  } else {
2630  // copy external contacts if same company
2631  if ($this->socid == $clonedObj->socid) {
2632  if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2633  $error++;
2634  }
2635  }
2636  }
2637 
2638  if (!$error) {
2639  foreach ($this->lines as $line) {
2640  $result = $clonedObj->addline($line->description, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit, $line->rang);
2641  if ($result < 0) {
2642  $error++;
2643  $this->error = $clonedObj->error;
2644  $this->errors[] = $clonedObj->error;
2645  }
2646  }
2647  }
2648 
2649  if (!$error) {
2650  // Hook of thirdparty module
2651  if (is_object($hookmanager)) {
2652  $parameters = array(
2653  'objFrom' => $this,
2654  'clonedObj' => $clonedObj
2655  );
2656  $action = '';
2657  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2658  if ($reshook < 0) {
2659  $this->setErrorsFromObject($hookmanager);
2660  $error++;
2661  }
2662  }
2663  }
2664 
2665  unset($clonedObj->context['createfromclone']);
2666 
2667  // End
2668  if (!$error) {
2669  $this->db->commit();
2670  return $clonedObj->id;
2671  } else {
2672  $this->db->rollback();
2673  return -1;
2674  }
2675  }
2676 
2677 
2687  public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2688  {
2689  global $langs, $user;
2690 
2691  $langs->load("agenda");
2692 
2693  $now = dol_now();
2694 
2695  $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2696 
2697  $error = 0;
2698  $this->output = '';
2699  $this->error='';
2700 
2701  $contractlineprocessed = array();
2702  $contractignored = array();
2703  $contracterror = array();
2704 
2705  dol_syslog(__METHOD__, LOG_DEBUG);
2706 
2707  $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2708  $sql.= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2709  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2710  $sql.= ' WHERE cd.fk_contrat = c.rowid';
2711  $sql.= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2712  $sql.= " AND cd.statut = 4";
2713  if ($thirdparty_id > 0) $sql.=" AND c.fk_soc = ".((int) $thirdparty_id);
2714  //print $sql;
2715 
2716  $resql = $this->db->query($sql);
2717  if ($resql) {
2718  $num = $this->db->num_rows($resql);
2719 
2720  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2721 
2722  $i=0;
2723  while ($i < $num) {
2724  $obj = $this->db->fetch_object($resql);
2725  if ($obj) {
2726  if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2727  continue;
2728  }
2729 
2730  // Load contract
2731  $object = new Contrat($this->db);
2732  $object->fetch($obj->rowid); // fetch also lines
2733  $object->fetch_thirdparty();
2734 
2735  if ($object->id <= 0) {
2736  $error++;
2737  $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2738  continue;
2739  }
2740 
2741  dol_syslog("* Process contract line in doRenewalContracts for contract id=".$object->id." ref=".$object->ref." ref_customer=".$object->ref_customer." contract line id=".$obj->lid);
2742 
2743  // Update expiration date of line
2744  $expirationdate = $this->db->jdate($obj->date_fin_validite);
2745  $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2746  $duration_unit = preg_replace('/\d/', '', $obj->duration);
2747  //var_dump($expirationdate.' '.$enddatetoscan);
2748 
2749  // Test if there is pending invoice
2750  $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2751 
2752  if (is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2753  usort($object->linkedObjects['facture'], "cmp");
2754 
2755  //dol_sort_array($contract->linkedObjects['facture'], 'date');
2756  $someinvoicenotpaid=0;
2757  foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2758  if ($invoice->statut == Facture::STATUS_DRAFT) continue; // Draft invoice are not invoice not paid
2759 
2760  if (empty($invoice->paye)) {
2761  $someinvoicenotpaid++;
2762  }
2763  }
2764  if ($someinvoicenotpaid) {
2765  $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2766  $contractignored[$object->id]=$object->ref;
2767  continue;
2768  }
2769  }
2770 
2771  if ($expirationdate && $expirationdate < $enddatetoscan) {
2772  dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2773  $newdate = $expirationdate;
2774  $protecti=0; //$protecti is to avoid infinite loop
2775  while ($newdate < $enddatetoscan && $protecti < 1000) {
2776  $newdate = dol_time_plus_duree($newdate, $duration_value, $duration_unit);
2777  $protecti++;
2778  }
2779 
2780  if ($protecti < 1000) { // If not, there is a pb
2781  // We will update the end of date of contrat, so first we refresh contract data
2782  dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2783 
2784  $this->db->begin();
2785 
2786  $errorforlocaltransaction = 0;
2787 
2788  $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2789  $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2790 
2791  $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2792  $sqlupdate.= ' WHERE rowid = '.((int) $obj->lid);
2793  $resqlupdate = $this->db->query($sqlupdate);
2794  if ($resqlupdate) {
2795  $contractlineprocessed[$obj->lid]=$object->ref;
2796 
2797  $actioncode = 'RENEW_CONTRACT';
2798  $now = dol_now();
2799 
2800  // Create an event
2801  $actioncomm = new ActionComm($this->db);
2802  $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2803  $actioncomm->code = 'AC_'.$actioncode;
2804  $actioncomm->label = $label;
2805  $actioncomm->datep = $now;
2806  $actioncomm->datef = $now;
2807  $actioncomm->percentage = -1; // Not applicable
2808  $actioncomm->socid = $object->thirdparty->id;
2809  $actioncomm->authorid = $user->id; // User saving action
2810  $actioncomm->userownerid = $user->id; // Owner of action
2811  $actioncomm->fk_element = $object->id;
2812  $actioncomm->elementtype = 'contract';
2813  $actioncomm->note_private = $comment;
2814 
2815  $ret = $actioncomm->create($user); // User creating action
2816  } else {
2817  $contracterror[$object->id]=$object->ref;
2818 
2819  $error++;
2820  $errorforlocaltransaction++;
2821  $this->error = $this->db->lasterror();
2822  }
2823 
2824  if (! $errorforlocaltransaction) {
2825  $this->db->commit();
2826  } else {
2827  $this->db->rollback();
2828  }
2829  } else {
2830  $error++;
2831  $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2832  dol_syslog($this->error, LOG_ERR);
2833  }
2834  }
2835  }
2836  $i++;
2837  }
2838  } else {
2839  $error++;
2840  $this->error = $this->db->lasterror();
2841  }
2842 
2843  $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed)>0 ? ' : '.join(',', $contractlineprocessed) : '');
2844 
2845  return ($error ? 1: 0);
2846  }
2847 
2855  public function getKanbanView($option = '', $arraydata = null)
2856  {
2857  global $langs;
2858 
2859  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2860 
2861  $return = '<div class="box-flex-item box-flex-grow-zero">';
2862  $return .= '<div class="info-box info-box-sm">';
2863  $return .= '<span class="info-box-icon bg-infobox-action">';
2864  $return .= img_picto('', $this->picto);
2865  $return .= '</span>';
2866  $return .= '<div class="info-box-content">';
2867  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2868  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2869  if (!empty($arraydata['thirdparty'])) {
2870  $tmpthirdparty = $arraydata['thirdparty'];
2871  $return .= '<br><div class="info-box-label inline-block">'.$tmpthirdparty->getNomUrl(1).'</div>';
2872  }
2873  if (property_exists($this, 'date_contrat')) {
2874  $return .= '<br><span class="opacitymedium">'.$langs->trans("DateContract").' : </span><span class="info-box-label">'.dol_print_date($this->date_contrat, 'day').'</span>';
2875  }
2876  if (method_exists($this, 'getLibStatut')) {
2877  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(7).'</div>';
2878  }
2879  $return .= '</div>';
2880  $return .= '</div>';
2881  $return .= '</div>';
2882  return $return;
2883  }
2884 }
2885 
2886 
2891 {
2895  public $element = 'contratdet';
2896 
2900  public $table_element = 'contratdet';
2901 
2906  public $element_for_permission = 'contrat';
2907 
2911  public $id;
2912 
2916  public $ref;
2917 
2918  public $tms;
2919 
2923  public $fk_contrat;
2924 
2928  public $fk_product;
2929 
2930  public $statut; // 0 inactive, 4 active, 5 closed
2931  public $type; // 0 for product, 1 for service
2932 
2937  public $label;
2938 
2943  public $libelle;
2944 
2948  public $description;
2949 
2950  public $product_type; // 0 for product, 1 for service
2951  public $product_ref;
2952  public $product_label;
2953 
2954  public $date_commande;
2955 
2956  public $date_start; // date start planned
2957  public $date_start_real; // date start real
2958  public $date_end; // date end planned
2959  public $date_end_real; // date end real
2960 
2961  public $tva_tx;
2962  public $vat_src_code;
2963  public $localtax1_tx;
2964  public $localtax2_tx;
2965  public $localtax1_type; // Local tax 1 type
2966  public $localtax2_type; // Local tax 2 type
2967  public $qty;
2968  public $remise_percent;
2969  public $remise;
2970 
2974  public $fk_remise_except;
2975 
2976  public $subprice; // Unit price HT
2977 
2983  public $price;
2984 
2985  public $price_ht;
2986 
2987  public $total_ht;
2988  public $total_tva;
2989  public $total_localtax1;
2990  public $total_localtax2;
2991  public $total_ttc;
2992 
2996  public $fk_fournprice;
2997 
2998  public $pa_ht;
2999 
3000  public $info_bits;
3001 
3005  public $fk_user_author;
3006 
3010  public $fk_user_ouverture;
3011 
3015  public $fk_user_cloture;
3016 
3017  public $commentaire;
3018 
3019 
3023  public $rang = 0;
3024 
3025 
3026  const STATUS_INITIAL = 0;
3027  const STATUS_OPEN = 4;
3028  const STATUS_CLOSED = 5;
3029 
3030 
3031  // BEGIN MODULEBUILDER PROPERTIES
3035  public $fields = array(
3036  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
3037  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
3038  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
3039  'qty' =>array('type'=>'integer', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>35, 'isameasure'=>1),
3040  'total_ht' =>array('type'=>'integer', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>36, 'isameasure'=>1),
3041  'total_tva' =>array('type'=>'integer', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>37, 'isameasure'=>1),
3042  'total_ttc' =>array('type'=>'integer', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>38, 'isameasure'=>1),
3043  //'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
3044  //'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3045  'fk_contrat' =>array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'Contract', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3046  'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
3047  //'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
3048  'note_private' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
3049  'note_public' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
3050  //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
3051  //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
3052  //'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
3053  'fk_user_ouverture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserStartingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3054  'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3055  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 4=>'Open', 5=>'Closed')),
3056  'rang' =>array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'position'=>500, 'default' =>0)
3057  );
3058  // END MODULEBUILDER PROPERTIES
3059 
3060 
3066  public function __construct($db)
3067  {
3068  $this->db = $db;
3069  }
3070 
3071 
3078  public function getLibStatut($mode)
3079  {
3080  return $this->LibStatut($this->statut, $mode, ((!empty($this->date_end)) ? ($this->date_end < dol_now() ? 1 : 0) : -1));
3081  }
3082 
3083  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3093  public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
3094  {
3095  // phpcs:enable
3096  global $langs;
3097  $langs->load("contracts");
3098 
3099  if ($status == self::STATUS_INITIAL) {
3100  $labelStatus = $langs->transnoentities("ServiceStatusInitial");
3101  $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
3102  } elseif ($status == self::STATUS_OPEN && $expired == -1) {
3103  $labelStatus = $langs->transnoentities("ServiceStatusRunning");
3104  $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
3105  } elseif ($status == self::STATUS_OPEN && $expired == 0) {
3106  $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
3107  $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
3108  } elseif ($status == self::STATUS_OPEN && $expired == 1) {
3109  $labelStatus = $langs->transnoentities("ServiceStatusLate");
3110  $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
3111  } elseif ($status == self::STATUS_CLOSED) {
3112  $labelStatus = $langs->transnoentities("ServiceStatusClosed");
3113  $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
3114  }
3115 
3116  $statusType = 'status'.$status;
3117  if ($status == self::STATUS_OPEN && $expired == 1) {
3118  $statusType = 'status1';
3119  }
3120  if ($status == self::STATUS_CLOSED) {
3121  $statusType = 'status6';
3122  }
3123 
3124  $params = array(); $reg = array();
3125  if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
3126  $params = array('badgeParams'=>array('css' => $reg[1]));
3127  }
3128  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
3129  }
3130 
3137  public function getTooltipContentArray($params)
3138  {
3139  global $conf, $langs, $user;
3140 
3141  $datas = [];
3142  $datas['label'] = $langs->trans("ShowContractOfService").': '.$this->label;
3143  if (empty($datas['label'])) {
3144  $datas['label'] = $this->description;
3145  }
3146 
3147  return $datas;
3148  }
3149 
3157  public function getNomUrl($withpicto = 0, $maxlength = 0)
3158  {
3159  global $langs;
3160 
3161  $result = '';
3162  $label = $langs->trans("ShowContractOfService").': '.$this->label;
3163  if (empty($label)) {
3164  $label = $this->description;
3165  }
3166  $classfortooltip = 'classfortooltip';
3167  $dataparams = '';
3168  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3169  $params = [
3170  'id' => $this->fk_contrat,
3171  'objecttype' => $this->element,
3172  ];
3173  $classfortooltip = 'classforajaxtooltip';
3174  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3175  $label = '';
3176  }
3177 
3178  $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'"';
3179  $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3180  $link .= $dataparams.' class="'.$classfortooltip.'">';
3181  $linkend = '</a>';
3182 
3183  $picto = 'service';
3184  if ($this->type == 0) {
3185  $picto = 'product';
3186  }
3187 
3188  if ($withpicto) {
3189  $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
3190  }
3191  if ($withpicto && $withpicto != 2) {
3192  $result .= ' ';
3193  }
3194  if ($withpicto != 2) {
3195  $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
3196  }
3197  return $result;
3198  }
3199 
3207  public function fetch($id, $ref = '')
3208  {
3209  // Check parameters
3210  if (empty($id) && empty($ref)) {
3211  return -1;
3212  }
3213 
3214  $sql = "SELECT";
3215  $sql .= " t.rowid,";
3216  $sql .= " t.tms,";
3217  $sql .= " t.fk_contrat,";
3218  $sql .= " t.fk_product,";
3219  $sql .= " t.statut,";
3220  $sql .= " t.label,"; // This field is not used. Only label of product
3221  $sql .= " p.ref as product_ref,";
3222  $sql .= " p.label as product_label,";
3223  $sql .= " p.description as product_desc,";
3224  $sql .= " p.fk_product_type as product_type,";
3225  $sql .= " t.description,";
3226  $sql .= " t.date_commande,";
3227  $sql .= " t.date_ouverture_prevue as date_start,";
3228  $sql .= " t.date_ouverture as date_start_real,";
3229  $sql .= " t.date_fin_validite as date_end,";
3230  $sql .= " t.date_cloture as date_end_real,";
3231  $sql .= " t.tva_tx,";
3232  $sql .= " t.vat_src_code,";
3233  $sql .= " t.localtax1_tx,";
3234  $sql .= " t.localtax2_tx,";
3235  $sql .= " t.localtax1_type,";
3236  $sql .= " t.localtax2_type,";
3237  $sql .= " t.qty,";
3238  $sql .= " t.remise_percent,";
3239  $sql .= " t.remise,";
3240  $sql .= " t.fk_remise_except,";
3241  $sql .= " t.subprice,";
3242  $sql .= " t.price_ht,";
3243  $sql .= " t.total_ht,";
3244  $sql .= " t.total_tva,";
3245  $sql .= " t.total_localtax1,";
3246  $sql .= " t.total_localtax2,";
3247  $sql .= " t.total_ttc,";
3248  $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
3249  $sql .= " t.buy_price_ht as pa_ht,";
3250  $sql .= " t.info_bits,";
3251  $sql .= " t.fk_user_author,";
3252  $sql .= " t.fk_user_ouverture,";
3253  $sql .= " t.fk_user_cloture,";
3254  $sql .= " t.commentaire,";
3255  $sql .= " t.fk_unit,";
3256  $sql .= " t.rang";
3257  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
3258  if ($id) {
3259  $sql .= " WHERE t.rowid = ".((int) $id);
3260  }
3261  if ($ref) {
3262  $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
3263  }
3264 
3265  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
3266  $resql = $this->db->query($sql);
3267  if ($resql) {
3268  if ($this->db->num_rows($resql)) {
3269  $obj = $this->db->fetch_object($resql);
3270 
3271  $this->id = $obj->rowid;
3272  $this->ref = $obj->rowid;
3273 
3274  $this->tms = $this->db->jdate($obj->tms);
3275  $this->fk_contrat = $obj->fk_contrat;
3276  $this->fk_product = $obj->fk_product;
3277  $this->statut = $obj->statut;
3278  $this->product_ref = $obj->product_ref;
3279  $this->product_label = $obj->product_label;
3280  $this->product_description = $obj->product_description;
3281  $this->product_type = $obj->product_type;
3282  $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
3283  $this->description = $obj->description;
3284  $this->date_commande = $this->db->jdate($obj->date_commande);
3285 
3286  $this->date_start = $this->db->jdate($obj->date_start);
3287  $this->date_start_real = $this->db->jdate($obj->date_start_real);
3288  $this->date_end = $this->db->jdate($obj->date_end);
3289  $this->date_end_real = $this->db->jdate($obj->date_end_real);
3290  // For backward compatibility
3291  //$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
3292  //$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
3293  //$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
3294  //$this->date_cloture = $this->db->jdate($obj->date_cloture);
3295 
3296  $this->tva_tx = $obj->tva_tx;
3297  $this->vat_src_code = $obj->vat_src_code;
3298  $this->localtax1_tx = $obj->localtax1_tx;
3299  $this->localtax2_tx = $obj->localtax2_tx;
3300  $this->localtax1_type = $obj->localtax1_type;
3301  $this->localtax2_type = $obj->localtax2_type;
3302  $this->qty = $obj->qty;
3303  $this->remise_percent = $obj->remise_percent;
3304  $this->fk_remise_except = $obj->fk_remise_except;
3305  $this->subprice = $obj->subprice;
3306  $this->price_ht = $obj->price_ht;
3307  $this->total_ht = $obj->total_ht;
3308  $this->total_tva = $obj->total_tva;
3309  $this->total_localtax1 = $obj->total_localtax1;
3310  $this->total_localtax2 = $obj->total_localtax2;
3311  $this->total_ttc = $obj->total_ttc;
3312  $this->info_bits = $obj->info_bits;
3313  $this->fk_user_author = $obj->fk_user_author;
3314  $this->fk_user_ouverture = $obj->fk_user_ouverture;
3315  $this->fk_user_cloture = $obj->fk_user_cloture;
3316  $this->commentaire = $obj->commentaire;
3317  $this->fk_fournprice = $obj->fk_fournprice;
3318 
3319  $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
3320  $this->pa_ht = $marginInfos[0];
3321  $this->fk_unit = $obj->fk_unit;
3322 
3323  $this->rang = $obj->rang;
3324 
3325  $this->fetch_optionals();
3326  }
3327 
3328  $this->db->free($resql);
3329 
3330  return 1;
3331  } else {
3332  $this->error = "Error ".$this->db->lasterror();
3333  return -1;
3334  }
3335  }
3336 
3337 
3345  public function update($user, $notrigger = 0)
3346  {
3347  global $conf, $langs, $mysoc;
3348 
3349  $error = 0;
3350 
3351  // Clean parameters
3352  $this->fk_contrat = (int) $this->fk_contrat;
3353  $this->fk_product = (int) $this->fk_product;
3354  $this->statut = (int) $this->statut;
3355  $this->label = trim($this->label);
3356  $this->description = trim($this->description);
3357  $this->vat_src_code = trim($this->vat_src_code);
3358  $this->tva_tx = trim($this->tva_tx);
3359  $this->localtax1_tx = trim($this->localtax1_tx);
3360  $this->localtax2_tx = trim($this->localtax2_tx);
3361  $this->qty = trim($this->qty);
3362  $this->remise_percent = trim($this->remise_percent);
3363  $this->fk_remise_except = (int) $this->fk_remise_except;
3364  $this->subprice = price2num($this->subprice);
3365  $this->price_ht = price2num($this->price_ht);
3366  $this->total_ht = trim($this->total_ht);
3367  $this->total_tva = trim($this->total_tva);
3368  $this->total_localtax1 = trim($this->total_localtax1);
3369  $this->total_localtax2 = trim($this->total_localtax2);
3370  $this->total_ttc = trim($this->total_ttc);
3371  $this->info_bits = trim($this->info_bits);
3372  $this->fk_user_author = (int) $this->fk_user_author;
3373  $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
3374  $this->fk_user_cloture = (int) $this->fk_user_cloture;
3375  $this->commentaire = trim($this->commentaire);
3376  $this->rang = (int) $this->rang;
3377  //if (empty($this->subprice)) $this->subprice = 0;
3378  if (empty($this->price_ht)) {
3379  $this->price_ht = 0;
3380  }
3381  if (empty($this->total_ht)) {
3382  $this->total_ht = 0;
3383  }
3384  if (empty($this->total_tva)) {
3385  $this->total_tva = 0;
3386  }
3387  if (empty($this->total_ttc)) {
3388  $this->total_ttc = 0;
3389  }
3390  if (empty($this->localtax1_tx)) {
3391  $this->localtax1_tx = 0;
3392  }
3393  if (empty($this->localtax2_tx)) {
3394  $this->localtax2_tx = 0;
3395  }
3396  if (empty($this->remise_percent)) {
3397  $this->remise_percent = 0;
3398  }
3399  // For backward compatibility
3400  if (empty($this->date_start)) {
3401  $this->date_start = $this->date_start;
3402  }
3403  if (empty($this->date_start_real)) {
3404  $this->date_start_real = $this->date_start_real;
3405  }
3406  if (empty($this->date_end)) {
3407  $this->date_end = $this->date_end;
3408  }
3409  if (empty($this->date_end_real)) {
3410  $this->date_end_real = $this->date_end_real;
3411  }
3412 
3413  // Calcul du total TTC et de la TVA pour la ligne a partir de
3414  // qty, pu, remise_percent et txtva
3415  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3416  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3417  $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->thirdparty, $mysoc);
3418 
3419  $tabprice = calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
3420  $this->total_ht = $tabprice[0];
3421  $this->total_tva = $tabprice[1];
3422  $this->total_ttc = $tabprice[2];
3423  $this->total_localtax1 = $tabprice[9];
3424  $this->total_localtax2 = $tabprice[10];
3425 
3426  if (empty($this->pa_ht)) {
3427  $this->pa_ht = 0;
3428  }
3429 
3430  // if buy price not defined, define buyprice as configured in margin admin
3431  if ($this->pa_ht == 0) {
3432  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
3433  return $result;
3434  } else {
3435  $this->pa_ht = $result;
3436  }
3437  }
3438 
3439  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
3440  if (empty($this->oldcopy)) {
3441  $this->oldcopy = dol_clone($this);
3442  }
3443 
3444  $this->db->begin();
3445 
3446  // Update request
3447  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3448  $sql .= " fk_contrat = ".((int) $this->fk_contrat).",";
3449  $sql .= " fk_product = ".($this->fk_product ? ((int) $this->fk_product) : 'null').",";
3450  $sql .= " statut = ".((int) $this->statut).",";
3451  $sql .= " label = '".$this->db->escape($this->label)."',";
3452  $sql .= " description = '".$this->db->escape($this->description)."',";
3453  $sql .= " date_commande = ".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
3454  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3455  $sql .= " date_ouverture = ".($this->date_start_real != '' ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3456  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3457  $sql .= " date_cloture = ".($this->date_end_real != '' ? "'".$this->db->idate($this->date_end_real)."'" : "null").",";
3458  $sql .= " vat_src_code = '".$this->db->escape($this->vat_src_code)."',";
3459  $sql .= " tva_tx = ".price2num($this->tva_tx).",";
3460  $sql .= " localtax1_tx = ".price2num($this->localtax1_tx).",";
3461  $sql .= " localtax2_tx = ".price2num($this->localtax2_tx).",";
3462  $sql .= " qty = ".price2num($this->qty).",";
3463  $sql .= " remise_percent = ".price2num($this->remise_percent).",";
3464  $sql .= " remise = ".($this->remise ?price2num($this->remise) : "null").",";
3465  $sql .= " fk_remise_except = ".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
3466  $sql .= " subprice = ".($this->subprice != '' ? $this->subprice : "null").",";
3467  $sql .= " price_ht = ".($this->price_ht != '' ? $this->price_ht : "null").",";
3468  $sql .= " total_ht = ".$this->total_ht.",";
3469  $sql .= " total_tva = ".$this->total_tva.",";
3470  $sql .= " total_localtax1 = ".$this->total_localtax1.",";
3471  $sql .= " total_localtax2 = ".$this->total_localtax2.",";
3472  $sql .= " total_ttc = ".$this->total_ttc.",";
3473  $sql .= " fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
3474  $sql .= " buy_price_ht = '".price2num($this->pa_ht)."',";
3475  $sql .= " info_bits = '".$this->db->escape($this->info_bits)."',";
3476  $sql .= " fk_user_author = ".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
3477  $sql .= " fk_user_ouverture = ".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
3478  $sql .= " fk_user_cloture = ".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3479  $sql .= " commentaire = '".$this->db->escape($this->commentaire)."',";
3480  $sql .= " fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit).",";
3481  $sql .= " rang = ".(empty($this->rang) ? '0' : (int) $this->rang);
3482  $sql .= " WHERE rowid = ".((int) $this->id);
3483 
3484  dol_syslog(get_class($this)."::update", LOG_DEBUG);
3485  $resql = $this->db->query($sql);
3486  if (!$resql) {
3487  $this->error = "Error ".$this->db->lasterror();
3488  $error++;
3489  }
3490 
3491  if (!$error) { // For avoid conflicts if trigger used
3492  $result = $this->insertExtraFields();
3493  if ($result < 0) {
3494  $error++;
3495  }
3496  }
3497 
3498  // If we change a planned date (start or end) of one contract line, sync dates for all other services too
3499  if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) {
3500  dol_syslog(get_class($this)."::update CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES is on so we update date for all lines", LOG_DEBUG);
3501 
3502  if ($this->date_start != $this->oldcopy->date_start) {
3503  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3504  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
3505  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3506 
3507  $resql = $this->db->query($sql);
3508  if (!$resql) {
3509  $error++;
3510  $this->error = "Error ".$this->db->lasterror();
3511  }
3512  }
3513  if ($this->date_end != $this->oldcopy->date_end) {
3514  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3515  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
3516  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3517 
3518  $resql = $this->db->query($sql);
3519  if (!$resql) {
3520  $error++;
3521  $this->error = "Error ".$this->db->lasterror();
3522  }
3523  }
3524  }
3525 
3526  if (!$error && !$notrigger) {
3527  // Call trigger
3528  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
3529  if ($result < 0) {
3530  $error++;
3531  $this->db->rollback();
3532  }
3533  // End call triggers
3534  }
3535 
3536  if (!$error) {
3537  $this->db->commit();
3538  return 1;
3539  } else {
3540  $this->db->rollback();
3541  $this->errors[] = $this->error;
3542  return -1;
3543  }
3544  }
3545 
3546 
3547  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3554  public function update_total()
3555  {
3556  // phpcs:enable
3557  $this->db->begin();
3558 
3559  // Mise a jour ligne en base
3560  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3561  $sql .= " total_ht=".price2num($this->total_ht, 'MT');
3562  $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
3563  $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT');
3564  $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT');
3565  $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
3566  $sql .= " WHERE rowid = ".((int) $this->id);
3567 
3568  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3569 
3570  $resql = $this->db->query($sql);
3571  if ($resql) {
3572  $this->db->commit();
3573  return 1;
3574  } else {
3575  $this->error = $this->db->error();
3576  $this->db->rollback();
3577  return -2;
3578  }
3579  }
3580 
3581 
3588  public function insert($notrigger = 0)
3589  {
3590  global $conf, $user;
3591 
3592  $error = 0;
3593 
3594  // Insertion dans la base
3595  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3596  $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3597  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3598  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3599  $sql .= " info_bits,";
3600  $sql .= " rang,";
3601  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3602  if ($this->date_start > 0) {
3603  $sql .= ",date_ouverture_prevue";
3604  }
3605  if ($this->date_end > 0) {
3606  $sql .= ",date_fin_validite";
3607  }
3608  $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3609  $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3610  $sql .= " '".$this->db->escape($this->qty)."',";
3611  $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3612  $sql .= " '".$this->db->escape($this->tva_tx)."',";
3613  $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3614  $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3615  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3616  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3617  $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3618  $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3619  $sql .= " '".$this->db->escape($this->info_bits)."',";
3620  $sql .= " ".(empty($this->rang) ? '0' : (int) $this->rang).",";
3621  $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3622  if ($this->fk_fournprice > 0) {
3623  $sql .= ' '.((int) $this->fk_fournprice).',';
3624  } else {
3625  $sql .= ' null,';
3626  }
3627  if ($this->pa_ht > 0) {
3628  $sql .= ' '.((float) price2num($this->pa_ht));
3629  } else {
3630  $sql .= ' null';
3631  }
3632  if ($this->date_start > 0) {
3633  $sql .= ",'".$this->db->idate($this->date_start)."'";
3634  }
3635  if ($this->date_end > 0) {
3636  $sql .= ",'".$this->db->idate($this->date_end)."'";
3637  }
3638  $sql .= ")";
3639 
3640  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3641 
3642  $resql = $this->db->query($sql);
3643  if ($resql) {
3644  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3645 
3646  // Insert of extrafields
3647  if (!$error) {
3648  $result = $this->insertExtraFields();
3649  if ($result < 0) {
3650  $this->db->rollback();
3651  return -1;
3652  }
3653  }
3654 
3655  if (!$notrigger) {
3656  // Call trigger
3657  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3658  if ($result < 0) {
3659  $this->db->rollback();
3660  return -1;
3661  }
3662  // End call triggers
3663  }
3664 
3665  $this->db->commit();
3666  return 1;
3667  } else {
3668  $this->db->rollback();
3669  $this->error = $this->db->error()." sql=".$sql;
3670  return -1;
3671  }
3672  }
3673 
3674  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3684  public function active_line($user, $date, $date_end = '', $comment = '')
3685  {
3686  // phpcs:enable
3687  global $langs, $conf;
3688 
3689  $error = 0;
3690 
3691  $this->db->begin();
3692 
3693  $this->statut = ContratLigne::STATUS_OPEN;
3694  $this->date_start_real = $date;
3695  $this->date_end = $date_end;
3696  $this->fk_user_ouverture = $user->id;
3697  $this->date_end_real = null;
3698  $this->commentaire = $comment;
3699 
3700  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) $this->statut).",";
3701  $sql .= " date_ouverture = ".(dol_strlen($this->date_start_real) != 0 ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3702  if ($date_end >= 0) {
3703  $sql .= " date_fin_validite = ".(dol_strlen($this->date_end) != 0 ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3704  }
3705  $sql .= " fk_user_ouverture = ".((int) $this->fk_user_ouverture).",";
3706  $sql .= " date_cloture = null,";
3707  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3708  $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3709 
3710  dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3711  $resql = $this->db->query($sql);
3712  if ($resql) {
3713  // Call trigger
3714  $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3715  if ($result < 0) {
3716  $error++;
3717  }
3718  // End call triggers
3719 
3720  if (!$error) {
3721  $this->db->commit();
3722  return 1;
3723  } else {
3724  $this->db->rollback();
3725  return -1;
3726  }
3727  } else {
3728  $this->error = $this->db->lasterror();
3729  $this->db->rollback();
3730  return -1;
3731  }
3732  }
3733 
3734  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3744  public function close_line($user, $date_end_real, $comment = '', $notrigger = 0)
3745  {
3746  // phpcs:enable
3747  global $langs, $conf;
3748 
3749  // Update object
3750  $this->date_cloture = $date_end_real;
3751  $this->date_end_real = $date_end_real;
3752  $this->fk_user_cloture = $user->id;
3753  $this->commentaire = $comment;
3754 
3755  $error = 0;
3756 
3757  // statut actif : 4
3758 
3759  $this->db->begin();
3760 
3761  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
3762  $sql .= " date_cloture = '".$this->db->idate($date_end_real)."',";
3763  $sql .= " fk_user_cloture = ".((int) $user->id).",";
3764  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3765  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
3766 
3767  $resql = $this->db->query($sql);
3768  if ($resql) {
3769  if (!$notrigger) {
3770  // Call trigger
3771  $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3772  if ($result < 0) {
3773  $error++;
3774  $this->db->rollback();
3775  return -1;
3776  }
3777  // End call triggers
3778  }
3779 
3780  $this->db->commit();
3781  return 1;
3782  } else {
3783  $this->error = $this->db->lasterror();
3784  $this->db->rollback();
3785  return -1;
3786  }
3787  }
3788 }
$object ref
Definition: info.php:78
Class to manage agenda events (actions)
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...
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setErrorsFromObject($object)
setErrorsFromObject
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
fetch_project()
Load the project with id $this->fk_project into this->project.
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage contracts.
createFromClone(User $user, $socid=0, $notrigger=0)
Load an object from its id and create a new one in database.
update_statut($user)
Update statut of contract according to services.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
create($user)
Create a contract into database.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
array_detail($status=-1)
Return list of line rowid.
update($user, $notrigger=0)
Update object into database.
closeAll(User $user, $notrigger=0, $comment='')
Close all lines of a contract.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=0, $fk_unit=null, $rang=0)
Ajoute une ligne de contrat en base.
$table_ref_field
{}
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
info($id)
Charge les informations d'ordre info dans l'objet contrat.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
deleteline($idline, User $user)
Delete a contract line.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
fetch_lines($only_services=0, $loadalsotranslation=0)
Load lines array into this->lines.
__construct($db)
Constructor.
doAutoRenewContracts($thirdparty_id=0, $delayindaysshort=0)
Action executed by scheduler CAN BE A CRON TASK Loop on each contract lines and update the end of dat...
getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
fetch($id, $ref='', $ref_customer='', $ref_supplier='')
Load a contract from database.
getLibStatut($mode)
Return label of a contract status.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_start_real='', $date_end_real='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=0, $fk_unit=null, $rang=0)
Mets a jour une ligne de contrat.
getIdServiceContact()
Return id des contacts clients de prestation.
load_state_board()
Charge indicateurs this->nb de tableau de bord.
getNextNumRef($soc)
Return next contract ref.
Class to manage lines of contracts.
active_line($user, $date, $date_end='', $comment='')
Activate a contract line.
getLibStatut($mode)
Return label of this contract line status.
insert($notrigger=0)
Inserts a contrat line into database.
fetch($id, $ref='')
Load object in memory from database.
close_line($user, $date_end_real, $comment='', $notrigger=0)
Close a contract line.
update($user, $notrigger=0)
Update database for contract line.
update_total()
Mise a jour en base des champs total_xxx de ligne Used by migration process.
static LibStatut($status, $mode, $expired=-1, $moreatt='')
Return label of a contract line status.
__construct($db)
Constructor.
getTooltipContentArray($params)
getTooltipContentArray
getNomUrl($withpicto=0, $maxlength=0)
Return clicable name (with picto eventually) for ContratLigne.
Class to manage Dolibarr database access.
Class to manage shipments.
const STATUS_DRAFT
Draft status.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
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
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
print *****$script_file(".$version.") pid cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1485
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:62
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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)
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:86
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:120