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