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