dolibarr 23.0.4
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-2026 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
15 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 3 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <https://www.gnu.org/licenses/>.
29 */
30
37require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
38require_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonsignedobject.class.php';
42
49class Contrat extends CommonObject
50{
51 use CommonSignedObject;
52
56 public $element = 'contrat';
57
61 public $table_element = 'contrat';
62
66 public $table_element_line = 'contratdet';
67
71 public $fk_element = 'fk_contrat';
72
76 public $picto = 'contract';
77
82 public $restrictiononfksoc = 1;
83
87 protected $table_ref_field = 'ref';
88
93 public $ref_customer;
94
98 public $from;
99
104 public $ref_supplier;
105
110 public $socid;
111
117 public $fk_soc;
118
122 public $societe;
123
129 public $statut = 0;
130
135 public $status = 0;
136
140 public $product;
141
145 public $fk_user_author;
146
152 public $user_author_id;
153
154
159 public $user_creation;
160
164 public $user_cloture;
165
169 public $date_contrat;
170
174 public $commercial_signature_id;
175
180 public $fk_commercial_signature;
181
185 public $commercial_suivi_id;
186
192 public $fk_commercial_suivi;
193
197 public $extraparams = array();
198
202 public $lines = array();
203
207 public $nbofservices;
211 public $nbofserviceswait;
215 public $nbofservicesopened;
219 public $nbofservicesexpired;
223 public $nbofservicesclosed;
224 //public $lower_planned_end_date;
225 //public $higher_planner_end_date;
226
231 protected $lines_id_index_mapper = array();
232
233
258 // BEGIN MODULEBUILDER PROPERTIES
262 public $fields = array(
263 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
264 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'showoncombobox' => 1, 'position' => 15, 'searchall' => 1),
265 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 20),
266 'ref_customer' => array('type' => 'varchar(50)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 25, 'searchall' => 1),
267 'ref_supplier' => array('type' => 'varchar(50)', 'label' => 'RefSupplier', 'enabled' => 1, 'visible' => -1, 'position' => 26, 'searchall' => 1),
268 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 30, 'index' => 1),
269 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 35),
270 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 40),
271 'date_contrat' => array('type' => 'datetime', 'label' => 'Date contrat', 'enabled' => 1, 'visible' => -1, 'position' => 45),
272 'signed_status' => array('type' => 'smallint(6)', 'label' => 'SignedStatus', 'enabled' => 1, 'visible' => -1, 'position' => 50, 'arrayofkeyval' => array(0 => 'NoSignature', 1 => 'SignedSender', 2 => 'SignedReceiver', 3 => 'SignedReceiverOnline', 9 => 'SignedAll')),
273 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 70),
274 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 75),
275 'fk_commercial_signature' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative Signature', 'enabled' => 1, 'visible' => -1, 'position' => 80),
276 'fk_commercial_suivi' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative follower', 'enabled' => 1, 'visible' => -1, 'position' => 85),
277 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 90),
278 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 105, 'searchall' => 1),
279 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 110, 'searchall' => 1),
280 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 115),
281 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 120),
282 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 125),
283 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 135),
284 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'Last main doc', 'enabled' => 1, 'visible' => -1, 'position' => 140),
285 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => -1, 'position' => 500, 'notnull' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 2 => 'Closed'))
286 );
287 // END MODULEBUILDER PROPERTIES
288
289 const STATUS_DRAFT = 0;
290 const STATUS_VALIDATED = 1;
291 const STATUS_CLOSED = 2;
292
298 public function __construct($db)
299 {
300 $this->db = $db;
301
302 $this->ismultientitymanaged = 1;
303 $this->isextrafieldmanaged = 1;
304 }
305
312 public function getNextNumRef($soc)
313 {
314 global $db, $langs, $conf;
315 $langs->load("contracts");
316
317 if (getDolGlobalString('CONTRACT_ADDON')) {
318 $mybool = false;
319
320 $file = getDolGlobalString('CONTRACT_ADDON') . ".php";
321 $classname = getDolGlobalString('CONTRACT_ADDON');
322
323 // Include file with class
324 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
325
326 foreach ($dirmodels as $reldir) {
327 $dir = dol_buildpath($reldir."core/modules/contract/");
328
329 // Load file with numbering class (if found)
330 $mybool = ((bool) @include_once $dir.$file) || $mybool;
331 }
332
333 if (!$mybool) {
334 dol_print_error(null, "Failed to include file ".$file);
335 return '';
336 }
337
338 $obj = new $classname();
339 '@phan-var-force ModelNumRefContracts $obj';
341 $numref = $obj->getNextValue($soc, $this);
342
343 if ($numref != "") {
344 return $numref;
345 } else {
346 $this->error = $obj->error;
347 dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
348 return "";
349 }
350 } else {
351 $langs->load("errors");
352 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
353 return "";
354 }
355 }
356
357 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
368 public function active_line($user, $line_id, $date_start, $date_end = '', $comment = '')
369 {
370 // phpcs:enable
371 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
372 if ($result < 0) {
373 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
374 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
375 }
376 return $result;
377 }
378
379
380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
390 public function close_line($user, $line_id, $date_end, $comment = '')
391 {
392 // phpcs:enable
393 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
394 if ($result < 0) {
395 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
396 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
397 }
398 return $result;
399 }
400
401
413 public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
414 {
415 if (empty($date_start)) {
416 $date_start = dol_now();
417 }
418
419 $this->db->begin();
420
421 $error = 0;
422
423 // Load lines
424 $this->fetch_lines();
425
426 foreach ($this->lines as $contratline) {
427 // Open lines not already open
428 if ($contratline->statut != ContratLigne::STATUS_OPEN) {
429 $contratline->context = $this->context;
430
431 $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
432 if ($result < 0) {
433 $error++;
434 $this->setErrorsFromObject($contratline);
435 break;
436 }
437 }
438 }
439
440 if (!$error && $this->statut == 0) {
441 $result = $this->validate($user, '', $notrigger);
442 if ($result < 0) {
443 $error++;
444 }
445 }
446
447 if (!$error) {
448 $this->db->commit();
449 return 1;
450 } else {
451 $this->db->rollback();
452 return -1;
453 }
454 }
455
466 public function closeAll(User $user, $notrigger = 0, $comment = '', $nofetchlines = 0)
467 {
468 dol_syslog("closeAll begin", LOG_DEBUG, 1);
469
470 $this->db->begin();
471
472 // Load lines
473 if (empty($nofetchlines)) {
474 $this->fetch_lines();
475 }
476
477 $now = dol_now();
478
479 $error = 0;
480
481 foreach ($this->lines as $contratline) {
482 // Close lines not already closed
483 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
484 $contratline->date_end_real = $now;
485 $contratline->date_cloture = $now; // For backward compatibility
486 $contratline->user_closing_id = $user->id;
487 $contratline->statut = ContratLigne::STATUS_CLOSED;
488
489 $result = $contratline->close_line($user, $now, $comment, $notrigger);
490
491 if ($result < 0) {
492 $error++;
493 $this->error = $contratline->error.($contratline->error ? ' ('.$this->ref.')' : '');
494 $this->errors = $contratline->errors;
495 break;
496 }
497 }
498 }
499
500 if (!$error && $this->status == 0) {
501 $result = $this->validate($user, '', $notrigger);
502 if ($result < 0) {
503 $error++;
504 }
505 }
506
507 if (!$error) {
508 $this->db->commit();
509
510 dol_syslog("closeAll end", LOG_DEBUG, -1);
511
512 return 1;
513 } else {
514 $this->db->rollback();
515
516 dol_syslog("closeAll end", LOG_DEBUG, -1);
517
518 return -1;
519 }
520 }
521
530 public function validate(User $user, $force_number = '', $notrigger = 0)
531 {
532 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
533 global $conf;
534
535 $now = dol_now();
536
537 $error = 0;
538 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
539
540
541 $this->db->begin();
542
543 $this->fetch_thirdparty();
544
545 // A contract is validated so we can move thirdparty to status customer
546 if (!getDolGlobalString('CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
547 $result = $this->thirdparty->setAsCustomer();
548 }
549
550 // Define new ref
551 if ($force_number) {
552 $num = $force_number;
553 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
554 $num = $this->getNextNumRef($this->thirdparty);
555 } else {
556 $num = (string) $this->ref;
557 }
558 $this->newref = dol_sanitizeFileName($num);
559
560 if ($num) {
561 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
562 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
563
564 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
565 $resql = $this->db->query($sql);
566 if (!$resql) {
567 dol_print_error($this->db);
568 $error++;
569 $this->error = $this->db->lasterror();
570 }
571
572 // Trigger calls
573 if (!$error && !$notrigger) {
574 // Call trigger
575 $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
576 if ($result < 0) {
577 $error++;
578 }
579 // End call triggers
580 }
581
582 if (!$error) {
583 $this->oldref = $this->ref;
584
585 // Rename directory if dir was a temporary ref
586 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
587 // Now we rename also files into index
588 $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)."'";
589 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
590 $resql = $this->db->query($sql);
591 if (!$resql) {
592 $error++;
593 $this->error = $this->db->lasterror();
594 }
595 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files SET filepath = 'contract/".$this->db->escape($this->newref)."'";
596 $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
597 $resql = $this->db->query($sql);
598 if (!$resql) {
599 $error++;
600 $this->error = $this->db->lasterror();
601 }
602
603 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
604 $oldref = dol_sanitizeFileName($this->ref);
605 $newref = dol_sanitizeFileName($num);
606 $dirsource = $conf->contract->dir_output.'/'.$oldref;
607 $dirdest = $conf->contract->dir_output.'/'.$newref;
608 if (!$error && file_exists($dirsource)) {
609 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
610
611 if (@rename($dirsource, $dirdest)) {
612 dol_syslog("Rename ok");
613 // Rename docs starting with $oldref with $newref
614 $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
615 foreach ($listoffiles as $fileentry) {
616 $dirsource = $fileentry['name'];
617 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
618 $dirsource = $fileentry['path'].'/'.$dirsource;
619 $dirdest = $fileentry['path'].'/'.$dirdest;
620 @rename($dirsource, $dirdest);
621 }
622 }
623 }
624 }
625 }
626
627 // Set new ref and define current status
628 if (!$error) {
629 $this->ref = $num;
630 $this->status = self::STATUS_VALIDATED;
631 $this->statut = self::STATUS_VALIDATED; // deprecated
632 $this->date_validation = $now;
633 }
634 } else {
635 $error++;
636 }
637
638 if (!$error) {
639 $this->db->commit();
640 return 1;
641 } else {
642 $this->db->rollback();
643 return -1;
644 }
645 }
646
654 public function reopen($user, $notrigger = 0)
655 {
656 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
657
658 $now = dol_now();
659
660 $error = 0;
661 dol_syslog(get_class($this).'::reopen user='.$user->id);
662
663 $this->db->begin();
664
665 $this->fetch_thirdparty();
666
667 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
668 //$sql.= ", fk_user_valid = null, date_valid = null";
669 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
670
671 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
672 $resql = $this->db->query($sql);
673 if (!$resql) {
674 dol_print_error($this->db);
675 $error++;
676 $this->error = $this->db->lasterror();
677 }
678
679 // Trigger calls
680 if (!$error && !$notrigger) {
681 // Call trigger
682 $result = $this->call_trigger('CONTRACT_REOPEN', $user);
683 if ($result < 0) {
684 $error++;
685 }
686 // End call triggers
687 }
688
689 // Set new ref and define current status
690 if (!$error) {
691 $this->statut = self::STATUS_DRAFT;
692 $this->status = self::STATUS_DRAFT;
693 $this->date_validation = $now;
694 }
695
696 if (!$error) {
697 $this->db->commit();
698 return 1;
699 } else {
700 $this->db->rollback();
701 return -1;
702 }
703 }
704
716 public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '', $noextrafields = 0, $nolines = 0)
717 {
718 $result = -10;
719
720 $sql = "SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
721 $sql .= " ref_supplier, ref_customer,";
722 $sql .= " ref_ext,";
723 $sql .= " entity,";
724 $sql .= " signed_status,";
725 $sql .= " date_contrat as datecontrat,";
726 $sql .= " fk_user_author,";
727 $sql .= " fk_projet as fk_project,";
728 $sql .= " fk_commercial_signature, fk_commercial_suivi,";
729 $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
730 $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
731 if (!$id) {
732 $sql .= " WHERE entity IN (".getEntity('contract').")";
733 } else {
734 $sql .= " WHERE rowid = ".(int) $id;
735 }
736 if ($ref_customer) {
737 $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
738 }
739 if ($ref_supplier) {
740 $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
741 }
742 if ($ref) {
743 $sql .= " AND ref = '".$this->db->escape($ref)."'";
744 }
745
746 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
747
748 $resql = $this->db->query($sql);
749 if ($resql) {
750 $num = $this->db->num_rows($resql);
751 if ($num > 1) {
752 $this->error = 'Fetch found several records.';
753 dol_syslog($this->error, LOG_ERR);
754 $result = -2;
755 return 0;
756 } elseif ($num) { // $num = 1
757 $obj = $this->db->fetch_object($resql);
758 if ($obj) {
759 $this->id = $obj->rowid;
760 $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
761 $this->ref_customer = $obj->ref_customer;
762 $this->ref_supplier = $obj->ref_supplier;
763 $this->ref_ext = $obj->ref_ext;
764 $this->entity = $obj->entity;
765 $this->statut = $obj->status;
766 $this->status = $obj->status;
767 $this->signed_status = $obj->signed_status;
768
769 $this->date_contrat = $this->db->jdate($obj->datecontrat);
770 $this->date_creation = $this->db->jdate($obj->datecontrat);
771
772 $this->user_author_id = $obj->fk_user_author;
773
774 $this->commercial_signature_id = $obj->fk_commercial_signature;
775 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
776
777 $this->note_private = $obj->note_private;
778 $this->note_public = $obj->note_public;
779 $this->model_pdf = $obj->model_pdf;
780
781 $this->fk_projet = $obj->fk_project; // deprecated
782 $this->fk_project = $obj->fk_project;
783
784 $this->socid = $obj->thirdpartyid;
785 $this->fk_soc = $obj->thirdpartyid;
786 $this->last_main_doc = $obj->last_main_doc;
787 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
788
789 $this->db->free($resql);
790
791 // Retrieve all extrafields
792 // fetch optionals attributes and labels
793 if (empty($noextrafields)) {
794 $result = $this->fetch_optionals();
795 if ($result < 0) {
796 $this->error = $this->db->lasterror();
797 return -4;
798 }
799 }
800
801 // Lines
802 if (empty($nolines)) {
803 if ($result >= 0 && !empty($this->table_element_line)) {
804 $result = $this->fetch_lines();
805 if ($result < 0) {
806 $this->error = $this->db->lasterror();
807 return -3;
808 }
809 }
810 }
811
812 return $this->id;
813 } else {
814 dol_syslog(get_class($this)."::fetch Contract failed");
815 $this->error = "Fetch contract failed";
816 return -1;
817 }
818 } else {
819 dol_syslog(get_class($this)."::fetch Contract not found");
820 $this->error = "Contract not found";
821 return 0;
822 }
823 } else {
824 dol_syslog(get_class($this)."::fetch Error searching contract");
825 $this->error = $this->db->error();
826 return -1;
827 }
828 }
829
830 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
840 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
841 {
842 // phpcs:enable
843 $this->nbofservices = 0;
844 $this->nbofserviceswait = 0;
845 $this->nbofservicesopened = 0;
846 $this->nbofservicesexpired = 0;
847 $this->nbofservicesclosed = 0;
848
849 $total_ttc = 0;
850 $total_vat = 0;
851 $total_ht = 0;
852
853 $now = dol_now();
854
855 $this->lines = array();
856 $pos = 0;
857
858 // Selects contract lines related to a product
859 $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
860 $sql .= " d.rowid, d.fk_contrat, d.statut as status, d.description, d.subprice, 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.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
861 $sql .= " d.total_ht,";
862 $sql .= " d.total_tva,";
863 $sql .= " d.total_localtax1,";
864 $sql .= " d.total_localtax2,";
865 $sql .= " d.total_ttc,";
866 $sql .= " d.info_bits, d.fk_product,";
867 $sql .= " d.date_ouverture_prevue as date_start,";
868 $sql .= " d.date_ouverture as date_start_real,";
869 $sql .= " d.date_fin_validite as date_end,";
870 $sql .= " d.date_cloture as date_end_real,";
871 $sql .= " d.fk_user_author,";
872 $sql .= " d.fk_user_ouverture,";
873 $sql .= " d.fk_user_cloture,";
874 $sql .= " d.fk_unit,";
875 $sql .= " d.extraparams,";
876 $sql .= " d.product_type as type,";
877 $sql .= " d.rang";
878 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
879 $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
880 if ($only_services == 1) {
881 $sql .= " AND d.product_type = 1";
882 }
883 $sql .= " ORDER by d.rang ASC";
884
885 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
886 $result = $this->db->query($sql);
887 if ($result) {
888 $num = $this->db->num_rows($result);
889 $i = 0;
890
891 while ($i < $num) {
892 $objp = $this->db->fetch_object($result);
893
894 $line = new ContratLigne($this->db);
895
896 $line->id = $objp->rowid;
897 $line->ref = $objp->rowid;
898 $line->fk_contrat = $objp->fk_contrat;
899 $line->desc = $objp->description; // Description line
900 $line->qty = $objp->qty;
901 $line->vat_src_code = $objp->vat_src_code;
902 $line->tva_tx = $objp->tva_tx;
903 $line->localtax1_tx = $objp->localtax1_tx;
904 $line->localtax2_tx = $objp->localtax2_tx;
905 $line->localtax1_type = $objp->localtax1_type;
906 $line->localtax2_type = $objp->localtax2_type;
907 $line->subprice = $objp->subprice;
908 $line->statut = $objp->status; // For backward compatibility
909 $line->status = $objp->status;
910 $line->remise_percent = $objp->remise_percent;
911 $line->total_ht = $objp->total_ht;
912 $line->total_tva = $objp->total_tva;
913 $line->total_localtax1 = $objp->total_localtax1;
914 $line->total_localtax2 = $objp->total_localtax2;
915 $line->total_ttc = $objp->total_ttc;
916 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
917 $line->info_bits = $objp->info_bits;
918 $line->type = $objp->type;
919
920 $line->fk_fournprice = $objp->fk_fournprice;
921 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
922 $line->pa_ht = $marginInfos[0];
923
924 $line->fk_user_author = $objp->fk_user_author;
925 $line->fk_user_ouverture = $objp->fk_user_ouverture;
926 $line->fk_user_cloture = $objp->fk_user_cloture;
927 $line->fk_unit = $objp->fk_unit;
928
929 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
930
931 $line->ref = $objp->product_ref; // deprecated
932 $line->product_ref = $objp->product_ref; // Product Ref
933 $line->product_type = $objp->product_type; // Product Type
934 $line->product_desc = $objp->product_desc; // Product Description
935 $line->product_label = $objp->product_label; // Product Label
936
937 $line->description = $objp->description;
938
939 $line->date_start = $this->db->jdate($objp->date_start);
940 $line->date_start_real = $this->db->jdate($objp->date_start_real);
941 $line->date_end = $this->db->jdate($objp->date_end);
942 $line->date_end_real = $this->db->jdate($objp->date_end_real);
943 // For backward compatibility
944 //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
945 //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
946 //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
947 //$line->date_cloture = $this->db->jdate($objp->date_cloture);
948 //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
949 //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
950 //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
951 //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
952
953 $line->rang = $objp->rang;
954
955 // Retrieve all extrafields for contract line
956 // fetch optionals attributes and labels
957 if (empty($noextrafields)) {
958 $line->fetch_optionals();
959 }
960
961 // multilangs
962 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
963 $tmpproduct = new Product($this->db);
964 $tmpproduct->fetch($objp->fk_product);
965 $tmpproduct->getMultiLangs();
966
967 $line->multilangs = $tmpproduct->multilangs;
968 }
969
970 $this->lines[$pos] = $line;
971
972 $this->lines_id_index_mapper[$line->id] = $pos;
973
974 //dol_syslog("1 ".$line->desc);
975 //dol_syslog("2 ".$line->product_desc);
976
977 if ($line->statut == ContratLigne::STATUS_INITIAL) {
978 $this->nbofserviceswait++;
979 }
980 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
981 $this->nbofservicesopened++;
982 }
983 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
984 $this->nbofservicesexpired++;
985 }
986 if ($line->statut == ContratLigne::STATUS_CLOSED) {
987 $this->nbofservicesclosed++;
988 }
989
990 // TODO Not saved into database
991 $total_ttc += $objp->total_ttc;
992 $total_vat += $objp->total_tva;
993 $total_ht += $objp->total_ht;
994
995 $i++;
996 $pos++;
997 }
998 $this->db->free($result);
999 } else {
1000 dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
1001 return -3;
1002 }
1003
1004 // Now set the global properties on contract not stored into database.
1005 $this->nbofservices = count($this->lines);
1006 $this->total_ttc = (float) price2num($total_ttc);
1007 $this->total_tva = (float) price2num($total_vat);
1008 $this->total_ht = (float) price2num($total_ht);
1009
1010 return $this->lines;
1011 }
1012
1020 public function create($user, $notrigger = 0)
1021 {
1022 global $conf, $langs;
1023
1024 // Check parameters
1025 $paramsok = 1;
1026 if ($this->commercial_signature_id <= 0) {
1027 $langs->load("commercial");
1028 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
1029 $paramsok = 0;
1030 }
1031 if ($this->commercial_suivi_id <= 0) {
1032 $langs->load("commercial");
1033 $this->error .= ($this->error ? "<br>" : '');
1034 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
1035 $paramsok = 0;
1036 }
1037 $this->entity = setEntity($this);
1038 if (!$paramsok) {
1039 return -1;
1040 }
1041
1042
1043 $this->db->begin();
1044
1045 $now = dol_now();
1046
1047 // Insert contract
1048 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
1049 $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1050 $sql .= " ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1051 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
1052 $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
1053 $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
1054 $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
1055 $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
1056 $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
1057 $sql .= ", ".((int) $this->entity);
1058 $sql .= ", ".((int) $this->signed_status);
1059 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
1060 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
1061 $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
1062 $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
1063 $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
1064 $sql .= ")";
1065 $resql = $this->db->query($sql);
1066
1067 if ($resql) {
1068 $error = 0;
1069
1070 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
1071
1072 // Load object modContract
1073 $module = getDolGlobalString('CONTRACT_ADDON', 'mod_contract_serpis');
1074 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1075 $module = substr($module, 0, dol_strlen($module) - 4);
1076 }
1077 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1078 if ($result > 0) {
1079 $modCodeContract = new $module();
1080 '@phan-var-force ModelNumRefContracts $modCodeContract';
1083 if (!empty($modCodeContract->code_auto)) {
1084 // Force the ref to a draft value if numbering module is an automatic numbering
1085 $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1086 if ($this->db->query($sql)) {
1087 if ($this->id) {
1088 $this->ref = "(PROV".$this->id.")";
1089 }
1090 }
1091 }
1092 }
1093
1094 $result = $this->insertExtraFields();
1095 if ($result < 0) {
1096 $error++;
1097 }
1098
1099 // Insert business contacts ('SALESREPSIGN','contrat')
1100 if (!$error && !empty($this->commercial_signature_id)) {
1101 $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1102 if ($result < 0) {
1103 $error++;
1104 }
1105 }
1106
1107 // Insert business contacts ('SALESREPFOLL','contrat')
1108 if (!$error && !empty($this->commercial_suivi_id)) {
1109 $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1110 if ($result < 0) {
1111 $error++;
1112 }
1113 }
1114
1115 if (!$error) {
1116 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1117 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1118 }
1119
1120 // Add object linked
1121 if ($this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1122 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1123 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, ...))
1124 foreach ($tmp_origin_id as $origin_id) {
1125 $ret = $this->add_object_linked($origin, $origin_id);
1126 if (!$ret) {
1127 $this->error = $this->db->lasterror();
1128 $error++;
1129 }
1130 }
1131 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1132 $origin_id = $tmp_origin_id;
1133 $ret = $this->add_object_linked($origin, $origin_id);
1134 if (!$ret) {
1135 $this->error = $this->db->lasterror();
1136 $error++;
1137 }
1138 }
1139 }
1140 }
1141
1142 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1143 $originforcontact = $this->origin;
1144 $originidforcontact = $this->origin_id;
1145 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1146 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1147 $exp = new Expedition($this->db);
1148 $exp->fetch($this->origin_id);
1149 $exp->fetchObjectLinked();
1150 if (count($exp->linkedObjectsIds['commande']) > 0) {
1151 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1152 $originforcontact = 'commande';
1153 $originidforcontact = $value;
1154 break; // We take first one
1155 }
1156 }
1157 }
1158
1159 $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";
1160 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1161
1162 $resqlcontact = $this->db->query($sqlcontact);
1163 if ($resqlcontact) {
1164 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1165 if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1166 continue; // ignore this, already forced previously
1167 }
1168
1169 $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
1170 }
1171 } else {
1172 dol_print_error($this->db);
1173 }
1174 }
1175 }
1176
1177 if (!$error && !$notrigger) {
1178 // Call trigger
1179 $result = $this->call_trigger('CONTRACT_CREATE', $user);
1180 if ($result < 0) {
1181 $error++;
1182 }
1183 // End call triggers
1184 }
1185
1186 if (!$error) {
1187 $this->db->commit();
1188 return $this->id;
1189 } else {
1190 $this->error = "Failed to add contract";
1191 dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1192 $this->db->rollback();
1193 return -2;
1194 }
1195 } else {
1196 $this->error = $langs->trans("UnknownError").": ".$this->db->error();
1197 dol_syslog(get_class($this)."::create - 10 - ".$this->error, LOG_ERR);
1198
1199 $this->db->rollback();
1200 return -1;
1201 }
1202 }
1203
1204
1211 public function delete($user)
1212 {
1213 global $conf;
1214
1215 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1216
1217 $error = 0;
1218
1219 $this->db->begin();
1220
1221 // Call trigger
1222 $result = $this->call_trigger('CONTRACT_DELETE', $user);
1223 if ($result < 0) {
1224 $error++;
1225 }
1226 // End call triggers
1227
1228 if (!$error) {
1229 // Delete linked contacts
1230 $res = $this->delete_linked_contact();
1231 if ($res < 0) {
1232 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1233 $error++;
1234 }
1235 }
1236
1237 if (!$error) {
1238 // Delete linked object
1239 $res = $this->deleteObjectLinked();
1240 if ($res < 0) {
1241 $error++;
1242 }
1243 }
1244
1245 // Delete lines
1246 if (!$error) {
1247 // Delete contratdet extrafields
1248 $main = MAIN_DB_PREFIX.'contratdet';
1249 $ef = $main."_extrafields";
1250 $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1251
1252 dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1253 $resql = $this->db->query($sql);
1254 if (!$resql) {
1255 $this->error = $this->db->error();
1256 $error++;
1257 }
1258 }
1259
1260 if (!$error) {
1261 // Delete contratdet
1262 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1263 $sql .= " WHERE fk_contrat=".((int) $this->id);
1264
1265 dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1266 $resql = $this->db->query($sql);
1267 if (!$resql) {
1268 $this->error = $this->db->error();
1269 $error++;
1270 }
1271 }
1272
1273 // Delete record into ECM index and physically
1274 if (!$error) {
1275 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1276 if ($res) {
1277 $res = $this->deleteEcmFiles(1);
1278 } // Deleting files physically is done later with the dol_delete_dir_recursive
1279 if (!$res) {
1280 $error++;
1281 }
1282 }
1283
1284 // Delete contract
1285 if (!$error) {
1286 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1287 $sql .= " WHERE rowid=".((int) $this->id);
1288
1289 dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1290 $resql = $this->db->query($sql);
1291 if (!$resql) {
1292 $this->error = $this->db->error();
1293 $error++;
1294 }
1295 }
1296
1297 // Removed extrafields
1298 if (!$error) {
1299 $result = $this->deleteExtraFields();
1300 if ($result < 0) {
1301 $error++;
1302 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1303 }
1304 }
1305
1306 if (!$error) {
1307 // We remove directory
1308 $ref = dol_sanitizeFileName($this->ref);
1309 if ($conf->contrat->dir_output && !empty($ref)) {
1310 $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1311 if (file_exists($dir)) {
1312 $res = @dol_delete_dir_recursive($dir);
1313 if (!$res) {
1314 $this->error = 'ErrorFailToDeleteDir';
1315 $error++;
1316 }
1317 }
1318 }
1319 }
1320
1321 if (!$error) {
1322 $this->db->commit();
1323 return 1;
1324 } else {
1325 $this->error = $this->db->lasterror();
1326 $this->db->rollback();
1327 return -1;
1328 }
1329 }
1330
1338 public function update($user, $notrigger = 0)
1339 {
1340 global $conf;
1341 $error = 0;
1342
1343 // Clean parameters
1344 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1345 $this->fk_commercial_signature = $this->commercial_signature_id;
1346 }
1347 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1348 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1349 }
1350 if (empty($this->socid) && $this->fk_soc > 0) {
1351 $this->socid = (int) $this->fk_soc;
1352 }
1353
1354 if (isset($this->ref)) {
1355 $this->ref = trim($this->ref);
1356 }
1357 if (isset($this->ref_customer)) {
1358 $this->ref_customer = trim($this->ref_customer);
1359 }
1360 if (isset($this->ref_supplier)) {
1361 $this->ref_supplier = trim($this->ref_supplier);
1362 }
1363 if (isset($this->ref_ext)) {
1364 $this->ref_ext = trim($this->ref_ext);
1365 }
1366 if (isset($this->entity)) {
1367 $this->entity = (int) $this->entity;
1368 }
1369 if (isset($this->status)) {
1370 $this->status = (int) $this->status;
1371 }
1372 if ((int) $this->socid > 0) {
1373 $this->socid = (int) $this->socid;
1374 }
1375 if (isset($this->fk_commercial_signature)) {
1376 $this->fk_commercial_signature = (int) $this->fk_commercial_signature;
1377 }
1378 if (isset($this->fk_commercial_suivi)) {
1379 $this->fk_commercial_suivi = (int) $this->fk_commercial_suivi;
1380 }
1381 if (isset($this->note_private)) {
1382 $this->note_private = trim($this->note_private);
1383 }
1384 if (isset($this->note_public)) {
1385 $this->note_public = trim($this->note_public);
1386 }
1387 if (isset($this->import_key)) {
1388 $this->import_key = trim($this->import_key);
1389 }
1390
1391 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
1392 $extraparams = dol_trunc($extraparams, 250);
1393
1394 // $this->oldcopy must have been set by the caller of update
1395
1396 // Update request
1397 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1398 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1399 $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1400 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1401 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1402 $sql .= " entity=".((int) $conf->entity).",";
1403 $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1404 $sql .= " statut=".(isset($this->statut) ? $this->statut : (isset($this->status) ? $this->status : "null")).",";
1405 $sql .= " fk_soc=".($this->socid > 0 ? $this->socid : "null").",";
1406 $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1407 $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1408 $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1409 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1410 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1411 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
1412 $sql .= " fk_user_modif=".(isset($user->id) ? ((int) $user->id) : "null").",";
1413 $sql .= " extraparams=".(isset($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
1414 $sql .= " WHERE rowid=".((int) $this->id);
1415
1416 $this->db->begin();
1417
1418 $resql = $this->db->query($sql);
1419 if (!$resql) {
1420 $error++;
1421 $this->errors[] = "Error ".$this->db->lasterror();
1422 }
1423
1424 if (!$error) {
1425 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
1426 if ($result < 0) {
1427 $error++;
1428 }
1429 }
1430
1431 if (!$error && !$notrigger) {
1432 // Call triggers
1433 $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1434 if ($result < 0) {
1435 $error++;
1436 }
1437 // End call triggers
1438 }
1439
1440 // Commit or rollback
1441 if ($error) {
1442 foreach ($this->errors as $errmsg) {
1443 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1444 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1445 }
1446 $this->db->rollback();
1447 return -1 * $error;
1448 } else {
1449 if (isset($user->id)) {
1450 $this->fk_user_modif = (int) $user->id;
1451 }
1452 $this->db->commit();
1453 return 1;
1454 }
1455 }
1456
1457
1481 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 = array(), $fk_unit = null, $rang = 0)
1482 {
1483 global $user, $langs, $mysoc;
1484 $error = 0;
1485
1486 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");
1487
1488 // Check parameters
1489 if ($fk_product <= 0 && empty($desc)) {
1490 $this->error = "ErrorDescRequiredForFreeProductLines";
1491 return -1;
1492 }
1493
1494 if ($this->status >= 0) {
1495 // Clean parameters
1496 $pu_ht = price2num($pu_ht);
1497 $pu_ttc = price2num($pu_ttc);
1498 $pa_ht = price2num($pa_ht);
1499
1500 // Clean vat code
1501 $reg = array();
1502 $vat_src_code = '';
1503 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1504 $vat_src_code = $reg[1];
1505 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code into vatrate.
1506 }
1507 $txtva = price2num($txtva);
1508 $txlocaltax1 = price2num($txlocaltax1);
1509 $txlocaltax2 = price2num($txlocaltax2);
1510
1511 $remise_percent = price2num($remise_percent);
1512 $qty = price2num($qty);
1513 if (empty($qty)) {
1514 $qty = 1;
1515 }
1516 if (empty($info_bits)) {
1517 $info_bits = 0;
1518 }
1519 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1520 $pu_ht = 0;
1521 }
1522 if (empty($pu_ttc)) {
1523 $pu_ttc = 0;
1524 }
1525 if (empty($txtva) || !is_numeric($txtva)) {
1526 $txtva = 0;
1527 }
1528 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1529 $txlocaltax1 = 0;
1530 }
1531 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1532 $txlocaltax2 = 0;
1533 }
1534
1535 if ($price_base_type == 'HT') {
1536 $pu = $pu_ht;
1537 } else {
1538 $pu = $pu_ttc;
1539 }
1540
1541 // Check parameters
1542 if (empty($remise_percent)) {
1543 $remise_percent = 0;
1544 }
1545 if (empty($rang)) {
1546 $rang = 0;
1547 }
1548
1549 if ($date_start && $date_end && $date_start > $date_end) {
1550 $langs->load("errors");
1551 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1552 return -1;
1553 }
1554
1555 $this->db->begin();
1556
1557 $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1558
1559 // Calcul du total TTC et de la TVA pour la ligne a partir de
1560 // qty, pu, remise_percent et txtva
1561 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1562 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1563
1564 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1565 $total_ht = $tabprice[0];
1566 $total_tva = $tabprice[1];
1567 $total_ttc = $tabprice[2];
1568 $total_localtax1 = $tabprice[9];
1569 $total_localtax2 = $tabprice[10];
1570
1571 if (count($localtaxes_type) > 0) {
1572 $localtax1_type = $localtaxes_type[0];
1573 $localtax2_type = $localtaxes_type[2];
1574 } else {
1575 $localtax1_type = "";
1576 $localtax2_type = "";
1577 }
1578
1579 if (empty($pa_ht)) {
1580 $pa_ht = 0;
1581 }
1582
1583
1584 // if buy price not defined, define buyprice as configured in margin admin
1585 if ($pa_ht == 0) {
1586 $result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product);
1587 if ($result < 0) {
1588 return -1;
1589 } else {
1590 $pa_ht = $result;
1591 }
1592 }
1593
1594 // Insertion dans la base
1595 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1596 $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1597 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1598 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1599 $sql .= " info_bits,";
1600 $sql .= " fk_product_fournisseur_price, buy_price_ht";
1601 if ($date_start > 0) {
1602 $sql .= ",date_ouverture_prevue";
1603 }
1604 if ($date_end > 0) {
1605 $sql .= ",date_fin_validite";
1606 }
1607 $sql .= ", fk_unit";
1608 $sql .= ", rang";
1609 $sql .= ") VALUES (";
1610 $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1611 $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1612 $sql .= " ".((float) $qty).",";
1613 $sql .= " ".((float) $txtva).",";
1614 $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1615 $sql .= " ".((float) $txlocaltax1).",";
1616 $sql .= " ".((float) $txlocaltax2).",";
1617 $sql .= " '".$this->db->escape($localtax1_type)."',";
1618 $sql .= " '".$this->db->escape($localtax2_type)."',";
1619 $sql .= " ".price2num($remise_percent).",";
1620 $sql .= " ".price2num($pu_ht).",";
1621 $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1622 $sql .= " ".((int) $info_bits).",";
1623 if (isset($fk_fournprice)) {
1624 $sql .= ' '.((int) $fk_fournprice).',';
1625 } else {
1626 $sql .= ' null,';
1627 }
1628 if (isset($pa_ht)) {
1629 $sql .= ' '.price2num($pa_ht);
1630 } else {
1631 $sql .= ' null';
1632 }
1633 if ($date_start > 0) {
1634 $sql .= ",'".$this->db->idate($date_start)."'";
1635 }
1636 if ($date_end > 0) {
1637 $sql .= ",'".$this->db->idate($date_end)."'";
1638 }
1639 $sql .= ", ".($fk_unit ? "'".$this->db->escape((string) $fk_unit)."'" : "null");
1640 $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1641 $sql .= ")";
1642
1643 $resql = $this->db->query($sql);
1644 if ($resql) {
1645 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1646
1647 $contractline = new ContratLigne($this->db);
1648 $contractline->array_options = $array_options;
1649 $contractline->id = $contractlineid;
1650 $result = $contractline->insertExtraFields();
1651 if ($result < 0) {
1652 $this->setErrorsFromObject($contractline);
1653 $error++;
1654 }
1655
1656 if (empty($error)) {
1657 // Call trigger
1658 $this->context['line_id'] = $contractlineid;
1659 $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1660 if ($result < 0) {
1661 $error++;
1662 }
1663 // End call triggers
1664 }
1665
1666 if ($error) {
1667 $this->db->rollback();
1668 return -1;
1669 } else {
1670 $this->db->commit();
1671 return $contractlineid;
1672 }
1673 } else {
1674 $this->db->rollback();
1675 $this->error = $this->db->error()." sql=".$sql;
1676 return -1;
1677 }
1678 } else {
1679 dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1680 return -2;
1681 }
1682 }
1683
1708 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 = array(), $fk_unit = null, $rang = 0)
1709 {
1710 global $user, $langs, $mysoc;
1711
1712 $error = 0;
1713
1714 // Clean parameters
1715 $qty = trim((string) $qty);
1716 $desc = trim($desc);
1717 $desc = trim($desc);
1718 $subprice = price2num($pu);
1719 $tvatx = price2num($tvatx);
1720 $localtax1tx = price2num($localtax1tx);
1721 $localtax2tx = price2num($localtax2tx);
1722 $pa_ht = price2num($pa_ht);
1723 if (empty($fk_fournprice)) {
1724 $fk_fournprice = 0;
1725 }
1726 if (empty($rang)) {
1727 $rang = 0;
1728 }
1729
1730 if ($date_start && $date_end && $date_start > $date_end) {
1731 $langs->load("errors");
1732 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1733 return -1;
1734 }
1735
1736 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");
1737
1738 $this->db->begin();
1739
1740 // Calcul du total TTC et de la TVA pour la ligne a partir de
1741 // qty, pu, remise_percent et tvatx
1742 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1743 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1744
1745 $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1746 $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1747
1748 $tabprice = calcul_price_total((float) $qty, $pu, $remise_percent, (float) price2num($tvatx), (float) $localtax1tx, (float) $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1749 $total_ht = $tabprice[0];
1750 $total_tva = $tabprice[1];
1751 $total_ttc = $tabprice[2];
1752 $total_localtax1 = $tabprice[9];
1753 $total_localtax2 = $tabprice[10];
1754
1755 $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1756 $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1757
1758 if (empty($pa_ht)) {
1759 $pa_ht = 0;
1760 }
1761
1762 // if buy price not defined, define buyprice as configured in margin admin
1763 if ($pa_ht == 0) {
1764 $result = $this->defineBuyPrice($pu, $remise_percent);
1765 if ($result < 0) {
1766 return -1;
1767 } else {
1768 $pa_ht = $result;
1769 }
1770 }
1771
1772 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET description = '".$this->db->escape($desc)."'";
1773 $sql .= ",subprice = ".((float) price2num($subprice));
1774 $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1775 $sql .= ",qty = ".((float) $qty);
1776 $sql .= ",tva_tx = ".((float) price2num($tvatx));
1777 $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1778 $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1779 $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1780 $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1781 $sql .= ", total_ht = ".((float) price2num($total_ht));
1782 $sql .= ", total_tva = ".((float) price2num($total_tva));
1783 $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1784 $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1785 $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1786 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1787 $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1788 if ($date_start > 0) {
1789 $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1790 } else {
1791 $sql .= ",date_ouverture_prevue = null";
1792 }
1793 if ($date_end > 0) {
1794 $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1795 } else {
1796 $sql .= ",date_fin_validite = null";
1797 }
1798 if ($date_start_real > 0) {
1799 $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1800 } else {
1801 $sql .= ",date_ouverture = null";
1802 }
1803 if ($date_end_real > 0) {
1804 $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1805 } else {
1806 $sql .= ",date_cloture = null";
1807 }
1808 $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1809 $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1810 $sql .= " WHERE rowid = ".((int) $rowid);
1811
1812 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1813 $result = $this->db->query($sql);
1814 if ($result) {
1815 if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1816 $contractline = new ContratLigne($this->db);
1817 $contractline->fetch($rowid);
1818
1819 // We replace values in $contractline->array_options only for entries defined into $array_options
1820 foreach ($array_options as $key => $value) {
1821 $contractline->array_options[$key] = $array_options[$key];
1822 }
1823
1824 $result = $contractline->insertExtraFields();
1825 if ($result < 0) {
1826 $this->errors[] = $contractline->error;
1827 $error++;
1828 }
1829 }
1830
1831 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
1832 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
1833 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $this->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
1834 $sqltoupdatecontract .= " WHERE rowid = ".((int) $this->id);
1835 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
1836 if (!$resqltoupdatecontract) {
1837 $this->error = $this->db->lasterror();
1838 $this->db->rollback();
1839 return -1;
1840 }
1841
1842 if (empty($error)) {
1843 // Call trigger
1844 $this->context['line_id'] = $rowid;
1845 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1846 if ($result < 0) {
1847 $this->db->rollback();
1848 return -3;
1849 }
1850 // End call triggers
1851
1852 $this->db->commit();
1853 return 1;
1854 } else {
1855 $this->db->rollback();
1856 return -1;
1857 }
1858 } else {
1859 $this->db->rollback();
1860 $this->error = $this->db->error();
1861 dol_syslog(get_class($this)."::updateline Erreur -1");
1862 return -1;
1863 }
1864 }
1865
1873 public function deleteLine($idline, User $user)
1874 {
1875 $error = 0;
1876
1877 if ($this->statut >= 0) {
1878 // Call trigger
1879 $this->context['line_id'] = $idline;
1880 $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1881 if ($result < 0) {
1882 return -1;
1883 }
1884 // End call triggers
1885
1886 $this->db->begin();
1887
1888 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1889 $sql .= " WHERE rowid = ".((int) $idline);
1890
1891 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1892 $resql = $this->db->query($sql);
1893 if (!$resql) {
1894 $this->error = "Error ".$this->db->lasterror();
1895 $error++;
1896 }
1897
1898 if (!$error) {
1899 // Remove extrafields
1900 $contractline = new ContratLigne($this->db);
1901 $contractline->id = $idline;
1902 $result = $contractline->deleteExtraFields();
1903 if ($result < 0) {
1904 $error++;
1905 $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1906 }
1907 }
1908
1909 if (empty($error)) {
1910 $this->db->commit();
1911 return 1;
1912 } else {
1913 dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1914 $this->db->rollback();
1915 return -1;
1916 }
1917 } else {
1918 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1919 return -2;
1920 }
1921 }
1922
1923
1924 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1932 public function update_statut($user)
1933 {
1934 // phpcs:enable
1935 dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1936
1937 // If draft, we keep it (should not happen)
1938 if ($this->statut == 0) {
1939 return 1;
1940 }
1941
1942 // Load $this->lines array
1943 // $this->fetch_lines();
1944
1945 // $newstatut=1;
1946 // foreach($this->lines as $key => $contractline)
1947 // {
1948 // // if ($contractline) // Loop on each service
1949 // }
1950
1951 return 1;
1952 }
1953
1954
1961 public function getLibStatut($mode)
1962 {
1963 return $this->LibStatut($this->statut, $mode);
1964 }
1965
1966 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1974 public function LibStatut($status, $mode)
1975 {
1976 // phpcs:enable
1977 global $langs;
1978
1979 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1980 global $langs;
1981 $langs->load("contracts");
1982 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1983 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1984 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1985 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1986 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1987 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1988 }
1989
1990 $statusType = 'status'.$status;
1991 if ($status == self::STATUS_VALIDATED) {
1992 $statusType = 'status6';
1993 }
1994
1995 if ($mode == 4 || $mode == 6 || $mode == 7) {
1996 $text = '';
1997 if ($mode == 4) {
1998 $text = '<span class="hideonsmartphone">';
1999 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2000 $text .= ' '.$langs->trans("Services");
2001 $text .= ': &nbsp; &nbsp; ';
2002 $text .= '</span>';
2003 }
2004 $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
2005 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2006 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2007 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2008 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2009 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2010 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2011 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
2012 $text .= ($mode == 7 ? '</span>' : '');
2013 if (getDolGlobalString('CONTRACT_SHOW_SIGNATURE_STATUS_WITH_SERVICE_STATUS')) {
2014 $text .= is_null($this->signed_status) ? '' : ' '.$this->getLibSignedStatus(5);
2015 }
2016 return $text;
2017 } else {
2018 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2019 }
2020 }
2021
2028 public function getTooltipContentArray($params)
2029 {
2030 global $conf, $langs, $user;
2031
2032 $langs->load('contracts');
2033
2034 $datas = [];
2035 $nofetch = !empty($params['nofetch']);
2036
2037 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2038 return ['optimize' => $langs->trans("ShowContract")];
2039 }
2040 if ($user->hasRight('contrat', 'lire')) {
2041 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2042 /* Status of a contract is status of all services, so disabled
2043 if (isset($this->statut)) {
2044 $label .= ' '.$this->getLibStatut(5);
2045 }*/
2046 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2047 if (!$nofetch) {
2048 $langs->load('companies');
2049 if (empty($this->thirdparty)) {
2050 $this->fetch_thirdparty();
2051 }
2052 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2053 }
2054 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2055 if (!$nofetch) {
2056 $langs->load('project');
2057 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2058 $res = $this->fetchProject();
2059 if ($res > 0 && $this->project instanceof Project) {
2060 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
2061 }
2062 }
2063 }
2064 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2065 if (!empty($this->total_ht)) {
2066 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2067 }
2068 if (!empty($this->total_tva)) {
2069 $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2070 }
2071 if (!empty($this->total_ttc)) {
2072 $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2073 }
2074 }
2075 return $datas;
2076 }
2077
2087 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2088 {
2089 global $langs, $user, $hookmanager;
2090
2091 $result = '';
2092
2093 $baseurl = DOL_URL_ROOT . '/contrat/card.php';
2094 $query = ['id' => $this->id];
2095
2096 //if ($option !== 'nolink')
2097 //{
2098 // Add param to save lastsearch_values or not
2099 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2100 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2101 $add_save_lastsearch_values = 1;
2102 }
2103 if ($add_save_lastsearch_values) {
2104 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2105 }
2106 //}
2107 $url = dolBuildUrl($baseurl, $query);
2108 $params = [
2109 'id' => $this->id,
2110 'objecttype' => $this->element,
2111 'nofetch' => 1,
2112 ];
2113 $classfortooltip = 'classfortooltip';
2114 $dataparams = '';
2115 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2116 $classfortooltip = 'classforajaxtooltip';
2117 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2118 $label = '';
2119 } else {
2120 $label = implode($this->getTooltipContentArray($params));
2121 }
2122
2123 $linkclose = '';
2124 if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2125 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2126 $label = $langs->trans("ShowContract");
2127 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2128 }
2129 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2130 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2131 }
2132 $linkstart = '<a href="'.$url.'"';
2133 $linkstart .= $linkclose.'>';
2134 $linkend = '</a>';
2135
2136 $result .= $linkstart;
2137 if ($withpicto) {
2138 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2139 }
2140 if ($withpicto != 2) {
2141 $result .= ($this->ref ? $this->ref : $this->id);
2142 }
2143 $result .= $linkend;
2144
2145 global $action;
2146 $hookmanager->initHooks(array('contractdao'));
2147 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2148 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2149 if ($reshook > 0) {
2150 $result = $hookmanager->resPrint;
2151 } else {
2152 $result .= $hookmanager->resPrint;
2153 }
2154
2155 return $result;
2156 }
2157
2164 public function info($id)
2165 {
2166 $sql = "SELECT c.rowid, c.ref, c.datec,";
2167 $sql .= " c.tms as date_modification,";
2168 $sql .= " fk_user_author";
2169 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2170 $sql .= " WHERE c.rowid = ".((int) $id);
2171
2172 $result = $this->db->query($sql);
2173 if ($result) {
2174 if ($this->db->num_rows($result)) {
2175 $obj = $this->db->fetch_object($result);
2176
2177 $this->id = $obj->rowid;
2178 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2179
2180 $this->user_creation_id = $obj->fk_user_author;
2181 $this->date_creation = $this->db->jdate($obj->datec);
2182 $this->date_modification = $this->db->jdate($obj->date_modification);
2183 }
2184
2185 $this->db->free($result);
2186 } else {
2187 dol_print_error($this->db);
2188 }
2189 }
2190
2191 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2198 public function array_detail($status = -1)
2199 {
2200 // phpcs:enable
2201 $tab = array();
2202
2203 $sql = "SELECT cd.rowid";
2204 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2205 $sql .= " WHERE fk_contrat =".((int) $this->id);
2206 if ($status >= 0) {
2207 $sql .= " AND statut = ".((int) $status);
2208 }
2209
2210 dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2211 $resql = $this->db->query($sql);
2212 if ($resql) {
2213 $num = $this->db->num_rows($resql);
2214 $i = 0;
2215 while ($i < $num) {
2216 $obj = $this->db->fetch_object($resql);
2217 $tab[$i] = $obj->rowid;
2218 $i++;
2219 }
2220 return $tab;
2221 } else {
2222 $this->error = $this->db->error();
2223 return -1;
2224 }
2225 }
2226
2236 public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2237 {
2238 $tab = array();
2239
2240 $sql = "SELECT c.rowid";
2241 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2242 if (!empty($product_categories) || !empty($line_status)) {
2243 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2244 }
2245 if (!empty($product_categories)) {
2246 $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)).")";
2247 }
2248 $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2249 $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2250 $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2251 $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2252 $sql .= " GROUP BY c.rowid";
2253
2254 dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2255 $resql = $this->db->query($sql);
2256 if ($resql) {
2257 $num = $this->db->num_rows($resql);
2258 $i = 0;
2259 while ($i < $num) {
2260 $obj = $this->db->fetch_object($resql);
2261 $contrat = new Contrat($this->db);
2262 $contrat->fetch($obj->rowid);
2263 $tab[$contrat->id] = $contrat;
2264 $i++;
2265 }
2266 return $tab;
2267 } else {
2268 $this->error = $this->db->lasterror();
2269 return -1;
2270 }
2271 }
2272
2273
2274 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2282 public function load_board($user, $mode)
2283 {
2284 // phpcs:enable
2285 global $conf, $langs;
2286
2287 $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2288 $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2289 $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2290 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2291 $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2292 }
2293
2294 if ($mode == 'inactive') {
2295 $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2296 $sql .= $this->from;
2297 $sql .= " WHERE c.statut = 1";
2298 $sql .= " AND c.rowid = cd.fk_contrat";
2299 $sql .= " AND cd.statut = 0";
2300 } elseif ($mode == 'expired') {
2301 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2302 $sql .= $this->from;
2303 $sql .= " WHERE c.statut = 1";
2304 $sql .= " AND c.rowid = cd.fk_contrat";
2305 $sql .= " AND cd.statut = 4";
2306 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2307 } elseif ($mode == 'active') {
2308 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2309 $sql .= $this->from;
2310 $sql .= " WHERE c.statut = 1";
2311 $sql .= " AND c.rowid = cd.fk_contrat";
2312 $sql .= " AND cd.statut = 4";
2313 //$datetouse = dol_now();
2314 //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2315 } else {
2316 return -1;
2317 }
2318 $sql .= " AND c.fk_soc = s.rowid";
2319 $sql .= " AND c.entity = ".((int) $conf->entity);
2320 if ($user->socid) {
2321 $sql .= " AND c.fk_soc = ".((int) $user->socid);
2322 }
2323 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2324 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2325 }
2326
2327 $resql = $this->db->query($sql);
2328 if ($resql) {
2329 $langs->load("contracts");
2330 $now = dol_now();
2331
2332 if ($mode == 'inactive') {
2333 $warning_delay = $conf->contract->services->inactifs->warning_delay;
2334 $label = $langs->trans("BoardNotActivatedServices");
2335 $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2336 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2337 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2338 } elseif ($mode == 'expired') {
2339 $warning_delay = $conf->contract->services->expires->warning_delay;
2340 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2341 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2342 $label = $langs->trans("BoardExpiredServices");
2343 $labelShort = $langs->trans("BoardExpiredServicesShort");
2344 } else {
2345 $warning_delay = $conf->contract->services->expires->warning_delay;
2346 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2347 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2348 $label = $langs->trans("BoardRunningServices");
2349 $labelShort = $langs->trans("BoardRunningServicesShort");
2350 }
2351
2352 $response = new WorkboardResponse();
2353 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2354 $response->label = $label;
2355 $response->labelShort = $labelShort;
2356 $response->url = $url;
2357 $response->url_late = $url_late;
2358 $response->img = img_object('', "contract");
2359
2360 while ($obj = $this->db->fetch_object($resql)) {
2361 $response->nbtodo++;
2362
2363 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2364 $response->nbtodolate++;
2365 }
2366 }
2367
2368 return $response;
2369 } else {
2370 dol_print_error($this->db);
2371 $this->error = $this->db->error();
2372 return -1;
2373 }
2374 }
2375
2381 public function loadStateBoard()
2382 {
2383 global $conf, $user;
2384
2385 $this->nb = array();
2386 $clause = "WHERE";
2387
2388 $sql = "SELECT count(c.rowid) as nb";
2389 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2390 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2391 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2392 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2393 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2394 $clause = "AND";
2395 }
2396 $sql .= " ".$clause." c.entity = ".$conf->entity;
2397
2398 $resql = $this->db->query($sql);
2399 if ($resql) {
2400 while ($obj = $this->db->fetch_object($resql)) {
2401 $this->nb["contracts"] = $obj->nb;
2402 }
2403 $this->db->free($resql);
2404 return 1;
2405 } else {
2406 dol_print_error($this->db);
2407 $this->error = $this->db->error();
2408 return -1;
2409 }
2410 }
2411
2412
2413 /* gestion des contacts d'un contrat */
2414
2420 public function getIdBillingContact()
2421 {
2422 return $this->getIdContact('external', 'BILLING');
2423 }
2424
2430 public function getIdServiceContact()
2431 {
2432 return $this->getIdContact('external', 'SERVICE');
2433 }
2434
2435
2443 public function initAsSpecimen()
2444 {
2445 global $user, $langs, $conf;
2446
2447 // Load array of products prodids
2448 $num_prods = 0;
2449 $prodids = array();
2450 $sql = "SELECT rowid";
2451 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2452 $sql .= " WHERE entity IN (".getEntity('product').")";
2453 $sql .= " AND tosell = 1";
2454 $sql .= $this->db->plimit(100);
2455
2456 $resql = $this->db->query($sql);
2457 if ($resql) {
2458 $num_prods = $this->db->num_rows($resql);
2459 $i = 0;
2460 while ($i < $num_prods) {
2461 $i++;
2462 $row = $this->db->fetch_row($resql);
2463 $prodids[$i] = $row[0];
2464 }
2465 }
2466
2467 // Initialise parameters
2468 $this->id = 0;
2469 $this->specimen = 1;
2470
2471 $this->ref = 'SPECIMEN';
2472 $this->ref_customer = 'SPECIMENCUST';
2473 $this->ref_supplier = 'SPECIMENSUPP';
2474 $this->socid = 1;
2475 $this->status = 0;
2476 $this->date_creation = (dol_now() - 3600 * 24 * 7);
2477 $this->date_contrat = dol_now();
2478 $this->commercial_signature_id = 1;
2479 $this->commercial_suivi_id = 1;
2480 $this->note_private = 'This is a comment (private)';
2481 $this->note_public = 'This is a comment (public)';
2482 $this->fk_project = 0;
2483 // Lines
2484 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
2485 $xnbp = 0;
2486 while ($xnbp < $nbp) {
2487 $line = new ContratLigne($this->db);
2488 $line->qty = 1;
2489 $line->subprice = 100;
2490 $line->tva_tx = 19.6;
2491 $line->remise_percent = 10;
2492 $line->total_ht = 90;
2493 $line->total_ttc = 107.64; // 90 * 1.196
2494 $line->total_tva = 17.64;
2495 $line->date_start = dol_now() - 500000;
2496 $line->date_start_real = dol_now() - 200000;
2497 $line->date_end = dol_now() + 500000;
2498 $line->date_end_real = dol_now() - 100000;
2499 if ($num_prods > 0) {
2500 $prodid = mt_rand(1, $num_prods);
2501 $line->fk_product = $prodids[$prodid];
2502 }
2503 $this->lines[$xnbp] = $line;
2504 $xnbp++;
2505 }
2506
2507 return 1;
2508 }
2509
2515 public function getLinesArray()
2516 {
2517 return $this->fetch_lines();
2518 }
2519
2525 public function getTicketsArray()
2526 {
2527 global $user;
2528
2529 $ticket = new Ticket($this->db);
2530 $nbTicket = $ticket->fetchAll($user, 'ASC', 't.datec', 0, 0, 0, array('t.fk_contract' => $this->id));
2531
2532 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2533 }
2534
2535
2547 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2548 {
2549 global $conf, $langs;
2550
2551 if (!dol_strlen($modele)) {
2552 $modele = ''; // No doc template/generation by default
2553
2554 if (!empty($this->model_pdf)) {
2555 $modele = $this->model_pdf;
2556 } elseif (getDolGlobalString('CONTRACT_ADDON_PDF')) {
2557 $modele = getDolGlobalString('CONTRACT_ADDON_PDF');
2558 }
2559 }
2560
2561 if (empty($modele)) {
2562 return 0;
2563 } else {
2564 $langs->load("contracts");
2565 $outputlangs->load("products");
2566
2567 $modelpath = "core/modules/contract/doc/";
2568 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2569 }
2570 }
2571
2580 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2581 {
2582 $tables = array(
2583 'contrat'
2584 );
2585
2586 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2587 }
2588
2597 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2598 {
2599 $tables = array(
2600 'contratdet'
2601 );
2602
2603 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2604 }
2605
2614 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2615 {
2616 global $db, $langs, $conf, $hookmanager, $extrafields;
2617
2618 dol_include_once('/projet/class/project.class.php');
2619
2620 $error = 0;
2621
2622 $this->fetch($this->id);
2623
2624 // Load dest object
2625 $clonedObj = clone $this;
2626 $clonedObj->socid = $socid;
2627
2628 $this->db->begin();
2629
2630 $objsoc = new Societe($this->db);
2631
2632 $objsoc->fetch($clonedObj->socid);
2633
2634 // Clean data
2635 $clonedObj->statut = 0;
2636 $clonedObj->status = 0;
2637 // Clean extrafields
2638 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2639 $extrafields->fetch_name_optionals_label($this->table_element);
2640 foreach ($clonedObj->array_options as $key => $option) {
2641 $shortkey = preg_replace('/options_/', '', $key);
2642 //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2643 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2644 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2645 unset($clonedObj->array_options[$key]);
2646 }
2647 }
2648 }
2649
2650 if (!getDolGlobalString('CONTRACT_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').".php")) {
2651 $this->error = 'ErrorSetupNotComplete';
2652 dol_syslog($this->error);
2653 return -1;
2654 }
2655
2656 // Set ref
2657 require_once DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').'.php';
2658 $obj = getDolGlobalString('CONTRACT_ADDON');
2659 $modContract = new $obj();
2660 '@phan-var-force ModelNumRefContracts $modContract';
2662 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2663
2664 // get extrafields so they will be clone
2665 foreach ($this->lines as $line) {
2666 $line->fetch_optionals($line->id);
2667 }
2668
2669 // Create clone
2670 $clonedObj->context['createfromclone'] = 'createfromclone';
2671 $result = $clonedObj->create($user);
2672 if ($result < 0) {
2673 $error++;
2674 $this->setErrorsFromObject($clonedObj);
2675 } else {
2676 // copy external contacts if same company
2677 if ($this->socid == $clonedObj->socid) {
2678 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2679 $error++;
2680 }
2681 }
2682 }
2683
2684 if (!$error) {
2685 foreach ($this->lines as $line) {
2686 $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_start, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit, $line->rang);
2687 if ($result < 0) {
2688 $error++;
2689 $this->setErrorsFromObject($clonedObj);
2690 }
2691 }
2692 }
2693
2694 if (!$error) {
2695 // Hook of thirdparty module
2696 if (is_object($hookmanager)) {
2697 $parameters = array(
2698 'objFrom' => $this,
2699 'clonedObj' => $clonedObj
2700 );
2701 $action = '';
2702 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2703 if ($reshook < 0) {
2704 $this->setErrorsFromObject($hookmanager);
2705 $error++;
2706 }
2707 }
2708 }
2709
2710 unset($clonedObj->context['createfromclone']);
2711
2712 // End
2713 if (!$error) {
2714 $this->db->commit();
2715 return $clonedObj->id;
2716 } else {
2717 $this->db->rollback();
2718 return -1;
2719 }
2720 }
2721
2722
2732 public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2733 {
2734 global $langs, $user;
2735
2736 $langs->load("agenda");
2737
2738 $now = dol_now();
2739
2740 $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2741
2742 $error = 0;
2743 $this->output = '';
2744 $this->error = '';
2745
2746 $contractlineprocessed = array();
2747 $contractignored = array();
2748 $contracterror = array();
2749
2750 dol_syslog(__METHOD__, LOG_DEBUG);
2751
2752 $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2753 $sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2754 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2755 $sql .= ' WHERE cd.fk_contrat = c.rowid';
2756 $sql .= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2757 $sql .= " AND cd.statut = 4";
2758 if ($thirdparty_id > 0) {
2759 $sql .= " AND c.fk_soc = ".((int) $thirdparty_id);
2760 }
2761 //print $sql;
2762
2763 $resql = $this->db->query($sql);
2764 if ($resql) {
2765 $num = $this->db->num_rows($resql);
2766
2767 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2768 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2769
2770 $i = 0;
2771 while ($i < $num) {
2772 $obj = $this->db->fetch_object($resql);
2773 if ($obj) {
2774 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2775 continue;
2776 }
2777
2778 // Load contract
2779 $object = new Contrat($this->db);
2780 $object->fetch($obj->rowid); // fetch also lines
2781
2782 if ($object->id <= 0) {
2783 $error++;
2784 $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2785 continue;
2786 }
2787
2788 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);
2789
2790 // Update expiration date of line
2791 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2792 $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2793 $duration_unit = preg_replace('/\d/', '', $obj->duration);
2794 //var_dump($expirationdate.' '.$enddatetoscan);
2795
2796 // Load linked ->linkedObjects (objects linked)
2797 // @TODO Comment this line and then make the search if there is n open invoice(s) by doing a dedicated SQL COUNT request to fill $contractcanceled.
2798 $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2799
2800 // Test if there is at least 1 open invoice
2801 if (isset($object->linkedObjects['facture']) && is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2802 // Sort array of linked invoices by ascending date
2803 usort($object->linkedObjects['facture'], array('Contrat', 'contractCmpDate'));
2804 //dol_sort_array($object->linkedObjects['facture'], 'date');
2805
2806 $someinvoicenotpaid = 0;
2807 foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2808 if ($invoice->statut == Facture::STATUS_DRAFT) {
2809 continue;
2810 } // Draft invoice are not invoice not paid
2811
2812 if (empty($invoice->paye)) {
2813 $someinvoicenotpaid++;
2814 }
2815 }
2816 if ($someinvoicenotpaid) {
2817 $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2818 $contractignored[$object->id] = $object->ref;
2819 continue;
2820 }
2821 }
2822
2823 if ($expirationdate && $expirationdate < $enddatetoscan) {
2824 dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2825 $newdate = $expirationdate;
2826 $protecti = 0; // $protecti is to avoid infinite loop
2827 while ($newdate < $enddatetoscan && $protecti < 1000) {
2828 $newdate = dol_time_plus_duree($newdate, (int) $duration_value, $duration_unit);
2829 $protecti++;
2830 }
2831
2832 if ($protecti < 1000) { // If not, there is a pb
2833 // We will update the end of date of contrat, so first we refresh contract data
2834 dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2835
2836 $this->db->begin();
2837
2838 $errorforlocaltransaction = 0;
2839
2840 $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2841 $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2842
2843 $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2844 $sqlupdate .= ' WHERE rowid = '.((int) $obj->lid);
2845 $resqlupdate = $this->db->query($sqlupdate);
2846 if ($resqlupdate) {
2847 $contractlineprocessed[$obj->lid] = $object->ref;
2848
2849 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
2850 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
2851 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $object->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
2852 $sqltoupdatecontract .= " WHERE rowid = ".((int) $object->id);
2853 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
2854 if (!$resqltoupdatecontract) {
2855 $this->error = $this->db->lasterror();
2856 $this->db->rollback();
2857 return -1;
2858 }
2859
2860 $actioncode = 'RENEW_CONTRACT';
2861 $now = dol_now();
2862
2863 // Create an event
2864 $actioncomm = new ActionComm($this->db);
2865 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2866 $actioncomm->code = 'AC_'.$actioncode;
2867 $actioncomm->label = $label;
2868 $actioncomm->datep = $now;
2869 $actioncomm->datef = $now;
2870 $actioncomm->percentage = -1; // Not applicable
2871 $actioncomm->socid = $object->socid;
2872 $actioncomm->authorid = $user->id; // User saving action
2873 $actioncomm->userownerid = $user->id; // Owner of action
2874 $actioncomm->fk_element = $object->id;
2875 $actioncomm->elementid = $object->id;
2876 $actioncomm->elementtype = 'contract';
2877 $actioncomm->note_private = $comment;
2878
2879 $ret = $actioncomm->create($user); // User creating action
2880 } else {
2881 $contracterror[$object->id] = $object->ref;
2882
2883 $error++;
2884 $errorforlocaltransaction++;
2885 $this->error = $this->db->lasterror();
2886 }
2887
2888 if (! $errorforlocaltransaction) {
2889 $this->db->commit();
2890 } else {
2891 $this->db->rollback();
2892 }
2893 } else {
2894 $error++;
2895 $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2896 dol_syslog($this->error, LOG_ERR);
2897 }
2898 }
2899 }
2900 $i++;
2901 }
2902 } else {
2903 $error++;
2904 $this->error = $this->db->lasterror();
2905 }
2906
2907 $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed) > 0 ? ' : '.implode(',', $contractlineprocessed) : '');
2908
2909 return ($error ? 1 : 0);
2910 }
2911
2919 public static function contractCmpDate($a, $b)
2920 {
2921 if ($a->date == $b->date) {
2922 return strcmp((string) $a->id, (string) $b->id);
2923 }
2924 return ($a->date < $b->date) ? -1 : 1;
2925 }
2926
2934 public function getKanbanView($option = '', $arraydata = null)
2935 {
2936 global $langs;
2937
2938 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2939
2940 $return = '<div class="box-flex-item box-flex-grow-zero">';
2941 $return .= '<div class="info-box info-box-sm">';
2942 $return .= '<span class="info-box-icon bg-infobox-action">';
2943 $return .= img_picto('', $this->picto);
2944 $return .= '</span>';
2945 $return .= '<div class="info-box-content">';
2946 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
2947 if ($selected >= 0) {
2948 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2949 }
2950 if (!empty($arraydata['thirdparty']) && $arraydata['thirdparty'] instanceof Societe) {
2951 $tmpthirdparty = $arraydata['thirdparty'];
2952 '@phan-var-force Societe $tmpthirdparty';
2953 $return .= '<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).'</div>';
2954 }
2955 $return .= '<br><span class="opacitymedium valignmiddle">'.$langs->trans("DateContract").' : </span><span class="info-box-label valignmiddle">'.dol_print_date($this->date_contrat, 'day').'</span>';
2956 $return .= '<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).'</div>';
2957 $return .= '</div>';
2958 $return .= '</div>';
2959 $return .= '</div>';
2960
2961 return $return;
2962 }
2963
2964 // @Todo getLibSignedStatus, LibSignedStatus
2965
2975 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
2976 {
2977 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
2978 }
2979}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
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...
deleteEcmFiles($mode=0)
Delete related files of object in database.
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.
fetchProject()
Load the project with id $this->fk_project into this->project.
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=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
static contractCmpDate($a, $b)
Used to sort lines by date.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
loadStateBoard()
Load the indicators this->nb for state board.
update_statut($user)
Update statut of contract according to services.
closeAll(User $user, $notrigger=0, $comment='', $nofetchlines=0)
Close all lines of a contract.
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=array(), $fk_unit=null, $rang=0)
Update a contract line.
getTicketsArray()
Create an array of associated tickets.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
deleteLine($idline, User $user)
Delete a contract line.
array_detail($status=-1)
Return list of line rowid.
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=array(), $fk_unit=null, $rang=0)
Ajoute une ligne de contrat en base.
update($user, $notrigger=0)
Update object into database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
__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 clickable name (with picto eventually)
info($id)
Charge les information d'ordre info dans l'objet contrat.
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.
fetch_lines($only_services=0, $loadalsotranslation=0, $noextrafields=0)
Load lines array into this->lines.
getIdServiceContact()
Return id des contacts clients de prestation.
Class to manage lines of contracts.
Class to manage Dolibarr database access.
const STATUS_DRAFT
Draft status.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
setSignedStatusCommon(User $user, int $status, int $notrigger=0, string $triggercode='')
Set signed status & call trigger with context message.
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_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:64
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90