dolibarr  x.y.z
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-2021 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 $lower_planned_end_date;
189  //public $higher_planner_end_date;
190 
195  protected $lines_id_index_mapper = array();
196 
197 
222  // BEGIN MODULEBUILDER PROPERTIES
226  public $fields = array(
227  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
228  'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>15),
229  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>20),
230  'ref_supplier' =>array('type'=>'varchar(50)', 'label'=>'Ref supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
231  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
232  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
233  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
234  'date_contrat' =>array('type'=>'datetime', 'label'=>'Date contrat', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
235  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'$conf->societe->enabled', 'visible'=>-1, 'notnull'=>1, 'position'=>70),
236  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>75),
237  'fk_commercial_signature' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative Signature', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
238  'fk_commercial_suivi' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative follower', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
239  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
240  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
241  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
242  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
243  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
244  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
245  'ref_customer' =>array('type'=>'varchar(50)', 'label'=>'Ref customer', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
246  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
247  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
248  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'notnull'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed'))
249  );
250  // END MODULEBUILDER PROPERTIES
251 
252  const STATUS_DRAFT = 0;
253  const STATUS_VALIDATED = 1;
254  const STATUS_CLOSED = 2;
255 
256 
257 
263  public function __construct($db)
264  {
265  $this->db = $db;
266  }
267 
274  public function getNextNumRef($soc)
275  {
276  global $db, $langs, $conf;
277  $langs->load("contracts");
278 
279  if (!empty($conf->global->CONTRACT_ADDON)) {
280  $mybool = false;
281 
282  $file = $conf->global->CONTRACT_ADDON.".php";
283  $classname = $conf->global->CONTRACT_ADDON;
284 
285  // Include file with class
286  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
287 
288  foreach ($dirmodels as $reldir) {
289  $dir = dol_buildpath($reldir."core/modules/contract/");
290 
291  // Load file with numbering class (if found)
292  $mybool |= @include_once $dir.$file;
293  }
294 
295  if (!$mybool) {
296  dol_print_error('', "Failed to include file ".$file);
297  return '';
298  }
299 
300  $obj = new $classname();
301  $numref = $obj->getNextValue($soc, $this);
302 
303  if ($numref != "") {
304  return $numref;
305  } else {
306  $this->error = $obj->error;
307  dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
308  return "";
309  }
310  } else {
311  $langs->load("errors");
312  print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
313  return "";
314  }
315  }
316 
317  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
328  public function active_line($user, $line_id, $date, $date_end = '', $comment = '')
329  {
330  // phpcs:enable
331  $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment);
332  if ($result < 0) {
333  $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
334  $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
335  }
336  return $result;
337  }
338 
339 
340  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
350  public function close_line($user, $line_id, $date_end, $comment = '')
351  {
352  // phpcs:enable
353  $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
354  if ($result < 0) {
355  $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
356  $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
357  }
358  return $result;
359  }
360 
361 
373  public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
374  {
375  if (empty($date_start)) {
376  $date_start = dol_now();
377  }
378 
379  $this->db->begin();
380 
381  $error = 0;
382 
383  // Load lines
384  $this->fetch_lines();
385 
386  foreach ($this->lines as $contratline) {
387  // Open lines not already open
388  if ($contratline->statut != ContratLigne::STATUS_OPEN) {
389  $contratline->context = $this->context;
390 
391  $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
392  if ($result < 0) {
393  $error++;
394  $this->error = $contratline->error;
395  $this->errors = $contratline->errors;
396  break;
397  }
398  }
399  }
400 
401  if (!$error && $this->statut == 0) {
402  $result = $this->validate($user, '', $notrigger);
403  if ($result < 0) {
404  $error++;
405  }
406  }
407 
408  if (!$error) {
409  $this->db->commit();
410  return 1;
411  } else {
412  $this->db->rollback();
413  return -1;
414  }
415  }
416 
426  public function closeAll(User $user, $notrigger = 0, $comment = '')
427  {
428  $this->db->begin();
429 
430  // Load lines
431  $this->fetch_lines();
432 
433  $now = dol_now();
434 
435  $error = 0;
436 
437  foreach ($this->lines as $contratline) {
438  // Close lines not already closed
439  if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
440  $contratline->date_end_real = $now;
441  $contratline->date_cloture = $now; // For backward compatibility
442  $contratline->fk_user_cloture = $user->id;
443  $contratline->statut = ContratLigne::STATUS_CLOSED;
444  $result = $contratline->close_line($user, $now, $comment, $notrigger);
445  if ($result < 0) {
446  $error++;
447  $this->error = $contratline->error;
448  $this->errors = $contratline->errors;
449  break;
450  }
451  }
452  }
453 
454  if (!$error && $this->statut == 0) {
455  $result = $this->validate($user, '', $notrigger);
456  if ($result < 0) {
457  $error++;
458  }
459  }
460 
461  if (!$error) {
462  $this->db->commit();
463  return 1;
464  } else {
465  $this->db->rollback();
466  return -1;
467  }
468  }
469 
478  public function validate(User $user, $force_number = '', $notrigger = 0)
479  {
480  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
481  global $langs, $conf;
482 
483  $now = dol_now();
484 
485  $error = 0;
486  dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
487 
488 
489  $this->db->begin();
490 
491  $this->fetch_thirdparty();
492 
493  // A contract is validated so we can move thirdparty to status customer
494  if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) {
495  $result = $this->thirdparty->set_as_client();
496  }
497 
498  // Define new ref
499  if ($force_number) {
500  $num = $force_number;
501  } elseif (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
502  $num = $this->getNextNumRef($this->thirdparty);
503  } else {
504  $num = $this->ref;
505  }
506  $this->newref = dol_sanitizeFileName($num);
507 
508  if ($num) {
509  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
510  //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
511  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
512 
513  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
514  $resql = $this->db->query($sql);
515  if (!$resql) {
516  dol_print_error($this->db);
517  $error++;
518  $this->error = $this->db->lasterror();
519  }
520 
521  // Trigger calls
522  if (!$error && !$notrigger) {
523  // Call trigger
524  $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
525  if ($result < 0) {
526  $error++;
527  }
528  // End call triggers
529  }
530 
531  if (!$error) {
532  $this->oldref = $this->ref;
533 
534  // Rename directory if dir was a temporary ref
535  if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
536  // Now we rename also files into index
537  $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)."'";
538  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
539  $resql = $this->db->query($sql);
540  if (!$resql) {
541  $error++; $this->error = $this->db->lasterror();
542  }
543 
544  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
545  $oldref = dol_sanitizeFileName($this->ref);
546  $newref = dol_sanitizeFileName($num);
547  $dirsource = $conf->contract->dir_output.'/'.$oldref;
548  $dirdest = $conf->contract->dir_output.'/'.$newref;
549  if (!$error && file_exists($dirsource)) {
550  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
551 
552  if (@rename($dirsource, $dirdest)) {
553  dol_syslog("Rename ok");
554  // Rename docs starting with $oldref with $newref
555  $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
556  foreach ($listoffiles as $fileentry) {
557  $dirsource = $fileentry['name'];
558  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
559  $dirsource = $fileentry['path'].'/'.$dirsource;
560  $dirdest = $fileentry['path'].'/'.$dirdest;
561  @rename($dirsource, $dirdest);
562  }
563  }
564  }
565  }
566  }
567 
568  // Set new ref and define current statut
569  if (!$error) {
570  $this->ref = $num;
571  $this->statut = 1;
572  $this->brouillon = 0;
573  $this->date_validation = $now;
574  }
575  } else {
576  $error++;
577  }
578 
579  if (!$error) {
580  $this->db->commit();
581  return 1;
582  } else {
583  $this->db->rollback();
584  return -1;
585  }
586  }
587 
595  public function reopen($user, $notrigger = 0)
596  {
597  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
598  global $langs, $conf;
599 
600  $now = dol_now();
601 
602  $error = 0;
603  dol_syslog(get_class($this).'::reopen user='.$user->id);
604 
605  $this->db->begin();
606 
607  $this->fetch_thirdparty();
608 
609  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
610  //$sql.= ", fk_user_valid = null, date_valid = null";
611  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
612 
613  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
614  $resql = $this->db->query($sql);
615  if (!$resql) {
616  dol_print_error($this->db);
617  $error++;
618  $this->error = $this->db->lasterror();
619  }
620 
621  // Trigger calls
622  if (!$error && !$notrigger) {
623  // Call trigger
624  $result = $this->call_trigger('CONTRACT_REOPEN', $user);
625  if ($result < 0) {
626  $error++;
627  }
628  // End call triggers
629  }
630 
631  // Set new ref and define current status
632  if (!$error) {
633  $this->statut = 0;
634  $this->brouillon = 1;
635  $this->date_validation = $now;
636  }
637 
638  if (!$error) {
639  $this->db->commit();
640  return 1;
641  } else {
642  $this->db->rollback();
643  return -1;
644  }
645  }
646 
656  public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '')
657  {
658  $sql = "SELECT rowid, statut, ref, fk_soc,";
659  $sql .= " ref_supplier, ref_customer,";
660  $sql .= " ref_ext,";
661  $sql .= " entity,";
662  $sql .= " date_contrat as datecontrat,";
663  $sql .= " fk_user_author,";
664  $sql .= " fk_projet as fk_project,";
665  $sql .= " fk_commercial_signature, fk_commercial_suivi,";
666  $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
667  $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
668  if (!$id) {
669  $sql .= " WHERE entity IN (".getEntity('contract').")";
670  } else {
671  $sql .= " WHERE rowid = ".(int) $id;
672  }
673  if ($ref_customer) {
674  $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
675  }
676  if ($ref_supplier) {
677  $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
678  }
679  if ($ref) {
680  $sql .= " AND ref = '".$this->db->escape($ref)."'";
681  }
682 
683  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
684  $resql = $this->db->query($sql);
685  if ($resql) {
686  $num = $this->db->num_rows($resql);
687  if ($num > 1) {
688  $this->error = 'Fetch found several records.';
689  dol_syslog($this->error, LOG_ERR);
690  $result = -2;
691  } elseif ($num) { // $num = 1
692  $obj = $this->db->fetch_object($resql);
693  if ($obj) {
694  $this->id = $obj->rowid;
695  $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
696  $this->ref_customer = $obj->ref_customer;
697  $this->ref_supplier = $obj->ref_supplier;
698  $this->ref_ext = $obj->ref_ext;
699  $this->entity = $obj->entity;
700  $this->statut = $obj->statut;
701 
702  $this->date_contrat = $this->db->jdate($obj->datecontrat);
703  $this->date_creation = $this->db->jdate($obj->datecontrat);
704 
705  $this->user_author_id = $obj->fk_user_author;
706 
707  $this->commercial_signature_id = $obj->fk_commercial_signature;
708  $this->commercial_suivi_id = $obj->fk_commercial_suivi;
709 
710  $this->note_private = $obj->note_private;
711  $this->note_public = $obj->note_public;
712  $this->model_pdf = $obj->model_pdf;
713  $this->modelpdf = $obj->model_pdf; // deprecated
714 
715  $this->fk_projet = $obj->fk_project; // deprecated
716  $this->fk_project = $obj->fk_project;
717 
718  $this->socid = $obj->fk_soc;
719  $this->fk_soc = $obj->fk_soc;
720  $this->last_main_doc = $obj->last_main_doc;
721  $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
722 
723  $this->db->free($resql);
724 
725  // Retrieve all extrafields
726  // fetch optionals attributes and labels
727  $result = $this->fetch_optionals();
728 
729  // Lines
730  if ($result >= 0 && !empty($this->table_element_line)) {
731  $result = $this->fetch_lines();
732  }
733 
734  if ($result < 0) {
735  $this->error = $this->db->lasterror();
736  return -3;
737  }
738 
739  return $this->id;
740  }
741  } else {
742  dol_syslog(get_class($this)."::fetch Contract not found");
743  $this->error = "Contract not found";
744  return 0;
745  }
746  } else {
747  dol_syslog(get_class($this)."::fetch Error searching contract");
748  $this->error = $this->db->error();
749  return -1;
750  }
751  }
752 
753  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
762  public function fetch_lines($only_services = 0, $loadalsotranslation = 0)
763  {
764  // phpcs:enable
765  global $langs, $conf;
766 
767  $this->nbofservices = 0;
768  $this->nbofserviceswait = 0;
769  $this->nbofservicesopened = 0;
770  $this->nbofservicesexpired = 0;
771  $this->nbofservicesclosed = 0;
772 
773  $total_ttc = 0;
774  $total_vat = 0;
775  $total_ht = 0;
776 
777  $now = dol_now();
778 
779  $this->lines = array();
780  $pos = 0;
781 
782  // Selects contract lines related to a product
783  $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
784  $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,";
785  $sql .= " d.total_ht,";
786  $sql .= " d.total_tva,";
787  $sql .= " d.total_localtax1,";
788  $sql .= " d.total_localtax2,";
789  $sql .= " d.total_ttc,";
790  $sql .= " d.info_bits, d.fk_product,";
791  $sql .= " d.date_ouverture_prevue as date_start,";
792  $sql .= " d.date_ouverture as date_start_real,";
793  $sql .= " d.date_fin_validite as date_end,";
794  $sql .= " d.date_cloture as date_end_real,";
795  $sql .= " d.fk_user_author,";
796  $sql .= " d.fk_user_ouverture,";
797  $sql .= " d.fk_user_cloture,";
798  $sql .= " d.fk_unit,";
799  $sql .= " d.product_type as type,";
800  $sql .= " d.rang";
801  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
802  $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
803  if ($only_services == 1) {
804  $sql .= " AND d.product_type = 1";
805  }
806  $sql .= " ORDER by d.rang ASC";
807 
808  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
809  $result = $this->db->query($sql);
810  if ($result) {
811  $num = $this->db->num_rows($result);
812  $i = 0;
813 
814  while ($i < $num) {
815  $objp = $this->db->fetch_object($result);
816 
817  $line = new ContratLigne($this->db);
818 
819  $line->id = $objp->rowid;
820  $line->ref = $objp->rowid;
821  $line->fk_contrat = $objp->fk_contrat;
822  $line->desc = $objp->description; // Description line
823  $line->qty = $objp->qty;
824  $line->vat_src_code = $objp->vat_src_code;
825  $line->tva_tx = $objp->tva_tx;
826  $line->localtax1_tx = $objp->localtax1_tx;
827  $line->localtax2_tx = $objp->localtax2_tx;
828  $line->localtax1_type = $objp->localtax1_type;
829  $line->localtax2_type = $objp->localtax2_type;
830  $line->subprice = $objp->subprice;
831  $line->statut = $objp->statut;
832  $line->remise_percent = $objp->remise_percent;
833  $line->price_ht = $objp->price_ht;
834  $line->price = $objp->price_ht; // For backward compatibility
835  $line->total_ht = $objp->total_ht;
836  $line->total_tva = $objp->total_tva;
837  $line->total_localtax1 = $objp->total_localtax1;
838  $line->total_localtax2 = $objp->total_localtax2;
839  $line->total_ttc = $objp->total_ttc;
840  $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
841  $line->info_bits = $objp->info_bits;
842  $line->type = $objp->type;
843 
844  $line->fk_fournprice = $objp->fk_fournprice;
845  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
846  $line->pa_ht = $marginInfos[0];
847 
848  $line->fk_user_author = $objp->fk_user_author;
849  $line->fk_user_ouverture = $objp->fk_user_ouverture;
850  $line->fk_user_cloture = $objp->fk_user_cloture;
851  $line->fk_unit = $objp->fk_unit;
852 
853  $line->ref = $objp->product_ref; // deprecated
854  $line->product_ref = $objp->product_ref; // Product Ref
855  $line->product_type = $objp->product_type; // Product Type
856  $line->product_desc = $objp->product_desc; // Product Description
857  $line->product_label = $objp->product_label; // Product Label
858 
859  $line->description = $objp->description;
860 
861  $line->date_start = $this->db->jdate($objp->date_start);
862  $line->date_start_real = $this->db->jdate($objp->date_start_real);
863  $line->date_end = $this->db->jdate($objp->date_end);
864  $line->date_end_real = $this->db->jdate($objp->date_end_real);
865  // For backward compatibility
866  //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
867  //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
868  //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
869  //$line->date_cloture = $this->db->jdate($objp->date_cloture);
870  //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
871  //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
872  //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
873  //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
874 
875  $line->rang = $objp->rang;
876 
877  // Retrieve all extrafields for contract line
878  // fetch optionals attributes and labels
879  $line->fetch_optionals();
880 
881  // multilangs
882  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
883  $tmpproduct = new Product($this->db);
884  $tmpproduct->fetch($objp->fk_product);
885  $tmpproduct->getMultiLangs();
886 
887  $line->multilangs = $tmpproduct->multilangs;
888  }
889 
890  $this->lines[$pos] = $line;
891 
892  $this->lines_id_index_mapper[$line->id] = $pos;
893 
894  //dol_syslog("1 ".$line->desc);
895  //dol_syslog("2 ".$line->product_desc);
896 
897  if ($line->statut == ContratLigne::STATUS_INITIAL) {
898  $this->nbofserviceswait++;
899  }
900  if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
901  $this->nbofservicesopened++;
902  }
903  if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
904  $this->nbofservicesexpired++;
905  }
906  if ($line->statut == ContratLigne::STATUS_CLOSED) {
907  $this->nbofservicesclosed++;
908  }
909 
910  $total_ttc += $objp->total_ttc; // TODO Not saved into database
911  $total_vat += $objp->total_tva;
912  $total_ht += $objp->total_ht;
913 
914  $i++;
915  $pos++;
916  }
917  $this->db->free($result);
918  } else {
919  dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
920  return -3;
921  }
922 
923  // Now set the global properties on contract not stored into database.
924  $this->nbofservices = count($this->lines);
925  $this->total_ttc = price2num($total_ttc);
926  $this->total_tva = price2num($total_vat);
927  $this->total_ht = price2num($total_ht);
928 
929  return $this->lines;
930  }
931 
938  public function create($user)
939  {
940  global $conf, $langs, $mysoc;
941 
942  // Check parameters
943  $paramsok = 1;
944  if ($this->commercial_signature_id <= 0) {
945  $langs->load("commercial");
946  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
947  $paramsok = 0;
948  }
949  if ($this->commercial_suivi_id <= 0) {
950  $langs->load("commercial");
951  $this->error .= ($this->error ? "<br>" : '');
952  $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
953  $paramsok = 0;
954  }
955  if (!$paramsok) {
956  return -1;
957  }
958 
959 
960  $this->db->begin();
961 
962  $now = dol_now();
963 
964  // Insert contract
965  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
966  $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
967  $sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
968  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
969  $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
970  $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
971  $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
972  $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
973  $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
974  $sql .= ", ".((int) $conf->entity);
975  $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
976  $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
977  $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
978  $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
979  $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
980  $sql .= ")";
981  $resql = $this->db->query($sql);
982 
983  if ($resql) {
984  $error = 0;
985 
986  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
987 
988  // Load object modContract
989  $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
990  if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
991  $module = substr($module, 0, dol_strlen($module) - 4);
992  }
993  $result = dol_include_once('/core/modules/contract/'.$module.'.php');
994  if ($result > 0) {
995  $modCodeContract = new $module();
996 
997  if (!empty($modCodeContract->code_auto)) {
998  // Force the ref to a draft value if numbering module is an automatic numbering
999  $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1000  if ($this->db->query($sql)) {
1001  if ($this->id) {
1002  $this->ref = "(PROV".$this->id.")";
1003  }
1004  }
1005  }
1006  }
1007 
1008  if (!$error) {
1009  $result = $this->insertExtraFields();
1010  if ($result < 0) {
1011  $error++;
1012  }
1013  }
1014 
1015  // Insert business contacts ('SALESREPSIGN','contrat')
1016  if (!$error) {
1017  $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1018  if ($result < 0) {
1019  $error++;
1020  }
1021  }
1022 
1023  // Insert business contacts ('SALESREPFOLL','contrat')
1024  if (!$error) {
1025  $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1026  if ($result < 0) {
1027  $error++;
1028  }
1029  }
1030 
1031  if (!$error) {
1032  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1033  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1034  }
1035 
1036  // Add object linked
1037  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1038  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1039  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, ...))
1040  foreach ($tmp_origin_id as $origin_id) {
1041  $ret = $this->add_object_linked($origin, $origin_id);
1042  if (!$ret) {
1043  $this->error = $this->db->lasterror();
1044  $error++;
1045  }
1046  }
1047  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1048  {
1049  $origin_id = $tmp_origin_id;
1050  $ret = $this->add_object_linked($origin, $origin_id);
1051  if (!$ret) {
1052  $this->error = $this->db->lasterror();
1053  $error++;
1054  }
1055  }
1056  }
1057  }
1058 
1059  if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1060  $originforcontact = $this->origin;
1061  $originidforcontact = $this->origin_id;
1062  if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1063  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1064  $exp = new Expedition($this->db);
1065  $exp->fetch($this->origin_id);
1066  $exp->fetchObjectLinked();
1067  if (count($exp->linkedObjectsIds['commande']) > 0) {
1068  foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1069  $originforcontact = 'commande';
1070  $originidforcontact = $value;
1071  break; // We take first one
1072  }
1073  }
1074  }
1075 
1076  $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";
1077  $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1078 
1079  $resqlcontact = $this->db->query($sqlcontact);
1080  if ($resqlcontact) {
1081  while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1082  if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1083  continue; // ignore this, already forced previously
1084  }
1085 
1086  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1087  $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
1088  }
1089  } else {
1090  dol_print_error($resqlcontact);
1091  }
1092  }
1093  }
1094 
1095  if (!$error) {
1096  // Call trigger
1097  $result = $this->call_trigger('CONTRACT_CREATE', $user);
1098  if ($result < 0) {
1099  $error++;
1100  }
1101  // End call triggers
1102 
1103  if (!$error) {
1104  $this->db->commit();
1105  return $this->id;
1106  } else {
1107  dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1108  $this->db->rollback();
1109  return -3;
1110  }
1111  } else {
1112  $this->error = "Failed to add contract";
1113  dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1114  $this->db->rollback();
1115  return -2;
1116  }
1117  } else {
1118  $this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1119 
1120  $this->db->rollback();
1121  return -1;
1122  }
1123  }
1124 
1125 
1132  public function delete($user)
1133  {
1134  global $conf, $langs;
1135  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1136 
1137  $error = 0;
1138 
1139  $this->db->begin();
1140 
1141  // Call trigger
1142  $result = $this->call_trigger('CONTRACT_DELETE', $user);
1143  if ($result < 0) {
1144  $error++;
1145  }
1146  // End call triggers
1147 
1148  if (!$error) {
1149  // Delete linked contacts
1150  $res = $this->delete_linked_contact();
1151  if ($res < 0) {
1152  dol_syslog(get_class($this)."::delete error", LOG_ERR);
1153  $error++;
1154  }
1155  }
1156 
1157  if (!$error) {
1158  // Delete linked object
1159  $res = $this->deleteObjectLinked();
1160  if ($res < 0) {
1161  $error++;
1162  }
1163  }
1164 
1165  if (!$error) {
1166  // Delete contratdet_log
1167  /*
1168  $sql = "DELETE cdl";
1169  $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1170  $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1171  */
1172  $sql = "SELECT cdl.rowid as cdlrowid ";
1173  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1174  $sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1175 
1176  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1177  $resql = $this->db->query($sql);
1178  if (!$resql) {
1179  $this->error = $this->db->error();
1180  $error++;
1181  }
1182  $numressql = $this->db->num_rows($resql);
1183  if (!$error && $numressql) {
1184  $tab_resql = array();
1185  for ($i = 0; $i < $numressql; $i++) {
1186  $objresql = $this->db->fetch_object($resql);
1187  $tab_resql[] = $objresql->cdlrowid;
1188  }
1189  $this->db->free($resql);
1190 
1191  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1192  $sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".$this->db->sanitize(implode(",", $tab_resql)).")";
1193 
1194  dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1195  $resql = $this->db->query($sql);
1196  if (!$resql) {
1197  $this->error = $this->db->error();
1198  $error++;
1199  }
1200  }
1201  }
1202 
1203  // Delete lines
1204  if (!$error) {
1205  // Delete contratdet extrafields
1206  $main = MAIN_DB_PREFIX.'contratdet';
1207  $ef = $main."_extrafields";
1208  $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1209 
1210  dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1211  $resql = $this->db->query($sql);
1212  if (!$resql) {
1213  $this->error = $this->db->error();
1214  $error++;
1215  }
1216  }
1217 
1218  if (!$error) {
1219  // Delete contratdet
1220  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1221  $sql .= " WHERE fk_contrat=".((int) $this->id);
1222 
1223  dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1224  $resql = $this->db->query($sql);
1225  if (!$resql) {
1226  $this->error = $this->db->error();
1227  $error++;
1228  }
1229  }
1230 
1231  // Delete llx_ecm_files
1232  if (!$error) {
1233  $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);
1234  $resql = $this->db->query($sql);
1235  if (!$resql) {
1236  $this->error = $this->db->lasterror();
1237  $this->errors[] = $this->error;
1238  $error++;
1239  }
1240  }
1241 
1242  // Delete contract
1243  if (!$error) {
1244  $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1245  $sql .= " WHERE rowid=".((int) $this->id);
1246 
1247  dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1248  $resql = $this->db->query($sql);
1249  if (!$resql) {
1250  $this->error = $this->db->error();
1251  $error++;
1252  }
1253  }
1254 
1255  // Removed extrafields
1256  if (!$error) {
1257  $result = $this->deleteExtraFields();
1258  if ($result < 0) {
1259  $error++;
1260  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1261  }
1262  }
1263 
1264  if (!$error) {
1265  // We remove directory
1266  $ref = dol_sanitizeFileName($this->ref);
1267  if ($conf->contrat->dir_output) {
1268  $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1269  if (file_exists($dir)) {
1270  $res = @dol_delete_dir_recursive($dir);
1271  if (!$res) {
1272  $this->error = 'ErrorFailToDeleteDir';
1273  $error++;
1274  }
1275  }
1276  }
1277  }
1278 
1279  if (!$error) {
1280  $this->db->commit();
1281  return 1;
1282  } else {
1283  $this->error = $this->db->lasterror();
1284  $this->db->rollback();
1285  return -1;
1286  }
1287  }
1288 
1296  public function update($user, $notrigger = 0)
1297  {
1298  global $conf, $langs;
1299  $error = 0;
1300 
1301  // Clean parameters
1302  if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1303  $this->fk_commercial_signature = $this->commercial_signature_id;
1304  }
1305  if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1306  $this->fk_commercial_suivi = $this->commercial_suivi_id;
1307  }
1308  if (empty($this->fk_soc) && $this->socid > 0) {
1309  $this->fk_soc = (int) $this->socid;
1310  }
1311  if (empty($this->fk_project) && $this->projet > 0) {
1312  $this->fk_project = (int) $this->projet;
1313  }
1314 
1315  if (isset($this->ref)) {
1316  $this->ref = trim($this->ref);
1317  }
1318  if (isset($this->ref_customer)) {
1319  $this->ref_customer = trim($this->ref_customer);
1320  }
1321  if (isset($this->ref_supplier)) {
1322  $this->ref_supplier = trim($this->ref_supplier);
1323  }
1324  if (isset($this->ref_ext)) {
1325  $this->ref_ext = trim($this->ref_ext);
1326  }
1327  if (isset($this->entity)) {
1328  $this->entity = (int) $this->entity;
1329  }
1330  if (isset($this->statut)) {
1331  $this->statut = (int) $this->statut;
1332  }
1333  if (isset($this->fk_soc)) {
1334  $this->fk_soc = (int) $this->fk_soc;
1335  }
1336  if (isset($this->fk_commercial_signature)) {
1337  $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1338  }
1339  if (isset($this->fk_commercial_suivi)) {
1340  $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
1341  }
1342  if (isset($this->note_private)) {
1343  $this->note_private = trim($this->note_private);
1344  }
1345  if (isset($this->note_public)) {
1346  $this->note_public = trim($this->note_public);
1347  }
1348  if (isset($this->import_key)) {
1349  $this->import_key = trim($this->import_key);
1350  }
1351  //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1352 
1353  // Check parameters
1354  // Put here code to add a control on parameters values
1355 
1356  // Update request
1357  $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1358  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1359  $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1360  $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1361  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1362  $sql .= " entity=".$conf->entity.",";
1363  $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1364  $sql .= " statut=".(isset($this->statut) ? $this->statut : "null").",";
1365  $sql .= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc : "null").",";
1366  $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1367  $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1368  $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1369  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1370  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1371  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1372  //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null");
1373  $sql .= " WHERE rowid=".((int) $this->id);
1374 
1375  $this->db->begin();
1376 
1377  $resql = $this->db->query($sql);
1378  if (!$resql) {
1379  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1380  }
1381 
1382  if (!$error) {
1383  $result = $this->insertExtraFields();
1384  if ($result < 0) {
1385  $error++;
1386  }
1387  }
1388 
1389  if (!$error && !$notrigger) {
1390  // Call triggers
1391  $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1392  if ($result < 0) {
1393  $error++;
1394  }
1395  // End call triggers
1396  }
1397 
1398  // Commit or rollback
1399  if ($error) {
1400  foreach ($this->errors as $errmsg) {
1401  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1402  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1403  }
1404  $this->db->rollback();
1405  return -1 * $error;
1406  } else {
1407  $this->db->commit();
1408  return 1;
1409  }
1410  }
1411 
1412 
1436  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)
1437  {
1438  global $user, $langs, $conf, $mysoc;
1439  $error = 0;
1440 
1441  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");
1442 
1443  // Check parameters
1444  if ($fk_product <= 0 && empty($desc)) {
1445  $this->error = "ErrorDescRequiredForFreeProductLines";
1446  return -1;
1447  }
1448 
1449  if ($this->statut >= 0) {
1450  // Clean parameters
1451  $pu_ht = price2num($pu_ht);
1452  $pu_ttc = price2num($pu_ttc);
1453  $pa_ht = price2num($pa_ht);
1454 
1455  // Clean vat code
1456  $reg = array();
1457  $vat_src_code = '';
1458  if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1459  $vat_src_code = $reg[1];
1460  $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1461  }
1462  $txtva = price2num($txtva);
1463  $txlocaltax1 = price2num($txlocaltax1);
1464  $txlocaltax2 = price2num($txlocaltax2);
1465 
1466  $remise_percent = price2num($remise_percent);
1467  $qty = price2num($qty);
1468  if (empty($qty)) {
1469  $qty = 1;
1470  }
1471  if (empty($info_bits)) {
1472  $info_bits = 0;
1473  }
1474  if (empty($pu_ht) || !is_numeric($pu_ht)) {
1475  $pu_ht = 0;
1476  }
1477  if (empty($pu_ttc)) {
1478  $pu_ttc = 0;
1479  }
1480  if (empty($txtva) || !is_numeric($txtva)) {
1481  $txtva = 0;
1482  }
1483  if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1484  $txlocaltax1 = 0;
1485  }
1486  if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1487  $txlocaltax2 = 0;
1488  }
1489 
1490  if ($price_base_type == 'HT') {
1491  $pu = $pu_ht;
1492  } else {
1493  $pu = $pu_ttc;
1494  }
1495 
1496  // Check parameters
1497  if (empty($remise_percent)) {
1498  $remise_percent = 0;
1499  }
1500  if (empty($rang)) {
1501  $rang = 0;
1502  }
1503 
1504  if ($date_start && $date_end && $date_start > $date_end) {
1505  $langs->load("errors");
1506  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1507  return -1;
1508  }
1509 
1510  $this->db->begin();
1511 
1512  $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1513 
1514  // Calcul du total TTC et de la TVA pour la ligne a partir de
1515  // qty, pu, remise_percent et txtva
1516  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1517  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1518 
1519  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1520  $total_ht = $tabprice[0];
1521  $total_tva = $tabprice[1];
1522  $total_ttc = $tabprice[2];
1523  $total_localtax1 = $tabprice[9];
1524  $total_localtax2 = $tabprice[10];
1525 
1526  $localtax1_type = $localtaxes_type[0];
1527  $localtax2_type = $localtaxes_type[2];
1528 
1529  // TODO A virer
1530  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1531  $remise = 0;
1532  $price = price2num(round($pu_ht, 2));
1533  if (dol_strlen($remise_percent) > 0) {
1534  $remise = round(($pu_ht * $remise_percent / 100), 2);
1535  $price = $pu_ht - $remise;
1536  }
1537 
1538  if (empty($pa_ht)) {
1539  $pa_ht = 0;
1540  }
1541 
1542 
1543  // if buy price not defined, define buyprice as configured in margin admin
1544  if ($this->pa_ht == 0) {
1545  if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) {
1546  return $result;
1547  } else {
1548  $pa_ht = $result;
1549  }
1550  }
1551 
1552  // Insertion dans la base
1553  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1554  $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1555  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1556  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1557  $sql .= " info_bits,";
1558  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1559  if ($date_start > 0) {
1560  $sql .= ",date_ouverture_prevue";
1561  }
1562  if ($date_end > 0) {
1563  $sql .= ",date_fin_validite";
1564  }
1565  $sql .= ", fk_unit";
1566  $sql .= ", rang";
1567  $sql .= ") VALUES (";
1568  $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1569  $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1570  $sql .= " ".((float) $qty).",";
1571  $sql .= " ".((float) $txtva).",";
1572  $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1573  $sql .= " ".((float) $txlocaltax1).",";
1574  $sql .= " ".((float) $txlocaltax2).",";
1575  $sql .= " '".$this->db->escape($localtax1_type)."',";
1576  $sql .= " '".$this->db->escape($localtax2_type)."',";
1577  $sql .= " ".price2num($remise_percent).",";
1578  $sql .= " ".price2num($pu_ht).",";
1579  $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1580  $sql .= " '".$this->db->escape($info_bits)."',";
1581  $sql .= " ".price2num($price).",".price2num($remise).",";
1582  if (isset($fk_fournprice)) {
1583  $sql .= ' '.((int) $fk_fournprice).',';
1584  } else {
1585  $sql .= ' null,';
1586  }
1587  if (isset($pa_ht)) {
1588  $sql .= ' '.price2num($pa_ht);
1589  } else {
1590  $sql .= ' null';
1591  }
1592  if ($date_start > 0) {
1593  $sql .= ",'".$this->db->idate($date_start)."'";
1594  }
1595  if ($date_end > 0) {
1596  $sql .= ",'".$this->db->idate($date_end)."'";
1597  }
1598  $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1599  $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1600  $sql .= ")";
1601 
1602  $resql = $this->db->query($sql);
1603  if ($resql) {
1604  $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1605 
1606  if (!$error) {
1607  $contractline = new ContratLigne($this->db);
1608  $contractline->array_options = $array_options;
1609  $contractline->id = $contractlineid;
1610  $result = $contractline->insertExtraFields();
1611  if ($result < 0) {
1612  $this->error[] = $contractline->error;
1613  $error++;
1614  }
1615  }
1616 
1617  if (empty($error)) {
1618  // Call trigger
1619  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1620  if ($result < 0) {
1621  $error++;
1622  }
1623  // End call triggers
1624  }
1625 
1626  if ($error) {
1627  $this->db->rollback();
1628  return -1;
1629  } else {
1630  $this->db->commit();
1631  return $contractlineid;
1632  }
1633  } else {
1634  $this->db->rollback();
1635  $this->error = $this->db->error()." sql=".$sql;
1636  return -1;
1637  }
1638  } else {
1639  dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1640  return -2;
1641  }
1642  }
1643 
1668  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)
1669  {
1670  global $user, $conf, $langs, $mysoc;
1671 
1672  $error = 0;
1673 
1674  // Clean parameters
1675  $qty = trim($qty);
1676  $desc = trim($desc);
1677  $desc = trim($desc);
1678  $price = price2num($pu);
1679  $tvatx = price2num($tvatx);
1680  $localtax1tx = price2num($localtax1tx);
1681  $localtax2tx = price2num($localtax2tx);
1682  $pa_ht = price2num($pa_ht);
1683  if (empty($fk_fournprice)) {
1684  $fk_fournprice = 0;
1685  }
1686  if (empty($rang)) {
1687  $rang = 0;
1688  }
1689 
1690  $subprice = $price;
1691  $remise = 0;
1692  if (dol_strlen($remise_percent) > 0) {
1693  $remise = round(($pu * $remise_percent / 100), 2);
1694  $price = $pu - $remise;
1695  } else {
1696  $remise_percent = 0;
1697  }
1698 
1699  if ($date_start && $date_end && $date_start > $date_end) {
1700  $langs->load("errors");
1701  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1702  return -1;
1703  }
1704 
1705  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");
1706 
1707  $this->db->begin();
1708 
1709  // Calcul du total TTC et de la TVA pour la ligne a partir de
1710  // qty, pu, remise_percent et tvatx
1711  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1712  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1713 
1714  $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1715  $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1716 
1717  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1718  $total_ht = $tabprice[0];
1719  $total_tva = $tabprice[1];
1720  $total_ttc = $tabprice[2];
1721  $total_localtax1 = $tabprice[9];
1722  $total_localtax2 = $tabprice[10];
1723 
1724  $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1725  $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1726 
1727  // TODO A virer
1728  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1729  $remise = 0;
1730  $price = price2num(round($pu, 2));
1731  if (dol_strlen($remise_percent) > 0) {
1732  $remise = round(($pu * $remise_percent / 100), 2);
1733  $price = $pu - $remise;
1734  }
1735 
1736  if (empty($pa_ht)) {
1737  $pa_ht = 0;
1738  }
1739 
1740  // if buy price not defined, define buyprice as configured in margin admin
1741  if ($this->pa_ht == 0) {
1742  if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
1743  return $result;
1744  } else {
1745  $pa_ht = $result;
1746  }
1747  }
1748 
1749  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1750  $sql .= ",price_ht = ".((float) price2num($price));
1751  $sql .= ",subprice = ".((float) price2num($subprice));
1752  $sql .= ",remise = ".((float) price2num($remise));
1753  $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1754  $sql .= ",qty = ".((float) $qty);
1755  $sql .= ",tva_tx = ".((float) price2num($tvatx));
1756  $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1757  $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1758  $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1759  $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1760  $sql .= ", total_ht = ".((float) price2num($total_ht));
1761  $sql .= ", total_tva = ".((float) price2num($total_tva));
1762  $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1763  $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1764  $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1765  $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1766  $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1767  if ($date_start > 0) {
1768  $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1769  } else {
1770  $sql .= ",date_ouverture_prevue = null";
1771  }
1772  if ($date_end > 0) {
1773  $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1774  } else {
1775  $sql .= ",date_fin_validite = null";
1776  }
1777  if ($date_start_real > 0) {
1778  $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1779  } else {
1780  $sql .= ",date_ouverture = null";
1781  }
1782  if ($date_end_real > 0) {
1783  $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1784  } else {
1785  $sql .= ",date_cloture = null";
1786  }
1787  $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1788  $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1789  $sql .= " WHERE rowid = ".((int) $rowid);
1790 
1791  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1792  $result = $this->db->query($sql);
1793  if ($result) {
1794  if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1795  $contractline = new ContratLigne($this->db);
1796  $contractline->fetch($rowid);
1797 
1798  // We replace values in $contractline->array_options only for entries defined into $array_options
1799  foreach ($array_options as $key => $value) {
1800  $contractline->array_options[$key] = $array_options[$key];
1801  }
1802 
1803  $result = $contractline->insertExtraFields();
1804  if ($result < 0) {
1805  $this->error[] = $contractline->error;
1806  $error++;
1807  }
1808  }
1809 
1810  if (empty($error)) {
1811  // Call trigger
1812  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1813  if ($result < 0) {
1814  $this->db->rollback();
1815  return -3;
1816  }
1817  // End call triggers
1818 
1819  $this->db->commit();
1820  return 1;
1821  }
1822  } else {
1823  $this->db->rollback();
1824  $this->error = $this->db->error();
1825  dol_syslog(get_class($this)."::updateline Erreur -1");
1826  return -1;
1827  }
1828  }
1829 
1837  public function deleteline($idline, User $user)
1838  {
1839  global $conf, $langs;
1840 
1841  $error = 0;
1842 
1843  if ($this->statut >= 0) {
1844  // Call trigger
1845  $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1846  if ($result < 0) {
1847  return -1;
1848  }
1849  // End call triggers
1850 
1851  $this->db->begin();
1852 
1853  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1854  $sql .= " WHERE rowid = ".((int) $idline);
1855 
1856  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1857  $resql = $this->db->query($sql);
1858  if (!$resql) {
1859  $this->error = "Error ".$this->db->lasterror();
1860  $error++;
1861  }
1862 
1863  if (!$error) {
1864  // Remove extrafields
1865  $contractline = new ContratLigne($this->db);
1866  $contractline->id = $idline;
1867  $result = $contractline->deleteExtraFields();
1868  if ($result < 0) {
1869  $error++;
1870  $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1871  }
1872  }
1873 
1874  if (empty($error)) {
1875  $this->db->commit();
1876  return 1;
1877  } else {
1878  dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1879  $this->db->rollback();
1880  return -1;
1881  }
1882  } else {
1883  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1884  return -2;
1885  }
1886  }
1887 
1888 
1889  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1897  public function update_statut($user)
1898  {
1899  // phpcs:enable
1900  dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1901 
1902  // If draft, we keep it (should not happen)
1903  if ($this->statut == 0) {
1904  return 1;
1905  }
1906 
1907  // Load $this->lines array
1908  // $this->fetch_lines();
1909 
1910  // $newstatut=1;
1911  // foreach($this->lines as $key => $contractline)
1912  // {
1913  // // if ($contractline) // Loop on each service
1914  // }
1915 
1916  return 1;
1917  }
1918 
1919 
1926  public function getLibStatut($mode)
1927  {
1928  return $this->LibStatut($this->statut, $mode);
1929  }
1930 
1931  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1939  public function LibStatut($status, $mode)
1940  {
1941  // phpcs:enable
1942  global $langs;
1943 
1944  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1945  global $langs;
1946  $langs->load("contracts");
1947  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1948  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1949  $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1950  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1951  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1952  $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1953  }
1954 
1955  $statusType = 'status'.$status;
1956  if ($status == self::STATUS_VALIDATED) {
1957  $statusType = 'status6';
1958  }
1959 
1960  if ($mode == 4 || $mode == 6 || $mode == 7) {
1961  $text = '';
1962  if ($mode == 4) {
1963  $text = '<span class="hideonsmartphone">';
1964  $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
1965  $text .= ' '.$langs->trans("Services");
1966  $text .= ': &nbsp; &nbsp; ';
1967  $text .= '</span>';
1968  }
1969  $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
1970  $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1971  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1972  $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1973  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1974  $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1975  $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
1976  $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
1977  $text .= ($mode == 7 ? '</span>' : '');
1978  return $text;
1979  } else {
1980  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1981  }
1982  }
1983 
1984 
1994  public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
1995  {
1996  global $conf, $langs, $user, $hookmanager;
1997 
1998  $result = '';
1999 
2000  $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2001 
2002  //if ($option !== 'nolink')
2003  //{
2004  // Add param to save lastsearch_values or not
2005  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2006  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2007  $add_save_lastsearch_values = 1;
2008  }
2009  if ($add_save_lastsearch_values) {
2010  $url .= '&save_lastsearch_values=1';
2011  }
2012  //}
2013 
2014  $label = '';
2015 
2016  if ($user->rights->contrat->lire) {
2017  $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2018  /* Status of a contract is status of all services, so disabled
2019  if (isset($this->statut)) {
2020  $label .= ' '.$this->getLibStatut(5);
2021  }*/
2022  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2023  $ref_customer = (!empty($this->ref_customer) ? $this->ref_customer : (empty($this->ref_client) ? '' : $this->ref_client));
2024  $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$ref_customer;
2025  $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2026  if (!empty($this->total_ht)) {
2027  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2028  }
2029  if (!empty($this->total_tva)) {
2030  $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2031  }
2032  if (!empty($this->total_ttc)) {
2033  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2034  }
2035  }
2036 
2037  $linkclose = '';
2038  if (empty($notooltip) && $user->rights->contrat->lire) {
2039  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2040  $label = $langs->trans("ShowOrder");
2041  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2042  }
2043  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2044  $linkclose .= ' class="classfortooltip"';
2045  }
2046 
2047  $linkstart = '<a href="'.$url.'"';
2048  $linkstart .= $linkclose.'>';
2049  $linkend = '</a>';
2050 
2051  $result .= $linkstart;
2052  if ($withpicto) {
2053  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
2054  }
2055  if ($withpicto != 2) {
2056  $result .= ($this->ref ? $this->ref : $this->id);
2057  }
2058  $result .= $linkend;
2059 
2060  global $action;
2061  $hookmanager->initHooks(array('contractdao'));
2062  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2063  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2064  if ($reshook > 0) {
2065  $result = $hookmanager->resPrint;
2066  } else {
2067  $result .= $hookmanager->resPrint;
2068  }
2069 
2070  return $result;
2071  }
2072 
2079  public function info($id)
2080  {
2081  $sql = "SELECT c.rowid, c.ref, c.datec,";
2082  $sql .= " c.tms as date_modification,";
2083  $sql .= " fk_user_author";
2084  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2085  $sql .= " WHERE c.rowid = ".((int) $id);
2086 
2087  $result = $this->db->query($sql);
2088  if ($result) {
2089  if ($this->db->num_rows($result)) {
2090  $obj = $this->db->fetch_object($result);
2091 
2092  $this->id = $obj->rowid;
2093 
2094  if ($obj->fk_user_author) {
2095  $cuser = new User($this->db);
2096  $cuser->fetch($obj->fk_user_author);
2097  $this->user_creation = $cuser;
2098  }
2099 
2100  $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2101  $this->date_creation = $this->db->jdate($obj->datec);
2102  $this->date_modification = $this->db->jdate($obj->date_modification);
2103  }
2104 
2105  $this->db->free($result);
2106  } else {
2107  dol_print_error($this->db);
2108  }
2109  }
2110 
2111  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2118  public function array_detail($status = -1)
2119  {
2120  // phpcs:enable
2121  $tab = array();
2122 
2123  $sql = "SELECT cd.rowid";
2124  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2125  $sql .= " WHERE fk_contrat =".((int) $this->id);
2126  if ($status >= 0) {
2127  $sql .= " AND statut = ".((int) $status);
2128  }
2129 
2130  dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2131  $resql = $this->db->query($sql);
2132  if ($resql) {
2133  $num = $this->db->num_rows($resql);
2134  $i = 0;
2135  while ($i < $num) {
2136  $obj = $this->db->fetch_object($resql);
2137  $tab[$i] = $obj->rowid;
2138  $i++;
2139  }
2140  return $tab;
2141  } else {
2142  $this->error = $this->db->error();
2143  return -1;
2144  }
2145  }
2146 
2156  public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2157  {
2158  $tab = array();
2159 
2160  $sql = "SELECT c.rowid";
2161  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2162  if (!empty($product_categories)) {
2163  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2164  $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)).")";
2165  }
2166  $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2167  $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2168  $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2169  $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2170  $sql .= " GROUP BY c.rowid";
2171 
2172  dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2173  $resql = $this->db->query($sql);
2174  if ($resql) {
2175  $num = $this->db->num_rows($resql);
2176  $i = 0;
2177  while ($i < $num) {
2178  $obj = $this->db->fetch_object($resql);
2179  $contrat = new Contrat($this->db);
2180  $contrat->fetch($obj->rowid);
2181  $tab[$contrat->id] = $contrat;
2182  $i++;
2183  }
2184  return $tab;
2185  } else {
2186  $this->error = $this->db->lasterror();
2187  return -1;
2188  }
2189  }
2190 
2191 
2192  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2200  public function load_board($user, $mode)
2201  {
2202  // phpcs:enable
2203  global $conf, $langs;
2204 
2205  $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2206  $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2207  $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2208  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2209  $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2210  }
2211 
2212  if ($mode == 'inactive') {
2213  $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2214  $sql .= $this->from;
2215  $sql .= " WHERE c.statut = 1";
2216  $sql .= " AND c.rowid = cd.fk_contrat";
2217  $sql .= " AND cd.statut = 0";
2218  } elseif ($mode == 'expired') {
2219  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2220  $sql .= $this->from;
2221  $sql .= " WHERE c.statut = 1";
2222  $sql .= " AND c.rowid = cd.fk_contrat";
2223  $sql .= " AND cd.statut = 4";
2224  $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2225  } elseif ($mode == 'active') {
2226  $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2227  $sql .= $this->from;
2228  $sql .= " WHERE c.statut = 1";
2229  $sql .= " AND c.rowid = cd.fk_contrat";
2230  $sql .= " AND cd.statut = 4";
2231  //$datetouse = dol_now();
2232  //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2233  }
2234  $sql .= " AND c.fk_soc = s.rowid";
2235  $sql .= " AND c.entity = ".((int) $conf->entity);
2236  if ($user->socid) {
2237  $sql .= " AND c.fk_soc = ".((int) $user->socid);
2238  }
2239  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2240  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2241  }
2242 
2243  $resql = $this->db->query($sql);
2244  if ($resql) {
2245  $langs->load("contracts");
2246  $now = dol_now();
2247 
2248  if ($mode == 'inactive') {
2249  $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2250  $label = $langs->trans("BoardNotActivatedServices");
2251  $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2252  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=0&sortfield=cd.date_fin_validite&sortorder=asc';
2253  } elseif ($mode == 'expired') {
2254  $warning_delay = $conf->contrat->services->expires->warning_delay;
2255  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2256  $label = $langs->trans("BoardExpiredServices");
2257  $labelShort = $langs->trans("BoardExpiredServicesShort");
2258  } else {
2259  $warning_delay = $conf->contrat->services->expires->warning_delay;
2260  $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&sortfield=cd.date_fin_validite&sortorder=asc';
2261  //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
2262  //if ($warning_delay >= 0) $url.='&amp;filter=expired';
2263  $label = $langs->trans("BoardRunningServices");
2264  $labelShort = $langs->trans("BoardRunningServicesShort");
2265  }
2266 
2267  $response = new WorkboardResponse();
2268  $response->warning_delay = $warning_delay / 60 / 60 / 24;
2269  $response->label = $label;
2270  $response->labelShort = $labelShort;
2271  $response->url = $url;
2272  $response->img = img_object('', "contract");
2273 
2274  while ($obj = $this->db->fetch_object($resql)) {
2275  $response->nbtodo++;
2276 
2277  if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2278  $response->nbtodolate++;
2279  }
2280  }
2281 
2282  return $response;
2283  } else {
2284  dol_print_error($this->db);
2285  $this->error = $this->db->error();
2286  return -1;
2287  }
2288  }
2289 
2290  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2296  public function load_state_board()
2297  {
2298  // phpcs:enable
2299  global $conf, $user;
2300 
2301  $this->nb = array();
2302  $clause = "WHERE";
2303 
2304  $sql = "SELECT count(c.rowid) as nb";
2305  $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2306  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2307  if (empty($user->rights->societe->client->voir) && !$user->socid) {
2308  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2309  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2310  $clause = "AND";
2311  }
2312  $sql .= " ".$clause." c.entity = ".$conf->entity;
2313 
2314  $resql = $this->db->query($sql);
2315  if ($resql) {
2316  while ($obj = $this->db->fetch_object($resql)) {
2317  $this->nb["contracts"] = $obj->nb;
2318  }
2319  $this->db->free($resql);
2320  return 1;
2321  } else {
2322  dol_print_error($this->db);
2323  $this->error = $this->db->error();
2324  return -1;
2325  }
2326  }
2327 
2328 
2329  /* gestion des contacts d'un contrat */
2330 
2336  public function getIdBillingContact()
2337  {
2338  return $this->getIdContact('external', 'BILLING');
2339  }
2340 
2346  public function getIdServiceContact()
2347  {
2348  return $this->getIdContact('external', 'SERVICE');
2349  }
2350 
2351 
2359  public function initAsSpecimen()
2360  {
2361  global $user, $langs, $conf;
2362 
2363  // Load array of products prodids
2364  $num_prods = 0;
2365  $prodids = array();
2366  $sql = "SELECT rowid";
2367  $sql .= " FROM ".MAIN_DB_PREFIX."product";
2368  $sql .= " WHERE entity IN (".getEntity('product').")";
2369  $sql .= " AND tosell = 1";
2370  $sql .= $this->db->plimit(100);
2371 
2372  $resql = $this->db->query($sql);
2373  if ($resql) {
2374  $num_prods = $this->db->num_rows($resql);
2375  $i = 0;
2376  while ($i < $num_prods) {
2377  $i++;
2378  $row = $this->db->fetch_row($resql);
2379  $prodids[$i] = $row[0];
2380  }
2381  }
2382 
2383  // Initialise parametres
2384  $this->id = 0;
2385  $this->specimen = 1;
2386 
2387  $this->ref = 'SPECIMEN';
2388  $this->ref_customer = 'SPECIMENCUST';
2389  $this->ref_supplier = 'SPECIMENSUPP';
2390  $this->socid = 1;
2391  $this->statut = 0;
2392  $this->date_creation = (dol_now() - 3600 * 24 * 7);
2393  $this->date_contrat = dol_now();
2394  $this->commercial_signature_id = 1;
2395  $this->commercial_suivi_id = 1;
2396  $this->note_private = 'This is a comment (private)';
2397  $this->note_public = 'This is a comment (public)';
2398  $this->fk_projet = 0;
2399  // Lines
2400  $nbp = 5;
2401  $xnbp = 0;
2402  while ($xnbp < $nbp) {
2403  $line = new ContratLigne($this->db);
2404  $line->qty = 1;
2405  $line->subprice = 100;
2406  $line->price = 100;
2407  $line->tva_tx = 19.6;
2408  $line->remise_percent = 10;
2409  $line->total_ht = 90;
2410  $line->total_ttc = 107.64; // 90 * 1.196
2411  $line->total_tva = 17.64;
2412  $line->date_start = dol_now() - 500000;
2413  $line->date_start_real = dol_now() - 200000;
2414  $line->date_end = dol_now() + 500000;
2415  $line->date_end_real = dol_now() - 100000;
2416  if ($num_prods > 0) {
2417  $prodid = mt_rand(1, $num_prods);
2418  $line->fk_product = $prodids[$prodid];
2419  }
2420  $this->lines[$xnbp] = $line;
2421  $xnbp++;
2422  }
2423  }
2424 
2430  public function getLinesArray()
2431  {
2432  return $this->fetch_lines();
2433  }
2434 
2435 
2447  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2448  {
2449  global $conf, $langs;
2450 
2451  if (!dol_strlen($modele)) {
2452  $modele = ''; // No doc template/generation by default
2453 
2454  if (!empty($this->model_pdf)) {
2455  $modele = $this->model_pdf;
2456  } elseif (!empty($this->modelpdf)) { // deprecated
2457  $modele = $this->modelpdf;
2458  } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
2459  $modele = $conf->global->CONTRACT_ADDON_PDF;
2460  }
2461  }
2462 
2463  if (empty($modele)) {
2464  return 0;
2465  } else {
2466  $langs->load("contracts");
2467  $outputlangs->load("products");
2468 
2469  $modelpath = "core/modules/contract/doc/";
2470  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2471  }
2472  }
2473 
2482  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2483  {
2484  $tables = array(
2485  'contrat'
2486  );
2487 
2488  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2489  }
2490 
2499  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2500  {
2501  $tables = array(
2502  'contratdet'
2503  );
2504 
2505  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2506  }
2507 
2516  public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2517  {
2518  global $db, $langs, $conf, $hookmanager, $extrafields;
2519 
2520  dol_include_once('/projet/class/project.class.php');
2521 
2522  $error = 0;
2523 
2524  $this->fetch($this->id);
2525 
2526  // Load dest object
2527  $clonedObj = clone $this;
2528  $clonedObj->socid = $socid;
2529 
2530  $this->db->begin();
2531 
2532  $objsoc = new Societe($this->db);
2533 
2534  $objsoc->fetch($clonedObj->socid);
2535 
2536  // Clean data
2537  $clonedObj->statut = 0;
2538  // Clean extrafields
2539  if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2540  $extrafields->fetch_name_optionals_label($this->table_element);
2541  foreach ($clonedObj->array_options as $key => $option) {
2542  $shortkey = preg_replace('/options_/', '', $key);
2543  //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2544  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2545  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2546  unset($clonedObj->array_options[$key]);
2547  }
2548  }
2549  }
2550 
2551  if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
2552  $this->error = 'ErrorSetupNotComplete';
2553  dol_syslog($this->error);
2554  return -1;
2555  }
2556 
2557  // Set ref
2558  require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
2559  $obj = $conf->global->CONTRACT_ADDON;
2560  $modContract = new $obj();
2561  $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2562 
2563  // get extrafields so they will be clone
2564  foreach ($this->lines as $line) {
2565  $line->fetch_optionals($line->id);
2566  }
2567 
2568  // Create clone
2569  $clonedObj->context['createfromclone'] = 'createfromclone';
2570  $result = $clonedObj->create($user);
2571  if ($result < 0) {
2572  $error++;
2573  $this->error = $clonedObj->error;
2574  $this->errors[] = $clonedObj->error;
2575  } else {
2576  // copy external contacts if same company
2577  if ($this->socid == $clonedObj->socid) {
2578  if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2579  $error++;
2580  }
2581  }
2582  }
2583 
2584  if (!$error) {
2585  foreach ($this->lines as $line) {
2586  $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);
2587  if ($result < 0) {
2588  $error++;
2589  $this->error = $clonedObj->error;
2590  $this->errors[] = $clonedObj->error;
2591  }
2592  }
2593  }
2594 
2595  if (!$error) {
2596  // Hook of thirdparty module
2597  if (is_object($hookmanager)) {
2598  $parameters = array(
2599  'objFrom' => $this,
2600  'clonedObj' => $clonedObj
2601  );
2602  $action = '';
2603  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2604  if ($reshook < 0) {
2605  $error++;
2606  }
2607  }
2608  }
2609 
2610  unset($clonedObj->context['createfromclone']);
2611 
2612  // End
2613  if (!$error) {
2614  $this->db->commit();
2615  return $clonedObj->id;
2616  } else {
2617  $this->db->rollback();
2618  return -1;
2619  }
2620  }
2621 
2622 
2632  public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2633  {
2634  global $langs, $user;
2635 
2636  $langs->load("agenda");
2637 
2638  $now = dol_now();
2639 
2640  $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2641 
2642  $error = 0;
2643  $this->output = '';
2644  $this->error='';
2645 
2646  $contractlineprocessed = array();
2647  $contractignored = array();
2648  $contracterror = array();
2649 
2650  dol_syslog(__METHOD__, LOG_DEBUG);
2651 
2652  $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2653  $sql.= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2654  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2655  $sql.= ' WHERE cd.fk_contrat = c.rowid';
2656  $sql.= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2657  $sql.= " AND cd.statut = 4";
2658  if ($thirdparty_id > 0) $sql.=" AND c.fk_soc = ".((int) $thirdparty_id);
2659  //print $sql;
2660 
2661  $resql = $this->db->query($sql);
2662  if ($resql) {
2663  $num = $this->db->num_rows($resql);
2664 
2665  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2666 
2667  $i=0;
2668  while ($i < $num) {
2669  $obj = $this->db->fetch_object($resql);
2670  if ($obj) {
2671  if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2672  continue;
2673  }
2674 
2675  // Load contract
2676  $object = new Contrat($this->db);
2677  $object->fetch($obj->rowid); // fetch also lines
2678  $object->fetch_thirdparty();
2679 
2680  if ($object->id <= 0) {
2681  $error++;
2682  $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2683  continue;
2684  }
2685 
2686  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);
2687 
2688  // Update expiration date of line
2689  $expirationdate = $this->db->jdate($obj->date_fin_validite);
2690  $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2691  $duration_unit = preg_replace('/\d/', '', $obj->duration);
2692  //var_dump($expirationdate.' '.$enddatetoscan);
2693 
2694  // Test if there is pending invoice
2695  $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2696 
2697  if (is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2698  usort($object->linkedObjects['facture'], "cmp");
2699 
2700  //dol_sort_array($contract->linkedObjects['facture'], 'date');
2701  $someinvoicenotpaid=0;
2702  foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2703  if ($invoice->statut == Facture::STATUS_DRAFT) continue; // Draft invoice are not invoice not paid
2704 
2705  if (empty($invoice->paye)) {
2706  $someinvoicenotpaid++;
2707  }
2708  }
2709  if ($someinvoicenotpaid) {
2710  $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2711  $contractignored[$object->id]=$object->ref;
2712  continue;
2713  }
2714  }
2715 
2716  if ($expirationdate && $expirationdate < $enddatetoscan) {
2717  dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2718  $newdate = $expirationdate;
2719  $protecti=0; //$protecti is to avoid infinite loop
2720  while ($newdate < $enddatetoscan && $protecti < 1000) {
2721  $newdate = dol_time_plus_duree($newdate, $duration_value, $duration_unit);
2722  $protecti++;
2723  }
2724 
2725  if ($protecti < 1000) { // If not, there is a pb
2726  // We will update the end of date of contrat, so first we refresh contract data
2727  dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2728 
2729  $this->db->begin();
2730 
2731  $errorforlocaltransaction = 0;
2732 
2733  $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2734  $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2735 
2736  $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2737  $sqlupdate.= ' WHERE rowid = '.((int) $obj->lid);
2738  $resqlupdate = $this->db->query($sqlupdate);
2739  if ($resqlupdate) {
2740  $contractlineprocessed[$obj->lid]=$object->ref;
2741 
2742  $actioncode = 'RENEW_CONTRACT';
2743  $now = dol_now();
2744 
2745  // Create an event
2746  $actioncomm = new ActionComm($this->db);
2747  $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2748  $actioncomm->code = 'AC_'.$actioncode;
2749  $actioncomm->label = $label;
2750  $actioncomm->datep = $now;
2751  $actioncomm->datef = $now;
2752  $actioncomm->percentage = -1; // Not applicable
2753  $actioncomm->socid = $object->thirdparty->id;
2754  $actioncomm->authorid = $user->id; // User saving action
2755  $actioncomm->userownerid = $user->id; // Owner of action
2756  $actioncomm->fk_element = $object->id;
2757  $actioncomm->elementtype = 'contract';
2758  $actioncomm->note_private = $comment;
2759 
2760  $ret = $actioncomm->create($user); // User creating action
2761  } else {
2762  $contracterror[$object->id]=$object->ref;
2763 
2764  $error++;
2765  $errorforlocaltransaction++;
2766  $this->error = $this->db->lasterror();
2767  }
2768 
2769  if (! $errorforlocaltransaction) {
2770  $this->db->commit();
2771  } else {
2772  $this->db->rollback();
2773  }
2774  } else {
2775  $error++;
2776  $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2777  dol_syslog($this->error, LOG_ERR);
2778  }
2779  }
2780  }
2781  $i++;
2782  }
2783  } else {
2784  $error++;
2785  $this->error = $this->db->lasterror();
2786  }
2787 
2788  $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed)>0 ? ' : '.join(',', $contractlineprocessed) : '');
2789 
2790  return ($error ? 1: 0);
2791  }
2792 }
2793 
2794 
2799 {
2803  public $element = 'contratdet';
2804 
2808  public $table_element = 'contratdet';
2809 
2814  public $element_for_permission = 'contrat';
2815 
2819  public $id;
2820 
2824  public $ref;
2825 
2826  public $tms;
2827 
2831  public $fk_contrat;
2832 
2836  public $fk_product;
2837 
2838  public $statut; // 0 inactive, 4 active, 5 closed
2839  public $type; // 0 for product, 1 for service
2840 
2845  public $label;
2846 
2851  public $libelle;
2852 
2856  public $description;
2857 
2858  public $product_type; // 0 for product, 1 for service
2859  public $product_ref;
2860  public $product_label;
2861 
2862  public $date_commande;
2863 
2864  public $date_start; // date start planned
2865  public $date_start_real; // date start real
2866  public $date_end; // date end planned
2867  public $date_end_real; // date end real
2868 
2869  public $tva_tx;
2870  public $vat_src_code;
2871  public $localtax1_tx;
2872  public $localtax2_tx;
2873  public $localtax1_type; // Local tax 1 type
2874  public $localtax2_type; // Local tax 2 type
2875  public $qty;
2876  public $remise_percent;
2877  public $remise;
2878 
2882  public $fk_remise_except;
2883 
2884  public $subprice; // Unit price HT
2885 
2891  public $price;
2892 
2893  public $price_ht;
2894 
2895  public $total_ht;
2896  public $total_tva;
2897  public $total_localtax1;
2898  public $total_localtax2;
2899  public $total_ttc;
2900 
2904  public $fk_fournprice;
2905 
2906  public $pa_ht;
2907 
2908  public $info_bits;
2909 
2913  public $fk_user_author;
2914 
2918  public $fk_user_ouverture;
2919 
2923  public $fk_user_cloture;
2924 
2925  public $commentaire;
2926 
2927 
2931  public $rang = 0;
2932 
2933 
2934  const STATUS_INITIAL = 0;
2935  const STATUS_OPEN = 4;
2936  const STATUS_CLOSED = 5;
2937 
2938 
2939  // BEGIN MODULEBUILDER PROPERTIES
2943  public $fields = array(
2944  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
2945  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
2946  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
2947  'qty' =>array('type'=>'integer', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35, 'isameasure'=>1),
2948  'total_ht' =>array('type'=>'integer', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>36, 'isameasure'=>1),
2949  'total_tva' =>array('type'=>'integer', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>37, 'isameasure'=>1),
2950  'total_ttc' =>array('type'=>'integer', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>38, 'isameasure'=>1),
2951  //'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
2952  //'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
2953  'fk_contrat' =>array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'Contract', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
2954  'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
2955  //'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
2956  'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
2957  'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
2958  //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
2959  //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
2960  //'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
2961  'fk_user_ouverture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserStartingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
2962  'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
2963  'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 4=>'Open', 5=>'Closed')),
2964  'rang' =>array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'position'=>500, 'default' =>0)
2965  );
2966  // END MODULEBUILDER PROPERTIES
2967 
2968 
2974  public function __construct($db)
2975  {
2976  $this->db = $db;
2977  }
2978 
2979 
2986  public function getLibStatut($mode)
2987  {
2988  return $this->LibStatut($this->statut, $mode, ((!empty($this->date_end)) ? ($this->date_end < dol_now() ? 1 : 0) : -1));
2989  }
2990 
2991  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3001  public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
3002  {
3003  // phpcs:enable
3004  global $langs;
3005  $langs->load("contracts");
3006 
3007  if ($status == self::STATUS_INITIAL) {
3008  $labelStatus = $langs->transnoentities("ServiceStatusInitial");
3009  $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
3010  } elseif ($status == self::STATUS_OPEN && $expired == -1) {
3011  $labelStatus = $langs->transnoentities("ServiceStatusRunning");
3012  $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
3013  } elseif ($status == self::STATUS_OPEN && $expired == 0) {
3014  $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
3015  $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
3016  } elseif ($status == self::STATUS_OPEN && $expired == 1) {
3017  $labelStatus = $langs->transnoentities("ServiceStatusLate");
3018  $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
3019  } elseif ($status == self::STATUS_CLOSED) {
3020  $labelStatus = $langs->transnoentities("ServiceStatusClosed");
3021  $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
3022  }
3023 
3024  $statusType = 'status'.$status;
3025  if ($status == self::STATUS_OPEN && $expired == 1) {
3026  $statusType = 'status1';
3027  }
3028  if ($status == self::STATUS_CLOSED) {
3029  $statusType = 'status6';
3030  }
3031 
3032  $params = array(); $reg = array();
3033  if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
3034  $params = array('badgeParams'=>array('css' => $reg[1]));
3035  }
3036  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
3037  }
3038 
3046  public function getNomUrl($withpicto = 0, $maxlength = 0)
3047  {
3048  global $langs;
3049 
3050  $result = '';
3051  $label = $langs->trans("ShowContractOfService").': '.$this->label;
3052  if (empty($label)) {
3053  $label = $this->description;
3054  }
3055 
3056  $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
3057  $linkend = '</a>';
3058 
3059  $picto = 'service';
3060  if ($this->type == 0) {
3061  $picto = 'product';
3062  }
3063 
3064  if ($withpicto) {
3065  $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
3066  }
3067  if ($withpicto && $withpicto != 2) {
3068  $result .= ' ';
3069  }
3070  if ($withpicto != 2) {
3071  $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
3072  }
3073  return $result;
3074  }
3075 
3083  public function fetch($id, $ref = '')
3084  {
3085  // Check parameters
3086  if (empty($id) && empty($ref)) {
3087  return -1;
3088  }
3089 
3090  $sql = "SELECT";
3091  $sql .= " t.rowid,";
3092  $sql .= " t.tms,";
3093  $sql .= " t.fk_contrat,";
3094  $sql .= " t.fk_product,";
3095  $sql .= " t.statut,";
3096  $sql .= " t.label,"; // This field is not used. Only label of product
3097  $sql .= " p.ref as product_ref,";
3098  $sql .= " p.label as product_label,";
3099  $sql .= " p.description as product_desc,";
3100  $sql .= " p.fk_product_type as product_type,";
3101  $sql .= " t.description,";
3102  $sql .= " t.date_commande,";
3103  $sql .= " t.date_ouverture_prevue as date_start,";
3104  $sql .= " t.date_ouverture as date_start_real,";
3105  $sql .= " t.date_fin_validite as date_end,";
3106  $sql .= " t.date_cloture as date_end_real,";
3107  $sql .= " t.tva_tx,";
3108  $sql .= " t.vat_src_code,";
3109  $sql .= " t.localtax1_tx,";
3110  $sql .= " t.localtax2_tx,";
3111  $sql .= " t.localtax1_type,";
3112  $sql .= " t.localtax2_type,";
3113  $sql .= " t.qty,";
3114  $sql .= " t.remise_percent,";
3115  $sql .= " t.remise,";
3116  $sql .= " t.fk_remise_except,";
3117  $sql .= " t.subprice,";
3118  $sql .= " t.price_ht,";
3119  $sql .= " t.total_ht,";
3120  $sql .= " t.total_tva,";
3121  $sql .= " t.total_localtax1,";
3122  $sql .= " t.total_localtax2,";
3123  $sql .= " t.total_ttc,";
3124  $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
3125  $sql .= " t.buy_price_ht as pa_ht,";
3126  $sql .= " t.info_bits,";
3127  $sql .= " t.fk_user_author,";
3128  $sql .= " t.fk_user_ouverture,";
3129  $sql .= " t.fk_user_cloture,";
3130  $sql .= " t.commentaire,";
3131  $sql .= " t.fk_unit,";
3132  $sql .= " t.rang";
3133  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
3134  if ($id) {
3135  $sql .= " WHERE t.rowid = ".((int) $id);
3136  }
3137  if ($ref) {
3138  $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
3139  }
3140 
3141  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
3142  $resql = $this->db->query($sql);
3143  if ($resql) {
3144  if ($this->db->num_rows($resql)) {
3145  $obj = $this->db->fetch_object($resql);
3146 
3147  $this->id = $obj->rowid;
3148  $this->ref = $obj->rowid;
3149 
3150  $this->tms = $this->db->jdate($obj->tms);
3151  $this->fk_contrat = $obj->fk_contrat;
3152  $this->fk_product = $obj->fk_product;
3153  $this->statut = $obj->statut;
3154  $this->product_ref = $obj->product_ref;
3155  $this->product_label = $obj->product_label;
3156  $this->product_description = $obj->product_description;
3157  $this->product_type = $obj->product_type;
3158  $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
3159  $this->description = $obj->description;
3160  $this->date_commande = $this->db->jdate($obj->date_commande);
3161 
3162  $this->date_start = $this->db->jdate($obj->date_start);
3163  $this->date_start_real = $this->db->jdate($obj->date_start_real);
3164  $this->date_end = $this->db->jdate($obj->date_end);
3165  $this->date_end_real = $this->db->jdate($obj->date_end_real);
3166  // For backward compatibility
3167  //$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
3168  //$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
3169  //$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
3170  //$this->date_cloture = $this->db->jdate($obj->date_cloture);
3171 
3172  $this->tva_tx = $obj->tva_tx;
3173  $this->vat_src_code = $obj->vat_src_code;
3174  $this->localtax1_tx = $obj->localtax1_tx;
3175  $this->localtax2_tx = $obj->localtax2_tx;
3176  $this->localtax1_type = $obj->localtax1_type;
3177  $this->localtax2_type = $obj->localtax2_type;
3178  $this->qty = $obj->qty;
3179  $this->remise_percent = $obj->remise_percent;
3180  $this->fk_remise_except = $obj->fk_remise_except;
3181  $this->subprice = $obj->subprice;
3182  $this->price_ht = $obj->price_ht;
3183  $this->total_ht = $obj->total_ht;
3184  $this->total_tva = $obj->total_tva;
3185  $this->total_localtax1 = $obj->total_localtax1;
3186  $this->total_localtax2 = $obj->total_localtax2;
3187  $this->total_ttc = $obj->total_ttc;
3188  $this->info_bits = $obj->info_bits;
3189  $this->fk_user_author = $obj->fk_user_author;
3190  $this->fk_user_ouverture = $obj->fk_user_ouverture;
3191  $this->fk_user_cloture = $obj->fk_user_cloture;
3192  $this->commentaire = $obj->commentaire;
3193  $this->fk_fournprice = $obj->fk_fournprice;
3194 
3195  $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
3196  $this->pa_ht = $marginInfos[0];
3197  $this->fk_unit = $obj->fk_unit;
3198 
3199  $this->rang = $obj->rang;
3200 
3201  $this->fetch_optionals();
3202  }
3203 
3204  $this->db->free($resql);
3205 
3206  return 1;
3207  } else {
3208  $this->error = "Error ".$this->db->lasterror();
3209  return -1;
3210  }
3211  }
3212 
3213 
3221  public function update($user, $notrigger = 0)
3222  {
3223  global $conf, $langs, $mysoc;
3224 
3225  $error = 0;
3226 
3227  // Clean parameters
3228  $this->fk_contrat = (int) $this->fk_contrat;
3229  $this->fk_product = (int) $this->fk_product;
3230  $this->statut = (int) $this->statut;
3231  $this->label = trim($this->label);
3232  $this->description = trim($this->description);
3233  $this->vat_src_code = trim($this->vat_src_code);
3234  $this->tva_tx = trim($this->tva_tx);
3235  $this->localtax1_tx = trim($this->localtax1_tx);
3236  $this->localtax2_tx = trim($this->localtax2_tx);
3237  $this->qty = trim($this->qty);
3238  $this->remise_percent = trim($this->remise_percent);
3239  $this->fk_remise_except = (int) $this->fk_remise_except;
3240  $this->subprice = price2num($this->subprice);
3241  $this->price_ht = price2num($this->price_ht);
3242  $this->total_ht = trim($this->total_ht);
3243  $this->total_tva = trim($this->total_tva);
3244  $this->total_localtax1 = trim($this->total_localtax1);
3245  $this->total_localtax2 = trim($this->total_localtax2);
3246  $this->total_ttc = trim($this->total_ttc);
3247  $this->info_bits = trim($this->info_bits);
3248  $this->fk_user_author = (int) $this->fk_user_author;
3249  $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
3250  $this->fk_user_cloture = (int) $this->fk_user_cloture;
3251  $this->commentaire = trim($this->commentaire);
3252  $this->rang = (int) $this->rang;
3253  //if (empty($this->subprice)) $this->subprice = 0;
3254  if (empty($this->price_ht)) {
3255  $this->price_ht = 0;
3256  }
3257  if (empty($this->total_ht)) {
3258  $this->total_ht = 0;
3259  }
3260  if (empty($this->total_tva)) {
3261  $this->total_tva = 0;
3262  }
3263  if (empty($this->total_ttc)) {
3264  $this->total_ttc = 0;
3265  }
3266  if (empty($this->localtax1_tx)) {
3267  $this->localtax1_tx = 0;
3268  }
3269  if (empty($this->localtax2_tx)) {
3270  $this->localtax2_tx = 0;
3271  }
3272  if (empty($this->remise_percent)) {
3273  $this->remise_percent = 0;
3274  }
3275  // For backward compatibility
3276  if (empty($this->date_start)) {
3277  $this->date_start = $this->date_start;
3278  }
3279  if (empty($this->date_start_real)) {
3280  $this->date_start_real = $this->date_start_real;
3281  }
3282  if (empty($this->date_end)) {
3283  $this->date_end = $this->date_end;
3284  }
3285  if (empty($this->date_end_real)) {
3286  $this->date_end_real = $this->date_end_real;
3287  }
3288 
3289  // Calcul du total TTC et de la TVA pour la ligne a partir de
3290  // qty, pu, remise_percent et txtva
3291  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3292  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3293  $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->thirdparty, $mysoc);
3294 
3295  $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);
3296  $this->total_ht = $tabprice[0];
3297  $this->total_tva = $tabprice[1];
3298  $this->total_ttc = $tabprice[2];
3299  $this->total_localtax1 = $tabprice[9];
3300  $this->total_localtax2 = $tabprice[10];
3301 
3302  if (empty($this->pa_ht)) {
3303  $this->pa_ht = 0;
3304  }
3305 
3306  // if buy price not defined, define buyprice as configured in margin admin
3307  if ($this->pa_ht == 0) {
3308  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
3309  return $result;
3310  } else {
3311  $this->pa_ht = $result;
3312  }
3313  }
3314 
3315  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
3316  if (empty($this->oldcopy)) {
3317  $this->oldcopy = dol_clone($this);
3318  }
3319 
3320  $this->db->begin();
3321 
3322  // Update request
3323  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3324  $sql .= " fk_contrat = ".((int) $this->fk_contrat).",";
3325  $sql .= " fk_product = ".($this->fk_product ? ((int) $this->fk_product) : 'null').",";
3326  $sql .= " statut = ".((int) $this->statut).",";
3327  $sql .= " label = '".$this->db->escape($this->label)."',";
3328  $sql .= " description = '".$this->db->escape($this->description)."',";
3329  $sql .= " date_commande = ".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
3330  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3331  $sql .= " date_ouverture = ".($this->date_start_real != '' ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3332  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3333  $sql .= " date_cloture = ".($this->date_end_real != '' ? "'".$this->db->idate($this->date_end_real)."'" : "null").",";
3334  $sql .= " vat_src_code = '".$this->db->escape($this->vat_src_code)."',";
3335  $sql .= " tva_tx = ".price2num($this->tva_tx).",";
3336  $sql .= " localtax1_tx = ".price2num($this->localtax1_tx).",";
3337  $sql .= " localtax2_tx = ".price2num($this->localtax2_tx).",";
3338  $sql .= " qty = ".price2num($this->qty).",";
3339  $sql .= " remise_percent = ".price2num($this->remise_percent).",";
3340  $sql .= " remise = ".($this->remise ?price2num($this->remise) : "null").",";
3341  $sql .= " fk_remise_except = ".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
3342  $sql .= " subprice = ".($this->subprice != '' ? $this->subprice : "null").",";
3343  $sql .= " price_ht = ".($this->price_ht != '' ? $this->price_ht : "null").",";
3344  $sql .= " total_ht = ".$this->total_ht.",";
3345  $sql .= " total_tva = ".$this->total_tva.",";
3346  $sql .= " total_localtax1 = ".$this->total_localtax1.",";
3347  $sql .= " total_localtax2 = ".$this->total_localtax2.",";
3348  $sql .= " total_ttc = ".$this->total_ttc.",";
3349  $sql .= " fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
3350  $sql .= " buy_price_ht = '".price2num($this->pa_ht)."',";
3351  $sql .= " info_bits = '".$this->db->escape($this->info_bits)."',";
3352  $sql .= " fk_user_author = ".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
3353  $sql .= " fk_user_ouverture = ".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
3354  $sql .= " fk_user_cloture = ".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3355  $sql .= " commentaire = '".$this->db->escape($this->commentaire)."',";
3356  $sql .= " fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit).",";
3357  $sql .= " rang = ".(empty($this->rang) ? '0' : (int) $this->rang);
3358  $sql .= " WHERE rowid = ".((int) $this->id);
3359 
3360  dol_syslog(get_class($this)."::update", LOG_DEBUG);
3361  $resql = $this->db->query($sql);
3362  if (!$resql) {
3363  $this->error = "Error ".$this->db->lasterror();
3364  $error++;
3365  }
3366 
3367  if (!$error) { // For avoid conflicts if trigger used
3368  $result = $this->insertExtraFields();
3369  if ($result < 0) {
3370  $error++;
3371  }
3372  }
3373 
3374  // If we change a planned date (start or end) of one contract line, sync dates for all other services too
3375  if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) {
3376  dol_syslog(get_class($this)."::update CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES is on so we update date for all lines", LOG_DEBUG);
3377 
3378  if ($this->date_start != $this->oldcopy->date_start) {
3379  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3380  $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
3381  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3382 
3383  $resql = $this->db->query($sql);
3384  if (!$resql) {
3385  $error++;
3386  $this->error = "Error ".$this->db->lasterror();
3387  }
3388  }
3389  if ($this->date_end != $this->oldcopy->date_end) {
3390  $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3391  $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
3392  $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3393 
3394  $resql = $this->db->query($sql);
3395  if (!$resql) {
3396  $error++;
3397  $this->error = "Error ".$this->db->lasterror();
3398  }
3399  }
3400  }
3401 
3402  if (!$error && !$notrigger) {
3403  // Call trigger
3404  $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
3405  if ($result < 0) {
3406  $error++;
3407  $this->db->rollback();
3408  }
3409  // End call triggers
3410  }
3411 
3412  if (!$error) {
3413  $this->db->commit();
3414  return 1;
3415  } else {
3416  $this->db->rollback();
3417  $this->errors[] = $this->error;
3418  return -1;
3419  }
3420  }
3421 
3422 
3423  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3430  public function update_total()
3431  {
3432  // phpcs:enable
3433  $this->db->begin();
3434 
3435  // Mise a jour ligne en base
3436  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3437  $sql .= " total_ht=".price2num($this->total_ht, 'MT');
3438  $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
3439  $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT');
3440  $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT');
3441  $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
3442  $sql .= " WHERE rowid = ".((int) $this->id);
3443 
3444  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3445 
3446  $resql = $this->db->query($sql);
3447  if ($resql) {
3448  $this->db->commit();
3449  return 1;
3450  } else {
3451  $this->error = $this->db->error();
3452  $this->db->rollback();
3453  return -2;
3454  }
3455  }
3456 
3457 
3464  public function insert($notrigger = 0)
3465  {
3466  global $conf, $user;
3467 
3468  $error = 0;
3469 
3470  // Insertion dans la base
3471  $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3472  $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3473  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3474  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3475  $sql .= " info_bits,";
3476  $sql .= " rang,";
3477  $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3478  if ($this->date_start > 0) {
3479  $sql .= ",date_ouverture_prevue";
3480  }
3481  if ($this->date_end > 0) {
3482  $sql .= ",date_fin_validite";
3483  }
3484  $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3485  $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3486  $sql .= " '".$this->db->escape($this->qty)."',";
3487  $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3488  $sql .= " '".$this->db->escape($this->tva_tx)."',";
3489  $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3490  $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3491  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3492  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3493  $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3494  $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3495  $sql .= " '".$this->db->escape($this->info_bits)."',";
3496  $sql .= " ".(empty($this->rang) ? '0' : (int) $this->rang).",";
3497  $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3498  if ($this->fk_fournprice > 0) {
3499  $sql .= ' '.((int) $this->fk_fournprice).',';
3500  } else {
3501  $sql .= ' null,';
3502  }
3503  if ($this->pa_ht > 0) {
3504  $sql .= ' '.((float) price2num($this->pa_ht));
3505  } else {
3506  $sql .= ' null';
3507  }
3508  if ($this->date_start > 0) {
3509  $sql .= ",'".$this->db->idate($this->date_start)."'";
3510  }
3511  if ($this->date_end > 0) {
3512  $sql .= ",'".$this->db->idate($this->date_end)."'";
3513  }
3514  $sql .= ")";
3515 
3516  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3517 
3518  $resql = $this->db->query($sql);
3519  if ($resql) {
3520  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3521 
3522  // Insert of extrafields
3523  if (!$error) {
3524  $result = $this->insertExtraFields();
3525  if ($result < 0) {
3526  $this->db->rollback();
3527  return -1;
3528  }
3529  }
3530 
3531  if (!$notrigger) {
3532  // Call trigger
3533  $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3534  if ($result < 0) {
3535  $this->db->rollback();
3536  return -1;
3537  }
3538  // End call triggers
3539  }
3540 
3541  $this->db->commit();
3542  return 1;
3543  } else {
3544  $this->db->rollback();
3545  $this->error = $this->db->error()." sql=".$sql;
3546  return -1;
3547  }
3548  }
3549 
3550  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3560  public function active_line($user, $date, $date_end = '', $comment = '')
3561  {
3562  // phpcs:enable
3563  global $langs, $conf;
3564 
3565  $error = 0;
3566 
3567  $this->db->begin();
3568 
3569  $this->statut = ContratLigne::STATUS_OPEN;
3570  $this->date_start = $date;
3571  $this->date_end = $date_end;
3572  $this->fk_user_ouverture = $user->id;
3573  $this->date_end_real = null;
3574  $this->commentaire = $comment;
3575 
3576  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".$this->statut.",";
3577  $sql .= " date_ouverture = ".(dol_strlen($this->date_start_real) != 0 ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3578  if ($date_end >= 0) {
3579  $sql .= " date_fin_validite = ".(dol_strlen($this->date_end) != 0 ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3580  }
3581  $sql .= " fk_user_ouverture = ".((int) $this->fk_user_ouverture).",";
3582  $sql .= " date_cloture = null,";
3583  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3584  $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3585 
3586  dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3587  $resql = $this->db->query($sql);
3588  if ($resql) {
3589  // Call trigger
3590  $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3591  if ($result < 0) {
3592  $error++;
3593  }
3594  // End call triggers
3595 
3596  if (!$error) {
3597  $this->db->commit();
3598  return 1;
3599  } else {
3600  $this->db->rollback();
3601  return -1;
3602  }
3603  } else {
3604  $this->error = $this->db->lasterror();
3605  $this->db->rollback();
3606  return -1;
3607  }
3608  }
3609 
3610  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3620  public function close_line($user, $date_end_real, $comment = '', $notrigger = 0)
3621  {
3622  // phpcs:enable
3623  global $langs, $conf;
3624 
3625  // Update object
3626  $this->date_cloture = $date_end_real;
3627  $this->date_end_real = $date_end_real;
3628  $this->fk_user_cloture = $user->id;
3629  $this->commentaire = $comment;
3630 
3631  $error = 0;
3632 
3633  // statut actif : 4
3634 
3635  $this->db->begin();
3636 
3637  $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
3638  $sql .= " date_cloture = '".$this->db->idate($date_end_real)."',";
3639  $sql .= " fk_user_cloture = ".((int) $user->id).",";
3640  $sql .= " commentaire = '".$this->db->escape($comment)."'";
3641  $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
3642 
3643  $resql = $this->db->query($sql);
3644  if ($resql) {
3645  if (!$notrigger) {
3646  // Call trigger
3647  $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3648  if ($result < 0) {
3649  $error++;
3650  $this->db->rollback();
3651  return -1;
3652  }
3653  // End call triggers
3654  }
3655 
3656  $this->db->commit();
3657  return 1;
3658  } else {
3659  $this->error = $this->db->lasterror();
3660  $this->db->rollback();
3661  return -1;
3662  }
3663  }
3664 }
$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.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
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.
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.
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.
active_line($user, $line_id, $date, $date_end='', $comment='')
Activate a contract line.
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.
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)
Renvoi 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.
getNomUrl($withpicto=0, $maxlength=0)
Return clicable name (with picto eventually)
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:45
if(isModEnabled('facture') &&!empty($user->rights->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') &&!empty($user->rights->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)) $resql
Social contributions to pay.
Definition: index.php:745
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
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:1401
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:61
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
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:119
$conf db
API class for accounts.
Definition: inc.php:41