dolibarr 21.0.0-alpha
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-2024 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 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' => 'Ref ext', '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 $this->db->begin();
474
475 // Load lines
476 $this->fetch_lines();
477
478 $now = dol_now();
479
480 $error = 0;
481
482 foreach ($this->lines as $contratline) {
483 // Close lines not already closed
484 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
485 $contratline->date_end_real = $now;
486 $contratline->date_cloture = $now; // For backward compatibility
487 $contratline->user_closing_id = $user->id;
488 $contratline->statut = ContratLigne::STATUS_CLOSED;
489 $result = $contratline->close_line($user, $now, $comment, $notrigger);
490 if ($result < 0) {
491 $error++;
492 $this->error = $contratline->error;
493 $this->errors = $contratline->errors;
494 break;
495 }
496 }
497 }
498
499 if (!$error && $this->statut == 0) {
500 $result = $this->validate($user, '', $notrigger);
501 if ($result < 0) {
502 $error++;
503 }
504 }
505
506 if (!$error) {
507 $this->db->commit();
508 return 1;
509 } else {
510 $this->db->rollback();
511 return -1;
512 }
513 }
514
523 public function validate(User $user, $force_number = '', $notrigger = 0)
524 {
525 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
526 global $conf;
527
528 $now = dol_now();
529
530 $error = 0;
531 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
532
533
534 $this->db->begin();
535
536 $this->fetch_thirdparty();
537
538 // A contract is validated so we can move thirdparty to status customer
539 if (!getDolGlobalString('CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
540 $result = $this->thirdparty->setAsCustomer();
541 }
542
543 // Define new ref
544 if ($force_number) {
545 $num = $force_number;
546 } elseif (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
547 $num = $this->getNextNumRef($this->thirdparty);
548 } else {
549 $num = $this->ref;
550 }
551 $this->newref = dol_sanitizeFileName($num);
552
553 if ($num) {
554 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
555 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
556
557 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
558 $resql = $this->db->query($sql);
559 if (!$resql) {
560 dol_print_error($this->db);
561 $error++;
562 $this->error = $this->db->lasterror();
563 }
564
565 // Trigger calls
566 if (!$error && !$notrigger) {
567 // Call trigger
568 $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
569 if ($result < 0) {
570 $error++;
571 }
572 // End call triggers
573 }
574
575 if (!$error) {
576 $this->oldref = $this->ref;
577
578 // Rename directory if dir was a temporary ref
579 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
580 // Now we rename also files into index
581 $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)."'";
582 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
583 $resql = $this->db->query($sql);
584 if (!$resql) {
585 $error++;
586 $this->error = $this->db->lasterror();
587 }
588 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'contract/".$this->db->escape($this->newref)."'";
589 $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
590 $resql = $this->db->query($sql);
591 if (!$resql) {
592 $error++;
593 $this->error = $this->db->lasterror();
594 }
595
596 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
597 $oldref = dol_sanitizeFileName($this->ref);
598 $newref = dol_sanitizeFileName($num);
599 $dirsource = $conf->contract->dir_output.'/'.$oldref;
600 $dirdest = $conf->contract->dir_output.'/'.$newref;
601 if (!$error && file_exists($dirsource)) {
602 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
603
604 if (@rename($dirsource, $dirdest)) {
605 dol_syslog("Rename ok");
606 // Rename docs starting with $oldref with $newref
607 $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
608 foreach ($listoffiles as $fileentry) {
609 $dirsource = $fileentry['name'];
610 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
611 $dirsource = $fileentry['path'].'/'.$dirsource;
612 $dirdest = $fileentry['path'].'/'.$dirdest;
613 @rename($dirsource, $dirdest);
614 }
615 }
616 }
617 }
618 }
619
620 // Set new ref and define current status
621 if (!$error) {
622 $this->ref = $num;
623 $this->status = self::STATUS_VALIDATED;
624 $this->statut = self::STATUS_VALIDATED; // deprecated
625 $this->date_validation = $now;
626 }
627 } else {
628 $error++;
629 }
630
631 if (!$error) {
632 $this->db->commit();
633 return 1;
634 } else {
635 $this->db->rollback();
636 return -1;
637 }
638 }
639
647 public function reopen($user, $notrigger = 0)
648 {
649 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
650
651 $now = dol_now();
652
653 $error = 0;
654 dol_syslog(get_class($this).'::reopen user='.$user->id);
655
656 $this->db->begin();
657
658 $this->fetch_thirdparty();
659
660 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
661 //$sql.= ", fk_user_valid = null, date_valid = null";
662 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
663
664 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
665 $resql = $this->db->query($sql);
666 if (!$resql) {
667 dol_print_error($this->db);
668 $error++;
669 $this->error = $this->db->lasterror();
670 }
671
672 // Trigger calls
673 if (!$error && !$notrigger) {
674 // Call trigger
675 $result = $this->call_trigger('CONTRACT_REOPEN', $user);
676 if ($result < 0) {
677 $error++;
678 }
679 // End call triggers
680 }
681
682 // Set new ref and define current status
683 if (!$error) {
684 $this->statut = self::STATUS_DRAFT;
685 $this->status = self::STATUS_DRAFT;
686 $this->date_validation = $now;
687 }
688
689 if (!$error) {
690 $this->db->commit();
691 return 1;
692 } else {
693 $this->db->rollback();
694 return -1;
695 }
696 }
697
709 public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '', $noextrafields = 0, $nolines = 0)
710 {
711 $result = -10;
712
713 $sql = "SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
714 $sql .= " ref_supplier, ref_customer,";
715 $sql .= " ref_ext,";
716 $sql .= " entity,";
717 $sql .= " signed_status,";
718 $sql .= " date_contrat as datecontrat,";
719 $sql .= " fk_user_author,";
720 $sql .= " fk_projet as fk_project,";
721 $sql .= " fk_commercial_signature, fk_commercial_suivi,";
722 $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
723 $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
724 if (!$id) {
725 $sql .= " WHERE entity IN (".getEntity('contract').")";
726 } else {
727 $sql .= " WHERE rowid = ".(int) $id;
728 }
729 if ($ref_customer) {
730 $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
731 }
732 if ($ref_supplier) {
733 $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
734 }
735 if ($ref) {
736 $sql .= " AND ref = '".$this->db->escape($ref)."'";
737 }
738
739 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
740 $resql = $this->db->query($sql);
741 if ($resql) {
742 $num = $this->db->num_rows($resql);
743 if ($num > 1) {
744 $this->error = 'Fetch found several records.';
745 dol_syslog($this->error, LOG_ERR);
746 $result = -2;
747 return 0;
748 } elseif ($num) { // $num = 1
749 $obj = $this->db->fetch_object($resql);
750 if ($obj) {
751 $this->id = $obj->rowid;
752 $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
753 $this->ref_customer = $obj->ref_customer;
754 $this->ref_supplier = $obj->ref_supplier;
755 $this->ref_ext = $obj->ref_ext;
756 $this->entity = $obj->entity;
757 $this->statut = $obj->status;
758 $this->status = $obj->status;
759 $this->signed_status = $obj->signed_status;
760
761 $this->date_contrat = $this->db->jdate($obj->datecontrat);
762 $this->date_creation = $this->db->jdate($obj->datecontrat);
763
764 $this->user_author_id = $obj->fk_user_author;
765
766 $this->commercial_signature_id = $obj->fk_commercial_signature;
767 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
768
769 $this->note_private = $obj->note_private;
770 $this->note_public = $obj->note_public;
771 $this->model_pdf = $obj->model_pdf;
772
773 $this->fk_projet = $obj->fk_project; // deprecated
774 $this->fk_project = $obj->fk_project;
775
776 $this->socid = $obj->thirdpartyid;
777 $this->fk_soc = $obj->thirdpartyid;
778 $this->last_main_doc = $obj->last_main_doc;
779 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
780
781 $this->db->free($resql);
782
783 // Retrieve all extrafields
784 // fetch optionals attributes and labels
785 if (empty($noextrafields)) {
786 $result = $this->fetch_optionals();
787 if ($result < 0) {
788 $this->error = $this->db->lasterror();
789 return -4;
790 }
791 }
792
793 // Lines
794 if (empty($nolines)) {
795 if ($result >= 0 && !empty($this->table_element_line)) {
796 $result = $this->fetch_lines();
797 if ($result < 0) {
798 $this->error = $this->db->lasterror();
799 return -3;
800 }
801 }
802 }
803
804 return $this->id;
805 } else {
806 dol_syslog(get_class($this)."::fetch Contract failed");
807 $this->error = "Fetch contract failed";
808 return -1;
809 }
810 } else {
811 dol_syslog(get_class($this)."::fetch Contract not found");
812 $this->error = "Contract not found";
813 return 0;
814 }
815 } else {
816 dol_syslog(get_class($this)."::fetch Error searching contract");
817 $this->error = $this->db->error();
818 return -1;
819 }
820 }
821
822 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
832 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
833 {
834 // phpcs:enable
835 $this->nbofservices = 0;
836 $this->nbofserviceswait = 0;
837 $this->nbofservicesopened = 0;
838 $this->nbofservicesexpired = 0;
839 $this->nbofservicesclosed = 0;
840
841 $total_ttc = 0;
842 $total_vat = 0;
843 $total_ht = 0;
844
845 $now = dol_now();
846
847 $this->lines = array();
848 $pos = 0;
849
850 // Selects contract lines related to a product
851 $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
852 $sql .= " d.rowid, d.fk_contrat, d.statut as status, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
853 $sql .= " d.total_ht,";
854 $sql .= " d.total_tva,";
855 $sql .= " d.total_localtax1,";
856 $sql .= " d.total_localtax2,";
857 $sql .= " d.total_ttc,";
858 $sql .= " d.info_bits, d.fk_product,";
859 $sql .= " d.date_ouverture_prevue as date_start,";
860 $sql .= " d.date_ouverture as date_start_real,";
861 $sql .= " d.date_fin_validite as date_end,";
862 $sql .= " d.date_cloture as date_end_real,";
863 $sql .= " d.fk_user_author,";
864 $sql .= " d.fk_user_ouverture,";
865 $sql .= " d.fk_user_cloture,";
866 $sql .= " d.fk_unit,";
867 $sql .= " d.product_type as type,";
868 $sql .= " d.rang";
869 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
870 $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
871 if ($only_services == 1) {
872 $sql .= " AND d.product_type = 1";
873 }
874 $sql .= " ORDER by d.rang ASC";
875
876 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
877 $result = $this->db->query($sql);
878 if ($result) {
879 $num = $this->db->num_rows($result);
880 $i = 0;
881
882 while ($i < $num) {
883 $objp = $this->db->fetch_object($result);
884
885 $line = new ContratLigne($this->db);
886
887 $line->id = $objp->rowid;
888 $line->ref = $objp->rowid;
889 $line->fk_contrat = $objp->fk_contrat;
890 $line->desc = $objp->description; // Description line
891 $line->qty = $objp->qty;
892 $line->vat_src_code = $objp->vat_src_code;
893 $line->tva_tx = $objp->tva_tx;
894 $line->localtax1_tx = $objp->localtax1_tx;
895 $line->localtax2_tx = $objp->localtax2_tx;
896 $line->localtax1_type = $objp->localtax1_type;
897 $line->localtax2_type = $objp->localtax2_type;
898 $line->subprice = $objp->subprice;
899 $line->statut = $objp->status;
900 $line->status = $objp->status;
901 $line->remise_percent = $objp->remise_percent;
902 $line->price_ht = $objp->price_ht;
903 $line->price = $objp->price_ht; // For backward compatibility
904 $line->total_ht = $objp->total_ht;
905 $line->total_tva = $objp->total_tva;
906 $line->total_localtax1 = $objp->total_localtax1;
907 $line->total_localtax2 = $objp->total_localtax2;
908 $line->total_ttc = $objp->total_ttc;
909 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
910 $line->info_bits = $objp->info_bits;
911 $line->type = $objp->type;
912
913 $line->fk_fournprice = $objp->fk_fournprice;
914 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
915 $line->pa_ht = $marginInfos[0];
916
917 $line->fk_user_author = $objp->fk_user_author;
918 $line->fk_user_ouverture = $objp->fk_user_ouverture;
919 $line->fk_user_cloture = $objp->fk_user_cloture;
920 $line->fk_unit = $objp->fk_unit;
921
922 $line->ref = $objp->product_ref; // deprecated
923 $line->product_ref = $objp->product_ref; // Product Ref
924 $line->product_type = $objp->product_type; // Product Type
925 $line->product_desc = $objp->product_desc; // Product Description
926 $line->product_label = $objp->product_label; // Product Label
927
928 $line->description = $objp->description;
929
930 $line->date_start = $this->db->jdate($objp->date_start);
931 $line->date_start_real = $this->db->jdate($objp->date_start_real);
932 $line->date_end = $this->db->jdate($objp->date_end);
933 $line->date_end_real = $this->db->jdate($objp->date_end_real);
934 // For backward compatibility
935 //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
936 //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
937 //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
938 //$line->date_cloture = $this->db->jdate($objp->date_cloture);
939 //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
940 //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
941 //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
942 //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
943
944 $line->rang = $objp->rang;
945
946 // Retrieve all extrafields for contract line
947 // fetch optionals attributes and labels
948 if (empty($noextrafields)) {
949 $line->fetch_optionals();
950 }
951
952 // multilangs
953 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
954 $tmpproduct = new Product($this->db);
955 $tmpproduct->fetch($objp->fk_product);
956 $tmpproduct->getMultiLangs();
957
958 $line->multilangs = $tmpproduct->multilangs;
959 }
960
961 $this->lines[$pos] = $line;
962
963 $this->lines_id_index_mapper[$line->id] = $pos;
964
965 //dol_syslog("1 ".$line->desc);
966 //dol_syslog("2 ".$line->product_desc);
967
968 if ($line->statut == ContratLigne::STATUS_INITIAL) {
969 $this->nbofserviceswait++;
970 }
971 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
972 $this->nbofservicesopened++;
973 }
974 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
975 $this->nbofservicesexpired++;
976 }
977 if ($line->statut == ContratLigne::STATUS_CLOSED) {
978 $this->nbofservicesclosed++;
979 }
980
981 // TODO Not saved into database
982 $total_ttc += $objp->total_ttc;
983 $total_vat += $objp->total_tva;
984 $total_ht += $objp->total_ht;
985
986 $i++;
987 $pos++;
988 }
989 $this->db->free($result);
990 } else {
991 dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
992 return -3;
993 }
994
995 // Now set the global properties on contract not stored into database.
996 $this->nbofservices = count($this->lines);
997 $this->total_ttc = (float) price2num($total_ttc);
998 $this->total_tva = (float) price2num($total_vat);
999 $this->total_ht = (float) price2num($total_ht);
1000
1001 return $this->lines;
1002 }
1003
1010 public function create($user)
1011 {
1012 global $conf, $langs, $mysoc;
1013
1014 // Check parameters
1015 $paramsok = 1;
1016 if ($this->commercial_signature_id <= 0) {
1017 $langs->load("commercial");
1018 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
1019 $paramsok = 0;
1020 }
1021 if ($this->commercial_suivi_id <= 0) {
1022 $langs->load("commercial");
1023 $this->error .= ($this->error ? "<br>" : '');
1024 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
1025 $paramsok = 0;
1026 }
1027 if (!$paramsok) {
1028 return -1;
1029 }
1030
1031
1032 $this->db->begin();
1033
1034 $now = dol_now();
1035
1036 // Insert contract
1037 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
1038 $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1039 $sql .= " ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1040 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
1041 $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
1042 $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
1043 $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
1044 $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
1045 $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
1046 $sql .= ", ".((int) $conf->entity);
1047 $sql .= ", ".((int) $this->signed_status);
1048 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
1049 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
1050 $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
1051 $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
1052 $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
1053 $sql .= ")";
1054 $resql = $this->db->query($sql);
1055
1056 if ($resql) {
1057 $error = 0;
1058
1059 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
1060
1061 // Load object modContract
1062 $module = (getDolGlobalString('CONTRACT_ADDON') ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
1063 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1064 $module = substr($module, 0, dol_strlen($module) - 4);
1065 }
1066 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1067 if ($result > 0) {
1068 $modCodeContract = new $module();
1069 '@phan-var-force ModelNumRefContracts $modCodeContrat';
1070
1071 if (!empty($modCodeContract->code_auto)) {
1072 // Force the ref to a draft value if numbering module is an automatic numbering
1073 $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1074 if ($this->db->query($sql)) {
1075 if ($this->id) {
1076 $this->ref = "(PROV".$this->id.")";
1077 }
1078 }
1079 }
1080 }
1081
1082 if (!$error) {
1083 $result = $this->insertExtraFields();
1084 if ($result < 0) {
1085 $error++;
1086 }
1087 }
1088
1089 // Insert business contacts ('SALESREPSIGN','contrat')
1090 if (!$error) {
1091 $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1092 if ($result < 0) {
1093 $error++;
1094 }
1095 }
1096
1097 // Insert business contacts ('SALESREPFOLL','contrat')
1098 if (!$error) {
1099 $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1100 if ($result < 0) {
1101 $error++;
1102 }
1103 }
1104
1105 if (!$error) {
1106 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1107 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1108 }
1109
1110 // Add object linked
1111 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1112 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1113 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, ...))
1114 foreach ($tmp_origin_id as $origin_id) {
1115 $ret = $this->add_object_linked($origin, $origin_id);
1116 if (!$ret) {
1117 $this->error = $this->db->lasterror();
1118 $error++;
1119 }
1120 }
1121 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1122 $origin_id = $tmp_origin_id;
1123 $ret = $this->add_object_linked($origin, $origin_id);
1124 if (!$ret) {
1125 $this->error = $this->db->lasterror();
1126 $error++;
1127 }
1128 }
1129 }
1130 }
1131
1132 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1133 $originforcontact = $this->origin;
1134 $originidforcontact = $this->origin_id;
1135 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1136 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1137 $exp = new Expedition($this->db);
1138 $exp->fetch($this->origin_id);
1139 $exp->fetchObjectLinked();
1140 if (count($exp->linkedObjectsIds['commande']) > 0) {
1141 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1142 $originforcontact = 'commande';
1143 $originidforcontact = $value;
1144 break; // We take first one
1145 }
1146 }
1147 }
1148
1149 $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";
1150 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1151
1152 $resqlcontact = $this->db->query($sqlcontact);
1153 if ($resqlcontact) {
1154 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1155 if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1156 continue; // ignore this, already forced previously
1157 }
1158
1159 $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
1160 }
1161 } else {
1162 dol_print_error($this->db);
1163 }
1164 }
1165 }
1166
1167 if (!$error) {
1168 // Call trigger
1169 $result = $this->call_trigger('CONTRACT_CREATE', $user);
1170 if ($result < 0) {
1171 $error++;
1172 }
1173 // End call triggers
1174
1175 if (!$error) {
1176 $this->db->commit();
1177 return $this->id;
1178 } else {
1179 dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1180 $this->db->rollback();
1181 return -3;
1182 }
1183 } else {
1184 $this->error = "Failed to add contract";
1185 dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1186 $this->db->rollback();
1187 return -2;
1188 }
1189 } else {
1190 $this->error = $langs->trans("UnknownError").": ".$this->db->error();
1191 dol_syslog(get_class($this)."::create - 10 - ".$this->error, LOG_ERR);
1192
1193 $this->db->rollback();
1194 return -1;
1195 }
1196 }
1197
1198
1205 public function delete($user)
1206 {
1207 global $conf;
1208
1209 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1210
1211 $error = 0;
1212
1213 $this->db->begin();
1214
1215 // Call trigger
1216 $result = $this->call_trigger('CONTRACT_DELETE', $user);
1217 if ($result < 0) {
1218 $error++;
1219 }
1220 // End call triggers
1221
1222 if (!$error) {
1223 // Delete linked contacts
1224 $res = $this->delete_linked_contact();
1225 if ($res < 0) {
1226 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1227 $error++;
1228 }
1229 }
1230
1231 if (!$error) {
1232 // Delete linked object
1233 $res = $this->deleteObjectLinked();
1234 if ($res < 0) {
1235 $error++;
1236 }
1237 }
1238
1239 // Delete lines
1240 if (!$error) {
1241 // Delete contratdet extrafields
1242 $main = MAIN_DB_PREFIX.'contratdet';
1243 $ef = $main."_extrafields";
1244 $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1245
1246 dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1247 $resql = $this->db->query($sql);
1248 if (!$resql) {
1249 $this->error = $this->db->error();
1250 $error++;
1251 }
1252 }
1253
1254 if (!$error) {
1255 // Delete contratdet
1256 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1257 $sql .= " WHERE fk_contrat=".((int) $this->id);
1258
1259 dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1260 $resql = $this->db->query($sql);
1261 if (!$resql) {
1262 $this->error = $this->db->error();
1263 $error++;
1264 }
1265 }
1266
1267 // Delete llx_ecm_files
1268 if (!$error) {
1269 $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
1270 $resql = $this->db->query($sql);
1271 if (!$resql) {
1272 $this->error = $this->db->lasterror();
1273 $this->errors[] = $this->error;
1274 $error++;
1275 }
1276 }
1277
1278 // Delete contract
1279 if (!$error) {
1280 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1281 $sql .= " WHERE rowid=".((int) $this->id);
1282
1283 dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1284 $resql = $this->db->query($sql);
1285 if (!$resql) {
1286 $this->error = $this->db->error();
1287 $error++;
1288 }
1289 }
1290
1291 // Removed extrafields
1292 if (!$error) {
1293 $result = $this->deleteExtraFields();
1294 if ($result < 0) {
1295 $error++;
1296 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1297 }
1298 }
1299
1300 if (!$error) {
1301 // We remove directory
1302 $ref = dol_sanitizeFileName($this->ref);
1303 if ($conf->contrat->dir_output) {
1304 $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1305 if (file_exists($dir)) {
1306 $res = @dol_delete_dir_recursive($dir);
1307 if (!$res) {
1308 $this->error = 'ErrorFailToDeleteDir';
1309 $error++;
1310 }
1311 }
1312 }
1313 }
1314
1315 if (!$error) {
1316 $this->db->commit();
1317 return 1;
1318 } else {
1319 $this->error = $this->db->lasterror();
1320 $this->db->rollback();
1321 return -1;
1322 }
1323 }
1324
1332 public function update($user, $notrigger = 0)
1333 {
1334 global $conf;
1335 $error = 0;
1336
1337 // Clean parameters
1338 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1339 $this->fk_commercial_signature = $this->commercial_signature_id;
1340 }
1341 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1342 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1343 }
1344 if (empty($this->socid) && $this->fk_soc > 0) {
1345 $this->socid = (int) $this->fk_soc;
1346 }
1347 if (empty($this->fk_project) && $this->projet > 0) {
1348 $this->fk_project = (int) $this->projet;
1349 }
1350
1351 if (isset($this->ref)) {
1352 $this->ref = trim($this->ref);
1353 }
1354 if (isset($this->ref_customer)) {
1355 $this->ref_customer = trim($this->ref_customer);
1356 }
1357 if (isset($this->ref_supplier)) {
1358 $this->ref_supplier = trim($this->ref_supplier);
1359 }
1360 if (isset($this->ref_ext)) {
1361 $this->ref_ext = trim($this->ref_ext);
1362 }
1363 if (isset($this->entity)) {
1364 $this->entity = (int) $this->entity;
1365 }
1366 if (isset($this->statut)) {
1367 $this->statut = (int) $this->statut;
1368 }
1369 if (isset($this->status)) {
1370 $this->status = (int) $this->status;
1371 }
1372 if (isset($this->socid)) {
1373 $this->socid = (int) $this->socid;
1374 }
1375 if (isset($this->fk_commercial_signature)) {
1376 $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1377 }
1378 if (isset($this->fk_commercial_suivi)) {
1379 $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
1380 }
1381 if (isset($this->note_private)) {
1382 $this->note_private = trim($this->note_private);
1383 }
1384 if (isset($this->note_public)) {
1385 $this->note_public = trim($this->note_public);
1386 }
1387 if (isset($this->import_key)) {
1388 $this->import_key = trim($this->import_key);
1389 }
1390 //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1391
1392 // $this->oldcopy must have been set by the caller of update
1393
1394 // Update request
1395 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1396 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1397 $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1398 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1399 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1400 $sql .= " entity=".((int) $conf->entity).",";
1401 $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1402 $sql .= " statut=".(isset($this->statut) ? $this->statut : (isset($this->status) ? $this->status : "null")).",";
1403 $sql .= " fk_soc=".($this->socid > 0 ? $this->socid : "null").",";
1404 $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1405 $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1406 $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1407 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1408 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1409 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1410 //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null");
1411 $sql .= " WHERE rowid=".((int) $this->id);
1412
1413 $this->db->begin();
1414
1415 $resql = $this->db->query($sql);
1416 if (!$resql) {
1417 $error++;
1418 $this->errors[] = "Error ".$this->db->lasterror();
1419 }
1420
1421 if (!$error) {
1422 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
1423 if ($result < 0) {
1424 $error++;
1425 }
1426 }
1427
1428 if (!$error && !$notrigger) {
1429 // Call triggers
1430 $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1431 if ($result < 0) {
1432 $error++;
1433 }
1434 // End call triggers
1435 }
1436
1437 // Commit or rollback
1438 if ($error) {
1439 foreach ($this->errors as $errmsg) {
1440 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1441 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1442 }
1443 $this->db->rollback();
1444 return -1 * $error;
1445 } else {
1446 $this->db->commit();
1447 return 1;
1448 }
1449 }
1450
1451
1475 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)
1476 {
1477 global $user, $langs, $conf, $mysoc;
1478 $error = 0;
1479
1480 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");
1481
1482 // Check parameters
1483 if ($fk_product <= 0 && empty($desc)) {
1484 $this->error = "ErrorDescRequiredForFreeProductLines";
1485 return -1;
1486 }
1487
1488 if ($this->statut >= 0) {
1489 // Clean parameters
1490 $pu_ht = price2num($pu_ht);
1491 $pu_ttc = price2num($pu_ttc);
1492 $pa_ht = price2num($pa_ht);
1493
1494 // Clean vat code
1495 $reg = array();
1496 $vat_src_code = '';
1497 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1498 $vat_src_code = $reg[1];
1499 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code into vatrate.
1500 }
1501 $txtva = price2num($txtva);
1502 $txlocaltax1 = price2num($txlocaltax1);
1503 $txlocaltax2 = price2num($txlocaltax2);
1504
1505 $remise_percent = price2num($remise_percent);
1506 $qty = price2num($qty);
1507 if (empty($qty)) {
1508 $qty = 1;
1509 }
1510 if (empty($info_bits)) {
1511 $info_bits = 0;
1512 }
1513 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1514 $pu_ht = 0;
1515 }
1516 if (empty($pu_ttc)) {
1517 $pu_ttc = 0;
1518 }
1519 if (empty($txtva) || !is_numeric($txtva)) {
1520 $txtva = 0;
1521 }
1522 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1523 $txlocaltax1 = 0;
1524 }
1525 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1526 $txlocaltax2 = 0;
1527 }
1528
1529 if ($price_base_type == 'HT') {
1530 $pu = $pu_ht;
1531 } else {
1532 $pu = $pu_ttc;
1533 }
1534
1535 // Check parameters
1536 if (empty($remise_percent)) {
1537 $remise_percent = 0;
1538 }
1539 if (empty($rang)) {
1540 $rang = 0;
1541 }
1542
1543 if ($date_start && $date_end && $date_start > $date_end) {
1544 $langs->load("errors");
1545 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1546 return -1;
1547 }
1548
1549 $this->db->begin();
1550
1551 $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1552
1553 // Calcul du total TTC et de la TVA pour la ligne a partir de
1554 // qty, pu, remise_percent et txtva
1555 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1556 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1557
1558 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1559 $total_ht = $tabprice[0];
1560 $total_tva = $tabprice[1];
1561 $total_ttc = $tabprice[2];
1562 $total_localtax1 = $tabprice[9];
1563 $total_localtax2 = $tabprice[10];
1564
1565 $localtax1_type = $localtaxes_type[0];
1566 $localtax2_type = $localtaxes_type[2];
1567
1568 // TODO A virer
1569 // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1570 $remise = 0;
1571 $price = price2num(round($pu_ht, 2));
1572 if (dol_strlen(price2num($remise_percent)) > 0) {
1573 $remise = round(($pu_ht * $remise_percent / 100), 2);
1574 $price = $pu_ht - $remise;
1575 }
1576
1577 if (empty($pa_ht)) {
1578 $pa_ht = 0;
1579 }
1580
1581
1582 // if buy price not defined, define buyprice as configured in margin admin
1583 if ($pa_ht == 0) {
1584 $result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product);
1585 if ($result < 0) {
1586 return -1;
1587 } else {
1588 $pa_ht = $result;
1589 }
1590 }
1591
1592 // Insertion dans la base
1593 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1594 $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1595 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1596 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1597 $sql .= " info_bits,";
1598 $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1599 if ($date_start > 0) {
1600 $sql .= ",date_ouverture_prevue";
1601 }
1602 if ($date_end > 0) {
1603 $sql .= ",date_fin_validite";
1604 }
1605 $sql .= ", fk_unit";
1606 $sql .= ", rang";
1607 $sql .= ") VALUES (";
1608 $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1609 $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1610 $sql .= " ".((float) $qty).",";
1611 $sql .= " ".((float) $txtva).",";
1612 $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1613 $sql .= " ".((float) $txlocaltax1).",";
1614 $sql .= " ".((float) $txlocaltax2).",";
1615 $sql .= " '".$this->db->escape($localtax1_type)."',";
1616 $sql .= " '".$this->db->escape($localtax2_type)."',";
1617 $sql .= " ".price2num($remise_percent).",";
1618 $sql .= " ".price2num($pu_ht).",";
1619 $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1620 $sql .= " ".((int) $info_bits).",";
1621 $sql .= " ".price2num($price).",".price2num($remise).",";
1622 if (isset($fk_fournprice)) {
1623 $sql .= ' '.((int) $fk_fournprice).',';
1624 } else {
1625 $sql .= ' null,';
1626 }
1627 if (isset($pa_ht)) {
1628 $sql .= ' '.price2num($pa_ht);
1629 } else {
1630 $sql .= ' null';
1631 }
1632 if ($date_start > 0) {
1633 $sql .= ",'".$this->db->idate($date_start)."'";
1634 }
1635 if ($date_end > 0) {
1636 $sql .= ",'".$this->db->idate($date_end)."'";
1637 }
1638 $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1639 $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1640 $sql .= ")";
1641
1642 $resql = $this->db->query($sql);
1643 if ($resql) {
1644 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1645
1646 if (!$error) {
1647 $contractline = new ContratLigne($this->db);
1648 $contractline->array_options = $array_options;
1649 $contractline->id = $contractlineid;
1650 $result = $contractline->insertExtraFields();
1651 if ($result < 0) {
1652 $this->errors = array_merge($this->errors, $contractline->errors);
1653 $this->error = $contractline->error;
1654 $error++;
1655 }
1656 }
1657
1658 if (empty($error)) {
1659 // Call trigger
1660 $this->context['line_id'] = $contractlineid;
1661 $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1662 if ($result < 0) {
1663 $error++;
1664 }
1665 // End call triggers
1666 }
1667
1668 if ($error) {
1669 $this->db->rollback();
1670 return -1;
1671 } else {
1672 $this->db->commit();
1673 return $contractlineid;
1674 }
1675 } else {
1676 $this->db->rollback();
1677 $this->error = $this->db->error()." sql=".$sql;
1678 return -1;
1679 }
1680 } else {
1681 dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1682 return -2;
1683 }
1684 }
1685
1710 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)
1711 {
1712 global $user, $conf, $langs, $mysoc;
1713
1714 $error = 0;
1715
1716 // Clean parameters
1717 $qty = trim((string) $qty);
1718 $desc = trim($desc);
1719 $desc = trim($desc);
1720 $price = price2num($pu);
1721 $tvatx = price2num($tvatx);
1722 $localtax1tx = price2num($localtax1tx);
1723 $localtax2tx = price2num($localtax2tx);
1724 $pa_ht = price2num($pa_ht);
1725 if (empty($fk_fournprice)) {
1726 $fk_fournprice = 0;
1727 }
1728 if (empty($rang)) {
1729 $rang = 0;
1730 }
1731
1732 $subprice = $price;
1733 $remise = 0;
1734 if (dol_strlen(price2num($remise_percent)) > 0) {
1735 $remise = round(($pu * $remise_percent / 100), 2);
1736 $price = $pu - $remise;
1737 } else {
1738 $remise_percent = 0;
1739 }
1740
1741 if ($date_start && $date_end && $date_start > $date_end) {
1742 $langs->load("errors");
1743 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1744 return -1;
1745 }
1746
1747 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");
1748
1749 $this->db->begin();
1750
1751 // Calcul du total TTC et de la TVA pour la ligne a partir de
1752 // qty, pu, remise_percent et tvatx
1753 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1754 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1755
1756 $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1757 $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1758
1759 $tabprice = calcul_price_total($qty, $pu, $remise_percent, (float) price2num($tvatx), $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1760 $total_ht = $tabprice[0];
1761 $total_tva = $tabprice[1];
1762 $total_ttc = $tabprice[2];
1763 $total_localtax1 = $tabprice[9];
1764 $total_localtax2 = $tabprice[10];
1765
1766 $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1767 $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1768
1769 // TODO A virer
1770 // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1771 $remise = 0;
1772 $price = price2num(round($pu, 2));
1773 if (dol_strlen(price2num($remise_percent)) > 0) {
1774 $remise = round(($pu * $remise_percent / 100), 2);
1775 $price = $pu - $remise;
1776 }
1777
1778 if (empty($pa_ht)) {
1779 $pa_ht = 0;
1780 }
1781
1782 // if buy price not defined, define buyprice as configured in margin admin
1783 if ($pa_ht == 0) {
1784 $result = $this->defineBuyPrice($pu, $remise_percent);
1785 if ($result < 0) {
1786 return -1;
1787 } else {
1788 $pa_ht = $result;
1789 }
1790 }
1791
1792 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1793 $sql .= ",price_ht = ".((float) price2num($price));
1794 $sql .= ",subprice = ".((float) price2num($subprice));
1795 $sql .= ",remise = ".((float) price2num($remise));
1796 $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1797 $sql .= ",qty = ".((float) $qty);
1798 $sql .= ",tva_tx = ".((float) price2num($tvatx));
1799 $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1800 $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1801 $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1802 $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1803 $sql .= ", total_ht = ".((float) price2num($total_ht));
1804 $sql .= ", total_tva = ".((float) price2num($total_tva));
1805 $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1806 $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1807 $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1808 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1809 $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1810 if ($date_start > 0) {
1811 $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1812 } else {
1813 $sql .= ",date_ouverture_prevue = null";
1814 }
1815 if ($date_end > 0) {
1816 $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1817 } else {
1818 $sql .= ",date_fin_validite = null";
1819 }
1820 if ($date_start_real > 0) {
1821 $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1822 } else {
1823 $sql .= ",date_ouverture = null";
1824 }
1825 if ($date_end_real > 0) {
1826 $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1827 } else {
1828 $sql .= ",date_cloture = null";
1829 }
1830 $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1831 $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1832 $sql .= " WHERE rowid = ".((int) $rowid);
1833
1834 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1835 $result = $this->db->query($sql);
1836 if ($result) {
1837 if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1838 $contractline = new ContratLigne($this->db);
1839 $contractline->fetch($rowid);
1840
1841 // We replace values in $contractline->array_options only for entries defined into $array_options
1842 foreach ($array_options as $key => $value) {
1843 $contractline->array_options[$key] = $array_options[$key];
1844 }
1845
1846 $result = $contractline->insertExtraFields();
1847 if ($result < 0) {
1848 $this->errors[] = $contractline->error;
1849 $error++;
1850 }
1851 }
1852
1853 if (empty($error)) {
1854 // Call trigger
1855 $this->context['line_id'] = $rowid;
1856 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1857 if ($result < 0) {
1858 $this->db->rollback();
1859 return -3;
1860 }
1861 // End call triggers
1862
1863 $this->db->commit();
1864 return 1;
1865 } else {
1866 $this->db->rollback();
1867 return -1;
1868 }
1869 } else {
1870 $this->db->rollback();
1871 $this->error = $this->db->error();
1872 dol_syslog(get_class($this)."::updateline Erreur -1");
1873 return -1;
1874 }
1875 }
1876
1884 public function deleteLine($idline, User $user)
1885 {
1886 $error = 0;
1887
1888 if ($this->statut >= 0) {
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 (empty($error)) {
1921 $this->db->commit();
1922 return 1;
1923 } else {
1924 dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1925 $this->db->rollback();
1926 return -1;
1927 }
1928 } else {
1929 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1930 return -2;
1931 }
1932 }
1933
1934
1935 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1943 public function update_statut($user)
1944 {
1945 // phpcs:enable
1946 dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1947
1948 // If draft, we keep it (should not happen)
1949 if ($this->statut == 0) {
1950 return 1;
1951 }
1952
1953 // Load $this->lines array
1954 // $this->fetch_lines();
1955
1956 // $newstatut=1;
1957 // foreach($this->lines as $key => $contractline)
1958 // {
1959 // // if ($contractline) // Loop on each service
1960 // }
1961
1962 return 1;
1963 }
1964
1965
1972 public function getLibStatut($mode)
1973 {
1974 return $this->LibStatut($this->statut, $mode);
1975 }
1976
1977 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1985 public function LibStatut($status, $mode)
1986 {
1987 // phpcs:enable
1988 global $langs;
1989
1990 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1991 global $langs;
1992 $langs->load("contracts");
1993 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1994 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1995 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1996 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1997 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1998 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1999 }
2000
2001 $statusType = 'status'.$status;
2002 if ($status == self::STATUS_VALIDATED) {
2003 $statusType = 'status6';
2004 }
2005
2006 if ($mode == 4 || $mode == 6 || $mode == 7) {
2007 $text = '';
2008 if ($mode == 4) {
2009 $text = '<span class="hideonsmartphone">';
2010 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2011 $text .= ' '.$langs->trans("Services");
2012 $text .= ': &nbsp; &nbsp; ';
2013 $text .= '</span>';
2014 }
2015 $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
2016 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2017 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2018 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2019 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2020 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2021 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2022 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
2023 $text .= ($mode == 7 ? '</span>' : '');
2024 if (getDolGlobalString('CONTRACT_SHOW_SIGNATURE_STATUS_WITH_SERVICE_STATUS')) {
2025 $text .= is_null($this->signed_status) ? '' : ' '.$this->getLibSignedStatus(5);
2026 }
2027 return $text;
2028 } else {
2029 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2030 }
2031 }
2032
2039 public function getTooltipContentArray($params)
2040 {
2041 global $conf, $langs, $user;
2042
2043 $langs->load('contracts');
2044
2045 $datas = [];
2046 $nofetch = !empty($params['nofetch']);
2047
2048 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2049 return ['optimize' => $langs->trans("ShowContract")];
2050 }
2051 if ($user->hasRight('contrat', 'lire')) {
2052 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2053 /* Status of a contract is status of all services, so disabled
2054 if (isset($this->statut)) {
2055 $label .= ' '.$this->getLibStatut(5);
2056 }*/
2057 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2058 if (!$nofetch) {
2059 $langs->load('companies');
2060 if (empty($this->thirdparty)) {
2061 $this->fetch_thirdparty();
2062 }
2063 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2064 }
2065 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2066 if (!$nofetch) {
2067 $langs->load('project');
2068 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2069 $res = $this->fetchProject();
2070 if ($res > 0 && $this->project instanceof Project) {
2071 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
2072 }
2073 }
2074 }
2075 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2076 if (!empty($this->total_ht)) {
2077 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2078 }
2079 if (!empty($this->total_tva)) {
2080 $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2081 }
2082 if (!empty($this->total_ttc)) {
2083 $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2084 }
2085 }
2086 return $datas;
2087 }
2088
2098 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2099 {
2100 global $conf, $langs, $user, $hookmanager;
2101
2102 $result = '';
2103
2104 $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2105
2106 //if ($option !== 'nolink')
2107 //{
2108 // Add param to save lastsearch_values or not
2109 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2110 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2111 $add_save_lastsearch_values = 1;
2112 }
2113 if ($add_save_lastsearch_values) {
2114 $url .= '&save_lastsearch_values=1';
2115 }
2116 //}
2117 $params = [
2118 'id' => $this->id,
2119 'objecttype' => $this->element,
2120 'nofetch' => 1,
2121 ];
2122 $classfortooltip = 'classfortooltip';
2123 $dataparams = '';
2124 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2125 $classfortooltip = 'classforajaxtooltip';
2126 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2127 $label = '';
2128 } else {
2129 $label = implode($this->getTooltipContentArray($params));
2130 }
2131
2132 $linkclose = '';
2133 if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2134 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2135 $label = $langs->trans("ShowContract");
2136 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2137 }
2138 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2139 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2140 }
2141 $linkstart = '<a href="'.$url.'"';
2142 $linkstart .= $linkclose.'>';
2143 $linkend = '</a>';
2144
2145 $result .= $linkstart;
2146 if ($withpicto) {
2147 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2148 }
2149 if ($withpicto != 2) {
2150 $result .= ($this->ref ? $this->ref : $this->id);
2151 }
2152 $result .= $linkend;
2153
2154 global $action;
2155 $hookmanager->initHooks(array('contractdao'));
2156 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2157 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2158 if ($reshook > 0) {
2159 $result = $hookmanager->resPrint;
2160 } else {
2161 $result .= $hookmanager->resPrint;
2162 }
2163
2164 return $result;
2165 }
2166
2173 public function info($id)
2174 {
2175 $sql = "SELECT c.rowid, c.ref, c.datec,";
2176 $sql .= " c.tms as date_modification,";
2177 $sql .= " fk_user_author";
2178 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2179 $sql .= " WHERE c.rowid = ".((int) $id);
2180
2181 $result = $this->db->query($sql);
2182 if ($result) {
2183 if ($this->db->num_rows($result)) {
2184 $obj = $this->db->fetch_object($result);
2185
2186 $this->id = $obj->rowid;
2187 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2188
2189 $this->user_creation_id = $obj->fk_user_author;
2190 $this->date_creation = $this->db->jdate($obj->datec);
2191 $this->date_modification = $this->db->jdate($obj->date_modification);
2192 }
2193
2194 $this->db->free($result);
2195 } else {
2196 dol_print_error($this->db);
2197 }
2198 }
2199
2200 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2207 public function array_detail($status = -1)
2208 {
2209 // phpcs:enable
2210 $tab = array();
2211
2212 $sql = "SELECT cd.rowid";
2213 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2214 $sql .= " WHERE fk_contrat =".((int) $this->id);
2215 if ($status >= 0) {
2216 $sql .= " AND statut = ".((int) $status);
2217 }
2218
2219 dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2220 $resql = $this->db->query($sql);
2221 if ($resql) {
2222 $num = $this->db->num_rows($resql);
2223 $i = 0;
2224 while ($i < $num) {
2225 $obj = $this->db->fetch_object($resql);
2226 $tab[$i] = $obj->rowid;
2227 $i++;
2228 }
2229 return $tab;
2230 } else {
2231 $this->error = $this->db->error();
2232 return -1;
2233 }
2234 }
2235
2245 public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2246 {
2247 $tab = array();
2248
2249 $sql = "SELECT c.rowid";
2250 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2251 if (!empty($product_categories)) {
2252 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2253 $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)).")";
2254 }
2255 $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2256 $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2257 $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2258 $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2259 $sql .= " GROUP BY c.rowid";
2260
2261 dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2262 $resql = $this->db->query($sql);
2263 if ($resql) {
2264 $num = $this->db->num_rows($resql);
2265 $i = 0;
2266 while ($i < $num) {
2267 $obj = $this->db->fetch_object($resql);
2268 $contrat = new Contrat($this->db);
2269 $contrat->fetch($obj->rowid);
2270 $tab[$contrat->id] = $contrat;
2271 $i++;
2272 }
2273 return $tab;
2274 } else {
2275 $this->error = $this->db->lasterror();
2276 return -1;
2277 }
2278 }
2279
2280
2281 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2289 public function load_board($user, $mode)
2290 {
2291 // phpcs:enable
2292 global $conf, $langs;
2293
2294 $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2295 $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2296 $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2297 if (!$user->hasRight('societe', 'client', 'voir')) {
2298 $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2299 }
2300
2301 if ($mode == 'inactive') {
2302 $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2303 $sql .= $this->from;
2304 $sql .= " WHERE c.statut = 1";
2305 $sql .= " AND c.rowid = cd.fk_contrat";
2306 $sql .= " AND cd.statut = 0";
2307 } elseif ($mode == 'expired') {
2308 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2309 $sql .= $this->from;
2310 $sql .= " WHERE c.statut = 1";
2311 $sql .= " AND c.rowid = cd.fk_contrat";
2312 $sql .= " AND cd.statut = 4";
2313 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2314 } elseif ($mode == 'active') {
2315 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2316 $sql .= $this->from;
2317 $sql .= " WHERE c.statut = 1";
2318 $sql .= " AND c.rowid = cd.fk_contrat";
2319 $sql .= " AND cd.statut = 4";
2320 //$datetouse = dol_now();
2321 //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2322 }
2323 $sql .= " AND c.fk_soc = s.rowid";
2324 $sql .= " AND c.entity = ".((int) $conf->entity);
2325 if ($user->socid) {
2326 $sql .= " AND c.fk_soc = ".((int) $user->socid);
2327 }
2328 if (!$user->hasRight('societe', 'client', 'voir')) {
2329 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2330 }
2331
2332 $resql = $this->db->query($sql);
2333 if ($resql) {
2334 $langs->load("contracts");
2335 $now = dol_now();
2336
2337 if ($mode == 'inactive') {
2338 $warning_delay = $conf->contract->services->inactifs->warning_delay;
2339 $label = $langs->trans("BoardNotActivatedServices");
2340 $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2341 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2342 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2343 } elseif ($mode == 'active') {
2344 $warning_delay = $conf->contract->services->expires->warning_delay;
2345 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2346 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2347 $label = $langs->trans("BoardExpiredServices");
2348 $labelShort = $langs->trans("BoardExpiredServicesShort");
2349 } else {
2350 $warning_delay = $conf->contract->services->expires->warning_delay;
2351 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&sortfield=cd.date_fin_validite&sortorder=asc';
2352 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2353 $label = $langs->trans("BoardRunningServices");
2354 $labelShort = $langs->trans("BoardRunningServicesShort");
2355 }
2356
2357 $response = new WorkboardResponse();
2358 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2359 $response->label = $label;
2360 $response->labelShort = $labelShort;
2361 $response->url = $url;
2362 $response->url_late = $url_late;
2363 $response->img = img_object('', "contract");
2364
2365 while ($obj = $this->db->fetch_object($resql)) {
2366 $response->nbtodo++;
2367
2368 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2369 $response->nbtodolate++;
2370 }
2371 }
2372
2373 return $response;
2374 } else {
2375 dol_print_error($this->db);
2376 $this->error = $this->db->error();
2377 return -1;
2378 }
2379 }
2380
2386 public function loadStateBoard()
2387 {
2388 global $conf, $user;
2389
2390 $this->nb = array();
2391 $clause = "WHERE";
2392
2393 $sql = "SELECT count(c.rowid) as nb";
2394 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2395 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2396 if (!$user->hasRight('societe', 'client', 'voir')) {
2397 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2398 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2399 $clause = "AND";
2400 }
2401 $sql .= " ".$clause." c.entity = ".$conf->entity;
2402
2403 $resql = $this->db->query($sql);
2404 if ($resql) {
2405 while ($obj = $this->db->fetch_object($resql)) {
2406 $this->nb["contracts"] = $obj->nb;
2407 }
2408 $this->db->free($resql);
2409 return 1;
2410 } else {
2411 dol_print_error($this->db);
2412 $this->error = $this->db->error();
2413 return -1;
2414 }
2415 }
2416
2417
2418 /* gestion des contacts d'un contrat */
2419
2425 public function getIdBillingContact()
2426 {
2427 return $this->getIdContact('external', 'BILLING');
2428 }
2429
2435 public function getIdServiceContact()
2436 {
2437 return $this->getIdContact('external', 'SERVICE');
2438 }
2439
2440
2448 public function initAsSpecimen()
2449 {
2450 global $user, $langs, $conf;
2451
2452 // Load array of products prodids
2453 $num_prods = 0;
2454 $prodids = array();
2455 $sql = "SELECT rowid";
2456 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2457 $sql .= " WHERE entity IN (".getEntity('product').")";
2458 $sql .= " AND tosell = 1";
2459 $sql .= $this->db->plimit(100);
2460
2461 $resql = $this->db->query($sql);
2462 if ($resql) {
2463 $num_prods = $this->db->num_rows($resql);
2464 $i = 0;
2465 while ($i < $num_prods) {
2466 $i++;
2467 $row = $this->db->fetch_row($resql);
2468 $prodids[$i] = $row[0];
2469 }
2470 }
2471
2472 // Initialise parameters
2473 $this->id = 0;
2474 $this->specimen = 1;
2475
2476 $this->ref = 'SPECIMEN';
2477 $this->ref_customer = 'SPECIMENCUST';
2478 $this->ref_supplier = 'SPECIMENSUPP';
2479 $this->socid = 1;
2480 $this->status = 0;
2481 $this->date_creation = (dol_now() - 3600 * 24 * 7);
2482 $this->date_contrat = dol_now();
2483 $this->commercial_signature_id = 1;
2484 $this->commercial_suivi_id = 1;
2485 $this->note_private = 'This is a comment (private)';
2486 $this->note_public = 'This is a comment (public)';
2487 $this->fk_project = 0;
2488 // Lines
2489 $nbp = 5;
2490 $xnbp = 0;
2491 while ($xnbp < $nbp) {
2492 $line = new ContratLigne($this->db);
2493 $line->qty = 1;
2494 $line->subprice = 100;
2495 $line->tva_tx = 19.6;
2496 $line->remise_percent = 10;
2497 $line->total_ht = 90;
2498 $line->total_ttc = 107.64; // 90 * 1.196
2499 $line->total_tva = 17.64;
2500 $line->date_start = dol_now() - 500000;
2501 $line->date_start_real = dol_now() - 200000;
2502 $line->date_end = dol_now() + 500000;
2503 $line->date_end_real = dol_now() - 100000;
2504 if ($num_prods > 0) {
2505 $prodid = mt_rand(1, $num_prods);
2506 $line->fk_product = $prodids[$prodid];
2507 }
2508 $this->lines[$xnbp] = $line;
2509 $xnbp++;
2510 }
2511
2512 return 1;
2513 }
2514
2520 public function getLinesArray()
2521 {
2522 return $this->fetch_lines();
2523 }
2524
2530 public function getTicketsArray()
2531 {
2532 global $user;
2533
2534 $ticket = new Ticket($this->db);
2535 $nbTicket = $ticket->fetchAll($user, 'ASC', 't.datec', 0, 0, 0, array('t.fk_contract' => $this->id));
2536
2537 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2538 }
2539
2540
2552 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2553 {
2554 global $conf, $langs;
2555
2556 if (!dol_strlen($modele)) {
2557 $modele = ''; // No doc template/generation by default
2558
2559 if (!empty($this->model_pdf)) {
2560 $modele = $this->model_pdf;
2561 } elseif (getDolGlobalString('CONTRACT_ADDON_PDF')) {
2562 $modele = getDolGlobalString('CONTRACT_ADDON_PDF');
2563 }
2564 }
2565
2566 if (empty($modele)) {
2567 return 0;
2568 } else {
2569 $langs->load("contracts");
2570 $outputlangs->load("products");
2571
2572 $modelpath = "core/modules/contract/doc/";
2573 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2574 }
2575 }
2576
2585 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2586 {
2587 $tables = array(
2588 'contrat'
2589 );
2590
2591 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2592 }
2593
2602 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2603 {
2604 $tables = array(
2605 'contratdet'
2606 );
2607
2608 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2609 }
2610
2619 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2620 {
2621 global $db, $langs, $conf, $hookmanager, $extrafields;
2622
2623 dol_include_once('/projet/class/project.class.php');
2624
2625 $error = 0;
2626
2627 $this->fetch($this->id);
2628
2629 // Load dest object
2630 $clonedObj = clone $this;
2631 $clonedObj->socid = $socid;
2632
2633 $this->db->begin();
2634
2635 $objsoc = new Societe($this->db);
2636
2637 $objsoc->fetch($clonedObj->socid);
2638
2639 // Clean data
2640 $clonedObj->statut = 0;
2641 // Clean extrafields
2642 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2643 $extrafields->fetch_name_optionals_label($this->table_element);
2644 foreach ($clonedObj->array_options as $key => $option) {
2645 $shortkey = preg_replace('/options_/', '', $key);
2646 //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2647 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2648 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2649 unset($clonedObj->array_options[$key]);
2650 }
2651 }
2652 }
2653
2654 if (!getDolGlobalString('CONTRACT_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').".php")) {
2655 $this->error = 'ErrorSetupNotComplete';
2656 dol_syslog($this->error);
2657 return -1;
2658 }
2659
2660 // Set ref
2661 require_once DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').'.php';
2662 $obj = getDolGlobalString('CONTRACT_ADDON');
2663 $modContract = new $obj();
2664 '@phan-var-force ModelNumRefContracts $modContract';
2665 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2666
2667 // get extrafields so they will be clone
2668 foreach ($this->lines as $line) {
2669 $line->fetch_optionals($line->id);
2670 }
2671
2672 // Create clone
2673 $clonedObj->context['createfromclone'] = 'createfromclone';
2674 $result = $clonedObj->create($user);
2675 if ($result < 0) {
2676 $error++;
2677 $this->error = $clonedObj->error;
2678 $this->errors[] = $clonedObj->error;
2679 } else {
2680 // copy external contacts if same company
2681 if ($this->socid == $clonedObj->socid) {
2682 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2683 $error++;
2684 }
2685 }
2686 }
2687
2688 if (!$error) {
2689 foreach ($this->lines as $line) {
2690 $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);
2691 if ($result < 0) {
2692 $error++;
2693 $this->error = $clonedObj->error;
2694 $this->errors[] = $clonedObj->error;
2695 }
2696 }
2697 }
2698
2699 if (!$error) {
2700 // Hook of thirdparty module
2701 if (is_object($hookmanager)) {
2702 $parameters = array(
2703 'objFrom' => $this,
2704 'clonedObj' => $clonedObj
2705 );
2706 $action = '';
2707 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2708 if ($reshook < 0) {
2709 $this->setErrorsFromObject($hookmanager);
2710 $error++;
2711 }
2712 }
2713 }
2714
2715 unset($clonedObj->context['createfromclone']);
2716
2717 // End
2718 if (!$error) {
2719 $this->db->commit();
2720 return $clonedObj->id;
2721 } else {
2722 $this->db->rollback();
2723 return -1;
2724 }
2725 }
2726
2727
2737 public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2738 {
2739 global $langs, $user;
2740
2741 $langs->load("agenda");
2742
2743 $now = dol_now();
2744
2745 $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2746
2747 $error = 0;
2748 $this->output = '';
2749 $this->error = '';
2750
2751 $contractlineprocessed = array();
2752 $contractignored = array();
2753 $contracterror = array();
2754
2755 dol_syslog(__METHOD__, LOG_DEBUG);
2756
2757 $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2758 $sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2759 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2760 $sql .= ' WHERE cd.fk_contrat = c.rowid';
2761 $sql .= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2762 $sql .= " AND cd.statut = 4";
2763 if ($thirdparty_id > 0) {
2764 $sql .= " AND c.fk_soc = ".((int) $thirdparty_id);
2765 }
2766 //print $sql;
2767
2768 $resql = $this->db->query($sql);
2769 if ($resql) {
2770 $num = $this->db->num_rows($resql);
2771
2772 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2773
2774 $i = 0;
2775 while ($i < $num) {
2776 $obj = $this->db->fetch_object($resql);
2777 if ($obj) {
2778 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2779 continue;
2780 }
2781
2782 // Load contract
2783 $object = new Contrat($this->db);
2784 $object->fetch($obj->rowid); // fetch also lines
2785 //$object->fetch_thirdparty();
2786
2787 if ($object->id <= 0) {
2788 $error++;
2789 $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2790 continue;
2791 }
2792
2793 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);
2794
2795 // Update expiration date of line
2796 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2797 $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2798 $duration_unit = preg_replace('/\d/', '', $obj->duration);
2799 //var_dump($expirationdate.' '.$enddatetoscan);
2800
2801 // Load linked ->linkedObjects (objects linked)
2802 // @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.
2803 $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2804
2805 // Test if there is at least 1 open invoice
2806 if (isset($object->linkedObjects['facture']) && is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2807 // Sort array of linked invoices by ascending date
2808 usort($object->linkedObjects['facture'], array('Contrat', 'contractCmpDate'));
2809 //dol_sort_array($object->linkedObjects['facture'], 'date');
2810
2811 $someinvoicenotpaid = 0;
2812 foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2813 if ($invoice->statut == Facture::STATUS_DRAFT) {
2814 continue;
2815 } // Draft invoice are not invoice not paid
2816
2817 if (empty($invoice->paye)) {
2818 $someinvoicenotpaid++;
2819 }
2820 }
2821 if ($someinvoicenotpaid) {
2822 $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2823 $contractignored[$object->id] = $object->ref;
2824 continue;
2825 }
2826 }
2827
2828 if ($expirationdate && $expirationdate < $enddatetoscan) {
2829 dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2830 $newdate = $expirationdate;
2831 $protecti = 0; // $protecti is to avoid infinite loop
2832 while ($newdate < $enddatetoscan && $protecti < 1000) {
2833 $newdate = dol_time_plus_duree($newdate, (int) $duration_value, $duration_unit);
2834 $protecti++;
2835 }
2836
2837 if ($protecti < 1000) { // If not, there is a pb
2838 // We will update the end of date of contrat, so first we refresh contract data
2839 dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2840
2841 $this->db->begin();
2842
2843 $errorforlocaltransaction = 0;
2844
2845 $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2846 $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2847
2848 $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2849 $sqlupdate .= ' WHERE rowid = '.((int) $obj->lid);
2850 $resqlupdate = $this->db->query($sqlupdate);
2851 if ($resqlupdate) {
2852 $contractlineprocessed[$obj->lid] = $object->ref;
2853
2854 $actioncode = 'RENEW_CONTRACT';
2855 $now = dol_now();
2856
2857 // Create an event
2858 $actioncomm = new ActionComm($this->db);
2859 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2860 $actioncomm->code = 'AC_'.$actioncode;
2861 $actioncomm->label = $label;
2862 $actioncomm->datep = $now;
2863 $actioncomm->datef = $now;
2864 $actioncomm->percentage = -1; // Not applicable
2865 $actioncomm->socid = $object->socid;
2866 $actioncomm->authorid = $user->id; // User saving action
2867 $actioncomm->userownerid = $user->id; // Owner of action
2868 $actioncomm->fk_element = $object->id;
2869 $actioncomm->elementtype = 'contract';
2870 $actioncomm->note_private = $comment;
2871
2872 $ret = $actioncomm->create($user); // User creating action
2873 } else {
2874 $contracterror[$object->id] = $object->ref;
2875
2876 $error++;
2877 $errorforlocaltransaction++;
2878 $this->error = $this->db->lasterror();
2879 }
2880
2881 if (! $errorforlocaltransaction) {
2882 $this->db->commit();
2883 } else {
2884 $this->db->rollback();
2885 }
2886 } else {
2887 $error++;
2888 $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2889 dol_syslog($this->error, LOG_ERR);
2890 }
2891 }
2892 }
2893 $i++;
2894 }
2895 } else {
2896 $error++;
2897 $this->error = $this->db->lasterror();
2898 }
2899
2900 $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed) > 0 ? ' : '.implode(',', $contractlineprocessed) : '');
2901
2902 return ($error ? 1 : 0);
2903 }
2904
2912 public static function contractCmpDate($a, $b)
2913 {
2914 if ($a->date == $b->date) {
2915 return strcmp((string) $a->id, (string) $b->id);
2916 }
2917 return ($a->date < $b->date) ? -1 : 1;
2918 }
2919
2927 public function getKanbanView($option = '', $arraydata = null)
2928 {
2929 global $langs;
2930
2931 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2932
2933 $return = '<div class="box-flex-item box-flex-grow-zero">';
2934 $return .= '<div class="info-box info-box-sm">';
2935 $return .= '<span class="info-box-icon bg-infobox-action">';
2936 $return .= img_picto('', $this->picto);
2937 $return .= '</span>';
2938 $return .= '<div class="info-box-content">';
2939 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2940 if ($selected >= 0) {
2941 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2942 }
2943 if (!empty($arraydata['thirdparty'])) {
2944 $tmpthirdparty = $arraydata['thirdparty'];
2945 '@phan-var-force Societe $tmpthirdparty';
2946 $return .= '<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).'</div>';
2947 }
2948 if (property_exists($this, 'date_contrat')) {
2949 $return .= '<br><span class="opacitymedium valignmiddle">'.$langs->trans("DateContract").' : </span><span class="info-box-label valignmiddle">'.dol_print_date($this->date_contrat, 'day').'</span>';
2950 }
2951 if (method_exists($this, 'getLibStatut')) {
2952 $return .= '<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).'</div>';
2953 }
2954 $return .= '</div>';
2955 $return .= '</div>';
2956 $return .= '</div>';
2957
2958 return $return;
2959 }
2960}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
$object ref
Definition info.php:79
Class to manage agenda events (actions)
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
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.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
create($user)
Create a contract into database.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return 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.
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:162
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)
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
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:88