dolibarr  18.0.6
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  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'contract/".$this->db->escape($this->newref)."'";
545  $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
546  $resql = $this->db->query($sql);
547  if (!$resql) {
548  $error++; $this->error = $this->db->lasterror();
549  }
550 
551  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
552  $oldref = dol_sanitizeFileName($this->ref);
553  $newref = dol_sanitizeFileName($num);
554  $dirsource = $conf->contract->dir_output.'/'.$oldref;
555  $dirdest = $conf->contract->dir_output.'/'.$newref;
556  if (!$error && file_exists($dirsource)) {
557  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
558 
559  if (@rename($dirsource, $dirdest)) {
560  dol_syslog("Rename ok");
561  // Rename docs starting with $oldref with $newref
562  $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
563  foreach ($listoffiles as $fileentry) {
564  $dirsource = $fileentry['name'];
565  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
566  $dirsource = $fileentry['path'].'/'.$dirsource;
567  $dirdest = $fileentry['path'].'/'.$dirdest;
568  @rename($dirsource, $dirdest);
569  }
570  }
571  }
572  }
573  }
574 
575  // Set new ref and define current statut
576  if (!$error) {
577  $this->ref = $num;
578  $this->statut = 1;
579  $this->brouillon = 0;
580  $this->date_validation = $now;
581  }
582  } else {
583  $error++;
584  }
585 
586  if (!$error) {
587  $this->db->commit();
588  return 1;
589  } else {
590  $this->db->rollback();
591  return -1;
592  }
593  }
594 
602  public function reopen($user, $notrigger = 0)
603  {
604  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
605  global $langs, $conf;
606 
607  $now = dol_now();
608 
609  $error = 0;
610  dol_syslog(get_class($this).'::reopen user='.$user->id);
611 
612  $this->db->begin();
613 
614  $this->fetch_thirdparty();
615 
616  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
617  //$sql.= ", fk_user_valid = null, date_valid = null";
618  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
619 
620  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
621  $resql = $this->db->query($sql);
622  if (!$resql) {
623  dol_print_error($this->db);
624  $error++;
625  $this->error = $this->db->lasterror();
626  }
627 
628  // Trigger calls
629  if (!$error && !$notrigger) {
630  // Call trigger
631  $result = $this->call_trigger('CONTRACT_REOPEN', $user);
632  if ($result < 0) {
633  $error++;
634  }
635  // End call triggers
636  }
637 
638  // Set new ref and define current status
639  if (!$error) {
640  $this->statut = 0;
641  $this->brouillon = 1;
642  $this->date_validation = $now;
643  }
644 
645  if (!$error) {
646  $this->db->commit();
647  return 1;
648  } else {
649  $this->db->rollback();
650  return -1;
651  }
652  }
653 
663  public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '')
664  {
665  $sql = "SELECT rowid, statut, ref, fk_soc,";
666  $sql .= " ref_supplier, ref_customer,";
667  $sql .= " ref_ext,";
668  $sql .= " entity,";
669  $sql .= " date_contrat as datecontrat,";
670  $sql .= " fk_user_author,";
671  $sql .= " fk_projet as fk_project,";
672  $sql .= " fk_commercial_signature, fk_commercial_suivi,";
673  $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
674  $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
675  if (!$id) {
676  $sql .= " WHERE entity IN (".getEntity('contract').")";
677  } else {
678  $sql .= " WHERE rowid = ".(int) $id;
679  }
680  if ($ref_customer) {
681  $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
682  }
683  if ($ref_supplier) {
684  $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
685  }
686  if ($ref) {
687  $sql .= " AND ref = '".$this->db->escape($ref)."'";
688  }
689 
690  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
691  $resql = $this->db->query($sql);
692  if ($resql) {
693  $num = $this->db->num_rows($resql);
694  if ($num > 1) {
695  $this->error = 'Fetch found several records.';
696  dol_syslog($this->error, LOG_ERR);
697  $result = -2;
698  return 0;
699  } elseif ($num) { // $num = 1
700  $obj = $this->db->fetch_object($resql);
701  if ($obj) {
702  $this->id = $obj->rowid;
703  $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
704  $this->ref_customer = $obj->ref_customer;
705  $this->ref_supplier = $obj->ref_supplier;
706  $this->ref_ext = $obj->ref_ext;
707  $this->entity = $obj->entity;
708  $this->statut = $obj->statut;
709 
710  $this->date_contrat = $this->db->jdate($obj->datecontrat);
711  $this->date_creation = $this->db->jdate($obj->datecontrat);
712 
713  $this->user_author_id = $obj->fk_user_author;
714 
715  $this->commercial_signature_id = $obj->fk_commercial_signature;
716  $this->commercial_suivi_id = $obj->fk_commercial_suivi;
717 
718  $this->note_private = $obj->note_private;
719  $this->note_public = $obj->note_public;
720  $this->model_pdf = $obj->model_pdf;
721  $this->modelpdf = $obj->model_pdf; // deprecated
722 
723  $this->fk_projet = $obj->fk_project; // deprecated
724  $this->fk_project = $obj->fk_project;
725 
726  $this->socid = $obj->fk_soc;
727  $this->fk_soc = $obj->fk_soc;
728  $this->last_main_doc = $obj->last_main_doc;
729  $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
730 
731  $this->db->free($resql);
732 
733  // Retrieve all extrafields
734  // fetch optionals attributes and labels
735  $result = $this->fetch_optionals();
736 
737  // Lines
738  if ($result >= 0 && !empty($this->table_element_line)) {
739  $result = $this->fetch_lines();
740  }
741 
742  if ($result < 0) {
743  $this->error = $this->db->lasterror();
744  return -3;
745  }
746 
747  return $this->id;
748  } else {
749  dol_syslog(get_class($this)."::fetch Contract failed");
750  $this->error = "Fetch contract failed";
751  return -1;
752  }
753  } else {
754  dol_syslog(get_class($this)."::fetch Contract not found");
755  $this->error = "Contract not found";
756  return 0;
757  }
758  } else {
759  dol_syslog(get_class($this)."::fetch Error searching contract");
760  $this->error = $this->db->error();
761  return -1;
762  }
763  }
764 
765  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
774  public function fetch_lines($only_services = 0, $loadalsotranslation = 0)
775  {
776  // phpcs:enable
777  global $langs, $conf;
778 
779  $this->nbofservices = 0;
780  $this->nbofserviceswait = 0;
781  $this->nbofservicesopened = 0;
782  $this->nbofservicesexpired = 0;
783  $this->nbofservicesclosed = 0;
784 
785  $total_ttc = 0;
786  $total_vat = 0;
787  $total_ht = 0;
788 
789  $now = dol_now();
790 
791  $this->lines = array();
792  $pos = 0;
793 
794  // Selects contract lines related to a product
795  $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
796  $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,";
797  $sql .= " d.total_ht,";
798  $sql .= " d.total_tva,";
799  $sql .= " d.total_localtax1,";
800  $sql .= " d.total_localtax2,";
801  $sql .= " d.total_ttc,";
802  $sql .= " d.info_bits, d.fk_product,";
803  $sql .= " d.date_ouverture_prevue as date_start,";
804  $sql .= " d.date_ouverture as date_start_real,";
805  $sql .= " d.date_fin_validite as date_end,";
806  $sql .= " d.date_cloture as date_end_real,";
807  $sql .= " d.fk_user_author,";
808  $sql .= " d.fk_user_ouverture,";
809  $sql .= " d.fk_user_cloture,";
810  $sql .= " d.fk_unit,";
811  $sql .= " d.product_type as type,";
812  $sql .= " d.rang";
813  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
814  $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
815  if ($only_services == 1) {
816  $sql .= " AND d.product_type = 1";
817  }
818  $sql .= " ORDER by d.rang ASC";
819 
820  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
821  $result = $this->db->query($sql);
822  if ($result) {
823  $num = $this->db->num_rows($result);
824  $i = 0;
825 
826  while ($i < $num) {
827  $objp = $this->db->fetch_object($result);
828 
829  $line = new ContratLigne($this->db);
830 
831  $line->id = $objp->rowid;
832  $line->ref = $objp->rowid;
833  $line->fk_contrat = $objp->fk_contrat;
834  $line->desc = $objp->description; // Description line
835  $line->qty = $objp->qty;
836  $line->vat_src_code = $objp->vat_src_code;
837  $line->tva_tx = $objp->tva_tx;
838  $line->localtax1_tx = $objp->localtax1_tx;
839  $line->localtax2_tx = $objp->localtax2_tx;
840  $line->localtax1_type = $objp->localtax1_type;
841  $line->localtax2_type = $objp->localtax2_type;
842  $line->subprice = $objp->subprice;
843  $line->statut = $objp->statut;
844  $line->remise_percent = $objp->remise_percent;
845  $line->price_ht = $objp->price_ht;
846  $line->price = $objp->price_ht; // For backward compatibility
847  $line->total_ht = $objp->total_ht;
848  $line->total_tva = $objp->total_tva;
849  $line->total_localtax1 = $objp->total_localtax1;
850  $line->total_localtax2 = $objp->total_localtax2;
851  $line->total_ttc = $objp->total_ttc;
852  $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
853  $line->info_bits = $objp->info_bits;
854  $line->type = $objp->type;
855 
856  $line->fk_fournprice = $objp->fk_fournprice;
857  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
858  $line->pa_ht = $marginInfos[0];
859 
860  $line->fk_user_author = $objp->fk_user_author;
861  $line->fk_user_ouverture = $objp->fk_user_ouverture;
862  $line->fk_user_cloture = $objp->fk_user_cloture;
863  $line->fk_unit = $objp->fk_unit;
864 
865  $line->ref = $objp->product_ref; // deprecated
866  $line->product_ref = $objp->product_ref; // Product Ref
867  $line->product_type = $objp->product_type; // Product Type
868  $line->product_desc = $objp->product_desc; // Product Description
869  $line->product_label = $objp->product_label; // Product Label
870 
871  $line->description = $objp->description;
872 
873  $line->date_start = $this->db->jdate($objp->date_start);
874  $line->date_start_real = $this->db->jdate($objp->date_start_real);
875  $line->date_end = $this->db->jdate($objp->date_end);
876  $line->date_end_real = $this->db->jdate($objp->date_end_real);
877  // For backward compatibility
878  //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
879  //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
880  //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
881  //$line->date_cloture = $this->db->jdate($objp->date_cloture);
882  //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
883  //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
884  //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
885  //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
886 
887  $line->rang = $objp->rang;
888 
889  // Retrieve all extrafields for contract line
890  // fetch optionals attributes and labels
891  $line->fetch_optionals();
892 
893  // multilangs
894  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
895  $tmpproduct = new Product($this->db);
896  $tmpproduct->fetch($objp->fk_product);
897  $tmpproduct->getMultiLangs();
898 
899  $line->multilangs = $tmpproduct->multilangs;
900  }
901 
902  $this->lines[$pos] = $line;
903 
904  $this->lines_id_index_mapper[$line->id] = $pos;
905 
906  //dol_syslog("1 ".$line->desc);
907  //dol_syslog("2 ".$line->product_desc);
908 
909  if ($line->statut == ContratLigne::STATUS_INITIAL) {
910  $this->nbofserviceswait++;
911  }
912  if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
913  $this->nbofservicesopened++;
914  }
915  if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
916  $this->nbofservicesexpired++;
917  }
918  if ($line->statut == ContratLigne::STATUS_CLOSED) {
919  $this->nbofservicesclosed++;
920  }
921 
922  $total_ttc += $objp->total_ttc; // TODO Not saved into database
923  $total_vat += $objp->total_tva;
924  $total_ht += $objp->total_ht;
925 
926  $i++;
927  $pos++;
928  }
929  $this->db->free($result);
930  } else {
931  dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
932  return -3;
933  }
934 
935  // Now set the global properties on contract not stored into database.
936  $this->nbofservices = count($this->lines);
937  $this->total_ttc = price2num($total_ttc);
938  $this->total_tva = price2num($total_vat);
939  $this->total_ht = price2num($total_ht);
940 
941  return $this->lines;
942  }
943 
950  public function create($user)
951  {
952  global $conf, $langs, $mysoc;
953 
954  // Check parameters
955  $paramsok = 1;
956  if ($this->commercial_signature_id <= 0) {
957  $langs->load("commercial");
958  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
959  $paramsok = 0;
960  }
961  if ($this->commercial_suivi_id <= 0) {
962  $langs->load("commercial");
963  $this->error .= ($this->error ? "<br>" : '');
964  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
965  $paramsok = 0;
966  }
967  if (!$paramsok) {
968  return -1;
969  }
970 
971 
972  $this->db->begin();
973 
974  $now = dol_now();
975 
976  // Insert contract
977  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
978  $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
979  $sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
980  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
981  $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
982  $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
983  $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
984  $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
985  $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
986  $sql .= ", ".((int) $conf->entity);
987  $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
988  $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
989  $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
990  $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
991  $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
992  $sql .= ")";
993  $resql = $this->db->query($sql);
994 
995  if ($resql) {
996  $error = 0;
997 
998  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
999 
1000  // Load object modContract
1001  $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
1002  if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1003  $module = substr($module, 0, dol_strlen($module) - 4);
1004  }
1005  $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1006  if ($result > 0) {
1007  $modCodeContract = new $module();
1008 
1009  if (!empty($modCodeContract->code_auto)) {
1010  // Force the ref to a draft value if numbering module is an automatic numbering
1011  $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1012  if ($this->db->query($sql)) {
1013  if ($this->id) {
1014  $this->ref = "(PROV".$this->id.")";
1015  }
1016  }
1017  }
1018  }
1019 
1020  if (!$error) {
1021  $result = $this->insertExtraFields();
1022  if ($result < 0) {
1023  $error++;
1024  }
1025  }
1026 
1027  // Insert business contacts ('SALESREPSIGN','contrat')
1028  if (!$error) {
1029  $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1030  if ($result < 0) {
1031  $error++;
1032  }
1033  }
1034 
1035  // Insert business contacts ('SALESREPFOLL','contrat')
1036  if (!$error) {
1037  $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1038  if ($result < 0) {
1039  $error++;
1040  }
1041  }
1042 
1043  if (!$error) {
1044  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1045  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1046  }
1047 
1048  // Add object linked
1049  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1050  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1051  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, ...))
1052  foreach ($tmp_origin_id as $origin_id) {
1053  $ret = $this->add_object_linked($origin, $origin_id);
1054  if (!$ret) {
1055  $this->error = $this->db->lasterror();
1056  $error++;
1057  }
1058  }
1059  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1060  {
1061  $origin_id = $tmp_origin_id;
1062  $ret = $this->add_object_linked($origin, $origin_id);
1063  if (!$ret) {
1064  $this->error = $this->db->lasterror();
1065  $error++;
1066  }
1067  }
1068  }
1069  }
1070 
1071  if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1072  $originforcontact = $this->origin;
1073  $originidforcontact = $this->origin_id;
1074  if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1075  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1076  $exp = new Expedition($this->db);
1077  $exp->fetch($this->origin_id);
1078  $exp->fetchObjectLinked();
1079  if (count($exp->linkedObjectsIds['commande']) > 0) {
1080  foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1081  $originforcontact = 'commande';
1082  $originidforcontact = $value;
1083  break; // We take first one
1084  }
1085  }
1086  }
1087 
1088  $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";
1089  $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1090 
1091  $resqlcontact = $this->db->query($sqlcontact);
1092  if ($resqlcontact) {
1093  while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1094  if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1095  continue; // ignore this, already forced previously
1096  }
1097 
1098  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1099  $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
1100  }
1101  } else {
1102  dol_print_error($resqlcontact);
1103  }
1104  }
1105  }
1106 
1107  if (!$error) {
1108  // Call trigger
1109  $result = $this->call_trigger('CONTRACT_CREATE', $user);
1110  if ($result < 0) {
1111  $error++;
1112  }
1113  // End call triggers
1114 
1115  if (!$error) {
1116  $this->db->commit();
1117  return $this->id;
1118  } else {
1119  dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1120  $this->db->rollback();
1121  return -3;
1122  }
1123  } else {
1124  $this->error = "Failed to add contract";
1125  dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1126  $this->db->rollback();
1127  return -2;
1128  }
1129  } else {
1130  $this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1131 
1132  $this->db->rollback();
1133  return -1;
1134  }
1135  }
1136 
1137 
1144  public function delete($user)
1145  {
1146  global $conf, $langs;
1147  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1148 
1149  $error = 0;
1150 
1151  $this->db->begin();
1152 
1153  // Call trigger
1154  $result = $this->call_trigger('CONTRACT_DELETE', $user);
1155  if ($result < 0) {
1156  $error++;
1157  }
1158  // End call triggers
1159 
1160  if (!$error) {
1161  // Delete linked contacts
1162  $res = $this->delete_linked_contact();
1163  if ($res < 0) {
1164  dol_syslog(get_class($this)."::delete error", LOG_ERR);
1165  $error++;
1166  }
1167  }
1168 
1169  if (!$error) {
1170  // Delete linked object
1171  $res = $this->deleteObjectLinked();
1172  if ($res < 0) {
1173  $error++;
1174  }
1175  }
1176 
1177  if (!$error) {
1178  // Delete contratdet_log
1179  /*
1180  $sql = "DELETE cdl";
1181  $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1182  $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1183  */
1184  $sql = "SELECT cdl.rowid as cdlrowid ";
1185  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1186  $sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1187 
1188  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1189  $resql = $this->db->query($sql);
1190  if (!$resql) {
1191  $this->error = $this->db->error();
1192  $error++;
1193  }
1194  $numressql = $this->db->num_rows($resql);
1195  if (!$error && $numressql) {
1196  $tab_resql = array();
1197  for ($i = 0; $i < $numressql; $i++) {
1198  $objresql = $this->db->fetch_object($resql);
1199  $tab_resql[] = $objresql->cdlrowid;
1200  }
1201  $this->db->free($resql);
1202 
1203  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1204  $sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".$this->db->sanitize(implode(",", $tab_resql)).")";
1205 
1206  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1207  $resql = $this->db->query($sql);
1208  if (!$resql) {
1209  $this->error = $this->db->error();
1210  $error++;
1211  }
1212  }
1213  }
1214 
1215  // Delete lines
1216  if (!$error) {
1217  // Delete contratdet extrafields
1218  $main = MAIN_DB_PREFIX.'contratdet';
1219  $ef = $main."_extrafields";
1220  $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1221 
1222  dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1223  $resql = $this->db->query($sql);
1224  if (!$resql) {
1225  $this->error = $this->db->error();
1226  $error++;
1227  }
1228  }
1229 
1230  if (!$error) {
1231  // Delete contratdet
1232  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1233  $sql .= " WHERE fk_contrat=".((int) $this->id);
1234 
1235  dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1236  $resql = $this->db->query($sql);
1237  if (!$resql) {
1238  $this->error = $this->db->error();
1239  $error++;
1240  }
1241  }
1242 
1243  // Delete llx_ecm_files
1244  if (!$error) {
1245  $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);
1246  $resql = $this->db->query($sql);
1247  if (!$resql) {
1248  $this->error = $this->db->lasterror();
1249  $this->errors[] = $this->error;
1250  $error++;
1251  }
1252  }
1253 
1254  // Delete contract
1255  if (!$error) {
1256  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1257  $sql .= " WHERE rowid=".((int) $this->id);
1258 
1259  dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1260  $resql = $this->db->query($sql);
1261  if (!$resql) {
1262  $this->error = $this->db->error();
1263  $error++;
1264  }
1265  }
1266 
1267  // Removed extrafields
1268  if (!$error) {
1269  $result = $this->deleteExtraFields();
1270  if ($result < 0) {
1271  $error++;
1272  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1273  }
1274  }
1275 
1276  if (!$error) {
1277  // We remove directory
1278  $ref = dol_sanitizeFileName($this->ref);
1279  if ($conf->contrat->dir_output) {
1280  $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1281  if (file_exists($dir)) {
1282  $res = @dol_delete_dir_recursive($dir);
1283  if (!$res) {
1284  $this->error = 'ErrorFailToDeleteDir';
1285  $error++;
1286  }
1287  }
1288  }
1289  }
1290 
1291  if (!$error) {
1292  $this->db->commit();
1293  return 1;
1294  } else {
1295  $this->error = $this->db->lasterror();
1296  $this->db->rollback();
1297  return -1;
1298  }
1299  }
1300 
1308  public function update($user, $notrigger = 0)
1309  {
1310  global $conf, $langs;
1311  $error = 0;
1312 
1313  // Clean parameters
1314  if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1315  $this->fk_commercial_signature = $this->commercial_signature_id;
1316  }
1317  if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1318  $this->fk_commercial_suivi = $this->commercial_suivi_id;
1319  }
1320  if (empty($this->fk_soc) && $this->socid > 0) {
1321  $this->fk_soc = (int) $this->socid;
1322  }
1323  if (empty($this->fk_project) && $this->projet > 0) {
1324  $this->fk_project = (int) $this->projet;
1325  }
1326 
1327  if (isset($this->ref)) {
1328  $this->ref = trim($this->ref);
1329  }
1330  if (isset($this->ref_customer)) {
1331  $this->ref_customer = trim($this->ref_customer);
1332  }
1333  if (isset($this->ref_supplier)) {
1334  $this->ref_supplier = trim($this->ref_supplier);
1335  }
1336  if (isset($this->ref_ext)) {
1337  $this->ref_ext = trim($this->ref_ext);
1338  }
1339  if (isset($this->entity)) {
1340  $this->entity = (int) $this->entity;
1341  }
1342  if (isset($this->statut)) {
1343  $this->statut = (int) $this->statut;
1344  }
1345  if (isset($this->fk_soc)) {
1346  $this->fk_soc = (int) $this->fk_soc;
1347  }
1348  if (isset($this->fk_commercial_signature)) {
1349  $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1350  }
1351  if (isset($this->fk_commercial_suivi)) {
1352  $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
1353  }
1354  if (isset($this->note_private)) {
1355  $this->note_private = trim($this->note_private);
1356  }
1357  if (isset($this->note_public)) {
1358  $this->note_public = trim($this->note_public);
1359  }
1360  if (isset($this->import_key)) {
1361  $this->import_key = trim($this->import_key);
1362  }
1363  //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1364 
1365  // Check parameters
1366  // Put here code to add a control on parameters values
1367 
1368  // Update request
1369  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1370  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1371  $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1372  $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1373  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1374  $sql .= " entity=".$conf->entity.",";
1375  $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1376  $sql .= " statut=".(isset($this->statut) ? $this->statut : "null").",";
1377  $sql .= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc : "null").",";
1378  $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1379  $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1380  $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1381  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1382  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1383  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1384  //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null");
1385  $sql .= " WHERE rowid=".((int) $this->id);
1386 
1387  $this->db->begin();
1388 
1389  $resql = $this->db->query($sql);
1390  if (!$resql) {
1391  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1392  }
1393 
1394  if (!$error) {
1395  $result = $this->insertExtraFields();
1396  if ($result < 0) {
1397  $error++;
1398  }
1399  }
1400 
1401  if (!$error && !$notrigger) {
1402  // Call triggers
1403  $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1404  if ($result < 0) {
1405  $error++;
1406  }
1407  // End call triggers
1408  }
1409 
1410  // Commit or rollback
1411  if ($error) {
1412  foreach ($this->errors as $errmsg) {
1413  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1414  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1415  }
1416  $this->db->rollback();
1417  return -1 * $error;
1418  } else {
1419  $this->db->commit();
1420  return 1;
1421  }
1422  }
1423 
1424 
1448  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)
1449  {
1450  global $user, $langs, $conf, $mysoc;
1451  $error = 0;
1452 
1453  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");
1454 
1455  // Check parameters
1456  if ($fk_product <= 0 && empty($desc)) {
1457  $this->error = "ErrorDescRequiredForFreeProductLines";
1458  return -1;
1459  }
1460 
1461  if ($this->statut >= 0) {
1462  // Clean parameters
1463  $pu_ht = price2num($pu_ht);
1464  $pu_ttc = price2num($pu_ttc);
1465  $pa_ht = price2num($pa_ht);
1466 
1467  // Clean vat code
1468  $reg = array();
1469  $vat_src_code = '';
1470  if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1471  $vat_src_code = $reg[1];
1472  $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1473  }
1474  $txtva = price2num($txtva);
1475  $txlocaltax1 = price2num($txlocaltax1);
1476  $txlocaltax2 = price2num($txlocaltax2);
1477 
1478  $remise_percent = price2num($remise_percent);
1479  $qty = price2num($qty);
1480  if (empty($qty)) {
1481  $qty = 1;
1482  }
1483  if (empty($info_bits)) {
1484  $info_bits = 0;
1485  }
1486  if (empty($pu_ht) || !is_numeric($pu_ht)) {
1487  $pu_ht = 0;
1488  }
1489  if (empty($pu_ttc)) {
1490  $pu_ttc = 0;
1491  }
1492  if (empty($txtva) || !is_numeric($txtva)) {
1493  $txtva = 0;
1494  }
1495  if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1496  $txlocaltax1 = 0;
1497  }
1498  if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1499  $txlocaltax2 = 0;
1500  }
1501 
1502  if ($price_base_type == 'HT') {
1503  $pu = $pu_ht;
1504  } else {
1505  $pu = $pu_ttc;
1506  }
1507 
1508  // Check parameters
1509  if (empty($remise_percent)) {
1510  $remise_percent = 0;
1511  }
1512  if (empty($rang)) {
1513  $rang = 0;
1514  }
1515 
1516  if ($date_start && $date_end && $date_start > $date_end) {
1517  $langs->load("errors");
1518  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1519  return -1;
1520  }
1521 
1522  $this->db->begin();
1523 
1524  $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1525 
1526  // Calcul du total TTC et de la TVA pour la ligne a partir de
1527  // qty, pu, remise_percent et txtva
1528  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1529  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1530 
1531  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1532  $total_ht = $tabprice[0];
1533  $total_tva = $tabprice[1];
1534  $total_ttc = $tabprice[2];
1535  $total_localtax1 = $tabprice[9];
1536  $total_localtax2 = $tabprice[10];
1537 
1538  $localtax1_type = $localtaxes_type[0];
1539  $localtax2_type = $localtaxes_type[2];
1540 
1541  // TODO A virer
1542  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1543  $remise = 0;
1544  $price = price2num(round($pu_ht, 2));
1545  if (dol_strlen($remise_percent) > 0) {
1546  $remise = round(($pu_ht * $remise_percent / 100), 2);
1547  $price = $pu_ht - $remise;
1548  }
1549 
1550  if (empty($pa_ht)) {
1551  $pa_ht = 0;
1552  }
1553 
1554 
1555  // if buy price not defined, define buyprice as configured in margin admin
1556  if ($this->pa_ht == 0) {
1557  if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) {
1558  return $result;
1559  } else {
1560  $pa_ht = $result;
1561  }
1562  }
1563 
1564  // Insertion dans la base
1565  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1566  $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1567  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1568  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1569  $sql .= " info_bits,";
1570  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1571  if ($date_start > 0) {
1572  $sql .= ",date_ouverture_prevue";
1573  }
1574  if ($date_end > 0) {
1575  $sql .= ",date_fin_validite";
1576  }
1577  $sql .= ", fk_unit";
1578  $sql .= ", rang";
1579  $sql .= ") VALUES (";
1580  $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1581  $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1582  $sql .= " ".((float) $qty).",";
1583  $sql .= " ".((float) $txtva).",";
1584  $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1585  $sql .= " ".((float) $txlocaltax1).",";
1586  $sql .= " ".((float) $txlocaltax2).",";
1587  $sql .= " '".$this->db->escape($localtax1_type)."',";
1588  $sql .= " '".$this->db->escape($localtax2_type)."',";
1589  $sql .= " ".price2num($remise_percent).",";
1590  $sql .= " ".price2num($pu_ht).",";
1591  $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1592  $sql .= " '".$this->db->escape($info_bits)."',";
1593  $sql .= " ".price2num($price).",".price2num($remise).",";
1594  if (isset($fk_fournprice)) {
1595  $sql .= ' '.((int) $fk_fournprice).',';
1596  } else {
1597  $sql .= ' null,';
1598  }
1599  if (isset($pa_ht)) {
1600  $sql .= ' '.price2num($pa_ht);
1601  } else {
1602  $sql .= ' null';
1603  }
1604  if ($date_start > 0) {
1605  $sql .= ",'".$this->db->idate($date_start)."'";
1606  }
1607  if ($date_end > 0) {
1608  $sql .= ",'".$this->db->idate($date_end)."'";
1609  }
1610  $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1611  $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1612  $sql .= ")";
1613 
1614  $resql = $this->db->query($sql);
1615  if ($resql) {
1616  $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1617 
1618  if (!$error) {
1619  $contractline = new ContratLigne($this->db);
1620  $contractline->array_options = $array_options;
1621  $contractline->id = $contractlineid;
1622  $result = $contractline->insertExtraFields();
1623  if ($result < 0) {
1624  $this->error[] = $contractline->error;
1625  $error++;
1626  }
1627  }
1628 
1629  if (empty($error)) {
1630  // Call trigger
1631  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1632  if ($result < 0) {
1633  $error++;
1634  }
1635  // End call triggers
1636  }
1637 
1638  if ($error) {
1639  $this->db->rollback();
1640  return -1;
1641  } else {
1642  $this->db->commit();
1643  return $contractlineid;
1644  }
1645  } else {
1646  $this->db->rollback();
1647  $this->error = $this->db->error()." sql=".$sql;
1648  return -1;
1649  }
1650  } else {
1651  dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1652  return -2;
1653  }
1654  }
1655 
1680  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)
1681  {
1682  global $user, $conf, $langs, $mysoc;
1683 
1684  $error = 0;
1685 
1686  // Clean parameters
1687  $qty = trim($qty);
1688  $desc = trim($desc);
1689  $desc = trim($desc);
1690  $price = price2num($pu);
1691  $tvatx = price2num($tvatx);
1692  $localtax1tx = price2num($localtax1tx);
1693  $localtax2tx = price2num($localtax2tx);
1694  $pa_ht = price2num($pa_ht);
1695  if (empty($fk_fournprice)) {
1696  $fk_fournprice = 0;
1697  }
1698  if (empty($rang)) {
1699  $rang = 0;
1700  }
1701 
1702  $subprice = $price;
1703  $remise = 0;
1704  if (dol_strlen($remise_percent) > 0) {
1705  $remise = round(($pu * $remise_percent / 100), 2);
1706  $price = $pu - $remise;
1707  } else {
1708  $remise_percent = 0;
1709  }
1710 
1711  if ($date_start && $date_end && $date_start > $date_end) {
1712  $langs->load("errors");
1713  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1714  return -1;
1715  }
1716 
1717  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");
1718 
1719  $this->db->begin();
1720 
1721  // Calcul du total TTC et de la TVA pour la ligne a partir de
1722  // qty, pu, remise_percent et tvatx
1723  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1724  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1725 
1726  $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1727  $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1728 
1729  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1730  $total_ht = $tabprice[0];
1731  $total_tva = $tabprice[1];
1732  $total_ttc = $tabprice[2];
1733  $total_localtax1 = $tabprice[9];
1734  $total_localtax2 = $tabprice[10];
1735 
1736  $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1737  $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1738 
1739  // TODO A virer
1740  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1741  $remise = 0;
1742  $price = price2num(round($pu, 2));
1743  if (dol_strlen($remise_percent) > 0) {
1744  $remise = round(($pu * $remise_percent / 100), 2);
1745  $price = $pu - $remise;
1746  }
1747 
1748  if (empty($pa_ht)) {
1749  $pa_ht = 0;
1750  }
1751 
1752  // if buy price not defined, define buyprice as configured in margin admin
1753  if ($this->pa_ht == 0) {
1754  if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
1755  return $result;
1756  } else {
1757  $pa_ht = $result;
1758  }
1759  }
1760 
1761  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1762  $sql .= ",price_ht = ".((float) price2num($price));
1763  $sql .= ",subprice = ".((float) price2num($subprice));
1764  $sql .= ",remise = ".((float) price2num($remise));
1765  $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1766  $sql .= ",qty = ".((float) $qty);
1767  $sql .= ",tva_tx = ".((float) price2num($tvatx));
1768  $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1769  $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1770  $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1771  $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1772  $sql .= ", total_ht = ".((float) price2num($total_ht));
1773  $sql .= ", total_tva = ".((float) price2num($total_tva));
1774  $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1775  $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1776  $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1777  $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1778  $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1779  if ($date_start > 0) {
1780  $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1781  } else {
1782  $sql .= ",date_ouverture_prevue = null";
1783  }
1784  if ($date_end > 0) {
1785  $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1786  } else {
1787  $sql .= ",date_fin_validite = null";
1788  }
1789  if ($date_start_real > 0) {
1790  $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1791  } else {
1792  $sql .= ",date_ouverture = null";
1793  }
1794  if ($date_end_real > 0) {
1795  $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1796  } else {
1797  $sql .= ",date_cloture = null";
1798  }
1799  $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1800  $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1801  $sql .= " WHERE rowid = ".((int) $rowid);
1802 
1803  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1804  $result = $this->db->query($sql);
1805  if ($result) {
1806  if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1807  $contractline = new ContratLigne($this->db);
1808  $contractline->fetch($rowid);
1809 
1810  // We replace values in $contractline->array_options only for entries defined into $array_options
1811  foreach ($array_options as $key => $value) {
1812  $contractline->array_options[$key] = $array_options[$key];
1813  }
1814 
1815  $result = $contractline->insertExtraFields();
1816  if ($result < 0) {
1817  $this->error[] = $contractline->error;
1818  $error++;
1819  }
1820  }
1821 
1822  if (empty($error)) {
1823  // Call trigger
1824  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1825  if ($result < 0) {
1826  $this->db->rollback();
1827  return -3;
1828  }
1829  // End call triggers
1830 
1831  $this->db->commit();
1832  return 1;
1833  } else {
1834  $this->db->rollback();
1835  return -1;
1836  }
1837  } else {
1838  $this->db->rollback();
1839  $this->error = $this->db->error();
1840  dol_syslog(get_class($this)."::updateline Erreur -1");
1841  return -1;
1842  }
1843  }
1844 
1852  public function deleteline($idline, User $user)
1853  {
1854  global $conf, $langs;
1855 
1856  $error = 0;
1857 
1858  if ($this->statut >= 0) {
1859  // Call trigger
1860  $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1861  if ($result < 0) {
1862  return -1;
1863  }
1864  // End call triggers
1865 
1866  $this->db->begin();
1867 
1868  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1869  $sql .= " WHERE rowid = ".((int) $idline);
1870 
1871  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1872  $resql = $this->db->query($sql);
1873  if (!$resql) {
1874  $this->error = "Error ".$this->db->lasterror();
1875  $error++;
1876  }
1877 
1878  if (!$error) {
1879  // Remove extrafields
1880  $contractline = new ContratLigne($this->db);
1881  $contractline->id = $idline;
1882  $result = $contractline->deleteExtraFields();
1883  if ($result < 0) {
1884  $error++;
1885  $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1886  }
1887  }
1888 
1889  if (empty($error)) {
1890  $this->db->commit();
1891  return 1;
1892  } else {
1893  dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1894  $this->db->rollback();
1895  return -1;
1896  }
1897  } else {
1898  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1899  return -2;
1900  }
1901  }
1902 
1903 
1904  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1912  public function update_statut($user)
1913  {
1914  // phpcs:enable
1915  dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1916 
1917  // If draft, we keep it (should not happen)
1918  if ($this->statut == 0) {
1919  return 1;
1920  }
1921 
1922  // Load $this->lines array
1923  // $this->fetch_lines();
1924 
1925  // $newstatut=1;
1926  // foreach($this->lines as $key => $contractline)
1927  // {
1928  // // if ($contractline) // Loop on each service
1929  // }
1930 
1931  return 1;
1932  }
1933 
1934 
1941  public function getLibStatut($mode)
1942  {
1943  return $this->LibStatut($this->statut, $mode);
1944  }
1945 
1946  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1954  public function LibStatut($status, $mode)
1955  {
1956  // phpcs:enable
1957  global $langs;
1958 
1959  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1960  global $langs;
1961  $langs->load("contracts");
1962  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1963  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1964  $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1965  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1966  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1967  $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1968  }
1969 
1970  $statusType = 'status'.$status;
1971  if ($status == self::STATUS_VALIDATED) {
1972  $statusType = 'status6';
1973  }
1974 
1975  if ($mode == 4 || $mode == 6 || $mode == 7) {
1976  $text = '';
1977  if ($mode == 4) {
1978  $text = '<span class="hideonsmartphone">';
1979  $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
1980  $text .= ' '.$langs->trans("Services");
1981  $text .= ': &nbsp; &nbsp; ';
1982  $text .= '</span>';
1983  }
1984  $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
1985  $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1986  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1987  $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1988  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1989  $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1990  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1991  $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
1992  $text .= ($mode == 7 ? '</span>' : '');
1993  return $text;
1994  } else {
1995  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1996  }
1997  }
1998 
2005  public function getTooltipContentArray($params)
2006  {
2007  global $conf, $langs, $user;
2008 
2009  $langs->load('contracts');
2010 
2011  $datas = [];
2012  $nofetch = !empty($params['nofetch']);
2013 
2014  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2015  return ['optimize' => $langs->trans("ShowContract")];
2016  }
2017  if ($user->hasRight('contrat', 'lire')) {
2018  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2019  /* Status of a contract is status of all services, so disabled
2020  if (isset($this->statut)) {
2021  $label .= ' '.$this->getLibStatut(5);
2022  }*/
2023  $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2024  if (!$nofetch) {
2025  $langs->load('companies');
2026  if (empty($this->thirdparty)) {
2027  $this->fetch_thirdparty();
2028  }
2029  $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2030  }
2031  $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2032  if (!$nofetch) {
2033  $langs->load('project');
2034  if (empty($this->project)) {
2035  $res = $this->fetch_project();
2036  if ($res > 0) {
2037  $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
2038  }
2039  }
2040  }
2041  $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2042  if (!empty($this->total_ht)) {
2043  $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2044  }
2045  if (!empty($this->total_tva)) {
2046  $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2047  }
2048  if (!empty($this->total_ttc)) {
2049  $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2050  }
2051  }
2052  return $datas;
2053  }
2054 
2064  public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2065  {
2066  global $conf, $langs, $user, $hookmanager;
2067 
2068  $result = '';
2069 
2070  $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2071 
2072  //if ($option !== 'nolink')
2073  //{
2074  // Add param to save lastsearch_values or not
2075  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2076  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2077  $add_save_lastsearch_values = 1;
2078  }
2079  if ($add_save_lastsearch_values) {
2080  $url .= '&save_lastsearch_values=1';
2081  }
2082  //}
2083  $params = [
2084  'id' => $this->id,
2085  'objecttype' => $this->element,
2086  'nofetch' => 1,
2087  ];
2088  $classfortooltip = 'classfortooltip';
2089  $dataparams = '';
2090  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2091  $classfortooltip = 'classforajaxtooltip';
2092  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2093  $label = '';
2094  } else {
2095  $label = implode($this->getTooltipContentArray($params));
2096  }
2097 
2098  $linkclose = '';
2099  if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2100  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2101  $label = $langs->trans("ShowContract");
2102  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2103  }
2104  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2105  $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2106  }
2107  $linkstart = '<a href="'.$url.'"';
2108  $linkstart .= $linkclose.'>';
2109  $linkend = '</a>';
2110 
2111  $result .= $linkstart;
2112  if ($withpicto) {
2113  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2114  }
2115  if ($withpicto != 2) {
2116  $result .= ($this->ref ? $this->ref : $this->id);
2117  }
2118  $result .= $linkend;
2119 
2120  global $action;
2121  $hookmanager->initHooks(array('contractdao'));
2122  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2123  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2124  if ($reshook > 0) {
2125  $result = $hookmanager->resPrint;
2126  } else {
2127  $result .= $hookmanager->resPrint;
2128  }
2129 
2130  return $result;
2131  }
2132 
2139  public function info($id)
2140  {
2141  $sql = "SELECT c.rowid, c.ref, c.datec,";
2142  $sql .= " c.tms as date_modification,";
2143  $sql .= " fk_user_author";
2144  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2145  $sql .= " WHERE c.rowid = ".((int) $id);
2146 
2147  $result = $this->db->query($sql);
2148  if ($result) {
2149  if ($this->db->num_rows($result)) {
2150  $obj = $this->db->fetch_object($result);
2151 
2152  $this->id = $obj->rowid;
2153 
2154  if ($obj->fk_user_author) {
2155  $cuser = new User($this->db);
2156  $cuser->fetch($obj->fk_user_author);
2157  $this->user_creation = $cuser;
2158  }
2159 
2160  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2161  $this->date_creation = $this->db->jdate($obj->datec);
2162  $this->date_modification = $this->db->jdate($obj->date_modification);
2163  }
2164 
2165  $this->db->free($result);
2166  } else {
2167  dol_print_error($this->db);
2168  }
2169  }
2170 
2171  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2178  public function array_detail($status = -1)
2179  {
2180  // phpcs:enable
2181  $tab = array();
2182 
2183  $sql = "SELECT cd.rowid";
2184  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2185  $sql .= " WHERE fk_contrat =".((int) $this->id);
2186  if ($status >= 0) {
2187  $sql .= " AND statut = ".((int) $status);
2188  }
2189 
2190  dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2191  $resql = $this->db->query($sql);
2192  if ($resql) {
2193  $num = $this->db->num_rows($resql);
2194  $i = 0;
2195  while ($i < $num) {
2196  $obj = $this->db->fetch_object($resql);
2197  $tab[$i] = $obj->rowid;
2198  $i++;
2199  }
2200  return $tab;
2201  } else {
2202  $this->error = $this->db->error();
2203  return -1;
2204  }
2205  }
2206 
2216  public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2217  {
2218  $tab = array();
2219 
2220  $sql = "SELECT c.rowid";
2221  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2222  if (!empty($product_categories)) {
2223  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2224  $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)).")";
2225  }
2226  $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2227  $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2228  $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2229  $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2230  $sql .= " GROUP BY c.rowid";
2231 
2232  dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2233  $resql = $this->db->query($sql);
2234  if ($resql) {
2235  $num = $this->db->num_rows($resql);
2236  $i = 0;
2237  while ($i < $num) {
2238  $obj = $this->db->fetch_object($resql);
2239  $contrat = new Contrat($this->db);
2240  $contrat->fetch($obj->rowid);
2241  $tab[$contrat->id] = $contrat;
2242  $i++;
2243  }
2244  return $tab;
2245  } else {
2246  $this->error = $this->db->lasterror();
2247  return -1;
2248  }
2249  }
2250 
2251 
2252  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2260  public function load_board($user, $mode)
2261  {
2262  // phpcs:enable
2263  global $conf, $langs;
2264 
2265  $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2266  $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2267  $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2268  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2269  $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2270  }
2271 
2272  if ($mode == 'inactive') {
2273  $sql = "SELECT cd.rowid, cd.date_ouverture_prevue 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 = 0";
2278  } elseif ($mode == 'expired') {
2279  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2280  $sql .= $this->from;
2281  $sql .= " WHERE c.statut = 1";
2282  $sql .= " AND c.rowid = cd.fk_contrat";
2283  $sql .= " AND cd.statut = 4";
2284  $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2285  } elseif ($mode == 'active') {
2286  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2287  $sql .= $this->from;
2288  $sql .= " WHERE c.statut = 1";
2289  $sql .= " AND c.rowid = cd.fk_contrat";
2290  $sql .= " AND cd.statut = 4";
2291  //$datetouse = dol_now();
2292  //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2293  }
2294  $sql .= " AND c.fk_soc = s.rowid";
2295  $sql .= " AND c.entity = ".((int) $conf->entity);
2296  if ($user->socid) {
2297  $sql .= " AND c.fk_soc = ".((int) $user->socid);
2298  }
2299  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2300  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2301  }
2302 
2303  $resql = $this->db->query($sql);
2304  if ($resql) {
2305  $langs->load("contracts");
2306  $now = dol_now();
2307 
2308  if ($mode == 'inactive') {
2309  $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2310  $label = $langs->trans("BoardNotActivatedServices");
2311  $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2312  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2313  } elseif ($mode == 'expired') {
2314  $warning_delay = $conf->contrat->services->expires->warning_delay;
2315  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2316  $label = $langs->trans("BoardExpiredServices");
2317  $labelShort = $langs->trans("BoardExpiredServicesShort");
2318  } else {
2319  $warning_delay = $conf->contrat->services->expires->warning_delay;
2320  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2321  //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
2322  //if ($warning_delay >= 0) $url.='&amp;filter=expired';
2323  $label = $langs->trans("BoardRunningServices");
2324  $labelShort = $langs->trans("BoardRunningServicesShort");
2325  }
2326 
2327  $response = new WorkboardResponse();
2328  $response->warning_delay = $warning_delay / 60 / 60 / 24;
2329  $response->label = $label;
2330  $response->labelShort = $labelShort;
2331  $response->url = $url;
2332  $response->img = img_object('', "contract");
2333 
2334  while ($obj = $this->db->fetch_object($resql)) {
2335  $response->nbtodo++;
2336 
2337  if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2338  $response->nbtodolate++;
2339  }
2340  }
2341 
2342  return $response;
2343  } else {
2344  dol_print_error($this->db);
2345  $this->error = $this->db->error();
2346  return -1;
2347  }
2348  }
2349 
2350  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2356  public function load_state_board()
2357  {
2358  // phpcs:enable
2359  global $conf, $user;
2360 
2361  $this->nb = array();
2362  $clause = "WHERE";
2363 
2364  $sql = "SELECT count(c.rowid) as nb";
2365  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2366  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2367  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2368  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2369  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2370  $clause = "AND";
2371  }
2372  $sql .= " ".$clause." c.entity = ".$conf->entity;
2373 
2374  $resql = $this->db->query($sql);
2375  if ($resql) {
2376  while ($obj = $this->db->fetch_object($resql)) {
2377  $this->nb["contracts"] = $obj->nb;
2378  }
2379  $this->db->free($resql);
2380  return 1;
2381  } else {
2382  dol_print_error($this->db);
2383  $this->error = $this->db->error();
2384  return -1;
2385  }
2386  }
2387 
2388 
2389  /* gestion des contacts d'un contrat */
2390 
2396  public function getIdBillingContact()
2397  {
2398  return $this->getIdContact('external', 'BILLING');
2399  }
2400 
2406  public function getIdServiceContact()
2407  {
2408  return $this->getIdContact('external', 'SERVICE');
2409  }
2410 
2411 
2419  public function initAsSpecimen()
2420  {
2421  global $user, $langs, $conf;
2422 
2423  // Load array of products prodids
2424  $num_prods = 0;
2425  $prodids = array();
2426  $sql = "SELECT rowid";
2427  $sql .= " FROM ".MAIN_DB_PREFIX."product";
2428  $sql .= " WHERE entity IN (".getEntity('product').")";
2429  $sql .= " AND tosell = 1";
2430  $sql .= $this->db->plimit(100);
2431 
2432  $resql = $this->db->query($sql);
2433  if ($resql) {
2434  $num_prods = $this->db->num_rows($resql);
2435  $i = 0;
2436  while ($i < $num_prods) {
2437  $i++;
2438  $row = $this->db->fetch_row($resql);
2439  $prodids[$i] = $row[0];
2440  }
2441  }
2442 
2443  // Initialise parametres
2444  $this->id = 0;
2445  $this->specimen = 1;
2446 
2447  $this->ref = 'SPECIMEN';
2448  $this->ref_customer = 'SPECIMENCUST';
2449  $this->ref_supplier = 'SPECIMENSUPP';
2450  $this->socid = 1;
2451  $this->statut = 0;
2452  $this->date_creation = (dol_now() - 3600 * 24 * 7);
2453  $this->date_contrat = dol_now();
2454  $this->commercial_signature_id = 1;
2455  $this->commercial_suivi_id = 1;
2456  $this->note_private = 'This is a comment (private)';
2457  $this->note_public = 'This is a comment (public)';
2458  $this->fk_projet = 0;
2459  // Lines
2460  $nbp = 5;
2461  $xnbp = 0;
2462  while ($xnbp < $nbp) {
2463  $line = new ContratLigne($this->db);
2464  $line->qty = 1;
2465  $line->subprice = 100;
2466  $line->price = 100;
2467  $line->tva_tx = 19.6;
2468  $line->remise_percent = 10;
2469  $line->total_ht = 90;
2470  $line->total_ttc = 107.64; // 90 * 1.196
2471  $line->total_tva = 17.64;
2472  $line->date_start = dol_now() - 500000;
2473  $line->date_start_real = dol_now() - 200000;
2474  $line->date_end = dol_now() + 500000;
2475  $line->date_end_real = dol_now() - 100000;
2476  if ($num_prods > 0) {
2477  $prodid = mt_rand(1, $num_prods);
2478  $line->fk_product = $prodids[$prodid];
2479  }
2480  $this->lines[$xnbp] = $line;
2481  $xnbp++;
2482  }
2483  }
2484 
2490  public function getLinesArray()
2491  {
2492  return $this->fetch_lines();
2493  }
2494 
2495 
2507  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2508  {
2509  global $conf, $langs;
2510 
2511  if (!dol_strlen($modele)) {
2512  $modele = ''; // No doc template/generation by default
2513 
2514  if (!empty($this->model_pdf)) {
2515  $modele = $this->model_pdf;
2516  } elseif (!empty($this->modelpdf)) { // deprecated
2517  $modele = $this->modelpdf;
2518  } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
2519  $modele = $conf->global->CONTRACT_ADDON_PDF;
2520  }
2521  }
2522 
2523  if (empty($modele)) {
2524  return 0;
2525  } else {
2526  $langs->load("contracts");
2527  $outputlangs->load("products");
2528 
2529  $modelpath = "core/modules/contract/doc/";
2530  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2531  }
2532  }
2533 
2542  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2543  {
2544  $tables = array(
2545  'contrat'
2546  );
2547 
2548  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2549  }
2550 
2559  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2560  {
2561  $tables = array(
2562  'contratdet'
2563  );
2564 
2565  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2566  }
2567 
2576  public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2577  {
2578  global $db, $langs, $conf, $hookmanager, $extrafields;
2579 
2580  dol_include_once('/projet/class/project.class.php');
2581 
2582  $error = 0;
2583 
2584  $this->fetch($this->id);
2585 
2586  // Load dest object
2587  $clonedObj = clone $this;
2588  $clonedObj->socid = $socid;
2589 
2590  $this->db->begin();
2591 
2592  $objsoc = new Societe($this->db);
2593 
2594  $objsoc->fetch($clonedObj->socid);
2595 
2596  // Clean data
2597  $clonedObj->statut = 0;
2598  // Clean extrafields
2599  if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2600  $extrafields->fetch_name_optionals_label($this->table_element);
2601  foreach ($clonedObj->array_options as $key => $option) {
2602  $shortkey = preg_replace('/options_/', '', $key);
2603  //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2604  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2605  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2606  unset($clonedObj->array_options[$key]);
2607  }
2608  }
2609  }
2610 
2611  if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
2612  $this->error = 'ErrorSetupNotComplete';
2613  dol_syslog($this->error);
2614  return -1;
2615  }
2616 
2617  // Set ref
2618  require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
2619  $obj = $conf->global->CONTRACT_ADDON;
2620  $modContract = new $obj();
2621  $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2622 
2623  // get extrafields so they will be clone
2624  foreach ($this->lines as $line) {
2625  $line->fetch_optionals($line->id);
2626  }
2627 
2628  // Create clone
2629  $clonedObj->context['createfromclone'] = 'createfromclone';
2630  $result = $clonedObj->create($user);
2631  if ($result < 0) {
2632  $error++;
2633  $this->error = $clonedObj->error;
2634  $this->errors[] = $clonedObj->error;
2635  } else {
2636  // copy external contacts if same company
2637  if ($this->socid == $clonedObj->socid) {
2638  if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2639  $error++;
2640  }
2641  }
2642  }
2643 
2644  if (!$error) {
2645  foreach ($this->lines as $line) {
2646  $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);
2647  if ($result < 0) {
2648  $error++;
2649  $this->error = $clonedObj->error;
2650  $this->errors[] = $clonedObj->error;
2651  }
2652  }
2653  }
2654 
2655  if (!$error) {
2656  // Hook of thirdparty module
2657  if (is_object($hookmanager)) {
2658  $parameters = array(
2659  'objFrom' => $this,
2660  'clonedObj' => $clonedObj
2661  );
2662  $action = '';
2663  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2664  if ($reshook < 0) {
2665  $this->setErrorsFromObject($hookmanager);
2666  $error++;
2667  }
2668  }
2669  }
2670 
2671  unset($clonedObj->context['createfromclone']);
2672 
2673  // End
2674  if (!$error) {
2675  $this->db->commit();
2676  return $clonedObj->id;
2677  } else {
2678  $this->db->rollback();
2679  return -1;
2680  }
2681  }
2682 
2683 
2693  public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2694  {
2695  global $langs, $user;
2696 
2697  $langs->load("agenda");
2698 
2699  $now = dol_now();
2700 
2701  $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2702 
2703  $error = 0;
2704  $this->output = '';
2705  $this->error='';
2706 
2707  $contractlineprocessed = array();
2708  $contractignored = array();
2709  $contracterror = array();
2710 
2711  dol_syslog(__METHOD__, LOG_DEBUG);
2712 
2713  $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2714  $sql.= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2715  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2716  $sql.= ' WHERE cd.fk_contrat = c.rowid';
2717  $sql.= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2718  $sql.= " AND cd.statut = 4";
2719  if ($thirdparty_id > 0) $sql.=" AND c.fk_soc = ".((int) $thirdparty_id);
2720  //print $sql;
2721 
2722  $resql = $this->db->query($sql);
2723  if ($resql) {
2724  $num = $this->db->num_rows($resql);
2725 
2726  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2727 
2728  $i=0;
2729  while ($i < $num) {
2730  $obj = $this->db->fetch_object($resql);
2731  if ($obj) {
2732  if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2733  continue;
2734  }
2735 
2736  // Load contract
2737  $object = new Contrat($this->db);
2738  $object->fetch($obj->rowid); // fetch also lines
2739  $object->fetch_thirdparty();
2740 
2741  if ($object->id <= 0) {
2742  $error++;
2743  $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2744  continue;
2745  }
2746 
2747  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);
2748 
2749  // Update expiration date of line
2750  $expirationdate = $this->db->jdate($obj->date_fin_validite);
2751  $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2752  $duration_unit = preg_replace('/\d/', '', $obj->duration);
2753  //var_dump($expirationdate.' '.$enddatetoscan);
2754 
2755  // Test if there is pending invoice
2756  $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2757 
2758  if (is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2759  usort($object->linkedObjects['facture'], "cmp");
2760 
2761  //dol_sort_array($contract->linkedObjects['facture'], 'date');
2762  $someinvoicenotpaid=0;
2763  foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2764  if ($invoice->statut == Facture::STATUS_DRAFT) continue; // Draft invoice are not invoice not paid
2765 
2766  if (empty($invoice->paye)) {
2767  $someinvoicenotpaid++;
2768  }
2769  }
2770  if ($someinvoicenotpaid) {
2771  $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2772  $contractignored[$object->id]=$object->ref;
2773  continue;
2774  }
2775  }
2776 
2777  if ($expirationdate && $expirationdate < $enddatetoscan) {
2778  dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2779  $newdate = $expirationdate;
2780  $protecti=0; //$protecti is to avoid infinite loop
2781  while ($newdate < $enddatetoscan && $protecti < 1000) {
2782  $newdate = dol_time_plus_duree($newdate, $duration_value, $duration_unit);
2783  $protecti++;
2784  }
2785 
2786  if ($protecti < 1000) { // If not, there is a pb
2787  // We will update the end of date of contrat, so first we refresh contract data
2788  dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2789 
2790  $this->db->begin();
2791 
2792  $errorforlocaltransaction = 0;
2793 
2794  $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2795  $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2796 
2797  $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2798  $sqlupdate.= ' WHERE rowid = '.((int) $obj->lid);
2799  $resqlupdate = $this->db->query($sqlupdate);
2800  if ($resqlupdate) {
2801  $contractlineprocessed[$obj->lid]=$object->ref;
2802 
2803  $actioncode = 'RENEW_CONTRACT';
2804  $now = dol_now();
2805 
2806  // Create an event
2807  $actioncomm = new ActionComm($this->db);
2808  $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2809  $actioncomm->code = 'AC_'.$actioncode;
2810  $actioncomm->label = $label;
2811  $actioncomm->datep = $now;
2812  $actioncomm->datef = $now;
2813  $actioncomm->percentage = -1; // Not applicable
2814  $actioncomm->socid = $object->thirdparty->id;
2815  $actioncomm->authorid = $user->id; // User saving action
2816  $actioncomm->userownerid = $user->id; // Owner of action
2817  $actioncomm->fk_element = $object->id;
2818  $actioncomm->elementtype = 'contract';
2819  $actioncomm->note_private = $comment;
2820 
2821  $ret = $actioncomm->create($user); // User creating action
2822  } else {
2823  $contracterror[$object->id]=$object->ref;
2824 
2825  $error++;
2826  $errorforlocaltransaction++;
2827  $this->error = $this->db->lasterror();
2828  }
2829 
2830  if (! $errorforlocaltransaction) {
2831  $this->db->commit();
2832  } else {
2833  $this->db->rollback();
2834  }
2835  } else {
2836  $error++;
2837  $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2838  dol_syslog($this->error, LOG_ERR);
2839  }
2840  }
2841  }
2842  $i++;
2843  }
2844  } else {
2845  $error++;
2846  $this->error = $this->db->lasterror();
2847  }
2848 
2849  $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed)>0 ? ' : '.join(',', $contractlineprocessed) : '');
2850 
2851  return ($error ? 1: 0);
2852  }
2853 
2861  public function getKanbanView($option = '', $arraydata = null)
2862  {
2863  global $langs;
2864 
2865  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2866 
2867  $return = '<div class="box-flex-item box-flex-grow-zero">';
2868  $return .= '<div class="info-box info-box-sm">';
2869  $return .= '<span class="info-box-icon bg-infobox-action">';
2870  $return .= img_picto('', $this->picto);
2871  $return .= '</span>';
2872  $return .= '<div class="info-box-content">';
2873  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2874  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2875  if (!empty($arraydata['thirdparty'])) {
2876  $tmpthirdparty = $arraydata['thirdparty'];
2877  $return .= '<br><div class="info-box-label inline-block">'.$tmpthirdparty->getNomUrl(1).'</div>';
2878  }
2879  if (property_exists($this, 'date_contrat')) {
2880  $return .= '<br><span class="opacitymedium">'.$langs->trans("DateContract").' : </span><span class="info-box-label">'.dol_print_date($this->date_contrat, 'day').'</span>';
2881  }
2882  if (method_exists($this, 'getLibStatut')) {
2883  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(7).'</div>';
2884  }
2885  $return .= '</div>';
2886  $return .= '</div>';
2887  $return .= '</div>';
2888  return $return;
2889  }
2890 }
2891 
2892 
2897 {
2901  public $element = 'contratdet';
2902 
2906  public $table_element = 'contratdet';
2907 
2912  public $element_for_permission = 'contrat';
2913 
2917  public $id;
2918 
2922  public $ref;
2923 
2924  public $tms;
2925 
2929  public $fk_contrat;
2930 
2934  public $fk_product;
2935 
2936  public $statut; // 0 inactive, 4 active, 5 closed
2937  public $type; // 0 for product, 1 for service
2938 
2943  public $label;
2944 
2949  public $libelle;
2950 
2954  public $description;
2955 
2956  public $product_type; // 0 for product, 1 for service
2957  public $product_ref;
2958  public $product_label;
2959 
2960  public $date_commande;
2961 
2962  public $date_start; // date start planned
2963  public $date_start_real; // date start real
2964  public $date_end; // date end planned
2965  public $date_end_real; // date end real
2966 
2967  public $tva_tx;
2968  public $vat_src_code;
2969  public $localtax1_tx;
2970  public $localtax2_tx;
2971  public $localtax1_type; // Local tax 1 type
2972  public $localtax2_type; // Local tax 2 type
2973  public $qty;
2974  public $remise_percent;
2975  public $remise;
2976 
2980  public $fk_remise_except;
2981 
2982  public $subprice; // Unit price HT
2983 
2989  public $price;
2990 
2991  public $price_ht;
2992 
2993  public $total_ht;
2994  public $total_tva;
2995  public $total_localtax1;
2996  public $total_localtax2;
2997  public $total_ttc;
2998 
3002  public $fk_fournprice;
3003 
3004  public $pa_ht;
3005 
3006  public $info_bits;
3007 
3011  public $fk_user_author;
3012 
3016  public $fk_user_ouverture;
3017 
3021  public $fk_user_cloture;
3022 
3023  public $commentaire;
3024 
3025 
3029  public $rang = 0;
3030 
3031 
3032  const STATUS_INITIAL = 0;
3033  const STATUS_OPEN = 4;
3034  const STATUS_CLOSED = 5;
3035 
3036 
3037  // BEGIN MODULEBUILDER PROPERTIES
3041  public $fields = array(
3042  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
3043  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
3044  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
3045  'qty' =>array('type'=>'integer', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>35, 'isameasure'=>1),
3046  'total_ht' =>array('type'=>'integer', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>36, 'isameasure'=>1),
3047  'total_tva' =>array('type'=>'integer', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>37, 'isameasure'=>1),
3048  'total_ttc' =>array('type'=>'integer', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>38, 'isameasure'=>1),
3049  //'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
3050  //'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3051  'fk_contrat' =>array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'Contract', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3052  'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
3053  //'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
3054  'note_private' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
3055  'note_public' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
3056  //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
3057  //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
3058  //'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
3059  'fk_user_ouverture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserStartingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3060  'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3061  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 4=>'Open', 5=>'Closed')),
3062  'rang' =>array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'position'=>500, 'default' =>0)
3063  );
3064  // END MODULEBUILDER PROPERTIES
3065 
3066 
3072  public function __construct($db)
3073  {
3074  $this->db = $db;
3075  }
3076 
3077 
3084  public function getLibStatut($mode)
3085  {
3086  return $this->LibStatut($this->statut, $mode, ((!empty($this->date_end)) ? ($this->date_end < dol_now() ? 1 : 0) : -1));
3087  }
3088 
3089  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3099  public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
3100  {
3101  // phpcs:enable
3102  global $langs;
3103  $langs->load("contracts");
3104 
3105  if ($status == self::STATUS_INITIAL) {
3106  $labelStatus = $langs->transnoentities("ServiceStatusInitial");
3107  $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
3108  } elseif ($status == self::STATUS_OPEN && $expired == -1) {
3109  $labelStatus = $langs->transnoentities("ServiceStatusRunning");
3110  $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
3111  } elseif ($status == self::STATUS_OPEN && $expired == 0) {
3112  $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
3113  $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
3114  } elseif ($status == self::STATUS_OPEN && $expired == 1) {
3115  $labelStatus = $langs->transnoentities("ServiceStatusLate");
3116  $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
3117  } elseif ($status == self::STATUS_CLOSED) {
3118  $labelStatus = $langs->transnoentities("ServiceStatusClosed");
3119  $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
3120  }
3121 
3122  $statusType = 'status'.$status;
3123  if ($status == self::STATUS_OPEN && $expired == 1) {
3124  $statusType = 'status1';
3125  }
3126  if ($status == self::STATUS_CLOSED) {
3127  $statusType = 'status6';
3128  }
3129 
3130  $params = array(); $reg = array();
3131  if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
3132  $params = array('badgeParams'=>array('css' => $reg[1]));
3133  }
3134  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
3135  }
3136 
3143  public function getTooltipContentArray($params)
3144  {
3145  global $conf, $langs, $user;
3146 
3147  $datas = [];
3148  $datas['label'] = $langs->trans("ShowContractOfService").': '.$this->label;
3149  if (empty($datas['label'])) {
3150  $datas['label'] = $this->description;
3151  }
3152 
3153  return $datas;
3154  }
3155 
3163  public function getNomUrl($withpicto = 0, $maxlength = 0)
3164  {
3165  global $langs;
3166 
3167  $result = '';
3168  $label = $langs->trans("ShowContractOfService").': '.$this->label;
3169  if (empty($label)) {
3170  $label = $this->description;
3171  }
3172  $classfortooltip = 'classfortooltip';
3173  $dataparams = '';
3174  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3175  $params = [
3176  'id' => $this->fk_contrat,
3177  'objecttype' => $this->element,
3178  ];
3179  $classfortooltip = 'classforajaxtooltip';
3180  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3181  $label = '';
3182  }
3183 
3184  $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'"';
3185  $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3186  $link .= $dataparams.' class="'.$classfortooltip.'">';
3187  $linkend = '</a>';
3188 
3189  $picto = 'service';
3190  if ($this->type == 0) {
3191  $picto = 'product';
3192  }
3193 
3194  if ($withpicto) {
3195  $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
3196  }
3197  if ($withpicto && $withpicto != 2) {
3198  $result .= ' ';
3199  }
3200  if ($withpicto != 2) {
3201  $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
3202  }
3203  return $result;
3204  }
3205 
3213  public function fetch($id, $ref = '')
3214  {
3215  // Check parameters
3216  if (empty($id) && empty($ref)) {
3217  return -1;
3218  }
3219 
3220  $sql = "SELECT";
3221  $sql .= " t.rowid,";
3222  $sql .= " t.tms,";
3223  $sql .= " t.fk_contrat,";
3224  $sql .= " t.fk_product,";
3225  $sql .= " t.statut,";
3226  $sql .= " t.label,"; // This field is not used. Only label of product
3227  $sql .= " p.ref as product_ref,";
3228  $sql .= " p.label as product_label,";
3229  $sql .= " p.description as product_desc,";
3230  $sql .= " p.fk_product_type as product_type,";
3231  $sql .= " t.description,";
3232  $sql .= " t.date_commande,";
3233  $sql .= " t.date_ouverture_prevue as date_start,";
3234  $sql .= " t.date_ouverture as date_start_real,";
3235  $sql .= " t.date_fin_validite as date_end,";
3236  $sql .= " t.date_cloture as date_end_real,";
3237  $sql .= " t.tva_tx,";
3238  $sql .= " t.vat_src_code,";
3239  $sql .= " t.localtax1_tx,";
3240  $sql .= " t.localtax2_tx,";
3241  $sql .= " t.localtax1_type,";
3242  $sql .= " t.localtax2_type,";
3243  $sql .= " t.qty,";
3244  $sql .= " t.remise_percent,";
3245  $sql .= " t.remise,";
3246  $sql .= " t.fk_remise_except,";
3247  $sql .= " t.subprice,";
3248  $sql .= " t.price_ht,";
3249  $sql .= " t.total_ht,";
3250  $sql .= " t.total_tva,";
3251  $sql .= " t.total_localtax1,";
3252  $sql .= " t.total_localtax2,";
3253  $sql .= " t.total_ttc,";
3254  $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
3255  $sql .= " t.buy_price_ht as pa_ht,";
3256  $sql .= " t.info_bits,";
3257  $sql .= " t.fk_user_author,";
3258  $sql .= " t.fk_user_ouverture,";
3259  $sql .= " t.fk_user_cloture,";
3260  $sql .= " t.commentaire,";
3261  $sql .= " t.fk_unit,";
3262  $sql .= " t.rang";
3263  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
3264  if ($id) {
3265  $sql .= " WHERE t.rowid = ".((int) $id);
3266  }
3267  if ($ref) {
3268  $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
3269  }
3270 
3271  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
3272  $resql = $this->db->query($sql);
3273  if ($resql) {
3274  if ($this->db->num_rows($resql)) {
3275  $obj = $this->db->fetch_object($resql);
3276 
3277  $this->id = $obj->rowid;
3278  $this->ref = $obj->rowid;
3279 
3280  $this->tms = $this->db->jdate($obj->tms);
3281  $this->fk_contrat = $obj->fk_contrat;
3282  $this->fk_product = $obj->fk_product;
3283  $this->statut = $obj->statut;
3284  $this->product_ref = $obj->product_ref;
3285  $this->product_label = $obj->product_label;
3286  $this->product_description = $obj->product_description;
3287  $this->product_type = $obj->product_type;
3288  $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
3289  $this->description = $obj->description;
3290  $this->date_commande = $this->db->jdate($obj->date_commande);
3291 
3292  $this->date_start = $this->db->jdate($obj->date_start);
3293  $this->date_start_real = $this->db->jdate($obj->date_start_real);
3294  $this->date_end = $this->db->jdate($obj->date_end);
3295  $this->date_end_real = $this->db->jdate($obj->date_end_real);
3296  // For backward compatibility
3297  //$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
3298  //$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
3299  //$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
3300  //$this->date_cloture = $this->db->jdate($obj->date_cloture);
3301 
3302  $this->tva_tx = $obj->tva_tx;
3303  $this->vat_src_code = $obj->vat_src_code;
3304  $this->localtax1_tx = $obj->localtax1_tx;
3305  $this->localtax2_tx = $obj->localtax2_tx;
3306  $this->localtax1_type = $obj->localtax1_type;
3307  $this->localtax2_type = $obj->localtax2_type;
3308  $this->qty = $obj->qty;
3309  $this->remise_percent = $obj->remise_percent;
3310  $this->fk_remise_except = $obj->fk_remise_except;
3311  $this->subprice = $obj->subprice;
3312  $this->price_ht = $obj->price_ht;
3313  $this->total_ht = $obj->total_ht;
3314  $this->total_tva = $obj->total_tva;
3315  $this->total_localtax1 = $obj->total_localtax1;
3316  $this->total_localtax2 = $obj->total_localtax2;
3317  $this->total_ttc = $obj->total_ttc;
3318  $this->info_bits = $obj->info_bits;
3319  $this->fk_user_author = $obj->fk_user_author;
3320  $this->fk_user_ouverture = $obj->fk_user_ouverture;
3321  $this->fk_user_cloture = $obj->fk_user_cloture;
3322  $this->commentaire = $obj->commentaire;
3323  $this->fk_fournprice = $obj->fk_fournprice;
3324 
3325  $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
3326  $this->pa_ht = $marginInfos[0];
3327  $this->fk_unit = $obj->fk_unit;
3328 
3329  $this->rang = $obj->rang;
3330 
3331  $this->fetch_optionals();
3332  }
3333 
3334  $this->db->free($resql);
3335 
3336  return 1;
3337  } else {
3338  $this->error = "Error ".$this->db->lasterror();
3339  return -1;
3340  }
3341  }
3342 
3343 
3351  public function update($user, $notrigger = 0)
3352  {
3353  global $conf, $langs, $mysoc;
3354 
3355  $error = 0;
3356 
3357  // Clean parameters
3358  $this->fk_contrat = (int) $this->fk_contrat;
3359  $this->fk_product = (int) $this->fk_product;
3360  $this->statut = (int) $this->statut;
3361  $this->label = trim($this->label);
3362  $this->description = trim($this->description);
3363  $this->vat_src_code = trim($this->vat_src_code);
3364  $this->tva_tx = trim($this->tva_tx);
3365  $this->localtax1_tx = trim($this->localtax1_tx);
3366  $this->localtax2_tx = trim($this->localtax2_tx);
3367  $this->qty = trim($this->qty);
3368  $this->remise_percent = trim($this->remise_percent);
3369  $this->fk_remise_except = (int) $this->fk_remise_except;
3370  $this->subprice = price2num($this->subprice);
3371  $this->price_ht = price2num($this->price_ht);
3372  $this->total_ht = trim($this->total_ht);
3373  $this->total_tva = trim($this->total_tva);
3374  $this->total_localtax1 = trim($this->total_localtax1);
3375  $this->total_localtax2 = trim($this->total_localtax2);
3376  $this->total_ttc = trim($this->total_ttc);
3377  $this->info_bits = trim($this->info_bits);
3378  $this->fk_user_author = (int) $this->fk_user_author;
3379  $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
3380  $this->fk_user_cloture = (int) $this->fk_user_cloture;
3381  $this->commentaire = trim($this->commentaire);
3382  $this->rang = (int) $this->rang;
3383  //if (empty($this->subprice)) $this->subprice = 0;
3384  if (empty($this->price_ht)) {
3385  $this->price_ht = 0;
3386  }
3387  if (empty($this->total_ht)) {
3388  $this->total_ht = 0;
3389  }
3390  if (empty($this->total_tva)) {
3391  $this->total_tva = 0;
3392  }
3393  if (empty($this->total_ttc)) {
3394  $this->total_ttc = 0;
3395  }
3396  if (empty($this->localtax1_tx)) {
3397  $this->localtax1_tx = 0;
3398  }
3399  if (empty($this->localtax2_tx)) {
3400  $this->localtax2_tx = 0;
3401  }
3402  if (empty($this->remise_percent)) {
3403  $this->remise_percent = 0;
3404  }
3405  // For backward compatibility
3406  if (empty($this->date_start)) {
3407  $this->date_start = $this->date_start;
3408  }
3409  if (empty($this->date_start_real)) {
3410  $this->date_start_real = $this->date_start_real;
3411  }
3412  if (empty($this->date_end)) {
3413  $this->date_end = $this->date_end;
3414  }
3415  if (empty($this->date_end_real)) {
3416  $this->date_end_real = $this->date_end_real;
3417  }
3418 
3419  // Calcul du total TTC et de la TVA pour la ligne a partir de
3420  // qty, pu, remise_percent et txtva
3421  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3422  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3423  $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->thirdparty, $mysoc);
3424 
3425  $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);
3426  $this->total_ht = $tabprice[0];
3427  $this->total_tva = $tabprice[1];
3428  $this->total_ttc = $tabprice[2];
3429  $this->total_localtax1 = $tabprice[9];
3430  $this->total_localtax2 = $tabprice[10];
3431 
3432  if (empty($this->pa_ht)) {
3433  $this->pa_ht = 0;
3434  }
3435 
3436  // if buy price not defined, define buyprice as configured in margin admin
3437  if ($this->pa_ht == 0) {
3438  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
3439  return $result;
3440  } else {
3441  $this->pa_ht = $result;
3442  }
3443  }
3444 
3445  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
3446  if (empty($this->oldcopy)) {
3447  $this->oldcopy = dol_clone($this);
3448  }
3449 
3450  $this->db->begin();
3451 
3452  // Update request
3453  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3454  $sql .= " fk_contrat = ".((int) $this->fk_contrat).",";
3455  $sql .= " fk_product = ".($this->fk_product ? ((int) $this->fk_product) : 'null').",";
3456  $sql .= " statut = ".((int) $this->statut).",";
3457  $sql .= " label = '".$this->db->escape($this->label)."',";
3458  $sql .= " description = '".$this->db->escape($this->description)."',";
3459  $sql .= " date_commande = ".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
3460  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3461  $sql .= " date_ouverture = ".($this->date_start_real != '' ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3462  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3463  $sql .= " date_cloture = ".($this->date_end_real != '' ? "'".$this->db->idate($this->date_end_real)."'" : "null").",";
3464  $sql .= " vat_src_code = '".$this->db->escape($this->vat_src_code)."',";
3465  $sql .= " tva_tx = ".price2num($this->tva_tx).",";
3466  $sql .= " localtax1_tx = ".price2num($this->localtax1_tx).",";
3467  $sql .= " localtax2_tx = ".price2num($this->localtax2_tx).",";
3468  $sql .= " qty = ".price2num($this->qty).",";
3469  $sql .= " remise_percent = ".price2num($this->remise_percent).",";
3470  $sql .= " remise = ".($this->remise ?price2num($this->remise) : "null").",";
3471  $sql .= " fk_remise_except = ".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
3472  $sql .= " subprice = ".($this->subprice != '' ? $this->subprice : "null").",";
3473  $sql .= " price_ht = ".($this->price_ht != '' ? $this->price_ht : "null").",";
3474  $sql .= " total_ht = ".$this->total_ht.",";
3475  $sql .= " total_tva = ".$this->total_tva.",";
3476  $sql .= " total_localtax1 = ".$this->total_localtax1.",";
3477  $sql .= " total_localtax2 = ".$this->total_localtax2.",";
3478  $sql .= " total_ttc = ".$this->total_ttc.",";
3479  $sql .= " fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
3480  $sql .= " buy_price_ht = '".price2num($this->pa_ht)."',";
3481  $sql .= " info_bits = '".$this->db->escape($this->info_bits)."',";
3482  $sql .= " fk_user_author = ".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
3483  $sql .= " fk_user_ouverture = ".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
3484  $sql .= " fk_user_cloture = ".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3485  $sql .= " commentaire = '".$this->db->escape($this->commentaire)."',";
3486  $sql .= " fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit).",";
3487  $sql .= " rang = ".(empty($this->rang) ? '0' : (int) $this->rang);
3488  $sql .= " WHERE rowid = ".((int) $this->id);
3489 
3490  dol_syslog(get_class($this)."::update", LOG_DEBUG);
3491  $resql = $this->db->query($sql);
3492  if (!$resql) {
3493  $this->error = "Error ".$this->db->lasterror();
3494  $error++;
3495  }
3496 
3497  if (!$error) { // For avoid conflicts if trigger used
3498  $result = $this->insertExtraFields();
3499  if ($result < 0) {
3500  $error++;
3501  }
3502  }
3503 
3504  // If we change a planned date (start or end) of one contract line, sync dates for all other services too
3505  if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) {
3506  dol_syslog(get_class($this)."::update CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES is on so we update date for all lines", LOG_DEBUG);
3507 
3508  if ($this->date_start != $this->oldcopy->date_start) {
3509  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3510  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
3511  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3512 
3513  $resql = $this->db->query($sql);
3514  if (!$resql) {
3515  $error++;
3516  $this->error = "Error ".$this->db->lasterror();
3517  }
3518  }
3519  if ($this->date_end != $this->oldcopy->date_end) {
3520  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3521  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
3522  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3523 
3524  $resql = $this->db->query($sql);
3525  if (!$resql) {
3526  $error++;
3527  $this->error = "Error ".$this->db->lasterror();
3528  }
3529  }
3530  }
3531 
3532  if (!$error && !$notrigger) {
3533  // Call trigger
3534  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
3535  if ($result < 0) {
3536  $error++;
3537  $this->db->rollback();
3538  }
3539  // End call triggers
3540  }
3541 
3542  if (!$error) {
3543  $this->db->commit();
3544  return 1;
3545  } else {
3546  $this->db->rollback();
3547  $this->errors[] = $this->error;
3548  return -1;
3549  }
3550  }
3551 
3552 
3553  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3560  public function update_total()
3561  {
3562  // phpcs:enable
3563  $this->db->begin();
3564 
3565  // Mise a jour ligne en base
3566  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3567  $sql .= " total_ht=".price2num($this->total_ht, 'MT');
3568  $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
3569  $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT');
3570  $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT');
3571  $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
3572  $sql .= " WHERE rowid = ".((int) $this->id);
3573 
3574  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3575 
3576  $resql = $this->db->query($sql);
3577  if ($resql) {
3578  $this->db->commit();
3579  return 1;
3580  } else {
3581  $this->error = $this->db->error();
3582  $this->db->rollback();
3583  return -2;
3584  }
3585  }
3586 
3587 
3594  public function insert($notrigger = 0)
3595  {
3596  global $conf, $user;
3597 
3598  $error = 0;
3599 
3600  // Insertion dans la base
3601  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3602  $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3603  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3604  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3605  $sql .= " info_bits,";
3606  $sql .= " rang,";
3607  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3608  if ($this->date_start > 0) {
3609  $sql .= ",date_ouverture_prevue";
3610  }
3611  if ($this->date_end > 0) {
3612  $sql .= ",date_fin_validite";
3613  }
3614  $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3615  $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3616  $sql .= " '".$this->db->escape($this->qty)."',";
3617  $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3618  $sql .= " '".$this->db->escape($this->tva_tx)."',";
3619  $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3620  $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3621  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3622  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3623  $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3624  $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3625  $sql .= " '".$this->db->escape($this->info_bits)."',";
3626  $sql .= " ".(empty($this->rang) ? '0' : (int) $this->rang).",";
3627  $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3628  if ($this->fk_fournprice > 0) {
3629  $sql .= ' '.((int) $this->fk_fournprice).',';
3630  } else {
3631  $sql .= ' null,';
3632  }
3633  if ($this->pa_ht > 0) {
3634  $sql .= ' '.((float) price2num($this->pa_ht));
3635  } else {
3636  $sql .= ' null';
3637  }
3638  if ($this->date_start > 0) {
3639  $sql .= ",'".$this->db->idate($this->date_start)."'";
3640  }
3641  if ($this->date_end > 0) {
3642  $sql .= ",'".$this->db->idate($this->date_end)."'";
3643  }
3644  $sql .= ")";
3645 
3646  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3647 
3648  $resql = $this->db->query($sql);
3649  if ($resql) {
3650  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3651 
3652  // Insert of extrafields
3653  if (!$error) {
3654  $result = $this->insertExtraFields();
3655  if ($result < 0) {
3656  $this->db->rollback();
3657  return -1;
3658  }
3659  }
3660 
3661  if (!$notrigger) {
3662  // Call trigger
3663  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3664  if ($result < 0) {
3665  $this->db->rollback();
3666  return -1;
3667  }
3668  // End call triggers
3669  }
3670 
3671  $this->db->commit();
3672  return 1;
3673  } else {
3674  $this->db->rollback();
3675  $this->error = $this->db->error()." sql=".$sql;
3676  return -1;
3677  }
3678  }
3679 
3680  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3690  public function active_line($user, $date, $date_end = '', $comment = '')
3691  {
3692  // phpcs:enable
3693  global $langs, $conf;
3694 
3695  $error = 0;
3696 
3697  $this->db->begin();
3698 
3699  $this->statut = ContratLigne::STATUS_OPEN;
3700  $this->date_start_real = $date;
3701  $this->date_end = $date_end;
3702  $this->fk_user_ouverture = $user->id;
3703  $this->date_end_real = null;
3704  $this->commentaire = $comment;
3705 
3706  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) $this->statut).",";
3707  $sql .= " date_ouverture = ".(dol_strlen($this->date_start_real) != 0 ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3708  if ($date_end >= 0) {
3709  $sql .= " date_fin_validite = ".(dol_strlen($this->date_end) != 0 ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3710  }
3711  $sql .= " fk_user_ouverture = ".((int) $this->fk_user_ouverture).",";
3712  $sql .= " date_cloture = null,";
3713  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3714  $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3715 
3716  dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3717  $resql = $this->db->query($sql);
3718  if ($resql) {
3719  // Call trigger
3720  $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3721  if ($result < 0) {
3722  $error++;
3723  }
3724  // End call triggers
3725 
3726  if (!$error) {
3727  $this->db->commit();
3728  return 1;
3729  } else {
3730  $this->db->rollback();
3731  return -1;
3732  }
3733  } else {
3734  $this->error = $this->db->lasterror();
3735  $this->db->rollback();
3736  return -1;
3737  }
3738  }
3739 
3740  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3750  public function close_line($user, $date_end_real, $comment = '', $notrigger = 0)
3751  {
3752  // phpcs:enable
3753  global $langs, $conf;
3754 
3755  // Update object
3756  $this->date_cloture = $date_end_real;
3757  $this->date_end_real = $date_end_real;
3758  $this->fk_user_cloture = $user->id;
3759  $this->commentaire = $comment;
3760 
3761  $error = 0;
3762 
3763  // statut actif : 4
3764 
3765  $this->db->begin();
3766 
3767  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
3768  $sql .= " date_cloture = '".$this->db->idate($date_end_real)."',";
3769  $sql .= " fk_user_cloture = ".((int) $user->id).",";
3770  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3771  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
3772 
3773  $resql = $this->db->query($sql);
3774  if ($resql) {
3775  if (!$notrigger) {
3776  // Call trigger
3777  $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3778  if ($result < 0) {
3779  $error++;
3780  $this->db->rollback();
3781  return -1;
3782  }
3783  // End call triggers
3784  }
3785 
3786  $this->db->commit();
3787  return 1;
3788  } else {
3789  $this->error = $this->db->lasterror();
3790  $this->db->rollback();
3791  return -1;
3792  }
3793  }
3794 }
$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:1507
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