dolibarr 25.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-2025 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
15 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
16 * Copyright (C) 2026 Charlene Benke <charlene@patas-monkey.com>
17 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com
18 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
41require_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonsignedobject.class.php';
45
52class Contrat extends CommonObject
53{
54 use CommonSignedObject;
55
59 public $element = 'contrat';
60
64 public $table_element = 'contrat';
65
69 public $table_element_line = 'contratdet';
70
74 public $fk_element = 'fk_contrat';
75
79 public $picto = 'contract';
80
85 public $restrictiononfksoc = 1;
86
90 protected $table_ref_field = 'ref';
91
96 public $ref_customer;
97
101 public $from;
102
107 public $ref_supplier;
108
113 public $socid;
114
120 public $fk_soc;
121
125 public $societe;
126
132 public $statut = 0;
133
138 public $status = 0;
139
143 public $product;
144
148 public $fk_user_author;
149
155 public $user_author_id;
156
157
162 public $user_creation;
163
167 public $user_cloture;
168
172 public $date_contrat;
173
177 public $commercial_signature_id;
178
183 public $fk_commercial_signature;
184
188 public $commercial_suivi_id;
189
195 public $fk_commercial_suivi;
196
200 public $extraparams = array();
201
205 public $lines = array();
206
210 public $nbofservices;
214 public $nbofserviceswait;
218 public $nbofservicesopened;
222 public $nbofservicesexpired;
226 public $nbofservicesclosed;
227 //public $lower_planned_end_date;
228 //public $higher_planner_end_date;
229
234 protected $lines_id_index_mapper = array();
235
236
261 // BEGIN MODULEBUILDER PROPERTIES
265 public $fields = array(
266 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
267 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'showoncombobox' => 1, 'position' => 15, 'searchall' => 1),
268 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 20),
269 'ref_customer' => array('type' => 'varchar(50)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 25, 'searchall' => 1),
270 'ref_supplier' => array('type' => 'varchar(50)', 'label' => 'RefSupplier', 'enabled' => 1, 'visible' => -1, 'position' => 26, 'searchall' => 1),
271 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 30, 'index' => 1),
272 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 35),
273 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 40),
274 'date_contrat' => array('type' => 'datetime', 'label' => 'Date contrat', 'enabled' => 1, 'visible' => -1, 'position' => 45),
275 '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')),
276 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 70),
277 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 75),
278 'fk_commercial_signature' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative Signature', 'enabled' => 1, 'visible' => -1, 'position' => 80),
279 'fk_commercial_suivi' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative follower', 'enabled' => 1, 'visible' => -1, 'position' => 85),
280 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 90),
281 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 105, 'searchall' => 1),
282 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 110, 'searchall' => 1),
283 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 115),
284 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 120),
285 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 125),
286 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 135),
287 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'Last main doc', 'enabled' => 1, 'visible' => -1, 'position' => 140),
288 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => -1, 'position' => 500, 'notnull' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 2 => 'Closed'))
289 );
290 // END MODULEBUILDER PROPERTIES
291
292 const STATUS_DRAFT = 0;
293 const STATUS_VALIDATED = 1;
294 const STATUS_CLOSED = 2;
295
301 public function __construct($db)
302 {
303 $this->db = $db;
304
305 $this->ismultientitymanaged = 1;
306 $this->isextrafieldmanaged = 1;
307 }
308
315 public function getNextNumRef($soc)
316 {
317 global $db, $langs, $conf;
318 $langs->load("contracts");
319
320 if (getDolGlobalString('CONTRACT_ADDON')) {
321 $mybool = false;
322
323 $file = getDolGlobalString('CONTRACT_ADDON') . ".php";
324 $classname = getDolGlobalString('CONTRACT_ADDON');
325
326 // Include file with class
327 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
328
329 foreach ($dirmodels as $reldir) {
330 $dir = dol_buildpath($reldir."core/modules/contract/");
331
332 // Load file with numbering class (if found)
333 $mybool = ((bool) @include_once $dir.$file) || $mybool;
334 }
335
336 if (!$mybool) {
337 dol_print_error(null, "Failed to include file ".$file);
338 return '';
339 }
340
341 $obj = new $classname();
342 '@phan-var-force ModelNumRefContracts $obj';
344 $numref = $obj->getNextValue($soc, $this);
345
346 if ($numref != "") {
347 return $numref;
348 } else {
349 $this->error = $obj->error;
350 dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
351 return "";
352 }
353 } else {
354 $langs->load("errors");
355 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
356 return "";
357 }
358 }
359
360 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
371 public function active_line($user, $line_id, $date_start, $date_end = '', $comment = '')
372 {
373 // phpcs:enable
374 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
375 if ($result < 0) {
376 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
377 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
378 }
379 return $result;
380 }
381
382
383 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
393 public function close_line($user, $line_id, $date_end, $comment = '')
394 {
395 // phpcs:enable
396 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
397 if ($result < 0) {
398 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
399 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
400 }
401 return $result;
402 }
403
404
416 public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
417 {
418 if (empty($date_start)) {
420 }
421
422 $this->db->begin();
423
424 $error = 0;
425
426 // Load lines
427 $this->fetch_lines();
428
429 foreach ($this->lines as $contratline) {
430 // Open lines not already open
431 if ($contratline->statut != ContratLigne::STATUS_OPEN) {
432 $contratline->context = $this->context;
433
434 $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
435 if ($result < 0) {
436 $error++;
437 $this->setErrorsFromObject($contratline);
438 break;
439 }
440 }
441 }
442
443 if (!$error && $this->statut == 0) {
444 $result = $this->validate($user, '', $notrigger);
445 if ($result < 0) {
446 $error++;
447 }
448 }
449
450 if (!$error) {
451 $this->db->commit();
452 return 1;
453 } else {
454 $this->db->rollback();
455 return -1;
456 }
457 }
458
469 public function closeAll(User $user, $notrigger = 0, $comment = '', $nofetchlines = 0)
470 {
471 dol_syslog("closeAll begin", LOG_DEBUG, 1);
472
473 $this->db->begin();
474
475 // Load lines
476 if (empty($nofetchlines)) {
477 $this->fetch_lines();
478 }
479
480 $now = dol_now();
481
482 $error = 0;
483
484 foreach ($this->lines as $contratline) {
485 // Close lines not already closed
486 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
487 $contratline->date_end_real = $now;
488 $contratline->date_cloture = $now; // For backward compatibility
489 $contratline->user_closing_id = $user->id;
490 $contratline->statut = ContratLigne::STATUS_CLOSED;
491
492 $result = $contratline->close_line($user, $now, $comment, $notrigger);
493
494 if ($result < 0) {
495 $error++;
496 $this->error = $contratline->error.($contratline->error ? ' ('.$this->ref.')' : '');
497 $this->errors = $contratline->errors;
498 break;
499 }
500 }
501 }
502
503 if (!$error && $this->status == 0) {
504 $result = $this->validate($user, '', $notrigger);
505 if ($result < 0) {
506 $error++;
507 }
508 }
509
510 if (!$error) {
511 $this->db->commit();
512
513 dol_syslog("closeAll end", LOG_DEBUG, -1);
514
515 return 1;
516 } else {
517 $this->db->rollback();
518
519 dol_syslog("closeAll end", LOG_DEBUG, -1);
520
521 return -1;
522 }
523 }
524
533 public function validate(User $user, $force_number = '', $notrigger = 0)
534 {
535 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
536 global $conf;
537
538 $now = dol_now();
539
540 $error = 0;
541 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
542
543
544 $this->db->begin();
545
546 $this->fetch_thirdparty();
547
548 // A contract is validated so we can move thirdparty to status customer
549 if (!getDolGlobalString('CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
550 $result = $this->thirdparty->setAsCustomer();
551 }
552
553 // Define new ref
554 if ($force_number) {
555 $num = $force_number;
556 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
557 $num = $this->getNextNumRef($this->thirdparty);
558 } else {
559 $num = (string) $this->ref;
560 }
561 $this->newref = dol_sanitizeFileName($num);
562
563 if ($num) {
564 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
565 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
566
567 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
568 $resql = $this->db->query($sql);
569 if (!$resql) {
570 dol_print_error($this->db);
571 $error++;
572 $this->error = $this->db->lasterror();
573 }
574
575 // Trigger calls
576 if (!$error && !$notrigger) {
577 // Call trigger
578 $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
579 if ($result < 0) {
580 $error++;
581 }
582 // End call triggers
583 }
584
585 if (!$error) {
586 $this->oldref = $this->ref;
587
588 // Rename directory if dir was a temporary ref
589 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
590 // Now we rename also files into index
591 $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)."'";
592 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
593 $resql = $this->db->query($sql);
594 if (!$resql) {
595 $error++;
596 $this->error = $this->db->lasterror();
597 }
598 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files SET filepath = 'contract/".$this->db->escape($this->newref)."'";
599 $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
600 $resql = $this->db->query($sql);
601 if (!$resql) {
602 $error++;
603 $this->error = $this->db->lasterror();
604 }
605
606 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
607 $oldref = dol_sanitizeFileName($this->ref);
608 $newref = dol_sanitizeFileName($num);
609 $dirsource = $conf->contract->dir_output.'/'.$oldref;
610 $dirdest = $conf->contract->dir_output.'/'.$newref;
611 if (!$error && file_exists($dirsource)) {
612 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
613
614 if (@rename($dirsource, $dirdest)) {
615 dol_syslog("Rename ok");
616 // Rename docs starting with $oldref with $newref
617 $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
618 foreach ($listoffiles as $fileentry) {
619 $dirsource = $fileentry['name'];
620 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
621 $dirsource = $fileentry['path'].'/'.$dirsource;
622 $dirdest = $fileentry['path'].'/'.$dirdest;
623 @rename($dirsource, $dirdest);
624 }
625 }
626 }
627 }
628 }
629
630 // Set new ref and define current status
631 if (!$error) {
632 $this->ref = $num;
633 $this->status = self::STATUS_VALIDATED;
634 $this->statut = self::STATUS_VALIDATED; // deprecated
635 $this->date_validation = $now;
636 }
637 } else {
638 $error++;
639 }
640
641 if (!$error) {
642 $this->db->commit();
643 return 1;
644 } else {
645 $this->db->rollback();
646 return -1;
647 }
648 }
649
657 public function reopen($user, $notrigger = 0)
658 {
659 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
660
661 $now = dol_now();
662
663 $error = 0;
664 dol_syslog(get_class($this).'::reopen user='.$user->id);
665
666 $this->db->begin();
667
668 $this->fetch_thirdparty();
669
670 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
671 //$sql.= ", fk_user_valid = null, date_valid = null";
672 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
673
674 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
675 $resql = $this->db->query($sql);
676 if (!$resql) {
677 dol_print_error($this->db);
678 $error++;
679 $this->error = $this->db->lasterror();
680 }
681
682 // Trigger calls
683 if (!$error && !$notrigger) {
684 // Call trigger
685 $result = $this->call_trigger('CONTRACT_REOPEN', $user);
686 if ($result < 0) {
687 $error++;
688 }
689 // End call triggers
690 }
691
692 // Set new ref and define current status
693 if (!$error) {
694 $this->statut = self::STATUS_DRAFT;
695 $this->status = self::STATUS_DRAFT;
696 $this->date_validation = $now;
697 }
698
699 if (!$error) {
700 $this->db->commit();
701 return 1;
702 } else {
703 $this->db->rollback();
704 return -1;
705 }
706 }
707
719 public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '', $noextrafields = 0, $nolines = 0)
720 {
721 $result = -10;
722
723 $sql = "SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
724 $sql .= " ref_supplier, ref_customer,";
725 $sql .= " ref_ext,";
726 $sql .= " entity,";
727 $sql .= " signed_status,";
728 $sql .= " date_contrat as datecontrat,";
729 $sql .= " fk_user_author,";
730 $sql .= " fk_projet as fk_project,";
731 $sql .= " fk_commercial_signature, fk_commercial_suivi,";
732 $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
733 $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
734 if (!$id) {
735 $sql .= " WHERE entity IN (".getEntity('contract').")";
736 } else {
737 $sql .= " WHERE rowid = ".(int) $id;
738 }
739 if ($ref_customer) {
740 $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
741 }
742 if ($ref_supplier) {
743 $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
744 }
745 if ($ref) {
746 $sql .= " AND ref = '".$this->db->escape($ref)."'";
747 }
748
749 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
750
751 $resql = $this->db->query($sql);
752 if ($resql) {
753 $num = $this->db->num_rows($resql);
754 if ($num > 1) {
755 $this->error = 'Fetch found several records.';
756 dol_syslog($this->error, LOG_ERR);
757 $result = -2;
758 return 0;
759 } elseif ($num) { // $num = 1
760 $obj = $this->db->fetch_object($resql);
761 if ($obj) {
762 $this->id = $obj->rowid;
763 $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
764 $this->ref_customer = $obj->ref_customer;
765 $this->ref_supplier = $obj->ref_supplier;
766 $this->ref_ext = $obj->ref_ext;
767 $this->entity = $obj->entity;
768 $this->statut = $obj->status;
769 $this->status = $obj->status;
770 $this->signed_status = $obj->signed_status;
771
772 $this->date_contrat = $this->db->jdate($obj->datecontrat);
773 $this->date_creation = $this->db->jdate($obj->datecontrat);
774
775 $this->user_author_id = $obj->fk_user_author;
776
777 $this->commercial_signature_id = $obj->fk_commercial_signature;
778 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
779
780 $this->note_private = $obj->note_private;
781 $this->note_public = $obj->note_public;
782 $this->model_pdf = $obj->model_pdf;
783
784 $this->fk_projet = $obj->fk_project; // deprecated
785 $this->fk_project = $obj->fk_project;
786
787 $this->socid = $obj->thirdpartyid;
788 $this->fk_soc = $obj->thirdpartyid;
789 $this->last_main_doc = $obj->last_main_doc;
790 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
791
792 $this->db->free($resql);
793
794 // Retrieve all extrafields
795 // fetch optionals attributes and labels
796 if (empty($noextrafields)) {
797 $result = $this->fetch_optionals();
798 if ($result < 0) {
799 $this->error = $this->db->lasterror();
800 return -4;
801 }
802 }
803
804 // Lines
805 if (empty($nolines)) {
806 if ($result >= 0 && !empty($this->table_element_line)) {
807 $result = $this->fetch_lines();
808 if ($result < 0) {
809 $this->error = $this->db->lasterror();
810 return -3;
811 }
812 }
813 }
814
815 return $this->id;
816 } else {
817 dol_syslog(get_class($this)."::fetch Contract failed");
818 $this->error = "Fetch contract failed";
819 return -1;
820 }
821 } else {
822 dol_syslog(get_class($this)."::fetch Contract not found");
823 $this->error = "Contract not found";
824 return 0;
825 }
826 } else {
827 dol_syslog(get_class($this)."::fetch Error searching contract");
828 $this->error = $this->db->error();
829 return -1;
830 }
831 }
832
833 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
843 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
844 {
845 // phpcs:enable
846 $this->nbofservices = 0;
847 $this->nbofserviceswait = 0;
848 $this->nbofservicesopened = 0;
849 $this->nbofservicesexpired = 0;
850 $this->nbofservicesclosed = 0;
851
852 $total_ttc = 0;
853 $total_vat = 0;
854 $total_ht = 0;
855
856 $now = dol_now();
857
858 $this->lines = array();
859 $pos = 0;
860
861 // Selects contract lines related to a product
862 $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
863 $sql .= " d.rowid, d.fk_contrat, d.statut as status, d.description, d.subprice, d.subprice_ttc, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
864 $sql .= " d.total_ht,";
865 $sql .= " d.total_tva,";
866 $sql .= " d.total_localtax1,";
867 $sql .= " d.total_localtax2,";
868 $sql .= " d.total_ttc,";
869 $sql .= " d.info_bits, d.fk_product,";
870 $sql .= " d.date_ouverture_prevue as date_start,";
871 $sql .= " d.date_ouverture as date_start_real,";
872 $sql .= " d.date_fin_validite as date_end,";
873 $sql .= " d.date_cloture as date_end_real,";
874 $sql .= " d.fk_user_author,";
875 $sql .= " d.fk_user_ouverture,";
876 $sql .= " d.fk_user_cloture,";
877 $sql .= " d.fk_unit,";
878 $sql .= " d.extraparams,";
879 $sql .= " d.product_type as type,";
880 $sql .= " d.rang";
881 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
882 $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
883 if ($only_services == 1) {
884 $sql .= " AND d.product_type = 1";
885 }
886 $sql .= " ORDER by d.rang ASC";
887
888 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
889 $result = $this->db->query($sql);
890 if ($result) {
891 $num = $this->db->num_rows($result);
892 $i = 0;
893
894 while ($i < $num) {
895 $objp = $this->db->fetch_object($result);
896
897 $line = new ContratLigne($this->db);
898
899 $line->id = $objp->rowid;
900 $line->ref = $objp->rowid;
901 $line->fk_contrat = $objp->fk_contrat;
902 $line->desc = $objp->description; // Description line
903 $line->qty = $objp->qty;
904 $line->vat_src_code = $objp->vat_src_code;
905 $line->tva_tx = $objp->tva_tx;
906 $line->localtax1_tx = $objp->localtax1_tx;
907 $line->localtax2_tx = $objp->localtax2_tx;
908 $line->localtax1_type = $objp->localtax1_type;
909 $line->localtax2_type = $objp->localtax2_type;
910 $line->subprice = $objp->subprice;
911 $line->subprice_ttc = $objp->subprice_ttc;
912 $line->statut = $objp->status; // For backward compatibility
913 $line->status = $objp->status;
914 $line->remise_percent = $objp->remise_percent;
915 $line->total_ht = $objp->total_ht;
916 $line->total_tva = $objp->total_tva;
917 $line->total_localtax1 = $objp->total_localtax1;
918 $line->total_localtax2 = $objp->total_localtax2;
919 $line->total_ttc = $objp->total_ttc;
920 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
921 $line->info_bits = $objp->info_bits;
922 $line->type = $objp->type;
923
924 $line->fk_fournprice = $objp->fk_fournprice;
925 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
926 $line->pa_ht = $marginInfos[0];
927
928 $line->fk_user_author = $objp->fk_user_author;
929 $line->fk_user_ouverture = $objp->fk_user_ouverture;
930 $line->fk_user_cloture = $objp->fk_user_cloture;
931 $line->fk_unit = $objp->fk_unit;
932
933 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
934
935 $line->ref = $objp->product_ref; // deprecated
936 $line->product_ref = $objp->product_ref; // Product Ref
937 $line->product_type = $objp->product_type; // Product Type
938 $line->product_desc = $objp->product_desc; // Product Description
939 $line->product_label = $objp->product_label; // Product Label
940
941 $line->description = $objp->description;
942
943 $line->date_start = $this->db->jdate($objp->date_start);
944 $line->date_start_real = $this->db->jdate($objp->date_start_real);
945 $line->date_end = $this->db->jdate($objp->date_end);
946 $line->date_end_real = $this->db->jdate($objp->date_end_real);
947 // For backward compatibility
948 //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
949 //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
950 //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
951 //$line->date_cloture = $this->db->jdate($objp->date_cloture);
952 //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
953 //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
954 //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
955 //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
956
957 $line->rang = $objp->rang;
958
959 // Retrieve all extrafields for contract line
960 // fetch optionals attributes and labels
961 if (empty($noextrafields)) {
962 $line->fetch_optionals();
963 }
964
965 // multilangs
966 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
967 $tmpproduct = new Product($this->db);
968 $tmpproduct->fetch($objp->fk_product);
969 $tmpproduct->getMultiLangs();
970
971 $line->multilangs = $tmpproduct->multilangs;
972 }
973
974 $this->lines[$pos] = $line;
975
976 $this->lines_id_index_mapper[$line->id] = $pos;
977
978 //dol_syslog("1 ".$line->desc);
979 //dol_syslog("2 ".$line->product_desc);
980
981 if ($line->statut == ContratLigne::STATUS_INITIAL) {
982 $this->nbofserviceswait++;
983 }
984 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
985 $this->nbofservicesopened++;
986 }
987 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
988 $this->nbofservicesexpired++;
989 }
990 if ($line->statut == ContratLigne::STATUS_CLOSED) {
991 $this->nbofservicesclosed++;
992 }
993
994 // TODO Not saved into database
995 $total_ttc += $objp->total_ttc;
996 $total_vat += $objp->total_tva;
997 $total_ht += $objp->total_ht;
998
999 $i++;
1000 $pos++;
1001 }
1002 $this->db->free($result);
1003 } else {
1004 dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
1005 return -3;
1006 }
1007
1008 // Now set the global properties on contract not stored into database.
1009 $this->nbofservices = count($this->lines);
1010 $this->total_ttc = (float) price2num($total_ttc);
1011 $this->total_tva = (float) price2num($total_vat);
1012 $this->total_ht = (float) price2num($total_ht);
1013
1014 return $this->lines;
1015 }
1016
1024 public function create($user, $notrigger = 0)
1025 {
1026 global $conf, $langs;
1027
1028 // Check parameters
1029 $paramsok = 1;
1030 if ($this->commercial_signature_id <= 0) {
1031 $langs->load("commercial");
1032 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
1033 $paramsok = 0;
1034 }
1035 if ($this->commercial_suivi_id <= 0) {
1036 $langs->load("commercial");
1037 $this->error .= ($this->error ? "<br>" : '');
1038 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
1039 $paramsok = 0;
1040 }
1041 $this->entity = setEntity($this);
1042 if (!$paramsok) {
1043 return -1;
1044 }
1045
1046
1047 $this->db->begin();
1048
1049 $now = dol_now();
1050
1051 // Insert contract
1052 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
1053 $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1054 $sql .= " ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1055 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
1056 $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
1057 $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
1058 $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
1059 $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
1060 $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
1061 $sql .= ", ".((int) $this->entity);
1062 $sql .= ", ".((int) $this->signed_status);
1063 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
1064 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
1065 $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
1066 $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
1067 $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
1068 $sql .= ")";
1069 $resql = $this->db->query($sql);
1070
1071 if ($resql) {
1072 $error = 0;
1073
1074 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
1075
1076 // Load object modContract
1077 $module = getDolGlobalString('CONTRACT_ADDON', 'mod_contract_serpis');
1078 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1079 $module = substr($module, 0, dol_strlen($module) - 4);
1080 }
1081 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1082 if ($result > 0) {
1083 $modCodeContract = new $module();
1084 '@phan-var-force ModelNumRefContracts $modCodeContract';
1087 if (!empty($modCodeContract->code_auto)) {
1088 // Force the ref to a draft value if numbering module is an automatic numbering
1089 $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".((int) $this->id).")' WHERE rowid=".((int) $this->id);
1090 if ($this->db->query($sql)) {
1091 if ($this->id) {
1092 $this->ref = "(PROV".$this->id.")";
1093 }
1094 }
1095 }
1096 }
1097
1098 $result = $this->insertExtraFields();
1099 if ($result < 0) {
1100 $error++;
1101 }
1102
1103 // Insert business contacts ('SALESREPSIGN','contrat')
1104 if (!$error && !empty($this->commercial_signature_id)) {
1105 $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1106 if ($result < 0) {
1107 $error++;
1108 }
1109 }
1110
1111 // Insert business contacts ('SALESREPFOLL','contrat')
1112 if (!$error && !empty($this->commercial_suivi_id)) {
1113 $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1114 if ($result < 0) {
1115 $error++;
1116 }
1117 }
1118
1119 if (!$error) {
1120 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1121 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1122 }
1123
1124 // Add object linked
1125 if ($this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1126 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1127 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, ...))
1128 foreach ($tmp_origin_id as $origin_id) {
1129 $ret = $this->add_object_linked($origin, $origin_id);
1130 if (!$ret) {
1131 $this->error = $this->db->lasterror();
1132 $error++;
1133 }
1134 }
1135 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1136 $origin_id = $tmp_origin_id;
1137 $ret = $this->add_object_linked($origin, $origin_id);
1138 if (!$ret) {
1139 $this->error = $this->db->lasterror();
1140 $error++;
1141 }
1142 }
1143 }
1144 }
1145
1146 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1147 $originforcontact = $this->origin;
1148 $originidforcontact = $this->origin_id;
1149 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1150 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1151 $exp = new Expedition($this->db);
1152 $exp->fetch($this->origin_id);
1153 $exp->fetchObjectLinked();
1154 if (count($exp->linkedObjectsIds['commande']) > 0) {
1155 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1156 $originforcontact = 'commande';
1157 $originidforcontact = $value;
1158 break; // We take first one
1159 }
1160 }
1161 }
1162
1163 $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";
1164 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1165
1166 $resqlcontact = $this->db->query($sqlcontact);
1167 if ($resqlcontact) {
1168 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1169 if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1170 continue; // ignore this, already forced previously
1171 }
1172
1173 $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
1174 }
1175 } else {
1176 dol_print_error($this->db);
1177 }
1178 }
1179 }
1180
1181 if (!$error && !$notrigger) {
1182 // Call trigger
1183 $result = $this->call_trigger('CONTRACT_CREATE', $user);
1184 if ($result < 0) {
1185 $error++;
1186 }
1187 // End call triggers
1188 }
1189
1190 if (!$error) {
1191 $this->db->commit();
1192 return $this->id;
1193 } else {
1194 $this->error = "Failed to add contract";
1195 dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1196 $this->db->rollback();
1197 return -2;
1198 }
1199 } else {
1200 $this->error = $langs->trans("UnknownError").": ".$this->db->error();
1201 dol_syslog(get_class($this)."::create - 10 - ".$this->error, LOG_ERR);
1202
1203 $this->db->rollback();
1204 return -1;
1205 }
1206 }
1207
1208
1215 public function delete($user)
1216 {
1217 global $conf;
1218
1219 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1220
1221 $error = 0;
1222
1223 $this->db->begin();
1224
1225 // Call trigger
1226 $result = $this->call_trigger('CONTRACT_DELETE', $user);
1227 if ($result < 0) {
1228 $error++;
1229 }
1230 // End call triggers
1231
1232 if (!$error) {
1233 // Delete linked contacts
1234 $res = $this->delete_linked_contact();
1235 if ($res < 0) {
1236 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1237 $error++;
1238 }
1239 }
1240
1241 if (!$error) {
1242 // Delete linked object
1243 $res = $this->deleteObjectLinked();
1244 if ($res < 0) {
1245 $error++;
1246 }
1247 }
1248
1249 // Delete lines
1250 if (!$error) {
1251 // Delete contratdet extrafields
1252 $sql_main_table = MAIN_DB_PREFIX.'contratdet';
1253 $ef = $sql_main_table."_extrafields";
1254 $sql = "DELETE FROM ".$this->db->sanitize($ef)." WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_contrat = ".((int) $this->id).")";
1255
1256 dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1257 $resql = $this->db->query($sql);
1258 if (!$resql) {
1259 $this->error = $this->db->error();
1260 $error++;
1261 }
1262 }
1263
1264 if (!$error) {
1265 // Delete contratdet
1266 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1267 $sql .= " WHERE fk_contrat = ".((int) $this->id);
1268
1269 dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1270 $resql = $this->db->query($sql);
1271 if (!$resql) {
1272 $this->error = $this->db->error();
1273 $error++;
1274 }
1275 }
1276
1277 // Delete record into ECM index and physically
1278 if (!$error) {
1279 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1280 if ($res) {
1281 $res = $this->deleteEcmFiles(1);
1282 } // Deleting files physically is done later with the dol_delete_dir_recursive
1283 if (!$res) {
1284 $error++;
1285 }
1286 }
1287
1288 // Delete contract
1289 if (!$error) {
1290 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1291 $sql .= " WHERE rowid=".((int) $this->id);
1292
1293 dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1294 $resql = $this->db->query($sql);
1295 if (!$resql) {
1296 $this->error = $this->db->error();
1297 $error++;
1298 }
1299 }
1300
1301 // Removed extrafields
1302 if (!$error) {
1303 $result = $this->deleteExtraFields();
1304 if ($result < 0) {
1305 $error++;
1306 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1307 }
1308 }
1309
1310 if (!$error) {
1311 // We remove directory
1312 $ref = dol_sanitizeFileName($this->ref);
1313 if ($conf->contrat->dir_output && !empty($ref)) {
1314 $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1315 if (file_exists($dir)) {
1316 $res = @dol_delete_dir_recursive($dir);
1317 if (!$res) {
1318 $this->error = 'ErrorFailToDeleteDir';
1319 $error++;
1320 }
1321 }
1322 }
1323 }
1324
1325 if (!$error) {
1326 $this->db->commit();
1327 return 1;
1328 } else {
1329 $this->error = $this->db->lasterror();
1330 $this->db->rollback();
1331 return -1;
1332 }
1333 }
1334
1342 public function update($user, $notrigger = 0)
1343 {
1344 global $conf;
1345 $error = 0;
1346
1347 // Clean parameters
1348 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1349 $this->fk_commercial_signature = $this->commercial_signature_id;
1350 }
1351 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1352 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1353 }
1354 if (empty($this->socid) && $this->fk_soc > 0) {
1355 $this->socid = (int) $this->fk_soc;
1356 }
1357
1358 if (isset($this->ref)) {
1359 $this->ref = trim($this->ref);
1360 }
1361 if (isset($this->ref_customer)) {
1362 $this->ref_customer = trim($this->ref_customer);
1363 }
1364 if (isset($this->ref_supplier)) {
1365 $this->ref_supplier = trim($this->ref_supplier);
1366 }
1367 if (isset($this->ref_ext)) {
1368 $this->ref_ext = trim($this->ref_ext);
1369 }
1370 if (isset($this->entity)) {
1371 $this->entity = (int) $this->entity;
1372 }
1373 if (isset($this->status)) {
1374 $this->status = (int) $this->status;
1375 }
1376 if ((int) $this->socid > 0) {
1377 $this->socid = (int) $this->socid;
1378 }
1379 if (isset($this->fk_commercial_signature)) {
1380 $this->fk_commercial_signature = (int) $this->fk_commercial_signature;
1381 }
1382 if (isset($this->fk_commercial_suivi)) {
1383 $this->fk_commercial_suivi = (int) $this->fk_commercial_suivi;
1384 }
1385 if (isset($this->note_private)) {
1386 $this->note_private = trim($this->note_private);
1387 }
1388 if (isset($this->note_public)) {
1389 $this->note_public = trim($this->note_public);
1390 }
1391 if (isset($this->import_key)) {
1392 $this->import_key = trim($this->import_key);
1393 }
1394
1395 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
1396 $extraparams = dol_trunc($extraparams, 250);
1397
1398 // $this->oldcopy must have been set by the caller of update
1399
1400 // Update request
1401 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1402 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1403 $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1404 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1405 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1406 $sql .= " entity=".((int) $conf->entity).",";
1407 $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1408 $sql .= " statut=".(isset($this->statut) ? ((int) $this->statut) : (isset($this->status) ? ((int) $this->status) : "null")).",";
1409 $sql .= " fk_soc=".($this->socid > 0 ? ((int) $this->socid) : "null").",";
1410 $sql .= " fk_projet=".($this->fk_project > 0 ? ((int) $this->fk_project) : "null").",";
1411 $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? ((int) $this->fk_commercial_signature) : "null").",";
1412 $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? ((int) $this->fk_commercial_suivi) : "null").",";
1413 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1414 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1415 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
1416 $sql .= " extraparams=".(isset($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
1417 $sql .= " WHERE rowid=".((int) $this->id);
1418
1419 $this->db->begin();
1420
1421 $resql = $this->db->query($sql);
1422 if (!$resql) {
1423 $error++;
1424 $this->errors[] = "Error ".$this->db->lasterror();
1425 }
1426
1427 if (!$error) {
1428 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
1429 if ($result < 0) {
1430 $error++;
1431 }
1432 }
1433
1434 if (!$error && !$notrigger) {
1435 // Call triggers
1436 $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1437 if ($result < 0) {
1438 $error++;
1439 }
1440 // End call triggers
1441 }
1442
1443 // Commit or rollback
1444 if ($error) {
1445 foreach ($this->errors as $errmsg) {
1446 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1447 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1448 }
1449 $this->db->rollback();
1450 return -1 * $error;
1451 } else {
1452 $this->db->commit();
1453 return 1;
1454 }
1455 }
1456
1457
1481 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = array(), $fk_unit = null, $rang = 0)
1482 {
1483 global $user, $langs, $mysoc;
1484 $error = 0;
1485
1486 dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1487
1488 // Check parameters
1489 if ($fk_product <= 0 && empty($desc)) {
1490 $this->error = "ErrorDescRequiredForFreeProductLines";
1491 return -1;
1492 }
1493
1494 if ($this->status >= 0) {
1495 // Clean parameters
1496 $pu_ht = price2num($pu_ht);
1497 $pu_ttc = price2num($pu_ttc);
1498 $pa_ht = price2num($pa_ht);
1499
1500 // Clean vat code
1501 $reg = array();
1502 $vat_src_code = '';
1503 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1504 $vat_src_code = $reg[1];
1505 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code into vatrate.
1506 }
1507 $txtva = price2num($txtva);
1508 $txlocaltax1 = price2num($txlocaltax1);
1509 $txlocaltax2 = price2num($txlocaltax2);
1510
1511 $remise_percent = price2num($remise_percent);
1512 $qty = price2num($qty);
1513 if (empty($qty)) {
1514 $qty = 1;
1515 }
1516 if (empty($info_bits)) {
1517 $info_bits = 0;
1518 }
1519 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1520 $pu_ht = 0;
1521 }
1522 if (empty($pu_ttc)) {
1523 $pu_ttc = 0;
1524 }
1525 if (empty($txtva) || !is_numeric($txtva)) {
1526 $txtva = 0;
1527 }
1528 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1529 $txlocaltax1 = 0;
1530 }
1531 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1532 $txlocaltax2 = 0;
1533 }
1534
1535 if ($price_base_type == 'HT') {
1536 $pu = $pu_ht;
1537 } else {
1538 $pu = $pu_ttc;
1539 }
1540
1541 // Check parameters
1542 if (empty($remise_percent)) {
1543 $remise_percent = 0;
1544 }
1545 if (empty($rang)) {
1546 $rang = 0;
1547 }
1548
1549 if ($date_start && $date_end && $date_start > $date_end) {
1550 $langs->load("errors");
1551 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1552 return -1;
1553 }
1554
1555 $this->db->begin();
1556
1557 $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1558
1559 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1560 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1561 // and this is done at the line level, which has its own VAT rate
1562
1563 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1564 $total_ht = $tabprice[0];
1565 $total_tva = $tabprice[1];
1566 $total_ttc = $tabprice[2];
1567 $total_localtax1 = $tabprice[9];
1568 $total_localtax2 = $tabprice[10];
1569 $pu_ht = $tabprice[3];
1570 $pu_ttc = $tabprice[5];
1571
1572 if (count($localtaxes_type) > 0) {
1573 $localtax1_type = $localtaxes_type[0];
1574 $localtax2_type = $localtaxes_type[2];
1575 } else {
1576 $localtax1_type = "";
1577 $localtax2_type = "";
1578 }
1579
1580 if (empty($pa_ht)) {
1581 $pa_ht = 0;
1582 }
1583
1584
1585 // if buy price not defined, define buyprice as configured in margin admin
1586 if ($pa_ht == 0) {
1587 $result = $this->defineBuyPrice((float) $pu_ht, $remise_percent, $fk_product);
1588 if ($result < 0) {
1589 return -1;
1590 } else {
1591 $pa_ht = $result;
1592 }
1593 }
1594
1595 // Insert into database
1596 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1597 $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1598 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, subprice_ttc,";
1599 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1600 $sql .= " info_bits,";
1601 $sql .= " fk_product_fournisseur_price, buy_price_ht";
1602 if ($date_start > 0) {
1603 $sql .= ",date_ouverture_prevue";
1604 }
1605 if ($date_end > 0) {
1606 $sql .= ",date_fin_validite";
1607 }
1608 $sql .= ", fk_unit";
1609 $sql .= ", rang";
1610 $sql .= ") VALUES (";
1611 $sql .= ((int) $this->id).", '', '".$this->db->escape($desc)."',";
1612 $sql .= ($fk_product > 0 ? ((int) $fk_product) : "null").",";
1613 $sql .= " ".((float) $qty).",";
1614 $sql .= " ".((float) $txtva).",";
1615 $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1616 $sql .= " ".((float) $txlocaltax1).",";
1617 $sql .= " ".((float) $txlocaltax2).",";
1618 $sql .= " '".$this->db->escape($localtax1_type)."',";
1619 $sql .= " '".$this->db->escape($localtax2_type)."',";
1620 $sql .= " ".price2num($remise_percent).",";
1621 $sql .= " ".price2num($pu_ht).",";
1622 $sql .= " ".($price_base_type === 'TTC' ? (float) price2num($pu_ttc) : 0).",";
1623 $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1624 $sql .= " ".((int) $info_bits).",";
1625 if (isset($fk_fournprice)) {
1626 $sql .= ' '.((int) $fk_fournprice).',';
1627 } else {
1628 $sql .= ' null,';
1629 }
1630 if (isset($pa_ht)) {
1631 $sql .= ' '.price2num($pa_ht);
1632 } else {
1633 $sql .= ' null';
1634 }
1635 if ($date_start > 0) {
1636 $sql .= ",'".$this->db->idate($date_start)."'";
1637 }
1638 if ($date_end > 0) {
1639 $sql .= ",'".$this->db->idate($date_end)."'";
1640 }
1641 $sql .= ", ".($fk_unit ? "'".$this->db->escape((string) $fk_unit)."'" : "null");
1642 $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1643 $sql .= ")";
1644
1645 $resql = $this->db->query($sql);
1646 if ($resql) {
1647 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1648
1649 $contractline = new ContratLigne($this->db);
1650 $contractline->array_options = $array_options;
1651 $contractline->id = $contractlineid;
1652 $result = $contractline->insertExtraFields();
1653 if ($result < 0) {
1654 $this->setErrorsFromObject($contractline);
1655 $error++;
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, $langs, $mysoc;
1713
1714 $error = 0;
1715
1716 // Clean parameters
1717 $qty = trim((string) $qty);
1718 $desc = trim($desc);
1719 $desc = trim($desc);
1720 $tvatx = price2num($tvatx);
1721 $localtax1tx = price2num($localtax1tx);
1722 $localtax2tx = price2num($localtax2tx);
1723 $pa_ht = price2num($pa_ht);
1724 if (empty($fk_fournprice)) {
1725 $fk_fournprice = 0;
1726 }
1727 if (empty($rang)) {
1728 $rang = 0;
1729 }
1730
1731 if ($date_start && $date_end && $date_start > $date_end) {
1732 $langs->load("errors");
1733 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1734 return -1;
1735 }
1736
1737 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");
1738
1739 $this->db->begin();
1740
1741 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1742 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1743 // and this is done at the line level, which has its own VAT rate
1744
1745 $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1746 $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1747
1748 $tabprice = calcul_price_total((float) $qty, $pu, $remise_percent, (float) price2num($tvatx), (float) $localtax1tx, (float) $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1749 $total_ht = $tabprice[0];
1750 $total_tva = $tabprice[1];
1751 $total_ttc = $tabprice[2];
1752 $total_localtax1 = $tabprice[9];
1753 $total_localtax2 = $tabprice[10];
1754 $pu_ht = $tabprice[3];
1755 $pu_ttc = $tabprice[5];
1756
1757 $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1758 $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1759
1760 if (empty($pa_ht)) {
1761 $pa_ht = 0;
1762 }
1763
1764 // if buy price not defined, define buyprice as configured in margin admin
1765 if ($pa_ht == 0) {
1766 $result = $this->defineBuyPrice($pu, $remise_percent);
1767 if ($result < 0) {
1768 return -1;
1769 } else {
1770 $pa_ht = $result;
1771 }
1772 }
1773
1774 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET description = '".$this->db->escape($desc)."'";
1775 $sql .= ",subprice = ".((float) price2num($pu_ht));
1776 // Persist the original entry mode of the line so a no-op edit can preserve it later.
1777 $sql .= ",subprice_ttc = ".($price_base_type === 'TTC' ? (float) price2num($pu_ttc) : 0);
1778 $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1779 $sql .= ",qty = ".((float) $qty);
1780 $sql .= ",tva_tx = ".((float) price2num($tvatx));
1781 $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1782 $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1783 $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1784 $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1785 $sql .= ", total_ht = ".((float) price2num($total_ht));
1786 $sql .= ", total_tva = ".((float) price2num($total_tva));
1787 $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1788 $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1789 $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1790 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? ((int) $fk_fournprice) : "null");
1791 $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1792 if ($date_start > 0) {
1793 $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1794 } else {
1795 $sql .= ",date_ouverture_prevue = null";
1796 }
1797 if ($date_end > 0) {
1798 $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1799 } else {
1800 $sql .= ",date_fin_validite = null";
1801 }
1802 if ($date_start_real > 0) {
1803 $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1804 } else {
1805 $sql .= ",date_ouverture = null";
1806 }
1807 if ($date_end_real > 0) {
1808 $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1809 } else {
1810 $sql .= ",date_cloture = null";
1811 }
1812 $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1813 $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1814 $sql .= " WHERE rowid = ".((int) $rowid);
1815
1816 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1817 $result = $this->db->query($sql);
1818 if ($result) {
1819 if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1820 $contractline = new ContratLigne($this->db);
1821 $contractline->fetch($rowid);
1822
1823 // We replace values in $contractline->array_options only for entries defined into $array_options
1824 foreach ($array_options as $key => $value) {
1825 $contractline->array_options[$key] = $array_options[$key];
1826 }
1827
1828 $result = $contractline->insertExtraFields();
1829 if ($result < 0) {
1830 $this->errors[] = $contractline->error;
1831 $error++;
1832 }
1833 }
1834
1835 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
1836 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
1837 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $this->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
1838 $sqltoupdatecontract .= " WHERE rowid = ".((int) $this->id);
1839 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
1840 if (!$resqltoupdatecontract) {
1841 $this->error = $this->db->lasterror();
1842 $this->db->rollback();
1843 return -1;
1844 }
1845
1846 if (empty($error)) {
1847 // Call trigger
1848 $this->context['line_id'] = $rowid;
1849 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1850 if ($result < 0) {
1851 $this->db->rollback();
1852 return -3;
1853 }
1854 // End call triggers
1855
1856 $this->db->commit();
1857 return 1;
1858 } else {
1859 $this->db->rollback();
1860 return -1;
1861 }
1862 } else {
1863 $this->db->rollback();
1864 $this->error = $this->db->error();
1865 dol_syslog(get_class($this)."::updateline Erreur -1");
1866 return -1;
1867 }
1868 }
1869
1877 public function deleteLine($idline, User $user)
1878 {
1879 $error = 0;
1880
1881 if ($this->statut >= 0) {
1882 // Call trigger
1883 $this->context['line_id'] = $idline;
1884 $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1885 if ($result < 0) {
1886 return -1;
1887 }
1888 // End call triggers
1889
1890 $this->db->begin();
1891
1892 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1893 $sql .= " WHERE rowid = ".((int) $idline);
1894
1895 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1896 $resql = $this->db->query($sql);
1897 if (!$resql) {
1898 $this->error = "Error ".$this->db->lasterror();
1899 $error++;
1900 }
1901
1902 if (!$error) {
1903 // Remove extrafields
1904 $contractline = new ContratLigne($this->db);
1905 $contractline->id = $idline;
1906 $result = $contractline->deleteExtraFields();
1907 if ($result < 0) {
1908 $error++;
1909 $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1910 }
1911 }
1912
1913 if (empty($error)) {
1914 $this->db->commit();
1915 return 1;
1916 } else {
1917 dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1918 $this->db->rollback();
1919 return -1;
1920 }
1921 } else {
1922 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1923 return -2;
1924 }
1925 }
1926
1927
1928 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1936 public function update_statut($user)
1937 {
1938 // phpcs:enable
1939 dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1940
1941 // If draft, we keep it (should not happen)
1942 if ($this->statut == 0) {
1943 return 1;
1944 }
1945
1946 // Load $this->lines array
1947 // $this->fetch_lines();
1948
1949 // $newstatut=1;
1950 // foreach($this->lines as $key => $contractline)
1951 // {
1952 // // if ($contractline) // Loop on each service
1953 // }
1954
1955 return 1;
1956 }
1957
1958
1965 public function getLibStatut($mode)
1966 {
1967 return $this->LibStatut($this->statut, $mode);
1968 }
1969
1970 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1978 public function LibStatut($status, $mode)
1979 {
1980 // phpcs:enable
1981 global $langs;
1982
1983 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1984 global $langs;
1985 $langs->load("contracts");
1986 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1987 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1988 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1989 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1990 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1991 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1992 }
1993
1994 $statusType = 'status'.$status;
1995 if ($status == self::STATUS_VALIDATED) {
1996 $statusType = 'status6';
1997 }
1998
1999 if ($mode == 4 || $mode == 6 || $mode == 7) {
2000 $text = '';
2001 if ($mode == 4) {
2002 $text = '<span class="hideonsmartphone">';
2003 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2004 $text .= ' '.$langs->trans("Services");
2005 $text .= ': &nbsp; &nbsp; ';
2006 $text .= '</span>';
2007 }
2008 $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
2009 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2010 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2011 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2012 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2013 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2014 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2015 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
2016 $text .= ($mode == 7 ? '</span>' : '');
2017 if (getDolGlobalString('CONTRACT_SHOW_SIGNATURE_STATUS_WITH_SERVICE_STATUS')) {
2018 $text .= is_null($this->signed_status) ? '' : ' '.$this->getLibSignedStatus(5);
2019 }
2020 return $text;
2021 } else {
2022 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2023 }
2024 }
2025
2032 public function getTooltipContentArray($params)
2033 {
2034 global $conf, $langs, $user;
2035
2036 $langs->load('contracts');
2037
2038 $datas = [];
2039 $nofetch = !empty($params['nofetch']);
2040
2041 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2042 return ['optimize' => $langs->trans("ShowContract")];
2043 }
2044 if ($user->hasRight('contrat', 'lire')) {
2045 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2046 /* Status of a contract is status of all services, so disabled
2047 if (isset($this->statut)) {
2048 $label .= ' '.$this->getLibStatut(5);
2049 }*/
2050 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2051 if (!$nofetch) {
2052 $langs->load('companies');
2053 if (empty($this->thirdparty)) {
2054 $this->fetch_thirdparty();
2055 }
2056 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2057 }
2058 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2059 if (!$nofetch) {
2060 $langs->load('project');
2061 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2062 $res = $this->fetchProject();
2063 if ($res > 0 && $this->project instanceof Project) {
2064 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
2065 }
2066 }
2067 }
2068 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2069 if (!empty($this->total_ht)) {
2070 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2071 }
2072 if (!empty($this->total_tva)) {
2073 $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2074 }
2075 if (!empty($this->total_ttc)) {
2076 $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2077 }
2078 }
2079 return $datas;
2080 }
2081
2091 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2092 {
2093 global $langs, $user, $hookmanager;
2094
2095 $result = '';
2096
2097 $baseurl = DOL_URL_ROOT . '/contrat/card.php';
2098 $query = ['id' => $this->id];
2099
2100 //if ($option !== 'nolink')
2101 //{
2102 // Add param to save lastsearch_values or not
2103 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2104 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2105 $add_save_lastsearch_values = 1;
2106 }
2107 if ($add_save_lastsearch_values) {
2108 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2109 }
2110 //}
2111 $url = dolBuildUrl($baseurl, $query);
2112 $params = [
2113 'id' => $this->id,
2114 'objecttype' => $this->element,
2115 'nofetch' => 1,
2116 ];
2117 $classfortooltip = 'classfortooltip';
2118 $dataparams = '';
2119 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2120 $classfortooltip = 'classforajaxtooltip';
2121 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2122 $label = '';
2123 } else {
2124 $label = implode($this->getTooltipContentArray($params));
2125 }
2126
2127 $linkclose = '';
2128 if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2129 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2130 $label = $langs->trans("ShowContract");
2131 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2132 }
2133 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2134 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2135 }
2136 $linkstart = '<a href="'.$url.'"';
2137 $linkstart .= $linkclose.'>';
2138 $linkend = '</a>';
2139
2140 $result .= $linkstart;
2141 if ($withpicto) {
2142 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2143 }
2144 if ($withpicto != 2) {
2145 $result .= ($this->ref ? $this->ref : $this->id);
2146 }
2147 $result .= $linkend;
2148
2149 global $action;
2150 $hookmanager->initHooks(array('contractdao'));
2151 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2152 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2153 if ($reshook > 0) {
2154 $result = $hookmanager->resPrint;
2155 } else {
2156 $result .= $hookmanager->resPrint;
2157 }
2158
2159 return $result;
2160 }
2161
2168 public function info($id)
2169 {
2170 $sql = "SELECT c.rowid, c.ref, c.datec,";
2171 $sql .= " c.tms as date_modification,";
2172 $sql .= " fk_user_author";
2173 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2174 $sql .= " WHERE c.rowid = ".((int) $id);
2175
2176 $result = $this->db->query($sql);
2177 if ($result) {
2178 if ($this->db->num_rows($result)) {
2179 $obj = $this->db->fetch_object($result);
2180
2181 $this->id = $obj->rowid;
2182 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2183
2184 $this->user_creation_id = $obj->fk_user_author;
2185 $this->date_creation = $this->db->jdate($obj->datec);
2186 $this->date_modification = $this->db->jdate($obj->date_modification);
2187 }
2188
2189 $this->db->free($result);
2190 } else {
2191 dol_print_error($this->db);
2192 }
2193 }
2194
2195 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2202 public function array_detail($status = -1)
2203 {
2204 // phpcs:enable
2205 $tab = array();
2206
2207 $sql = "SELECT cd.rowid";
2208 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2209 $sql .= " WHERE fk_contrat =".((int) $this->id);
2210 if ($status >= 0) {
2211 $sql .= " AND statut = ".((int) $status);
2212 }
2213
2214 dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2215 $resql = $this->db->query($sql);
2216 if ($resql) {
2217 $num = $this->db->num_rows($resql);
2218 $i = 0;
2219 while ($i < $num) {
2220 $obj = $this->db->fetch_object($resql);
2221 $tab[$i] = $obj->rowid;
2222 $i++;
2223 }
2224 return $tab;
2225 } else {
2226 $this->error = $this->db->error();
2227 return -1;
2228 }
2229 }
2230
2240 public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2241 {
2242 $tab = array();
2243
2244 $sql = "SELECT c.rowid";
2245 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2246 if (!empty($product_categories) || !empty($line_status)) {
2247 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2248 }
2249 if (!empty($product_categories)) {
2250 $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)).")";
2251 }
2252 $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2253 $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2254 $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2255 $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2256 $sql .= " GROUP BY c.rowid";
2257
2258 dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2259 $resql = $this->db->query($sql);
2260 if ($resql) {
2261 $num = $this->db->num_rows($resql);
2262 $i = 0;
2263 while ($i < $num) {
2264 $obj = $this->db->fetch_object($resql);
2265 $contrat = new Contrat($this->db);
2266 $contrat->fetch($obj->rowid);
2267 $tab[$contrat->id] = $contrat;
2268 $i++;
2269 }
2270 return $tab;
2271 } else {
2272 $this->error = $this->db->lasterror();
2273 return -1;
2274 }
2275 }
2276
2277
2278 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2286 public function load_board($user, $mode)
2287 {
2288 // phpcs:enable
2289 global $conf, $langs;
2290
2291 $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2292 $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2293 $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2294 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2295 $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2296 }
2297
2298 if ($mode == 'inactive') {
2299 $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2300 $sql .= $this->from;
2301 $sql .= " WHERE c.statut = 1";
2302 $sql .= " AND c.rowid = cd.fk_contrat";
2303 $sql .= " AND cd.statut = 0";
2304 } elseif ($mode == 'expired') {
2305 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2306 $sql .= $this->from;
2307 $sql .= " WHERE c.statut = 1";
2308 $sql .= " AND c.rowid = cd.fk_contrat";
2309 $sql .= " AND cd.statut = 4";
2310 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2311 } elseif ($mode == 'active') {
2312 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2313 $sql .= $this->from;
2314 $sql .= " WHERE c.statut = 1";
2315 $sql .= " AND c.rowid = cd.fk_contrat";
2316 $sql .= " AND cd.statut = 4";
2317 //$datetouse = dol_now();
2318 //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2319 } else {
2320 return -1;
2321 }
2322 $sql .= " AND c.fk_soc = s.rowid";
2323 $sql .= " AND c.entity = ".((int) $conf->entity);
2324 if ($user->socid) {
2325 $sql .= " AND c.fk_soc = ".((int) $user->socid);
2326 }
2327 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2328 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2329 }
2330
2331 $resql = $this->db->query($sql);
2332 if ($resql) {
2333 $langs->load("contracts");
2334 $now = dol_now();
2335
2336 if ($mode == 'inactive') {
2337 $warning_delay = $conf->contract->services->inactifs->warning_delay;
2338 $label = $langs->trans("BoardNotActivatedServices");
2339 $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2340 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2341 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2342 } elseif ($mode == 'expired') {
2343 $warning_delay = $conf->contract->services->expires->warning_delay;
2344 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2345 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2346 $label = $langs->trans("BoardExpiredServices");
2347 $labelShort = $langs->trans("BoardExpiredServicesShort");
2348 } else {
2349 $warning_delay = $conf->contract->services->expires->warning_delay;
2350 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2351 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2352 $label = $langs->trans("BoardRunningServices");
2353 $labelShort = $langs->trans("BoardRunningServicesShort");
2354 }
2355
2356 $response = new WorkboardResponse();
2357 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2358 $response->label = $label;
2359 $response->labelShort = $labelShort;
2360 $response->url = $url;
2361 $response->url_late = $url_late;
2362 $response->img = img_object('', "contract");
2363
2364 while ($obj = $this->db->fetch_object($resql)) {
2365 $response->nbtodo++;
2366
2367 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2368 $response->nbtodolate++;
2369 }
2370 }
2371
2372 return $response;
2373 } else {
2374 dol_print_error($this->db);
2375 $this->error = $this->db->error();
2376 return -1;
2377 }
2378 }
2379
2385 public function loadStateBoard()
2386 {
2387 global $conf, $user;
2388
2389 $this->nb = array();
2390 $sanitizedclause = "WHERE";
2391
2392 $sql = "SELECT count(c.rowid) as nb";
2393 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2394 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2395 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2396 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2397 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2398 $sanitizedclause = "AND";
2399 }
2400 $sql .= " ".$sanitizedclause." c.entity = ".((int) $conf->entity);
2401
2402 $resql = $this->db->query($sql);
2403 if ($resql) {
2404 while ($obj = $this->db->fetch_object($resql)) {
2405 $this->nb["contracts"] = $obj->nb;
2406 }
2407 $this->db->free($resql);
2408 return 1;
2409 } else {
2410 dol_print_error($this->db);
2411 $this->error = $this->db->error();
2412 return -1;
2413 }
2414 }
2415
2416
2417 /* gestion des contacts d'un contrat */
2418
2424 public function getIdBillingContact()
2425 {
2426 return $this->getIdContact('external', 'BILLING');
2427 }
2428
2434 public function getIdServiceContact()
2435 {
2436 return $this->getIdContact('external', 'SERVICE');
2437 }
2438
2439
2447 public function initAsSpecimen()
2448 {
2449 global $user, $langs, $conf;
2450
2451 // Load array of products prodids
2452 $num_prods = 0;
2453 $prodids = array();
2454 $sql = "SELECT rowid";
2455 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2456 $sql .= " WHERE entity IN (".getEntity('product').")";
2457 $sql .= " AND tosell = 1";
2458 $sql .= $this->db->plimit(100);
2459
2460 $resql = $this->db->query($sql);
2461 if ($resql) {
2462 $num_prods = $this->db->num_rows($resql);
2463 $i = 0;
2464 while ($i < $num_prods) {
2465 $i++;
2466 $row = $this->db->fetch_row($resql);
2467 $prodids[$i] = $row[0];
2468 }
2469 }
2470
2471 // Initialise parameters
2472 $this->id = 0;
2473 $this->specimen = 1;
2474
2475 $this->ref = 'SPECIMEN';
2476 $this->ref_customer = 'SPECIMENCUST';
2477 $this->ref_supplier = 'SPECIMENSUPP';
2478 $this->socid = 1;
2479 $this->status = 0;
2480 $this->date_creation = (dol_now() - 3600 * 24 * 7);
2481 $this->date_contrat = dol_now();
2482 $this->commercial_signature_id = 1;
2483 $this->commercial_suivi_id = 1;
2484 $this->note_private = 'This is a comment (private)';
2485 $this->note_public = 'This is a comment (public)';
2486 $this->fk_project = 0;
2487 // Lines
2488 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
2489 $xnbp = 0;
2490 while ($xnbp < $nbp) {
2491 $line = new ContratLigne($this->db);
2492 $line->qty = 1;
2493 $line->subprice = 100;
2494 $line->tva_tx = 19.6;
2495 $line->remise_percent = 10;
2496 $line->total_ht = 90;
2497 $line->total_ttc = 107.64; // 90 * 1.196
2498 $line->total_tva = 17.64;
2499 $line->date_start = dol_now() - 500000;
2500 $line->date_start_real = dol_now() - 200000;
2501 $line->date_end = dol_now() + 500000;
2502 $line->date_end_real = dol_now() - 100000;
2503 if ($num_prods > 0) {
2504 $prodid = mt_rand(1, $num_prods);
2505 $line->fk_product = $prodids[$prodid];
2506 }
2507 $this->lines[$xnbp] = $line;
2508 $xnbp++;
2509 }
2510
2511 return 1;
2512 }
2513
2519 public function getLinesArray()
2520 {
2521 return $this->fetch_lines();
2522 }
2523
2529 public function getTicketsArray()
2530 {
2531 global $user;
2532
2533 $ticket = new Ticket($this->db);
2534 $nbTicket = $ticket->fetchAll($user, 'ASC', 't.datec', 0, 0, 0, array('t.fk_contract' => $this->id));
2535
2536 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2537 }
2538
2539
2551 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2552 {
2553 global $langs;
2554
2555 if (!dol_strlen($modele)) {
2556 $modele = ''; // No doc template/generation by default
2557
2558 if (!empty($this->model_pdf)) {
2559 $modele = $this->model_pdf;
2560 } elseif (getDolGlobalString('CONTRACT_ADDON_PDF')) {
2561 $modele = getDolGlobalString('CONTRACT_ADDON_PDF');
2562 }
2563 }
2564
2565 if (empty($modele)) {
2566 return 0;
2567 } else {
2568 $langs->load("contracts");
2569 $outputlangs->load("products");
2570
2571 $modelpath = "core/modules/contract/doc/";
2572 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2573 }
2574 }
2575
2584 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2585 {
2586 $tables = array(
2587 'contrat'
2588 );
2589
2590 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2591 }
2592
2601 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2602 {
2603 $tables = array(
2604 'contratdet'
2605 );
2606
2607 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2608 }
2609
2618 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2619 {
2620 global $db, $langs, $conf, $hookmanager, $extrafields;
2621
2622 dol_include_once('/projet/class/project.class.php');
2623
2624 $error = 0;
2625
2626 $this->fetch($this->id);
2627
2628 // Load dest object
2629 $clonedObj = clone $this;
2630 $clonedObj->socid = $socid;
2631
2632 $this->db->begin();
2633
2634 $objsoc = new Societe($this->db);
2635
2636 $objsoc->fetch($clonedObj->socid);
2637
2638 // Clean data
2639 $clonedObj->statut = 0;
2640 $clonedObj->status = 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 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2647 unset($clonedObj->array_options[$key]);
2648 }
2649 }
2650 }
2651
2652 if (!getDolGlobalString('CONTRACT_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').".php")) {
2653 $this->error = 'ErrorSetupNotComplete';
2654 dol_syslog($this->error);
2655 return -1;
2656 }
2657
2658 // Set ref
2659 require_once DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').'.php';
2660 $obj = getDolGlobalString('CONTRACT_ADDON');
2661 $modContract = new $obj();
2662 '@phan-var-force ModelNumRefContracts $modContract';
2664 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2665
2666 // get extrafields so they will be clone
2667 foreach ($this->lines as $line) {
2668 $line->fetch_optionals($line->id);
2669 }
2670
2671 // Create clone
2672 $clonedObj->context['createfromclone'] = 'createfromclone';
2673 $result = $clonedObj->create($user);
2674 if ($result < 0) {
2675 $error++;
2676 $this->setErrorsFromObject($clonedObj);
2677 } else {
2678 // copy external contacts if same company
2679 if ($this->socid == $clonedObj->socid) {
2680 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2681 $error++;
2682 }
2683 }
2684 }
2685
2686 if (!$error) {
2687 foreach ($this->lines as $line) {
2688 // Preserve the original entry mode of the line. Contrat::addline() stores subprice from the
2689 // $pu_ht argument as-is (like the card, which pre-computes it), so we pass the stored HT and
2690 // flag TTC + subprice_ttc so the total is computed from the typed value (no rounding drift).
2691 $line_price_base_type = $line->getPriceBaseType();
2692 $result = $clonedObj->addline($line->description, (float) $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, $line_price_base_type, (float) $line->subprice_ttc, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit, $line->rang);
2693 if ($result < 0) {
2694 $error++;
2695 $this->setErrorsFromObject($clonedObj);
2696 }
2697 }
2698 }
2699
2700 if (!$error) {
2701 // Hook of thirdparty module
2702 if (is_object($hookmanager)) {
2703 $parameters = array(
2704 'objFrom' => $this,
2705 'clonedObj' => $clonedObj
2706 );
2707 $action = '';
2708 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2709 if ($reshook < 0) {
2710 $this->setErrorsFromObject($hookmanager);
2711 $error++;
2712 }
2713 }
2714 }
2715
2716 unset($clonedObj->context['createfromclone']);
2717
2718 // End
2719 if (!$error) {
2720 $this->db->commit();
2721 return $clonedObj->id;
2722 } else {
2723 $this->db->rollback();
2724 return -1;
2725 }
2726 }
2727
2728
2738 public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2739 {
2740 global $langs, $user;
2741
2742 $langs->load("agenda");
2743
2744 $now = dol_now();
2745
2746 $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2747
2748 $error = 0;
2749 $this->output = '';
2750 $this->error = '';
2751
2752 $contractlineprocessed = array();
2753 $contractignored = array();
2754 $contracterror = array();
2755
2756 dol_syslog(__METHOD__, LOG_DEBUG);
2757
2758 $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2759 $sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2760 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2761 $sql .= ' WHERE cd.fk_contrat = c.rowid';
2762 $sql .= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2763 $sql .= " AND cd.statut = 4";
2764 if ($thirdparty_id > 0) {
2765 $sql .= " AND c.fk_soc = ".((int) $thirdparty_id);
2766 }
2767 //print $sql;
2768
2769 $resql = $this->db->query($sql);
2770 if ($resql) {
2771 $num = $this->db->num_rows($resql);
2772
2773 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2774 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2775
2776 $i = 0;
2777 while ($i < $num) {
2778 $obj = $this->db->fetch_object($resql);
2779 if ($obj) {
2780 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2781 continue;
2782 }
2783
2784 // Load contract
2785 $object = new Contrat($this->db);
2786 $object->fetch($obj->rowid); // fetch also lines
2787
2788 if ($object->id <= 0) {
2789 $error++;
2790 $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2791 continue;
2792 }
2793
2794 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);
2795
2796 // Update expiration date of line
2797 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2798 $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2799 $duration_unit = preg_replace('/\d/', '', $obj->duration);
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 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
2855 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
2856 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $object->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
2857 $sqltoupdatecontract .= " WHERE rowid = ".((int) $object->id);
2858 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
2859 if (!$resqltoupdatecontract) {
2860 $this->error = $this->db->lasterror();
2861 $this->db->rollback();
2862 return -1;
2863 }
2864
2865 $actioncode = 'RENEW_CONTRACT';
2866 $now = dol_now();
2867
2868 // Create an event
2869 $actioncomm = new ActionComm($this->db);
2870 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2871 $actioncomm->code = 'AC_'.$actioncode;
2872 $actioncomm->label = $label;
2873 $actioncomm->datep = $now;
2874 $actioncomm->datef = $now;
2875 $actioncomm->percentage = -1; // Not applicable
2876 $actioncomm->socid = $object->socid;
2877 $actioncomm->authorid = $user->id; // User saving action
2878 $actioncomm->userownerid = $user->id; // Owner of action
2879 $actioncomm->fk_element = $object->id;
2880 $actioncomm->elementid = $object->id;
2881 $actioncomm->elementtype = 'contract';
2882 $actioncomm->note_private = $comment;
2883
2884 $ret = $actioncomm->create($user); // User creating action
2885 } else {
2886 $contracterror[$object->id] = $object->ref;
2887
2888 $error++;
2889 $errorforlocaltransaction++;
2890 $this->error = $this->db->lasterror();
2891 }
2892
2893 if (! $errorforlocaltransaction) {
2894 $this->db->commit();
2895 } else {
2896 $this->db->rollback();
2897 }
2898 } else {
2899 $error++;
2900 $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2901 dol_syslog($this->error, LOG_ERR);
2902 }
2903 }
2904 }
2905 $i++;
2906 }
2907 } else {
2908 $error++;
2909 $this->error = $this->db->lasterror();
2910 }
2911
2912 $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed) > 0 ? ' : '.implode(',', $contractlineprocessed) : '');
2913
2914 return ($error ? 1 : 0);
2915 }
2916
2924 public static function contractCmpDate($a, $b)
2925 {
2926 if ($a->date == $b->date) {
2927 return strcmp((string) $a->id, (string) $b->id);
2928 }
2929 return ($a->date < $b->date) ? -1 : 1;
2930 }
2931
2939 public function getKanbanView($option = '', $arraydata = null)
2940 {
2941 global $langs;
2942
2943 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2944
2945 $return = '<div class="box-flex-item box-flex-grow-zero">';
2946 $return .= '<div class="info-box info-box-sm">';
2947 $return .= '<span class="info-box-icon bg-infobox-action">';
2948 $return .= img_picto('', $this->picto);
2949 $return .= '</span>';
2950 $return .= '<div class="info-box-content">';
2951 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
2952 if ($selected >= 0) {
2953 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2954 }
2955 if (!empty($arraydata['thirdparty']) && $arraydata['thirdparty'] instanceof Societe) {
2956 $tmpthirdparty = $arraydata['thirdparty'];
2957 '@phan-var-force Societe $tmpthirdparty';
2958 $return .= '<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).'</div>';
2959 }
2960 $return .= '<br><span class="opacitymedium valignmiddle">'.$langs->trans("DateContract").' : </span><span class="info-box-label valignmiddle">'.dol_print_date($this->date_contrat, 'day').'</span>';
2961 $return .= '<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).'</div>';
2962 $return .= '</div>';
2963 $return .= '</div>';
2964 $return .= '</div>';
2965
2966 return $return;
2967 }
2968
2976 public function getTotalizedLines($statut, int $expired)
2977 {
2978 $sql = "SELECT SUM(cd.qty) as total_qty, SUM(cd.total_ht) as total_ht, SUM(cd.total_tva) as total_tva, SUM(cd.total_ttc) as total_ttc,";
2979 $sql .= " SUM(cd.total_localtax1) as total_localtax1, SUM(cd.total_localtax2) as total_localtax2";
2980 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2981 $sql .= " WHERE cd.fk_contrat =".((int) $this->id);
2982 if ($statut >= 0) {
2983 $sql .= " AND cd.statut = ".((int) $statut);
2984 if ($expired > 0) {
2985 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2986 } else {
2987 $sql .= " AND cd.date_fin_validite >= '".$this->db->idate(dol_now())."'";
2988 }
2989 }
2990 $ret = $this->db->query($sql);
2991 $response = array();
2992 if ($ret) {
2993 $obj = $this->db->fetch_object($ret);
2994 $response['total_qty'] = $obj->total_qty;
2995 $response['total_ht'] = $obj->total_ht;
2996 $response['total_tva'] = $obj->total_tva;
2997 $response['total_localtax1'] = $obj->total_localtax1;
2998 $response['total_localtax2'] = $obj->total_localtax2;
2999 $response['total_ttc'] = $obj->total_ttc;
3000 } else {
3001 dol_print_error($this->db);
3002 $this->error = $this->db->lasterror();
3003 return -1;
3004 }
3005 return $response;
3006 }
3007
3008 // @Todo getLibSignedStatus, LibSignedStatus
3009
3019 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
3020 {
3021 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
3022 }
3023
3038 public function sendReminderForExpiredServices($daysbeforeendlist = '10', $fk_product = 0)
3039 {
3040 global $conf, $langs, $mysoc, $user;
3041
3042 $error = 0;
3043 $this->output = '';
3044 $this->error = '';
3045
3046 $blockingerrormsg = '';
3047
3048 if (!isModEnabled('contract')) { // Should not happen. If module disabled, cron job should not be visible.
3049 $langs->load("agenda");
3050 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Contract"));
3051 return 0;
3052 }
3053
3054 $now = dol_now();
3055 $nbok = 0;
3056 $nbko = 0;
3057
3058 $listoflinesok = array();
3059 $listoflinesko = array();
3060
3061 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
3062 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
3063 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
3064
3065 if (!is_numeric($daysbeforeend)) {
3066 $blockingerrormsg = "Value for delta is not a numeric value";
3067 $nbko++;
3068 break;
3069 }
3070
3071 $tmp = dol_getdate($now);
3072 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3073 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3074
3075 $sql = "SELECT cd.rowid, cd.fk_contrat";
3076 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
3077 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."contrat as c ON c.rowid = cd.fk_contrat";
3078 $sql .= " WHERE c.entity = ".((int) $conf->entity); // Do not use getEntity('contract') here, we want the batch to be on its entity only
3079 $sql .= " AND cd.statut = ".((int) ContratLigne::STATUS_OPEN);
3080 $sql .= " AND cd.date_fin_validite >= '".$this->db->idate($datetosearchfor)."'";
3081 $sql .= " AND cd.date_fin_validite <= '".$this->db->idate($datetosearchforend)."'";
3082 if ((int) $fk_product > 0) {
3083 $sql .= " AND cd.fk_product = ".((int) $fk_product);
3084 }
3085
3086 $resql = $this->db->query($sql);
3087 if ($resql) {
3088 $num_rows = $this->db->num_rows($resql);
3089
3090 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3091 include_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
3092 $formmail = new FormMail($this->db);
3093
3094 $i = 0;
3095 while ($i < $num_rows) {
3096 $obj = $this->db->fetch_object($resql);
3097
3098 $contractline = new ContratLigne($this->db);
3099 $contractline->fetch($obj->rowid);
3100
3101 $contractstatic = new Contrat($this->db);
3102 $contractstatic->fetch($obj->fk_contrat);
3103 $thirdpartyres = $contractstatic->fetch_thirdparty();
3104
3105 if ($thirdpartyres <= 0 || empty($contractstatic->thirdparty->email)) {
3106 $nbko++;
3107 $listoflinesko[$contractline->id] = $contractline->id;
3108 } else {
3109 $languagefromcountrycode = getLanguageCodeFromCountryCode($contractstatic->thirdparty->country_code);
3110 $languagecodetouse = (empty($contractstatic->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $contractstatic->thirdparty->default_lang);
3111
3112 $outputlangs = new Translate('', $conf);
3113 $outputlangs->setDefaultLang($languagecodetouse);
3114 $outputlangs->loadLangs(array("main", "contracts"));
3115 dol_syslog("sendReminderForExpiredServices Language for thirdparty id ".$contractstatic->thirdparty->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang);
3116
3117 $arraydefaultmessage = null;
3118 $labeltouse = getDolGlobalString('CONTRACT_EMAIL_TEMPLATE_REMIND_EXPIRATION');
3119
3120 if (!empty($labeltouse)) {
3121 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'contrat', $user, $outputlangs, 0, 1, $labeltouse);
3122 }
3123
3124 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3125 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $contractstatic);
3126 complete_substitutions_array($substitutionarray, $outputlangs, $contractstatic);
3127 $substitutionarray['__CONTRACT_LINE_LABEL__'] = ($contractline->label ? $contractline->label : $contractline->description);
3128 $substitutionarray['__CONTRACT_LINE_DATE_END__'] = dol_print_date($contractline->date_end, 'day', 'tzuserrel', $outputlangs);
3129
3130 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
3131 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
3132 $email_from = getDolGlobalString('CONTRACT_MAIL_FROM', $conf->email_from);
3133 $to = (string) $contractstatic->thirdparty->email;
3134 $cc = getDolGlobalString('CONTRACT_CC_MAIL_FROM');
3135
3136 $trackid = 'con'.$contractstatic->id;
3137 $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredServices'."\r\n";
3138
3139 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3140 $cmail = new CMailFile($subject, $to, $email_from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
3141 $result = $cmail->sendfile();
3142 if (!$result) {
3143 $error++;
3144 $this->error .= $cmail->error.' ';
3145 if (!is_null($cmail->errors)) {
3146 $this->errors = array_merge($this->errors, $cmail->errors);
3147 }
3148 $nbko++;
3149 $listoflinesko[$contractline->id] = $contractline->id;
3150 } else {
3151 $nbok++;
3152 $listoflinesok[$contractline->id] = $contractline->id;
3153
3154 // Insert record of email sent, as an agenda event on the contract (same convention as other automated reminder emails)
3155 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3156
3157 $actioncomm = new ActionComm($this->db);
3158 $actioncomm->type_code = 'AC_OTH_AUTO';
3159 $actioncomm->code = 'AC_EMAIL';
3160 $actioncomm->label = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($email_from, 4, 0, 1), CMailFile::getValidAddress($to, 4, 0, 1));
3161 $actioncomm->note_private = $msg;
3162 $actioncomm->fk_project = 0;
3163 $actioncomm->datep = $now;
3164 $actioncomm->datef = $now;
3165 $actioncomm->percentage = -1; // Not applicable
3166 $actioncomm->socid = $contractstatic->thirdparty->id;
3167 $actioncomm->contact_id = 0;
3168 $actioncomm->authorid = $user->id;
3169 $actioncomm->userownerid = $user->id;
3170 $actioncomm->email_msgid = $cmail->msgid;
3171 $actioncomm->email_from = $email_from;
3172 $actioncomm->email_sender = '';
3173 $actioncomm->email_to = $to;
3174 $actioncomm->email_subject = $subject;
3175
3176 $actioncomm->fk_element = $contractstatic->id;
3177 $actioncomm->elementid = $contractstatic->id;
3178 $actioncomm->elementtype = $contractstatic->element;
3179
3180 $actioncomm->create($user);
3181 }
3182 } else {
3183 $error++;
3184 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
3185
3186 $nbko++;
3187 $listoflinesko[$contractline->id] = $contractline->id;
3188
3189 break;
3190 }
3191 }
3192
3193 $i++;
3194 }
3195 } else {
3196 $this->error = $this->db->lasterror();
3197 return 1;
3198 }
3199 }
3200
3201 if ($blockingerrormsg) {
3202 $this->error = $blockingerrormsg;
3203 return 1;
3204 } else {
3205 $this->output = 'Found '.($nbok + $nbko).' contract lines to send reminder for.';
3206 $this->output .= ' Sent email successfully for '.$nbok.' lines';
3207 if ($nbko) {
3208 $this->output .= ' - Canceled for '.$nbko.' line(s) (no thirdparty email, missing template, or send error)';
3209 }
3210 }
3211
3212 if ($error) {
3213 return 1;
3214 }
3215 return 0;
3216 }
3217}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteEcmFiles($mode=0)
Delete related files of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
static contractCmpDate($a, $b)
Used to sort lines by date.
getTotalizedLines($statut, int $expired)
Return totalized lines.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
loadStateBoard()
Load the indicators this->nb for state board.
update_statut($user)
Update statut of contract according to services.
closeAll(User $user, $notrigger=0, $comment='', $nofetchlines=0)
Close all lines of a contract.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_start_real='', $date_end_real='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Update a contract line.
getTicketsArray()
Create an array of associated tickets.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
deleteLine($idline, User $user)
Delete a contract line.
array_detail($status=-1)
Return list of line rowid.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Insert contract line into database.
update($user, $notrigger=0)
Update object into database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
__construct($db)
Constructor.
doAutoRenewContracts($thirdparty_id=0, $delayindaysshort=0)
Action executed by scheduler CAN BE A CRON TASK Loop on each contract lines and update the end of dat...
getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
info($id)
Charge les information d'ordre info dans l'objet contrat.
getLibStatut($mode)
Return label of a contract status.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetch_lines($only_services=0, $loadalsotranslation=0, $noextrafields=0)
Load lines array into this->lines.
getIdServiceContact()
Return id des contacts clients de prestation.
sendReminderForExpiredServices($daysbeforeendlist='10', $fk_product=0)
Send reminders by email before a running contract service expires.
Class to manage lines of contracts.
Class to manage Dolibarr database access.
const STATUS_DRAFT
Draft status.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
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:169
setSignedStatusCommon(User $user, int $status, int $notrigger=0, string $triggercode='')
Set signed status & call trigger with context message.
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:65
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
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, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90