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