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->errors = array_merge($this->errors, $contractline->errors);
1625  $this->error = $contractline->error;
1626  $error++;
1627  }
1628  }
1629 
1630  if (empty($error)) {
1631  // Call trigger
1632  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1633  if ($result < 0) {
1634  $error++;
1635  }
1636  // End call triggers
1637  }
1638 
1639  if ($error) {
1640  $this->db->rollback();
1641  return -1;
1642  } else {
1643  $this->db->commit();
1644  return $contractlineid;
1645  }
1646  } else {
1647  $this->db->rollback();
1648  $this->error = $this->db->error()." sql=".$sql;
1649  return -1;
1650  }
1651  } else {
1652  dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1653  return -2;
1654  }
1655  }
1656 
1681  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)
1682  {
1683  global $user, $conf, $langs, $mysoc;
1684 
1685  $error = 0;
1686 
1687  // Clean parameters
1688  $qty = trim($qty);
1689  $desc = trim($desc);
1690  $desc = trim($desc);
1691  $price = price2num($pu);
1692  $tvatx = price2num($tvatx);
1693  $localtax1tx = price2num($localtax1tx);
1694  $localtax2tx = price2num($localtax2tx);
1695  $pa_ht = price2num($pa_ht);
1696  if (empty($fk_fournprice)) {
1697  $fk_fournprice = 0;
1698  }
1699  if (empty($rang)) {
1700  $rang = 0;
1701  }
1702 
1703  $subprice = $price;
1704  $remise = 0;
1705  if (dol_strlen($remise_percent) > 0) {
1706  $remise = round(($pu * $remise_percent / 100), 2);
1707  $price = $pu - $remise;
1708  } else {
1709  $remise_percent = 0;
1710  }
1711 
1712  if ($date_start && $date_end && $date_start > $date_end) {
1713  $langs->load("errors");
1714  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1715  return -1;
1716  }
1717 
1718  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");
1719 
1720  $this->db->begin();
1721 
1722  // Calcul du total TTC et de la TVA pour la ligne a partir de
1723  // qty, pu, remise_percent et tvatx
1724  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1725  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1726 
1727  $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1728  $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1729 
1730  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1731  $total_ht = $tabprice[0];
1732  $total_tva = $tabprice[1];
1733  $total_ttc = $tabprice[2];
1734  $total_localtax1 = $tabprice[9];
1735  $total_localtax2 = $tabprice[10];
1736 
1737  $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1738  $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1739 
1740  // TODO A virer
1741  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1742  $remise = 0;
1743  $price = price2num(round($pu, 2));
1744  if (dol_strlen($remise_percent) > 0) {
1745  $remise = round(($pu * $remise_percent / 100), 2);
1746  $price = $pu - $remise;
1747  }
1748 
1749  if (empty($pa_ht)) {
1750  $pa_ht = 0;
1751  }
1752 
1753  // if buy price not defined, define buyprice as configured in margin admin
1754  if ($this->pa_ht == 0) {
1755  if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
1756  return $result;
1757  } else {
1758  $pa_ht = $result;
1759  }
1760  }
1761 
1762  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1763  $sql .= ",price_ht = ".((float) price2num($price));
1764  $sql .= ",subprice = ".((float) price2num($subprice));
1765  $sql .= ",remise = ".((float) price2num($remise));
1766  $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1767  $sql .= ",qty = ".((float) $qty);
1768  $sql .= ",tva_tx = ".((float) price2num($tvatx));
1769  $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1770  $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1771  $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1772  $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1773  $sql .= ", total_ht = ".((float) price2num($total_ht));
1774  $sql .= ", total_tva = ".((float) price2num($total_tva));
1775  $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1776  $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1777  $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1778  $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1779  $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1780  if ($date_start > 0) {
1781  $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1782  } else {
1783  $sql .= ",date_ouverture_prevue = null";
1784  }
1785  if ($date_end > 0) {
1786  $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1787  } else {
1788  $sql .= ",date_fin_validite = null";
1789  }
1790  if ($date_start_real > 0) {
1791  $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1792  } else {
1793  $sql .= ",date_ouverture = null";
1794  }
1795  if ($date_end_real > 0) {
1796  $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1797  } else {
1798  $sql .= ",date_cloture = null";
1799  }
1800  $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1801  $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1802  $sql .= " WHERE rowid = ".((int) $rowid);
1803 
1804  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1805  $result = $this->db->query($sql);
1806  if ($result) {
1807  if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1808  $contractline = new ContratLigne($this->db);
1809  $contractline->fetch($rowid);
1810 
1811  // We replace values in $contractline->array_options only for entries defined into $array_options
1812  foreach ($array_options as $key => $value) {
1813  $contractline->array_options[$key] = $array_options[$key];
1814  }
1815 
1816  $result = $contractline->insertExtraFields();
1817  if ($result < 0) {
1818  $this->error[] = $contractline->error;
1819  $error++;
1820  }
1821  }
1822 
1823  if (empty($error)) {
1824  // Call trigger
1825  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1826  if ($result < 0) {
1827  $this->db->rollback();
1828  return -3;
1829  }
1830  // End call triggers
1831 
1832  $this->db->commit();
1833  return 1;
1834  } else {
1835  $this->db->rollback();
1836  return -1;
1837  }
1838  } else {
1839  $this->db->rollback();
1840  $this->error = $this->db->error();
1841  dol_syslog(get_class($this)."::updateline Erreur -1");
1842  return -1;
1843  }
1844  }
1845 
1853  public function deleteline($idline, User $user)
1854  {
1855  global $conf, $langs;
1856 
1857  $error = 0;
1858 
1859  if ($this->statut >= 0) {
1860  // Call trigger
1861  $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1862  if ($result < 0) {
1863  return -1;
1864  }
1865  // End call triggers
1866 
1867  $this->db->begin();
1868 
1869  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1870  $sql .= " WHERE rowid = ".((int) $idline);
1871 
1872  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1873  $resql = $this->db->query($sql);
1874  if (!$resql) {
1875  $this->error = "Error ".$this->db->lasterror();
1876  $error++;
1877  }
1878 
1879  if (!$error) {
1880  // Remove extrafields
1881  $contractline = new ContratLigne($this->db);
1882  $contractline->id = $idline;
1883  $result = $contractline->deleteExtraFields();
1884  if ($result < 0) {
1885  $error++;
1886  $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1887  }
1888  }
1889 
1890  if (empty($error)) {
1891  $this->db->commit();
1892  return 1;
1893  } else {
1894  dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1895  $this->db->rollback();
1896  return -1;
1897  }
1898  } else {
1899  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1900  return -2;
1901  }
1902  }
1903 
1904 
1905  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1913  public function update_statut($user)
1914  {
1915  // phpcs:enable
1916  dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1917 
1918  // If draft, we keep it (should not happen)
1919  if ($this->statut == 0) {
1920  return 1;
1921  }
1922 
1923  // Load $this->lines array
1924  // $this->fetch_lines();
1925 
1926  // $newstatut=1;
1927  // foreach($this->lines as $key => $contractline)
1928  // {
1929  // // if ($contractline) // Loop on each service
1930  // }
1931 
1932  return 1;
1933  }
1934 
1935 
1942  public function getLibStatut($mode)
1943  {
1944  return $this->LibStatut($this->statut, $mode);
1945  }
1946 
1947  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1955  public function LibStatut($status, $mode)
1956  {
1957  // phpcs:enable
1958  global $langs;
1959 
1960  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1961  global $langs;
1962  $langs->load("contracts");
1963  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1964  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1965  $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1966  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1967  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1968  $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1969  }
1970 
1971  $statusType = 'status'.$status;
1972  if ($status == self::STATUS_VALIDATED) {
1973  $statusType = 'status6';
1974  }
1975 
1976  if ($mode == 4 || $mode == 6 || $mode == 7) {
1977  $text = '';
1978  if ($mode == 4) {
1979  $text = '<span class="hideonsmartphone">';
1980  $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
1981  $text .= ' '.$langs->trans("Services");
1982  $text .= ': &nbsp; &nbsp; ';
1983  $text .= '</span>';
1984  }
1985  $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
1986  $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1987  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1988  $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1989  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1990  $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1991  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1992  $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
1993  $text .= ($mode == 7 ? '</span>' : '');
1994  return $text;
1995  } else {
1996  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1997  }
1998  }
1999 
2006  public function getTooltipContentArray($params)
2007  {
2008  global $conf, $langs, $user;
2009 
2010  $langs->load('contracts');
2011 
2012  $datas = [];
2013  $nofetch = !empty($params['nofetch']);
2014 
2015  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2016  return ['optimize' => $langs->trans("ShowContract")];
2017  }
2018  if ($user->hasRight('contrat', 'lire')) {
2019  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2020  /* Status of a contract is status of all services, so disabled
2021  if (isset($this->statut)) {
2022  $label .= ' '.$this->getLibStatut(5);
2023  }*/
2024  $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2025  if (!$nofetch) {
2026  $langs->load('companies');
2027  if (empty($this->thirdparty)) {
2028  $this->fetch_thirdparty();
2029  }
2030  $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2031  }
2032  $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2033  if (!$nofetch) {
2034  $langs->load('project');
2035  if (empty($this->project)) {
2036  $res = $this->fetch_project();
2037  if ($res > 0) {
2038  $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
2039  }
2040  }
2041  }
2042  $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2043  if (!empty($this->total_ht)) {
2044  $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2045  }
2046  if (!empty($this->total_tva)) {
2047  $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2048  }
2049  if (!empty($this->total_ttc)) {
2050  $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2051  }
2052  }
2053  return $datas;
2054  }
2055 
2065  public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2066  {
2067  global $conf, $langs, $user, $hookmanager;
2068 
2069  $result = '';
2070 
2071  $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2072 
2073  //if ($option !== 'nolink')
2074  //{
2075  // Add param to save lastsearch_values or not
2076  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2077  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2078  $add_save_lastsearch_values = 1;
2079  }
2080  if ($add_save_lastsearch_values) {
2081  $url .= '&save_lastsearch_values=1';
2082  }
2083  //}
2084  $params = [
2085  'id' => $this->id,
2086  'objecttype' => $this->element,
2087  'nofetch' => 1,
2088  ];
2089  $classfortooltip = 'classfortooltip';
2090  $dataparams = '';
2091  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2092  $classfortooltip = 'classforajaxtooltip';
2093  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2094  $label = '';
2095  } else {
2096  $label = implode($this->getTooltipContentArray($params));
2097  }
2098 
2099  $linkclose = '';
2100  if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2101  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2102  $label = $langs->trans("ShowContract");
2103  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2104  }
2105  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2106  $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2107  }
2108  $linkstart = '<a href="'.$url.'"';
2109  $linkstart .= $linkclose.'>';
2110  $linkend = '</a>';
2111 
2112  $result .= $linkstart;
2113  if ($withpicto) {
2114  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2115  }
2116  if ($withpicto != 2) {
2117  $result .= ($this->ref ? $this->ref : $this->id);
2118  }
2119  $result .= $linkend;
2120 
2121  global $action;
2122  $hookmanager->initHooks(array('contractdao'));
2123  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2124  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2125  if ($reshook > 0) {
2126  $result = $hookmanager->resPrint;
2127  } else {
2128  $result .= $hookmanager->resPrint;
2129  }
2130 
2131  return $result;
2132  }
2133 
2140  public function info($id)
2141  {
2142  $sql = "SELECT c.rowid, c.ref, c.datec,";
2143  $sql .= " c.tms as date_modification,";
2144  $sql .= " fk_user_author";
2145  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2146  $sql .= " WHERE c.rowid = ".((int) $id);
2147 
2148  $result = $this->db->query($sql);
2149  if ($result) {
2150  if ($this->db->num_rows($result)) {
2151  $obj = $this->db->fetch_object($result);
2152 
2153  $this->id = $obj->rowid;
2154 
2155  if ($obj->fk_user_author) {
2156  $cuser = new User($this->db);
2157  $cuser->fetch($obj->fk_user_author);
2158  $this->user_creation = $cuser;
2159  }
2160 
2161  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2162  $this->date_creation = $this->db->jdate($obj->datec);
2163  $this->date_modification = $this->db->jdate($obj->date_modification);
2164  }
2165 
2166  $this->db->free($result);
2167  } else {
2168  dol_print_error($this->db);
2169  }
2170  }
2171 
2172  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2179  public function array_detail($status = -1)
2180  {
2181  // phpcs:enable
2182  $tab = array();
2183 
2184  $sql = "SELECT cd.rowid";
2185  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2186  $sql .= " WHERE fk_contrat =".((int) $this->id);
2187  if ($status >= 0) {
2188  $sql .= " AND statut = ".((int) $status);
2189  }
2190 
2191  dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2192  $resql = $this->db->query($sql);
2193  if ($resql) {
2194  $num = $this->db->num_rows($resql);
2195  $i = 0;
2196  while ($i < $num) {
2197  $obj = $this->db->fetch_object($resql);
2198  $tab[$i] = $obj->rowid;
2199  $i++;
2200  }
2201  return $tab;
2202  } else {
2203  $this->error = $this->db->error();
2204  return -1;
2205  }
2206  }
2207 
2217  public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2218  {
2219  $tab = array();
2220 
2221  $sql = "SELECT c.rowid";
2222  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2223  if (!empty($product_categories)) {
2224  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2225  $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)).")";
2226  }
2227  $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2228  $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2229  $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2230  $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2231  $sql .= " GROUP BY c.rowid";
2232 
2233  dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2234  $resql = $this->db->query($sql);
2235  if ($resql) {
2236  $num = $this->db->num_rows($resql);
2237  $i = 0;
2238  while ($i < $num) {
2239  $obj = $this->db->fetch_object($resql);
2240  $contrat = new Contrat($this->db);
2241  $contrat->fetch($obj->rowid);
2242  $tab[$contrat->id] = $contrat;
2243  $i++;
2244  }
2245  return $tab;
2246  } else {
2247  $this->error = $this->db->lasterror();
2248  return -1;
2249  }
2250  }
2251 
2252 
2253  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2261  public function load_board($user, $mode)
2262  {
2263  // phpcs:enable
2264  global $conf, $langs;
2265 
2266  $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2267  $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2268  $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2269  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2270  $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2271  }
2272 
2273  if ($mode == 'inactive') {
2274  $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2275  $sql .= $this->from;
2276  $sql .= " WHERE c.statut = 1";
2277  $sql .= " AND c.rowid = cd.fk_contrat";
2278  $sql .= " AND cd.statut = 0";
2279  } elseif ($mode == 'expired') {
2280  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2281  $sql .= $this->from;
2282  $sql .= " WHERE c.statut = 1";
2283  $sql .= " AND c.rowid = cd.fk_contrat";
2284  $sql .= " AND cd.statut = 4";
2285  $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2286  } elseif ($mode == 'active') {
2287  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2288  $sql .= $this->from;
2289  $sql .= " WHERE c.statut = 1";
2290  $sql .= " AND c.rowid = cd.fk_contrat";
2291  $sql .= " AND cd.statut = 4";
2292  //$datetouse = dol_now();
2293  //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2294  }
2295  $sql .= " AND c.fk_soc = s.rowid";
2296  $sql .= " AND c.entity = ".((int) $conf->entity);
2297  if ($user->socid) {
2298  $sql .= " AND c.fk_soc = ".((int) $user->socid);
2299  }
2300  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2301  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2302  }
2303 
2304  $resql = $this->db->query($sql);
2305  if ($resql) {
2306  $langs->load("contracts");
2307  $now = dol_now();
2308 
2309  if ($mode == 'inactive') {
2310  $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2311  $label = $langs->trans("BoardNotActivatedServices");
2312  $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2313  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2314  } elseif ($mode == 'expired') {
2315  $warning_delay = $conf->contrat->services->expires->warning_delay;
2316  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2317  $label = $langs->trans("BoardExpiredServices");
2318  $labelShort = $langs->trans("BoardExpiredServicesShort");
2319  } else {
2320  $warning_delay = $conf->contrat->services->expires->warning_delay;
2321  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2322  //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
2323  //if ($warning_delay >= 0) $url.='&amp;filter=expired';
2324  $label = $langs->trans("BoardRunningServices");
2325  $labelShort = $langs->trans("BoardRunningServicesShort");
2326  }
2327 
2328  $response = new WorkboardResponse();
2329  $response->warning_delay = $warning_delay / 60 / 60 / 24;
2330  $response->label = $label;
2331  $response->labelShort = $labelShort;
2332  $response->url = $url;
2333  $response->img = img_object('', "contract");
2334 
2335  while ($obj = $this->db->fetch_object($resql)) {
2336  $response->nbtodo++;
2337 
2338  if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2339  $response->nbtodolate++;
2340  }
2341  }
2342 
2343  return $response;
2344  } else {
2345  dol_print_error($this->db);
2346  $this->error = $this->db->error();
2347  return -1;
2348  }
2349  }
2350 
2351  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2357  public function load_state_board()
2358  {
2359  // phpcs:enable
2360  global $conf, $user;
2361 
2362  $this->nb = array();
2363  $clause = "WHERE";
2364 
2365  $sql = "SELECT count(c.rowid) as nb";
2366  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2367  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2368  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2369  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2370  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2371  $clause = "AND";
2372  }
2373  $sql .= " ".$clause." c.entity = ".$conf->entity;
2374 
2375  $resql = $this->db->query($sql);
2376  if ($resql) {
2377  while ($obj = $this->db->fetch_object($resql)) {
2378  $this->nb["contracts"] = $obj->nb;
2379  }
2380  $this->db->free($resql);
2381  return 1;
2382  } else {
2383  dol_print_error($this->db);
2384  $this->error = $this->db->error();
2385  return -1;
2386  }
2387  }
2388 
2389 
2390  /* gestion des contacts d'un contrat */
2391 
2397  public function getIdBillingContact()
2398  {
2399  return $this->getIdContact('external', 'BILLING');
2400  }
2401 
2407  public function getIdServiceContact()
2408  {
2409  return $this->getIdContact('external', 'SERVICE');
2410  }
2411 
2412 
2420  public function initAsSpecimen()
2421  {
2422  global $user, $langs, $conf;
2423 
2424  // Load array of products prodids
2425  $num_prods = 0;
2426  $prodids = array();
2427  $sql = "SELECT rowid";
2428  $sql .= " FROM ".MAIN_DB_PREFIX."product";
2429  $sql .= " WHERE entity IN (".getEntity('product').")";
2430  $sql .= " AND tosell = 1";
2431  $sql .= $this->db->plimit(100);
2432 
2433  $resql = $this->db->query($sql);
2434  if ($resql) {
2435  $num_prods = $this->db->num_rows($resql);
2436  $i = 0;
2437  while ($i < $num_prods) {
2438  $i++;
2439  $row = $this->db->fetch_row($resql);
2440  $prodids[$i] = $row[0];
2441  }
2442  }
2443 
2444  // Initialise parametres
2445  $this->id = 0;
2446  $this->specimen = 1;
2447 
2448  $this->ref = 'SPECIMEN';
2449  $this->ref_customer = 'SPECIMENCUST';
2450  $this->ref_supplier = 'SPECIMENSUPP';
2451  $this->socid = 1;
2452  $this->statut = 0;
2453  $this->date_creation = (dol_now() - 3600 * 24 * 7);
2454  $this->date_contrat = dol_now();
2455  $this->commercial_signature_id = 1;
2456  $this->commercial_suivi_id = 1;
2457  $this->note_private = 'This is a comment (private)';
2458  $this->note_public = 'This is a comment (public)';
2459  $this->fk_projet = 0;
2460  // Lines
2461  $nbp = 5;
2462  $xnbp = 0;
2463  while ($xnbp < $nbp) {
2464  $line = new ContratLigne($this->db);
2465  $line->qty = 1;
2466  $line->subprice = 100;
2467  $line->price = 100;
2468  $line->tva_tx = 19.6;
2469  $line->remise_percent = 10;
2470  $line->total_ht = 90;
2471  $line->total_ttc = 107.64; // 90 * 1.196
2472  $line->total_tva = 17.64;
2473  $line->date_start = dol_now() - 500000;
2474  $line->date_start_real = dol_now() - 200000;
2475  $line->date_end = dol_now() + 500000;
2476  $line->date_end_real = dol_now() - 100000;
2477  if ($num_prods > 0) {
2478  $prodid = mt_rand(1, $num_prods);
2479  $line->fk_product = $prodids[$prodid];
2480  }
2481  $this->lines[$xnbp] = $line;
2482  $xnbp++;
2483  }
2484  }
2485 
2491  public function getLinesArray()
2492  {
2493  return $this->fetch_lines();
2494  }
2495 
2496 
2508  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2509  {
2510  global $conf, $langs;
2511 
2512  if (!dol_strlen($modele)) {
2513  $modele = ''; // No doc template/generation by default
2514 
2515  if (!empty($this->model_pdf)) {
2516  $modele = $this->model_pdf;
2517  } elseif (!empty($this->modelpdf)) { // deprecated
2518  $modele = $this->modelpdf;
2519  } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
2520  $modele = $conf->global->CONTRACT_ADDON_PDF;
2521  }
2522  }
2523 
2524  if (empty($modele)) {
2525  return 0;
2526  } else {
2527  $langs->load("contracts");
2528  $outputlangs->load("products");
2529 
2530  $modelpath = "core/modules/contract/doc/";
2531  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2532  }
2533  }
2534 
2543  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2544  {
2545  $tables = array(
2546  'contrat'
2547  );
2548 
2549  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2550  }
2551 
2560  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2561  {
2562  $tables = array(
2563  'contratdet'
2564  );
2565 
2566  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2567  }
2568 
2577  public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2578  {
2579  global $db, $langs, $conf, $hookmanager, $extrafields;
2580 
2581  dol_include_once('/projet/class/project.class.php');
2582 
2583  $error = 0;
2584 
2585  $this->fetch($this->id);
2586 
2587  // Load dest object
2588  $clonedObj = clone $this;
2589  $clonedObj->socid = $socid;
2590 
2591  $this->db->begin();
2592 
2593  $objsoc = new Societe($this->db);
2594 
2595  $objsoc->fetch($clonedObj->socid);
2596 
2597  // Clean data
2598  $clonedObj->statut = 0;
2599  // Clean extrafields
2600  if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2601  $extrafields->fetch_name_optionals_label($this->table_element);
2602  foreach ($clonedObj->array_options as $key => $option) {
2603  $shortkey = preg_replace('/options_/', '', $key);
2604  //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2605  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2606  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2607  unset($clonedObj->array_options[$key]);
2608  }
2609  }
2610  }
2611 
2612  if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
2613  $this->error = 'ErrorSetupNotComplete';
2614  dol_syslog($this->error);
2615  return -1;
2616  }
2617 
2618  // Set ref
2619  require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
2620  $obj = $conf->global->CONTRACT_ADDON;
2621  $modContract = new $obj();
2622  $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2623 
2624  // get extrafields so they will be clone
2625  foreach ($this->lines as $line) {
2626  $line->fetch_optionals($line->id);
2627  }
2628 
2629  // Create clone
2630  $clonedObj->context['createfromclone'] = 'createfromclone';
2631  $result = $clonedObj->create($user);
2632  if ($result < 0) {
2633  $error++;
2634  $this->error = $clonedObj->error;
2635  $this->errors[] = $clonedObj->error;
2636  } else {
2637  // copy external contacts if same company
2638  if ($this->socid == $clonedObj->socid) {
2639  if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2640  $error++;
2641  }
2642  }
2643  }
2644 
2645  if (!$error) {
2646  foreach ($this->lines as $line) {
2647  $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);
2648  if ($result < 0) {
2649  $error++;
2650  $this->error = $clonedObj->error;
2651  $this->errors[] = $clonedObj->error;
2652  }
2653  }
2654  }
2655 
2656  if (!$error) {
2657  // Hook of thirdparty module
2658  if (is_object($hookmanager)) {
2659  $parameters = array(
2660  'objFrom' => $this,
2661  'clonedObj' => $clonedObj
2662  );
2663  $action = '';
2664  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2665  if ($reshook < 0) {
2666  $this->setErrorsFromObject($hookmanager);
2667  $error++;
2668  }
2669  }
2670  }
2671 
2672  unset($clonedObj->context['createfromclone']);
2673 
2674  // End
2675  if (!$error) {
2676  $this->db->commit();
2677  return $clonedObj->id;
2678  } else {
2679  $this->db->rollback();
2680  return -1;
2681  }
2682  }
2683 
2684 
2694  public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2695  {
2696  global $langs, $user;
2697 
2698  $langs->load("agenda");
2699 
2700  $now = dol_now();
2701 
2702  $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2703 
2704  $error = 0;
2705  $this->output = '';
2706  $this->error='';
2707 
2708  $contractlineprocessed = array();
2709  $contractignored = array();
2710  $contracterror = array();
2711 
2712  dol_syslog(__METHOD__, LOG_DEBUG);
2713 
2714  $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2715  $sql.= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2716  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2717  $sql.= ' WHERE cd.fk_contrat = c.rowid';
2718  $sql.= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2719  $sql.= " AND cd.statut = 4";
2720  if ($thirdparty_id > 0) $sql.=" AND c.fk_soc = ".((int) $thirdparty_id);
2721  //print $sql;
2722 
2723  $resql = $this->db->query($sql);
2724  if ($resql) {
2725  $num = $this->db->num_rows($resql);
2726 
2727  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2728 
2729  $i=0;
2730  while ($i < $num) {
2731  $obj = $this->db->fetch_object($resql);
2732  if ($obj) {
2733  if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2734  continue;
2735  }
2736 
2737  // Load contract
2738  $object = new Contrat($this->db);
2739  $object->fetch($obj->rowid); // fetch also lines
2740  $object->fetch_thirdparty();
2741 
2742  if ($object->id <= 0) {
2743  $error++;
2744  $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2745  continue;
2746  }
2747 
2748  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);
2749 
2750  // Update expiration date of line
2751  $expirationdate = $this->db->jdate($obj->date_fin_validite);
2752  $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2753  $duration_unit = preg_replace('/\d/', '', $obj->duration);
2754  //var_dump($expirationdate.' '.$enddatetoscan);
2755 
2756  // Test if there is pending invoice
2757  $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2758 
2759  if (is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2760  usort($object->linkedObjects['facture'], "cmp");
2761 
2762  //dol_sort_array($contract->linkedObjects['facture'], 'date');
2763  $someinvoicenotpaid=0;
2764  foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2765  if ($invoice->statut == Facture::STATUS_DRAFT) continue; // Draft invoice are not invoice not paid
2766 
2767  if (empty($invoice->paye)) {
2768  $someinvoicenotpaid++;
2769  }
2770  }
2771  if ($someinvoicenotpaid) {
2772  $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2773  $contractignored[$object->id]=$object->ref;
2774  continue;
2775  }
2776  }
2777 
2778  if ($expirationdate && $expirationdate < $enddatetoscan) {
2779  dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2780  $newdate = $expirationdate;
2781  $protecti=0; //$protecti is to avoid infinite loop
2782  while ($newdate < $enddatetoscan && $protecti < 1000) {
2783  $newdate = dol_time_plus_duree($newdate, $duration_value, $duration_unit);
2784  $protecti++;
2785  }
2786 
2787  if ($protecti < 1000) { // If not, there is a pb
2788  // We will update the end of date of contrat, so first we refresh contract data
2789  dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2790 
2791  $this->db->begin();
2792 
2793  $errorforlocaltransaction = 0;
2794 
2795  $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2796  $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2797 
2798  $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2799  $sqlupdate.= ' WHERE rowid = '.((int) $obj->lid);
2800  $resqlupdate = $this->db->query($sqlupdate);
2801  if ($resqlupdate) {
2802  $contractlineprocessed[$obj->lid]=$object->ref;
2803 
2804  $actioncode = 'RENEW_CONTRACT';
2805  $now = dol_now();
2806 
2807  // Create an event
2808  $actioncomm = new ActionComm($this->db);
2809  $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2810  $actioncomm->code = 'AC_'.$actioncode;
2811  $actioncomm->label = $label;
2812  $actioncomm->datep = $now;
2813  $actioncomm->datef = $now;
2814  $actioncomm->percentage = -1; // Not applicable
2815  $actioncomm->socid = $object->thirdparty->id;
2816  $actioncomm->authorid = $user->id; // User saving action
2817  $actioncomm->userownerid = $user->id; // Owner of action
2818  $actioncomm->fk_element = $object->id;
2819  $actioncomm->elementtype = 'contract';
2820  $actioncomm->note_private = $comment;
2821 
2822  $ret = $actioncomm->create($user); // User creating action
2823  } else {
2824  $contracterror[$object->id]=$object->ref;
2825 
2826  $error++;
2827  $errorforlocaltransaction++;
2828  $this->error = $this->db->lasterror();
2829  }
2830 
2831  if (! $errorforlocaltransaction) {
2832  $this->db->commit();
2833  } else {
2834  $this->db->rollback();
2835  }
2836  } else {
2837  $error++;
2838  $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2839  dol_syslog($this->error, LOG_ERR);
2840  }
2841  }
2842  }
2843  $i++;
2844  }
2845  } else {
2846  $error++;
2847  $this->error = $this->db->lasterror();
2848  }
2849 
2850  $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed)>0 ? ' : '.join(',', $contractlineprocessed) : '');
2851 
2852  return ($error ? 1: 0);
2853  }
2854 
2862  public function getKanbanView($option = '', $arraydata = null)
2863  {
2864  global $langs;
2865 
2866  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2867 
2868  $return = '<div class="box-flex-item box-flex-grow-zero">';
2869  $return .= '<div class="info-box info-box-sm">';
2870  $return .= '<span class="info-box-icon bg-infobox-action">';
2871  $return .= img_picto('', $this->picto);
2872  $return .= '</span>';
2873  $return .= '<div class="info-box-content">';
2874  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2875  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2876  if (!empty($arraydata['thirdparty'])) {
2877  $tmpthirdparty = $arraydata['thirdparty'];
2878  $return .= '<br><div class="info-box-label inline-block">'.$tmpthirdparty->getNomUrl(1).'</div>';
2879  }
2880  if (property_exists($this, 'date_contrat')) {
2881  $return .= '<br><span class="opacitymedium">'.$langs->trans("DateContract").' : </span><span class="info-box-label">'.dol_print_date($this->date_contrat, 'day').'</span>';
2882  }
2883  if (method_exists($this, 'getLibStatut')) {
2884  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(7).'</div>';
2885  }
2886  $return .= '</div>';
2887  $return .= '</div>';
2888  $return .= '</div>';
2889  return $return;
2890  }
2891 }
2892 
2893 
2898 {
2902  public $element = 'contratdet';
2903 
2907  public $table_element = 'contratdet';
2908 
2913  public $element_for_permission = 'contrat';
2914 
2918  public $id;
2919 
2923  public $ref;
2924 
2925  public $tms;
2926 
2930  public $fk_contrat;
2931 
2935  public $fk_product;
2936 
2937  public $statut; // 0 inactive, 4 active, 5 closed
2938  public $type; // 0 for product, 1 for service
2939 
2944  public $label;
2945 
2950  public $libelle;
2951 
2955  public $description;
2956 
2957  public $product_type; // 0 for product, 1 for service
2958  public $product_ref;
2959  public $product_label;
2960 
2961  public $date_commande;
2962 
2963  public $date_start; // date start planned
2964  public $date_start_real; // date start real
2965  public $date_end; // date end planned
2966  public $date_end_real; // date end real
2967 
2968  public $tva_tx;
2969  public $vat_src_code;
2970  public $localtax1_tx;
2971  public $localtax2_tx;
2972  public $localtax1_type; // Local tax 1 type
2973  public $localtax2_type; // Local tax 2 type
2974  public $qty;
2975  public $remise_percent;
2976  public $remise;
2977 
2981  public $fk_remise_except;
2982 
2983  public $subprice; // Unit price HT
2984 
2990  public $price;
2991 
2992  public $price_ht;
2993 
2994  public $total_ht;
2995  public $total_tva;
2996  public $total_localtax1;
2997  public $total_localtax2;
2998  public $total_ttc;
2999 
3003  public $fk_fournprice;
3004 
3005  public $pa_ht;
3006 
3007  public $info_bits;
3008 
3012  public $fk_user_author;
3013 
3017  public $fk_user_ouverture;
3018 
3022  public $fk_user_cloture;
3023 
3024  public $commentaire;
3025 
3026 
3030  public $rang = 0;
3031 
3032 
3033  const STATUS_INITIAL = 0;
3034  const STATUS_OPEN = 4;
3035  const STATUS_CLOSED = 5;
3036 
3037 
3038  // BEGIN MODULEBUILDER PROPERTIES
3042  public $fields = array(
3043  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
3044  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
3045  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
3046  'qty' =>array('type'=>'integer', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>35, 'isameasure'=>1),
3047  'total_ht' =>array('type'=>'integer', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>36, 'isameasure'=>1),
3048  'total_tva' =>array('type'=>'integer', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>37, 'isameasure'=>1),
3049  'total_ttc' =>array('type'=>'integer', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>38, 'isameasure'=>1),
3050  //'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
3051  //'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3052  'fk_contrat' =>array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'Contract', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3053  'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
3054  //'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
3055  'note_private' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
3056  'note_public' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
3057  //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
3058  //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
3059  //'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
3060  'fk_user_ouverture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserStartingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3061  'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3062  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 4=>'Open', 5=>'Closed')),
3063  'rang' =>array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'position'=>500, 'default' =>0)
3064  );
3065  // END MODULEBUILDER PROPERTIES
3066 
3067 
3073  public function __construct($db)
3074  {
3075  $this->db = $db;
3076  }
3077 
3078 
3085  public function getLibStatut($mode)
3086  {
3087  return $this->LibStatut($this->statut, $mode, ((!empty($this->date_end)) ? ($this->date_end < dol_now() ? 1 : 0) : -1));
3088  }
3089 
3090  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3100  public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
3101  {
3102  // phpcs:enable
3103  global $langs;
3104  $langs->load("contracts");
3105 
3106  if ($status == self::STATUS_INITIAL) {
3107  $labelStatus = $langs->transnoentities("ServiceStatusInitial");
3108  $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
3109  } elseif ($status == self::STATUS_OPEN && $expired == -1) {
3110  $labelStatus = $langs->transnoentities("ServiceStatusRunning");
3111  $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
3112  } elseif ($status == self::STATUS_OPEN && $expired == 0) {
3113  $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
3114  $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
3115  } elseif ($status == self::STATUS_OPEN && $expired == 1) {
3116  $labelStatus = $langs->transnoentities("ServiceStatusLate");
3117  $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
3118  } elseif ($status == self::STATUS_CLOSED) {
3119  $labelStatus = $langs->transnoentities("ServiceStatusClosed");
3120  $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
3121  }
3122 
3123  $statusType = 'status'.$status;
3124  if ($status == self::STATUS_OPEN && $expired == 1) {
3125  $statusType = 'status1';
3126  }
3127  if ($status == self::STATUS_CLOSED) {
3128  $statusType = 'status6';
3129  }
3130 
3131  $params = array(); $reg = array();
3132  if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
3133  $params = array('badgeParams'=>array('css' => $reg[1]));
3134  }
3135  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
3136  }
3137 
3144  public function getTooltipContentArray($params)
3145  {
3146  global $conf, $langs, $user;
3147 
3148  $datas = [];
3149  $datas['label'] = $langs->trans("ShowContractOfService").': '.$this->label;
3150  if (empty($datas['label'])) {
3151  $datas['label'] = $this->description;
3152  }
3153 
3154  return $datas;
3155  }
3156 
3164  public function getNomUrl($withpicto = 0, $maxlength = 0)
3165  {
3166  global $langs;
3167 
3168  $result = '';
3169  $label = $langs->trans("ShowContractOfService").': '.$this->label;
3170  if (empty($label)) {
3171  $label = $this->description;
3172  }
3173  $classfortooltip = 'classfortooltip';
3174  $dataparams = '';
3175  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3176  $params = [
3177  'id' => $this->fk_contrat,
3178  'objecttype' => $this->element,
3179  ];
3180  $classfortooltip = 'classforajaxtooltip';
3181  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3182  $label = '';
3183  }
3184 
3185  $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'"';
3186  $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3187  $link .= $dataparams.' class="'.$classfortooltip.'">';
3188  $linkend = '</a>';
3189 
3190  $picto = 'service';
3191  if ($this->type == 0) {
3192  $picto = 'product';
3193  }
3194 
3195  if ($withpicto) {
3196  $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
3197  }
3198  if ($withpicto && $withpicto != 2) {
3199  $result .= ' ';
3200  }
3201  if ($withpicto != 2) {
3202  $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
3203  }
3204  return $result;
3205  }
3206 
3214  public function fetch($id, $ref = '')
3215  {
3216  // Check parameters
3217  if (empty($id) && empty($ref)) {
3218  return -1;
3219  }
3220 
3221  $sql = "SELECT";
3222  $sql .= " t.rowid,";
3223  $sql .= " t.tms,";
3224  $sql .= " t.fk_contrat,";
3225  $sql .= " t.fk_product,";
3226  $sql .= " t.statut,";
3227  $sql .= " t.label,"; // This field is not used. Only label of product
3228  $sql .= " p.ref as product_ref,";
3229  $sql .= " p.label as product_label,";
3230  $sql .= " p.description as product_desc,";
3231  $sql .= " p.fk_product_type as product_type,";
3232  $sql .= " t.description,";
3233  $sql .= " t.date_commande,";
3234  $sql .= " t.date_ouverture_prevue as date_start,";
3235  $sql .= " t.date_ouverture as date_start_real,";
3236  $sql .= " t.date_fin_validite as date_end,";
3237  $sql .= " t.date_cloture as date_end_real,";
3238  $sql .= " t.tva_tx,";
3239  $sql .= " t.vat_src_code,";
3240  $sql .= " t.localtax1_tx,";
3241  $sql .= " t.localtax2_tx,";
3242  $sql .= " t.localtax1_type,";
3243  $sql .= " t.localtax2_type,";
3244  $sql .= " t.qty,";
3245  $sql .= " t.remise_percent,";
3246  $sql .= " t.remise,";
3247  $sql .= " t.fk_remise_except,";
3248  $sql .= " t.subprice,";
3249  $sql .= " t.price_ht,";
3250  $sql .= " t.total_ht,";
3251  $sql .= " t.total_tva,";
3252  $sql .= " t.total_localtax1,";
3253  $sql .= " t.total_localtax2,";
3254  $sql .= " t.total_ttc,";
3255  $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
3256  $sql .= " t.buy_price_ht as pa_ht,";
3257  $sql .= " t.info_bits,";
3258  $sql .= " t.fk_user_author,";
3259  $sql .= " t.fk_user_ouverture,";
3260  $sql .= " t.fk_user_cloture,";
3261  $sql .= " t.commentaire,";
3262  $sql .= " t.fk_unit,";
3263  $sql .= " t.rang";
3264  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
3265  if ($id) {
3266  $sql .= " WHERE t.rowid = ".((int) $id);
3267  }
3268  if ($ref) {
3269  $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
3270  }
3271 
3272  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
3273  $resql = $this->db->query($sql);
3274  if ($resql) {
3275  if ($this->db->num_rows($resql)) {
3276  $obj = $this->db->fetch_object($resql);
3277 
3278  $this->id = $obj->rowid;
3279  $this->ref = $obj->rowid;
3280 
3281  $this->tms = $this->db->jdate($obj->tms);
3282  $this->fk_contrat = $obj->fk_contrat;
3283  $this->fk_product = $obj->fk_product;
3284  $this->statut = $obj->statut;
3285  $this->product_ref = $obj->product_ref;
3286  $this->product_label = $obj->product_label;
3287  $this->product_description = $obj->product_description;
3288  $this->product_type = $obj->product_type;
3289  $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
3290  $this->description = $obj->description;
3291  $this->date_commande = $this->db->jdate($obj->date_commande);
3292 
3293  $this->date_start = $this->db->jdate($obj->date_start);
3294  $this->date_start_real = $this->db->jdate($obj->date_start_real);
3295  $this->date_end = $this->db->jdate($obj->date_end);
3296  $this->date_end_real = $this->db->jdate($obj->date_end_real);
3297  // For backward compatibility
3298  //$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
3299  //$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
3300  //$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
3301  //$this->date_cloture = $this->db->jdate($obj->date_cloture);
3302 
3303  $this->tva_tx = $obj->tva_tx;
3304  $this->vat_src_code = $obj->vat_src_code;
3305  $this->localtax1_tx = $obj->localtax1_tx;
3306  $this->localtax2_tx = $obj->localtax2_tx;
3307  $this->localtax1_type = $obj->localtax1_type;
3308  $this->localtax2_type = $obj->localtax2_type;
3309  $this->qty = $obj->qty;
3310  $this->remise_percent = $obj->remise_percent;
3311  $this->fk_remise_except = $obj->fk_remise_except;
3312  $this->subprice = $obj->subprice;
3313  $this->price_ht = $obj->price_ht;
3314  $this->total_ht = $obj->total_ht;
3315  $this->total_tva = $obj->total_tva;
3316  $this->total_localtax1 = $obj->total_localtax1;
3317  $this->total_localtax2 = $obj->total_localtax2;
3318  $this->total_ttc = $obj->total_ttc;
3319  $this->info_bits = $obj->info_bits;
3320  $this->fk_user_author = $obj->fk_user_author;
3321  $this->fk_user_ouverture = $obj->fk_user_ouverture;
3322  $this->fk_user_cloture = $obj->fk_user_cloture;
3323  $this->commentaire = $obj->commentaire;
3324  $this->fk_fournprice = $obj->fk_fournprice;
3325 
3326  $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
3327  $this->pa_ht = $marginInfos[0];
3328  $this->fk_unit = $obj->fk_unit;
3329 
3330  $this->rang = $obj->rang;
3331 
3332  $this->fetch_optionals();
3333  }
3334 
3335  $this->db->free($resql);
3336 
3337  return 1;
3338  } else {
3339  $this->error = "Error ".$this->db->lasterror();
3340  return -1;
3341  }
3342  }
3343 
3344 
3352  public function update($user, $notrigger = 0)
3353  {
3354  global $conf, $langs, $mysoc;
3355 
3356  $error = 0;
3357 
3358  // Clean parameters
3359  $this->fk_contrat = (int) $this->fk_contrat;
3360  $this->fk_product = (int) $this->fk_product;
3361  $this->statut = (int) $this->statut;
3362  $this->label = trim($this->label);
3363  $this->description = trim($this->description);
3364  $this->vat_src_code = trim($this->vat_src_code);
3365  $this->tva_tx = trim($this->tva_tx);
3366  $this->localtax1_tx = trim($this->localtax1_tx);
3367  $this->localtax2_tx = trim($this->localtax2_tx);
3368  $this->qty = trim($this->qty);
3369  $this->remise_percent = trim($this->remise_percent);
3370  $this->fk_remise_except = (int) $this->fk_remise_except;
3371  $this->subprice = price2num($this->subprice);
3372  $this->price_ht = price2num($this->price_ht);
3373  $this->total_ht = trim($this->total_ht);
3374  $this->total_tva = trim($this->total_tva);
3375  $this->total_localtax1 = trim($this->total_localtax1);
3376  $this->total_localtax2 = trim($this->total_localtax2);
3377  $this->total_ttc = trim($this->total_ttc);
3378  $this->info_bits = trim($this->info_bits);
3379  $this->fk_user_author = (int) $this->fk_user_author;
3380  $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
3381  $this->fk_user_cloture = (int) $this->fk_user_cloture;
3382  $this->commentaire = trim($this->commentaire);
3383  $this->rang = (int) $this->rang;
3384  //if (empty($this->subprice)) $this->subprice = 0;
3385  if (empty($this->price_ht)) {
3386  $this->price_ht = 0;
3387  }
3388  if (empty($this->total_ht)) {
3389  $this->total_ht = 0;
3390  }
3391  if (empty($this->total_tva)) {
3392  $this->total_tva = 0;
3393  }
3394  if (empty($this->total_ttc)) {
3395  $this->total_ttc = 0;
3396  }
3397  if (empty($this->localtax1_tx)) {
3398  $this->localtax1_tx = 0;
3399  }
3400  if (empty($this->localtax2_tx)) {
3401  $this->localtax2_tx = 0;
3402  }
3403  if (empty($this->remise_percent)) {
3404  $this->remise_percent = 0;
3405  }
3406  // For backward compatibility
3407  if (empty($this->date_start)) {
3408  $this->date_start = $this->date_start;
3409  }
3410  if (empty($this->date_start_real)) {
3411  $this->date_start_real = $this->date_start_real;
3412  }
3413  if (empty($this->date_end)) {
3414  $this->date_end = $this->date_end;
3415  }
3416  if (empty($this->date_end_real)) {
3417  $this->date_end_real = $this->date_end_real;
3418  }
3419 
3420  // Calcul du total TTC et de la TVA pour la ligne a partir de
3421  // qty, pu, remise_percent et txtva
3422  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3423  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3424  $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->thirdparty, $mysoc);
3425 
3426  $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);
3427  $this->total_ht = $tabprice[0];
3428  $this->total_tva = $tabprice[1];
3429  $this->total_ttc = $tabprice[2];
3430  $this->total_localtax1 = $tabprice[9];
3431  $this->total_localtax2 = $tabprice[10];
3432 
3433  if (empty($this->pa_ht)) {
3434  $this->pa_ht = 0;
3435  }
3436 
3437  // if buy price not defined, define buyprice as configured in margin admin
3438  if ($this->pa_ht == 0) {
3439  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
3440  return $result;
3441  } else {
3442  $this->pa_ht = $result;
3443  }
3444  }
3445 
3446  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
3447  if (empty($this->oldcopy)) {
3448  $this->oldcopy = dol_clone($this);
3449  }
3450 
3451  $this->db->begin();
3452 
3453  // Update request
3454  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3455  $sql .= " fk_contrat = ".((int) $this->fk_contrat).",";
3456  $sql .= " fk_product = ".($this->fk_product ? ((int) $this->fk_product) : 'null').",";
3457  $sql .= " statut = ".((int) $this->statut).",";
3458  $sql .= " label = '".$this->db->escape($this->label)."',";
3459  $sql .= " description = '".$this->db->escape($this->description)."',";
3460  $sql .= " date_commande = ".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
3461  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3462  $sql .= " date_ouverture = ".($this->date_start_real != '' ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3463  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3464  $sql .= " date_cloture = ".($this->date_end_real != '' ? "'".$this->db->idate($this->date_end_real)."'" : "null").",";
3465  $sql .= " vat_src_code = '".$this->db->escape($this->vat_src_code)."',";
3466  $sql .= " tva_tx = ".price2num($this->tva_tx).",";
3467  $sql .= " localtax1_tx = ".price2num($this->localtax1_tx).",";
3468  $sql .= " localtax2_tx = ".price2num($this->localtax2_tx).",";
3469  $sql .= " qty = ".price2num($this->qty).",";
3470  $sql .= " remise_percent = ".price2num($this->remise_percent).",";
3471  $sql .= " remise = ".($this->remise ?price2num($this->remise) : "null").",";
3472  $sql .= " fk_remise_except = ".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
3473  $sql .= " subprice = ".($this->subprice != '' ? $this->subprice : "null").",";
3474  $sql .= " price_ht = ".($this->price_ht != '' ? $this->price_ht : "null").",";
3475  $sql .= " total_ht = ".$this->total_ht.",";
3476  $sql .= " total_tva = ".$this->total_tva.",";
3477  $sql .= " total_localtax1 = ".$this->total_localtax1.",";
3478  $sql .= " total_localtax2 = ".$this->total_localtax2.",";
3479  $sql .= " total_ttc = ".$this->total_ttc.",";
3480  $sql .= " fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
3481  $sql .= " buy_price_ht = '".price2num($this->pa_ht)."',";
3482  $sql .= " info_bits = '".$this->db->escape($this->info_bits)."',";
3483  $sql .= " fk_user_author = ".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
3484  $sql .= " fk_user_ouverture = ".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
3485  $sql .= " fk_user_cloture = ".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3486  $sql .= " commentaire = '".$this->db->escape($this->commentaire)."',";
3487  $sql .= " fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit).",";
3488  $sql .= " rang = ".(empty($this->rang) ? '0' : (int) $this->rang);
3489  $sql .= " WHERE rowid = ".((int) $this->id);
3490 
3491  dol_syslog(get_class($this)."::update", LOG_DEBUG);
3492  $resql = $this->db->query($sql);
3493  if (!$resql) {
3494  $this->error = "Error ".$this->db->lasterror();
3495  $error++;
3496  }
3497 
3498  if (!$error) { // For avoid conflicts if trigger used
3499  $result = $this->insertExtraFields();
3500  if ($result < 0) {
3501  $error++;
3502  }
3503  }
3504 
3505  // If we change a planned date (start or end) of one contract line, sync dates for all other services too
3506  if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) {
3507  dol_syslog(get_class($this)."::update CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES is on so we update date for all lines", LOG_DEBUG);
3508 
3509  if ($this->date_start != $this->oldcopy->date_start) {
3510  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3511  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
3512  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3513 
3514  $resql = $this->db->query($sql);
3515  if (!$resql) {
3516  $error++;
3517  $this->error = "Error ".$this->db->lasterror();
3518  }
3519  }
3520  if ($this->date_end != $this->oldcopy->date_end) {
3521  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3522  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
3523  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3524 
3525  $resql = $this->db->query($sql);
3526  if (!$resql) {
3527  $error++;
3528  $this->error = "Error ".$this->db->lasterror();
3529  }
3530  }
3531  }
3532 
3533  if (!$error && !$notrigger) {
3534  // Call trigger
3535  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
3536  if ($result < 0) {
3537  $error++;
3538  $this->db->rollback();
3539  }
3540  // End call triggers
3541  }
3542 
3543  if (!$error) {
3544  $this->db->commit();
3545  return 1;
3546  } else {
3547  $this->db->rollback();
3548  $this->errors[] = $this->error;
3549  return -1;
3550  }
3551  }
3552 
3553 
3554  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3561  public function update_total()
3562  {
3563  // phpcs:enable
3564  $this->db->begin();
3565 
3566  // Mise a jour ligne en base
3567  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3568  $sql .= " total_ht=".price2num($this->total_ht, 'MT');
3569  $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
3570  $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT');
3571  $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT');
3572  $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
3573  $sql .= " WHERE rowid = ".((int) $this->id);
3574 
3575  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3576 
3577  $resql = $this->db->query($sql);
3578  if ($resql) {
3579  $this->db->commit();
3580  return 1;
3581  } else {
3582  $this->error = $this->db->error();
3583  $this->db->rollback();
3584  return -2;
3585  }
3586  }
3587 
3588 
3595  public function insert($notrigger = 0)
3596  {
3597  global $conf, $user;
3598 
3599  $error = 0;
3600 
3601  // Insertion dans la base
3602  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3603  $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3604  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3605  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3606  $sql .= " info_bits,";
3607  $sql .= " rang,";
3608  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3609  if ($this->date_start > 0) {
3610  $sql .= ",date_ouverture_prevue";
3611  }
3612  if ($this->date_end > 0) {
3613  $sql .= ",date_fin_validite";
3614  }
3615  $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3616  $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3617  $sql .= " '".$this->db->escape($this->qty)."',";
3618  $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3619  $sql .= " '".$this->db->escape($this->tva_tx)."',";
3620  $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3621  $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3622  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3623  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3624  $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3625  $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3626  $sql .= " '".$this->db->escape($this->info_bits)."',";
3627  $sql .= " ".(empty($this->rang) ? '0' : (int) $this->rang).",";
3628  $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3629  if ($this->fk_fournprice > 0) {
3630  $sql .= ' '.((int) $this->fk_fournprice).',';
3631  } else {
3632  $sql .= ' null,';
3633  }
3634  if ($this->pa_ht > 0) {
3635  $sql .= ' '.((float) price2num($this->pa_ht));
3636  } else {
3637  $sql .= ' null';
3638  }
3639  if ($this->date_start > 0) {
3640  $sql .= ",'".$this->db->idate($this->date_start)."'";
3641  }
3642  if ($this->date_end > 0) {
3643  $sql .= ",'".$this->db->idate($this->date_end)."'";
3644  }
3645  $sql .= ")";
3646 
3647  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3648 
3649  $resql = $this->db->query($sql);
3650  if ($resql) {
3651  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3652 
3653  // Insert of extrafields
3654  if (!$error) {
3655  $result = $this->insertExtraFields();
3656  if ($result < 0) {
3657  $this->db->rollback();
3658  return -1;
3659  }
3660  }
3661 
3662  if (!$notrigger) {
3663  // Call trigger
3664  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3665  if ($result < 0) {
3666  $this->db->rollback();
3667  return -1;
3668  }
3669  // End call triggers
3670  }
3671 
3672  $this->db->commit();
3673  return 1;
3674  } else {
3675  $this->db->rollback();
3676  $this->error = $this->db->error()." sql=".$sql;
3677  return -1;
3678  }
3679  }
3680 
3681  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3691  public function active_line($user, $date, $date_end = '', $comment = '')
3692  {
3693  // phpcs:enable
3694  global $langs, $conf;
3695 
3696  $error = 0;
3697 
3698  $this->db->begin();
3699 
3700  $this->statut = ContratLigne::STATUS_OPEN;
3701  $this->date_start_real = $date;
3702  $this->date_end = $date_end;
3703  $this->fk_user_ouverture = $user->id;
3704  $this->date_end_real = null;
3705  $this->commentaire = $comment;
3706 
3707  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) $this->statut).",";
3708  $sql .= " date_ouverture = ".(dol_strlen($this->date_start_real) != 0 ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3709  if ($date_end >= 0) {
3710  $sql .= " date_fin_validite = ".(dol_strlen($this->date_end) != 0 ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3711  }
3712  $sql .= " fk_user_ouverture = ".((int) $this->fk_user_ouverture).",";
3713  $sql .= " date_cloture = null,";
3714  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3715  $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3716 
3717  dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3718  $resql = $this->db->query($sql);
3719  if ($resql) {
3720  // Call trigger
3721  $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3722  if ($result < 0) {
3723  $error++;
3724  }
3725  // End call triggers
3726 
3727  if (!$error) {
3728  $this->db->commit();
3729  return 1;
3730  } else {
3731  $this->db->rollback();
3732  return -1;
3733  }
3734  } else {
3735  $this->error = $this->db->lasterror();
3736  $this->db->rollback();
3737  return -1;
3738  }
3739  }
3740 
3741  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3751  public function close_line($user, $date_end_real, $comment = '', $notrigger = 0)
3752  {
3753  // phpcs:enable
3754  global $langs, $conf;
3755 
3756  // Update object
3757  $this->date_cloture = $date_end_real;
3758  $this->date_end_real = $date_end_real;
3759  $this->fk_user_cloture = $user->id;
3760  $this->commentaire = $comment;
3761 
3762  $error = 0;
3763 
3764  // statut actif : 4
3765 
3766  $this->db->begin();
3767 
3768  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
3769  $sql .= " date_cloture = '".$this->db->idate($date_end_real)."',";
3770  $sql .= " fk_user_cloture = ".((int) $user->id).",";
3771  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3772  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
3773 
3774  $resql = $this->db->query($sql);
3775  if ($resql) {
3776  if (!$notrigger) {
3777  // Call trigger
3778  $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3779  if ($result < 0) {
3780  $error++;
3781  $this->db->rollback();
3782  return -1;
3783  }
3784  // End call triggers
3785  }
3786 
3787  $this->db->commit();
3788  return 1;
3789  } else {
3790  $this->error = $this->db->lasterror();
3791  $this->db->rollback();
3792  return -1;
3793  }
3794  }
3795 }
$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