dolibarr 19.0.3
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-2023 Frédéric France <frederic.france@netlogic.fr>
13 * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
35require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
36require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
37require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
39
43class Contrat extends CommonObject
44{
48 public $element = 'contrat';
49
53 public $table_element = 'contrat';
54
58 public $table_element_line = 'contratdet';
59
63 public $fk_element = 'fk_contrat';
64
68 public $picto = 'contract';
69
74 public $ismultientitymanaged = 1;
75
79 public $isextrafieldmanaged = 1;
80
85 public $restrictiononfksoc = 1;
86
90 protected $table_ref_field = 'ref';
91
96 public $ref_customer;
97 public $from;
98
103 public $ref_supplier;
104
109 public $entity;
110
115 public $socid;
116
122 public $fk_soc;
123
124
125 public $societe; // Objet societe
126
132 public $statut = 0;
137 public $status = 0;
138
139 public $product;
140
144 public $fk_user_author;
145
151 public $user_author_id;
152
153
158 public $user_creation;
159
163 public $user_cloture;
164
168 public $date_creation;
169
173 public $date_modification;
174
178 public $date_validation;
179
183 public $date_contrat;
184
185 public $commercial_signature_id;
186 public $fk_commercial_signature;
187 public $commercial_suivi_id;
188 public $fk_commercial_suivi;
189
195
196 public $extraparams = array();
197
201 public $lines = array();
202
203 public $nbofservices;
204 public $nbofserviceswait;
205 public $nbofservicesopened;
206 public $nbofservicesexpired;
207 public $nbofservicesclosed;
208 //public $lower_planned_end_date;
209 //public $higher_planner_end_date;
210
215 protected $lines_id_index_mapper = array();
216
217
242 // BEGIN MODULEBUILDER PROPERTIES
246 public $fields = array(
247 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
248 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>15, 'searchall'=>1),
249 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>20),
250 'ref_customer' =>array('type'=>'varchar(50)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>25, 'searchall'=>1),
251 'ref_supplier' =>array('type'=>'varchar(50)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>26, 'searchall'=>1),
252 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
253 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
254 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
255 'date_contrat' =>array('type'=>'datetime', 'label'=>'Date contrat', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
256 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'notnull'=>1, 'position'=>70),
257 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>75),
258 'fk_commercial_signature' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative Signature', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
259 'fk_commercial_suivi' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'SaleRepresentative follower', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
260 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
261 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105, 'searchall'=>1),
262 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110, 'searchall'=>1),
263 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
264 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
265 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
266 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
267 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
268 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'notnull'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed'))
269 );
270 // END MODULEBUILDER PROPERTIES
271
272 const STATUS_DRAFT = 0;
273 const STATUS_VALIDATED = 1;
274 const STATUS_CLOSED = 2;
275
276
277
283 public function __construct($db)
284 {
285 $this->db = $db;
286 }
287
294 public function getNextNumRef($soc)
295 {
296 global $db, $langs, $conf;
297 $langs->load("contracts");
298
299 if (getDolGlobalString('CONTRACT_ADDON')) {
300 $mybool = false;
301
302 $file = getDolGlobalString('CONTRACT_ADDON') . ".php";
303 $classname = $conf->global->CONTRACT_ADDON;
304
305 // Include file with class
306 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
307
308 foreach ($dirmodels as $reldir) {
309 $dir = dol_buildpath($reldir."core/modules/contract/");
310
311 // Load file with numbering class (if found)
312 $mybool |= @include_once $dir.$file;
313 }
314
315 if (!$mybool) {
316 dol_print_error('', "Failed to include file ".$file);
317 return '';
318 }
319
320 $obj = new $classname();
321 $numref = $obj->getNextValue($soc, $this);
322
323 if ($numref != "") {
324 return $numref;
325 } else {
326 $this->error = $obj->error;
327 dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
328 return "";
329 }
330 } else {
331 $langs->load("errors");
332 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
333 return "";
334 }
335 }
336
337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
348 public function active_line($user, $line_id, $date_start, $date_end = '', $comment = '')
349 {
350 // phpcs:enable
351 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
352 if ($result < 0) {
353 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
354 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
355 }
356 return $result;
357 }
358
359
360 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
370 public function close_line($user, $line_id, $date_end, $comment = '')
371 {
372 // phpcs:enable
373 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
374 if ($result < 0) {
375 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
376 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
377 }
378 return $result;
379 }
380
381
393 public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
394 {
395 if (empty($date_start)) {
396 $date_start = dol_now();
397 }
398
399 $this->db->begin();
400
401 $error = 0;
402
403 // Load lines
404 $this->fetch_lines();
405
406 foreach ($this->lines as $contratline) {
407 // Open lines not already open
408 if ($contratline->statut != ContratLigne::STATUS_OPEN) {
409 $contratline->context = $this->context;
410
411 $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
412 if ($result < 0) {
413 $error++;
414 $this->error = $contratline->error;
415 $this->errors = $contratline->errors;
416 break;
417 }
418 }
419 }
420
421 if (!$error && $this->statut == 0) {
422 $result = $this->validate($user, '', $notrigger);
423 if ($result < 0) {
424 $error++;
425 }
426 }
427
428 if (!$error) {
429 $this->db->commit();
430 return 1;
431 } else {
432 $this->db->rollback();
433 return -1;
434 }
435 }
436
446 public function closeAll(User $user, $notrigger = 0, $comment = '')
447 {
448 $this->db->begin();
449
450 // Load lines
451 $this->fetch_lines();
452
453 $now = dol_now();
454
455 $error = 0;
456
457 foreach ($this->lines as $contratline) {
458 // Close lines not already closed
459 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
460 $contratline->date_end_real = $now;
461 $contratline->date_cloture = $now; // For backward compatibility
462 $contratline->user_closing_id = $user->id;
463 $contratline->statut = ContratLigne::STATUS_CLOSED;
464 $result = $contratline->close_line($user, $now, $comment, $notrigger);
465 if ($result < 0) {
466 $error++;
467 $this->error = $contratline->error;
468 $this->errors = $contratline->errors;
469 break;
470 }
471 }
472 }
473
474 if (!$error && $this->statut == 0) {
475 $result = $this->validate($user, '', $notrigger);
476 if ($result < 0) {
477 $error++;
478 }
479 }
480
481 if (!$error) {
482 $this->db->commit();
483 return 1;
484 } else {
485 $this->db->rollback();
486 return -1;
487 }
488 }
489
498 public function validate(User $user, $force_number = '', $notrigger = 0)
499 {
500 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
501 global $conf;
502
503 $now = dol_now();
504
505 $error = 0;
506 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
507
508
509 $this->db->begin();
510
511 $this->fetch_thirdparty();
512
513 // A contract is validated so we can move thirdparty to status customer
514 if (!getDolGlobalString('CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
515 $result = $this->thirdparty->setAsCustomer();
516 }
517
518 // Define new ref
519 if ($force_number) {
520 $num = $force_number;
521 } elseif (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
522 $num = $this->getNextNumRef($this->thirdparty);
523 } else {
524 $num = $this->ref;
525 }
526 $this->newref = dol_sanitizeFileName($num);
527
528 if ($num) {
529 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
530 //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
531 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
532
533 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
534 $resql = $this->db->query($sql);
535 if (!$resql) {
536 dol_print_error($this->db);
537 $error++;
538 $this->error = $this->db->lasterror();
539 }
540
541 // Trigger calls
542 if (!$error && !$notrigger) {
543 // Call trigger
544 $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
545 if ($result < 0) {
546 $error++;
547 }
548 // End call triggers
549 }
550
551 if (!$error) {
552 $this->oldref = $this->ref;
553
554 // Rename directory if dir was a temporary ref
555 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
556 // Now we rename also files into index
557 $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)."'";
558 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
559 $resql = $this->db->query($sql);
560 if (!$resql) {
561 $error++;
562 $this->error = $this->db->lasterror();
563 }
564 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'contract/".$this->db->escape($this->newref)."'";
565 $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
566 $resql = $this->db->query($sql);
567 if (!$resql) {
568 $error++;
569 $this->error = $this->db->lasterror();
570 }
571
572 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
573 $oldref = dol_sanitizeFileName($this->ref);
574 $newref = dol_sanitizeFileName($num);
575 $dirsource = $conf->contract->dir_output.'/'.$oldref;
576 $dirdest = $conf->contract->dir_output.'/'.$newref;
577 if (!$error && file_exists($dirsource)) {
578 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
579
580 if (@rename($dirsource, $dirdest)) {
581 dol_syslog("Rename ok");
582 // Rename docs starting with $oldref with $newref
583 $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
584 foreach ($listoffiles as $fileentry) {
585 $dirsource = $fileentry['name'];
586 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
587 $dirsource = $fileentry['path'].'/'.$dirsource;
588 $dirdest = $fileentry['path'].'/'.$dirdest;
589 @rename($dirsource, $dirdest);
590 }
591 }
592 }
593 }
594 }
595
596 // Set new ref and define current statut
597 if (!$error) {
598 $this->ref = $num;
599 $this->status = self::STATUS_VALIDATED;
600 $this->statut = self::STATUS_VALIDATED; // deprecated
601 $this->date_validation = $now;
602 }
603 } else {
604 $error++;
605 }
606
607 if (!$error) {
608 $this->db->commit();
609 return 1;
610 } else {
611 $this->db->rollback();
612 return -1;
613 }
614 }
615
623 public function reopen($user, $notrigger = 0)
624 {
625 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
626
627 $now = dol_now();
628
629 $error = 0;
630 dol_syslog(get_class($this).'::reopen user='.$user->id);
631
632 $this->db->begin();
633
634 $this->fetch_thirdparty();
635
636 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
637 //$sql.= ", fk_user_valid = null, date_valid = null";
638 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
639
640 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
641 $resql = $this->db->query($sql);
642 if (!$resql) {
643 dol_print_error($this->db);
644 $error++;
645 $this->error = $this->db->lasterror();
646 }
647
648 // Trigger calls
649 if (!$error && !$notrigger) {
650 // Call trigger
651 $result = $this->call_trigger('CONTRACT_REOPEN', $user);
652 if ($result < 0) {
653 $error++;
654 }
655 // End call triggers
656 }
657
658 // Set new ref and define current status
659 if (!$error) {
660 $this->statut = self::STATUS_DRAFT;
661 $this->status = self::STATUS_DRAFT;
662 $this->date_validation = $now;
663 }
664
665 if (!$error) {
666 $this->db->commit();
667 return 1;
668 } else {
669 $this->db->rollback();
670 return -1;
671 }
672 }
673
685 public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '', $noextrafields = 0, $nolines = 0)
686 {
687 $sql = "SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
688 $sql .= " ref_supplier, ref_customer,";
689 $sql .= " ref_ext,";
690 $sql .= " entity,";
691 $sql .= " date_contrat as datecontrat,";
692 $sql .= " fk_user_author,";
693 $sql .= " fk_projet as fk_project,";
694 $sql .= " fk_commercial_signature, fk_commercial_suivi,";
695 $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams";
696 $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
697 if (!$id) {
698 $sql .= " WHERE entity IN (".getEntity('contract').")";
699 } else {
700 $sql .= " WHERE rowid = ".(int) $id;
701 }
702 if ($ref_customer) {
703 $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
704 }
705 if ($ref_supplier) {
706 $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
707 }
708 if ($ref) {
709 $sql .= " AND ref = '".$this->db->escape($ref)."'";
710 }
711
712 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
713 $resql = $this->db->query($sql);
714 if ($resql) {
715 $num = $this->db->num_rows($resql);
716 if ($num > 1) {
717 $this->error = 'Fetch found several records.';
718 dol_syslog($this->error, LOG_ERR);
719 $result = -2;
720 return 0;
721 } elseif ($num) { // $num = 1
722 $obj = $this->db->fetch_object($resql);
723 if ($obj) {
724 $this->id = $obj->rowid;
725 $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
726 $this->ref_customer = $obj->ref_customer;
727 $this->ref_supplier = $obj->ref_supplier;
728 $this->ref_ext = $obj->ref_ext;
729 $this->entity = $obj->entity;
730 $this->statut = $obj->status;
731 $this->status = $obj->status;
732
733 $this->date_contrat = $this->db->jdate($obj->datecontrat);
734 $this->date_creation = $this->db->jdate($obj->datecontrat);
735
736 $this->user_author_id = $obj->fk_user_author;
737
738 $this->commercial_signature_id = $obj->fk_commercial_signature;
739 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
740
741 $this->note_private = $obj->note_private;
742 $this->note_public = $obj->note_public;
743 $this->model_pdf = $obj->model_pdf;
744
745 $this->fk_projet = $obj->fk_project; // deprecated
746 $this->fk_project = $obj->fk_project;
747
748 $this->socid = $obj->thirdpartyid;
749 $this->fk_soc = $obj->thirdpartyid;
750 $this->last_main_doc = $obj->last_main_doc;
751 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
752
753 $this->db->free($resql);
754
755 // Retrieve all extrafields
756 // fetch optionals attributes and labels
757 if (empty($noextrafields)) {
758 $result = $this->fetch_optionals();
759 if ($result < 0) {
760 $this->error = $this->db->lasterror();
761 return -4;
762 }
763 }
764
765 // Lines
766 if (empty($nolines)) {
767 if ($result >= 0 && !empty($this->table_element_line)) {
768 $result = $this->fetch_lines();
769 if ($result < 0) {
770 $this->error = $this->db->lasterror();
771 return -3;
772 }
773 }
774 }
775
776 return $this->id;
777 } else {
778 dol_syslog(get_class($this)."::fetch Contract failed");
779 $this->error = "Fetch contract failed";
780 return -1;
781 }
782 } else {
783 dol_syslog(get_class($this)."::fetch Contract not found");
784 $this->error = "Contract not found";
785 return 0;
786 }
787 } else {
788 dol_syslog(get_class($this)."::fetch Error searching contract");
789 $this->error = $this->db->error();
790 return -1;
791 }
792 }
793
794 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
804 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
805 {
806 // phpcs:enable
807 $this->nbofservices = 0;
808 $this->nbofserviceswait = 0;
809 $this->nbofservicesopened = 0;
810 $this->nbofservicesexpired = 0;
811 $this->nbofservicesclosed = 0;
812
813 $total_ttc = 0;
814 $total_vat = 0;
815 $total_ht = 0;
816
817 $now = dol_now();
818
819 $this->lines = array();
820 $pos = 0;
821
822 // Selects contract lines related to a product
823 $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
824 $sql .= " d.rowid, d.fk_contrat, d.statut as status, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
825 $sql .= " d.total_ht,";
826 $sql .= " d.total_tva,";
827 $sql .= " d.total_localtax1,";
828 $sql .= " d.total_localtax2,";
829 $sql .= " d.total_ttc,";
830 $sql .= " d.info_bits, d.fk_product,";
831 $sql .= " d.date_ouverture_prevue as date_start,";
832 $sql .= " d.date_ouverture as date_start_real,";
833 $sql .= " d.date_fin_validite as date_end,";
834 $sql .= " d.date_cloture as date_end_real,";
835 $sql .= " d.fk_user_author,";
836 $sql .= " d.fk_user_ouverture,";
837 $sql .= " d.fk_user_cloture,";
838 $sql .= " d.fk_unit,";
839 $sql .= " d.product_type as type,";
840 $sql .= " d.rang";
841 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
842 $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
843 if ($only_services == 1) {
844 $sql .= " AND d.product_type = 1";
845 }
846 $sql .= " ORDER by d.rang ASC";
847
848 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
849 $result = $this->db->query($sql);
850 if ($result) {
851 $num = $this->db->num_rows($result);
852 $i = 0;
853
854 while ($i < $num) {
855 $objp = $this->db->fetch_object($result);
856
857 $line = new ContratLigne($this->db);
858
859 $line->id = $objp->rowid;
860 $line->ref = $objp->rowid;
861 $line->fk_contrat = $objp->fk_contrat;
862 $line->desc = $objp->description; // Description line
863 $line->qty = $objp->qty;
864 $line->vat_src_code = $objp->vat_src_code;
865 $line->tva_tx = $objp->tva_tx;
866 $line->localtax1_tx = $objp->localtax1_tx;
867 $line->localtax2_tx = $objp->localtax2_tx;
868 $line->localtax1_type = $objp->localtax1_type;
869 $line->localtax2_type = $objp->localtax2_type;
870 $line->subprice = $objp->subprice;
871 $line->statut = $objp->status;
872 $line->status = $objp->status;
873 $line->remise_percent = $objp->remise_percent;
874 $line->price_ht = $objp->price_ht;
875 $line->price = $objp->price_ht; // For backward compatibility
876 $line->total_ht = $objp->total_ht;
877 $line->total_tva = $objp->total_tva;
878 $line->total_localtax1 = $objp->total_localtax1;
879 $line->total_localtax2 = $objp->total_localtax2;
880 $line->total_ttc = $objp->total_ttc;
881 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
882 $line->info_bits = $objp->info_bits;
883 $line->type = $objp->type;
884
885 $line->fk_fournprice = $objp->fk_fournprice;
886 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
887 $line->pa_ht = $marginInfos[0];
888
889 $line->fk_user_author = $objp->fk_user_author;
890 $line->fk_user_ouverture = $objp->fk_user_ouverture;
891 $line->fk_user_cloture = $objp->fk_user_cloture;
892 $line->fk_unit = $objp->fk_unit;
893
894 $line->ref = $objp->product_ref; // deprecated
895 $line->product_ref = $objp->product_ref; // Product Ref
896 $line->product_type = $objp->product_type; // Product Type
897 $line->product_desc = $objp->product_desc; // Product Description
898 $line->product_label = $objp->product_label; // Product Label
899
900 $line->description = $objp->description;
901
902 $line->date_start = $this->db->jdate($objp->date_start);
903 $line->date_start_real = $this->db->jdate($objp->date_start_real);
904 $line->date_end = $this->db->jdate($objp->date_end);
905 $line->date_end_real = $this->db->jdate($objp->date_end_real);
906 // For backward compatibility
907 //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
908 //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
909 //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
910 //$line->date_cloture = $this->db->jdate($objp->date_cloture);
911 //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
912 //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
913 //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
914 //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
915
916 $line->rang = $objp->rang;
917
918 // Retrieve all extrafields for contract line
919 // fetch optionals attributes and labels
920 if (empty($noextrafields)) {
921 $line->fetch_optionals();
922 }
923
924 // multilangs
925 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
926 $tmpproduct = new Product($this->db);
927 $tmpproduct->fetch($objp->fk_product);
928 $tmpproduct->getMultiLangs();
929
930 $line->multilangs = $tmpproduct->multilangs;
931 }
932
933 $this->lines[$pos] = $line;
934
935 $this->lines_id_index_mapper[$line->id] = $pos;
936
937 //dol_syslog("1 ".$line->desc);
938 //dol_syslog("2 ".$line->product_desc);
939
940 if ($line->statut == ContratLigne::STATUS_INITIAL) {
941 $this->nbofserviceswait++;
942 }
943 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
944 $this->nbofservicesopened++;
945 }
946 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
947 $this->nbofservicesexpired++;
948 }
949 if ($line->statut == ContratLigne::STATUS_CLOSED) {
950 $this->nbofservicesclosed++;
951 }
952
953 $total_ttc += $objp->total_ttc; // TODO Not saved into database
954 $total_vat += $objp->total_tva;
955 $total_ht += $objp->total_ht;
956
957 $i++;
958 $pos++;
959 }
960 $this->db->free($result);
961 } else {
962 dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
963 return -3;
964 }
965
966 // Now set the global properties on contract not stored into database.
967 $this->nbofservices = count($this->lines);
968 $this->total_ttc = price2num($total_ttc);
969 $this->total_tva = price2num($total_vat);
970 $this->total_ht = price2num($total_ht);
971
972 return $this->lines;
973 }
974
981 public function create($user)
982 {
983 global $conf, $langs, $mysoc;
984
985 // Check parameters
986 $paramsok = 1;
987 if ($this->commercial_signature_id <= 0) {
988 $langs->load("commercial");
989 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
990 $paramsok = 0;
991 }
992 if ($this->commercial_suivi_id <= 0) {
993 $langs->load("commercial");
994 $this->error .= ($this->error ? "<br>" : '');
995 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
996 $paramsok = 0;
997 }
998 if (!$paramsok) {
999 return -1;
1000 }
1001
1002
1003 $this->db->begin();
1004
1005 $now = dol_now();
1006
1007 // Insert contract
1008 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
1009 $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1010 $sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1011 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
1012 $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
1013 $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
1014 $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
1015 $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
1016 $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
1017 $sql .= ", ".((int) $conf->entity);
1018 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
1019 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
1020 $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
1021 $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
1022 $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
1023 $sql .= ")";
1024 $resql = $this->db->query($sql);
1025
1026 if ($resql) {
1027 $error = 0;
1028
1029 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
1030
1031 // Load object modContract
1032 $module = (getDolGlobalString('CONTRACT_ADDON') ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
1033 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1034 $module = substr($module, 0, dol_strlen($module) - 4);
1035 }
1036 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1037 if ($result > 0) {
1038 $modCodeContract = new $module();
1039
1040 if (!empty($modCodeContract->code_auto)) {
1041 // Force the ref to a draft value if numbering module is an automatic numbering
1042 $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
1043 if ($this->db->query($sql)) {
1044 if ($this->id) {
1045 $this->ref = "(PROV".$this->id.")";
1046 }
1047 }
1048 }
1049 }
1050
1051 if (!$error) {
1052 $result = $this->insertExtraFields();
1053 if ($result < 0) {
1054 $error++;
1055 }
1056 }
1057
1058 // Insert business contacts ('SALESREPSIGN','contrat')
1059 if (!$error) {
1060 $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1061 if ($result < 0) {
1062 $error++;
1063 }
1064 }
1065
1066 // Insert business contacts ('SALESREPFOLL','contrat')
1067 if (!$error) {
1068 $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1069 if ($result < 0) {
1070 $error++;
1071 }
1072 }
1073
1074 if (!$error) {
1075 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1076 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1077 }
1078
1079 // Add object linked
1080 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1081 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1082 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, ...))
1083 foreach ($tmp_origin_id as $origin_id) {
1084 $ret = $this->add_object_linked($origin, $origin_id);
1085 if (!$ret) {
1086 $this->error = $this->db->lasterror();
1087 $error++;
1088 }
1089 }
1090 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1091 $origin_id = $tmp_origin_id;
1092 $ret = $this->add_object_linked($origin, $origin_id);
1093 if (!$ret) {
1094 $this->error = $this->db->lasterror();
1095 $error++;
1096 }
1097 }
1098 }
1099 }
1100
1101 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1102 $originforcontact = $this->origin;
1103 $originidforcontact = $this->origin_id;
1104 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1105 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1106 $exp = new Expedition($this->db);
1107 $exp->fetch($this->origin_id);
1108 $exp->fetchObjectLinked();
1109 if (count($exp->linkedObjectsIds['commande']) > 0) {
1110 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1111 $originforcontact = 'commande';
1112 $originidforcontact = $value;
1113 break; // We take first one
1114 }
1115 }
1116 }
1117
1118 $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";
1119 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1120
1121 $resqlcontact = $this->db->query($sqlcontact);
1122 if ($resqlcontact) {
1123 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1124 if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1125 continue; // ignore this, already forced previously
1126 }
1127
1128 $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
1129 }
1130 } else {
1131 dol_print_error($resqlcontact);
1132 }
1133 }
1134 }
1135
1136 if (!$error) {
1137 // Call trigger
1138 $result = $this->call_trigger('CONTRACT_CREATE', $user);
1139 if ($result < 0) {
1140 $error++;
1141 }
1142 // End call triggers
1143
1144 if (!$error) {
1145 $this->db->commit();
1146 return $this->id;
1147 } else {
1148 dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1149 $this->db->rollback();
1150 return -3;
1151 }
1152 } else {
1153 $this->error = "Failed to add contract";
1154 dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1155 $this->db->rollback();
1156 return -2;
1157 }
1158 } else {
1159 $this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1160
1161 $this->db->rollback();
1162 return -1;
1163 }
1164 }
1165
1166
1173 public function delete($user)
1174 {
1175 global $conf, $langs;
1176 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1177
1178 $error = 0;
1179
1180 $this->db->begin();
1181
1182 // Call trigger
1183 $result = $this->call_trigger('CONTRACT_DELETE', $user);
1184 if ($result < 0) {
1185 $error++;
1186 }
1187 // End call triggers
1188
1189 if (!$error) {
1190 // Delete linked contacts
1191 $res = $this->delete_linked_contact();
1192 if ($res < 0) {
1193 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1194 $error++;
1195 }
1196 }
1197
1198 if (!$error) {
1199 // Delete linked object
1200 $res = $this->deleteObjectLinked();
1201 if ($res < 0) {
1202 $error++;
1203 }
1204 }
1205
1206 if (!$error) {
1207 // Delete contratdet_log
1208 /*
1209 $sql = "DELETE cdl";
1210 $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1211 $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1212 */
1213 $sql = "SELECT cdl.rowid as cdlrowid ";
1214 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1215 $sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
1216
1217 dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1218 $resql = $this->db->query($sql);
1219 if (!$resql) {
1220 $this->error = $this->db->error();
1221 $error++;
1222 }
1223 $numressql = $this->db->num_rows($resql);
1224 if (!$error && $numressql) {
1225 $tab_resql = array();
1226 for ($i = 0; $i < $numressql; $i++) {
1227 $objresql = $this->db->fetch_object($resql);
1228 $tab_resql[] = $objresql->cdlrowid;
1229 }
1230 $this->db->free($resql);
1231
1232 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1233 $sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".$this->db->sanitize(implode(",", $tab_resql)).")";
1234
1235 dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1236 $resql = $this->db->query($sql);
1237 if (!$resql) {
1238 $this->error = $this->db->error();
1239 $error++;
1240 }
1241 }
1242 }
1243
1244 // Delete lines
1245 if (!$error) {
1246 // Delete contratdet extrafields
1247 $main = MAIN_DB_PREFIX.'contratdet';
1248 $ef = $main."_extrafields";
1249 $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
1250
1251 dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1252 $resql = $this->db->query($sql);
1253 if (!$resql) {
1254 $this->error = $this->db->error();
1255 $error++;
1256 }
1257 }
1258
1259 if (!$error) {
1260 // Delete contratdet
1261 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1262 $sql .= " WHERE fk_contrat=".((int) $this->id);
1263
1264 dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1265 $resql = $this->db->query($sql);
1266 if (!$resql) {
1267 $this->error = $this->db->error();
1268 $error++;
1269 }
1270 }
1271
1272 // Delete llx_ecm_files
1273 if (!$error) {
1274 $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
1275 $resql = $this->db->query($sql);
1276 if (!$resql) {
1277 $this->error = $this->db->lasterror();
1278 $this->errors[] = $this->error;
1279 $error++;
1280 }
1281 }
1282
1283 // Delete contract
1284 if (!$error) {
1285 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1286 $sql .= " WHERE rowid=".((int) $this->id);
1287
1288 dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1289 $resql = $this->db->query($sql);
1290 if (!$resql) {
1291 $this->error = $this->db->error();
1292 $error++;
1293 }
1294 }
1295
1296 // Removed extrafields
1297 if (!$error) {
1298 $result = $this->deleteExtraFields();
1299 if ($result < 0) {
1300 $error++;
1301 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1302 }
1303 }
1304
1305 if (!$error) {
1306 // We remove directory
1307 $ref = dol_sanitizeFileName($this->ref);
1308 if ($conf->contrat->dir_output) {
1309 $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1310 if (file_exists($dir)) {
1311 $res = @dol_delete_dir_recursive($dir);
1312 if (!$res) {
1313 $this->error = 'ErrorFailToDeleteDir';
1314 $error++;
1315 }
1316 }
1317 }
1318 }
1319
1320 if (!$error) {
1321 $this->db->commit();
1322 return 1;
1323 } else {
1324 $this->error = $this->db->lasterror();
1325 $this->db->rollback();
1326 return -1;
1327 }
1328 }
1329
1337 public function update($user, $notrigger = 0)
1338 {
1339 global $conf;
1340 $error = 0;
1341
1342 // Clean parameters
1343 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1344 $this->fk_commercial_signature = $this->commercial_signature_id;
1345 }
1346 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1347 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1348 }
1349 if (empty($this->socid) && $this->fk_soc > 0) {
1350 $this->socid = (int) $this->fk_soc;
1351 }
1352 if (empty($this->fk_project) && $this->projet > 0) {
1353 $this->fk_project = (int) $this->projet;
1354 }
1355
1356 if (isset($this->ref)) {
1357 $this->ref = trim($this->ref);
1358 }
1359 if (isset($this->ref_customer)) {
1360 $this->ref_customer = trim($this->ref_customer);
1361 }
1362 if (isset($this->ref_supplier)) {
1363 $this->ref_supplier = trim($this->ref_supplier);
1364 }
1365 if (isset($this->ref_ext)) {
1366 $this->ref_ext = trim($this->ref_ext);
1367 }
1368 if (isset($this->entity)) {
1369 $this->entity = (int) $this->entity;
1370 }
1371 if (isset($this->statut)) {
1372 $this->statut = (int) $this->statut;
1373 }
1374 if (isset($this->status)) {
1375 $this->status = (int) $this->status;
1376 }
1377 if (isset($this->socid)) {
1378 $this->socid = (int) $this->socid;
1379 }
1380 if (isset($this->fk_commercial_signature)) {
1381 $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1382 }
1383 if (isset($this->fk_commercial_suivi)) {
1384 $this->fk_commercial_suivi = trim($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 //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1396
1397 // $this->oldcopy should have been set by the caller of update
1398
1399 // Update request
1400 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1401 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1402 $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1403 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1404 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1405 $sql .= " entity=".$conf->entity.",";
1406 $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1407 $sql .= " statut=".(isset($this->statut) ? $this->statut : (isset($this->status) ? $this->status : "null")).",";
1408 $sql .= " fk_soc=".($this->socid > 0 ? $this->socid : "null").",";
1409 $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1410 $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1411 $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1412 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1413 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1414 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1415 //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null");
1416 $sql .= " WHERE rowid=".((int) $this->id);
1417
1418 $this->db->begin();
1419
1420 $resql = $this->db->query($sql);
1421 if (!$resql) {
1422 $error++;
1423 $this->errors[] = "Error ".$this->db->lasterror();
1424 }
1425
1426 if (!$error) {
1427 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
1428 if ($result < 0) {
1429 $error++;
1430 }
1431 }
1432
1433 if (!$error && !$notrigger) {
1434 // Call triggers
1435 $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1436 if ($result < 0) {
1437 $error++;
1438 }
1439 // End call triggers
1440 }
1441
1442 // Commit or rollback
1443 if ($error) {
1444 foreach ($this->errors as $errmsg) {
1445 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1446 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1447 }
1448 $this->db->rollback();
1449 return -1 * $error;
1450 } else {
1451 $this->db->commit();
1452 return 1;
1453 }
1454 }
1455
1456
1480 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)
1481 {
1482 global $user, $langs, $conf, $mysoc;
1483 $error = 0;
1484
1485 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");
1486
1487 // Check parameters
1488 if ($fk_product <= 0 && empty($desc)) {
1489 $this->error = "ErrorDescRequiredForFreeProductLines";
1490 return -1;
1491 }
1492
1493 if ($this->statut >= 0) {
1494 // Clean parameters
1495 $pu_ht = price2num($pu_ht);
1496 $pu_ttc = price2num($pu_ttc);
1497 $pa_ht = price2num($pa_ht);
1498
1499 // Clean vat code
1500 $reg = array();
1501 $vat_src_code = '';
1502 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1503 $vat_src_code = $reg[1];
1504 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1505 }
1506 $txtva = price2num($txtva);
1507 $txlocaltax1 = price2num($txlocaltax1);
1508 $txlocaltax2 = price2num($txlocaltax2);
1509
1510 $remise_percent = price2num($remise_percent);
1511 $qty = price2num($qty);
1512 if (empty($qty)) {
1513 $qty = 1;
1514 }
1515 if (empty($info_bits)) {
1516 $info_bits = 0;
1517 }
1518 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1519 $pu_ht = 0;
1520 }
1521 if (empty($pu_ttc)) {
1522 $pu_ttc = 0;
1523 }
1524 if (empty($txtva) || !is_numeric($txtva)) {
1525 $txtva = 0;
1526 }
1527 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1528 $txlocaltax1 = 0;
1529 }
1530 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1531 $txlocaltax2 = 0;
1532 }
1533
1534 if ($price_base_type == 'HT') {
1535 $pu = $pu_ht;
1536 } else {
1537 $pu = $pu_ttc;
1538 }
1539
1540 // Check parameters
1541 if (empty($remise_percent)) {
1542 $remise_percent = 0;
1543 }
1544 if (empty($rang)) {
1545 $rang = 0;
1546 }
1547
1548 if ($date_start && $date_end && $date_start > $date_end) {
1549 $langs->load("errors");
1550 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1551 return -1;
1552 }
1553
1554 $this->db->begin();
1555
1556 $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1557
1558 // Calcul du total TTC et de la TVA pour la ligne a partir de
1559 // qty, pu, remise_percent et txtva
1560 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1561 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1562
1563 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1564 $total_ht = $tabprice[0];
1565 $total_tva = $tabprice[1];
1566 $total_ttc = $tabprice[2];
1567 $total_localtax1 = $tabprice[9];
1568 $total_localtax2 = $tabprice[10];
1569
1570 $localtax1_type = $localtaxes_type[0];
1571 $localtax2_type = $localtaxes_type[2];
1572
1573 // TODO A virer
1574 // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1575 $remise = 0;
1576 $price = price2num(round($pu_ht, 2));
1577 if (dol_strlen($remise_percent) > 0) {
1578 $remise = round(($pu_ht * $remise_percent / 100), 2);
1579 $price = $pu_ht - $remise;
1580 }
1581
1582 if (empty($pa_ht)) {
1583 $pa_ht = 0;
1584 }
1585
1586
1587 // if buy price not defined, define buyprice as configured in margin admin
1588 if ($pa_ht == 0) {
1589 if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) {
1590 return $result;
1591 } else {
1592 $pa_ht = $result;
1593 }
1594 }
1595
1596 // Insertion dans la base
1597 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1598 $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1599 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1600 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1601 $sql .= " info_bits,";
1602 $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1603 if ($date_start > 0) {
1604 $sql .= ",date_ouverture_prevue";
1605 }
1606 if ($date_end > 0) {
1607 $sql .= ",date_fin_validite";
1608 }
1609 $sql .= ", fk_unit";
1610 $sql .= ", rang";
1611 $sql .= ") VALUES (";
1612 $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1613 $sql .= ($fk_product > 0 ? $fk_product : "null").",";
1614 $sql .= " ".((float) $qty).",";
1615 $sql .= " ".((float) $txtva).",";
1616 $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1617 $sql .= " ".((float) $txlocaltax1).",";
1618 $sql .= " ".((float) $txlocaltax2).",";
1619 $sql .= " '".$this->db->escape($localtax1_type)."',";
1620 $sql .= " '".$this->db->escape($localtax2_type)."',";
1621 $sql .= " ".price2num($remise_percent).",";
1622 $sql .= " ".price2num($pu_ht).",";
1623 $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1624 $sql .= " '".$this->db->escape($info_bits)."',";
1625 $sql .= " ".price2num($price).",".price2num($remise).",";
1626 if (isset($fk_fournprice)) {
1627 $sql .= ' '.((int) $fk_fournprice).',';
1628 } else {
1629 $sql .= ' null,';
1630 }
1631 if (isset($pa_ht)) {
1632 $sql .= ' '.price2num($pa_ht);
1633 } else {
1634 $sql .= ' null';
1635 }
1636 if ($date_start > 0) {
1637 $sql .= ",'".$this->db->idate($date_start)."'";
1638 }
1639 if ($date_end > 0) {
1640 $sql .= ",'".$this->db->idate($date_end)."'";
1641 }
1642 $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1643 $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1644 $sql .= ")";
1645
1646 $resql = $this->db->query($sql);
1647 if ($resql) {
1648 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1649
1650 if (!$error) {
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->errors = array_merge($this->errors, $contractline->errors);
1657 $this->error = $contractline->error;
1658 $error++;
1659 }
1660 }
1661
1662 if (empty($error)) {
1663 // Call trigger
1664 $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1665 if ($result < 0) {
1666 $error++;
1667 }
1668 // End call triggers
1669 }
1670
1671 if ($error) {
1672 $this->db->rollback();
1673 return -1;
1674 } else {
1675 $this->db->commit();
1676 return $contractlineid;
1677 }
1678 } else {
1679 $this->db->rollback();
1680 $this->error = $this->db->error()." sql=".$sql;
1681 return -1;
1682 }
1683 } else {
1684 dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1685 return -2;
1686 }
1687 }
1688
1713 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)
1714 {
1715 global $user, $conf, $langs, $mysoc;
1716
1717 $error = 0;
1718
1719 // Clean parameters
1720 $qty = trim($qty);
1721 $desc = trim($desc);
1722 $desc = trim($desc);
1723 $price = price2num($pu);
1724 $tvatx = price2num($tvatx);
1725 $localtax1tx = price2num($localtax1tx);
1726 $localtax2tx = price2num($localtax2tx);
1727 $pa_ht = price2num($pa_ht);
1728 if (empty($fk_fournprice)) {
1729 $fk_fournprice = 0;
1730 }
1731 if (empty($rang)) {
1732 $rang = 0;
1733 }
1734
1735 $subprice = $price;
1736 $remise = 0;
1737 if (dol_strlen($remise_percent) > 0) {
1738 $remise = round(($pu * $remise_percent / 100), 2);
1739 $price = $pu - $remise;
1740 } else {
1741 $remise_percent = 0;
1742 }
1743
1744 if ($date_start && $date_end && $date_start > $date_end) {
1745 $langs->load("errors");
1746 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1747 return -1;
1748 }
1749
1750 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");
1751
1752 $this->db->begin();
1753
1754 // Calcul du total TTC et de la TVA pour la ligne a partir de
1755 // qty, pu, remise_percent et tvatx
1756 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1757 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1758
1759 $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1760 $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1761
1762 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1763 $total_ht = $tabprice[0];
1764 $total_tva = $tabprice[1];
1765 $total_ttc = $tabprice[2];
1766 $total_localtax1 = $tabprice[9];
1767 $total_localtax2 = $tabprice[10];
1768
1769 $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1770 $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1771
1772 // TODO A virer
1773 // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1774 $remise = 0;
1775 $price = price2num(round($pu, 2));
1776 if (dol_strlen($remise_percent) > 0) {
1777 $remise = round(($pu * $remise_percent / 100), 2);
1778 $price = $pu - $remise;
1779 }
1780
1781 if (empty($pa_ht)) {
1782 $pa_ht = 0;
1783 }
1784
1785 // if buy price not defined, define buyprice as configured in margin admin
1786 if ($pa_ht == 0) {
1787 if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
1788 return $result;
1789 } else {
1790 $pa_ht = $result;
1791 }
1792 }
1793
1794 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
1795 $sql .= ",price_ht = ".((float) price2num($price));
1796 $sql .= ",subprice = ".((float) price2num($subprice));
1797 $sql .= ",remise = ".((float) price2num($remise));
1798 $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1799 $sql .= ",qty = ".((float) $qty);
1800 $sql .= ",tva_tx = ".((float) price2num($tvatx));
1801 $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1802 $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1803 $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1804 $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1805 $sql .= ", total_ht = ".((float) price2num($total_ht));
1806 $sql .= ", total_tva = ".((float) price2num($total_tva));
1807 $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1808 $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1809 $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1810 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1811 $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1812 if ($date_start > 0) {
1813 $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1814 } else {
1815 $sql .= ",date_ouverture_prevue = null";
1816 }
1817 if ($date_end > 0) {
1818 $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1819 } else {
1820 $sql .= ",date_fin_validite = null";
1821 }
1822 if ($date_start_real > 0) {
1823 $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1824 } else {
1825 $sql .= ",date_ouverture = null";
1826 }
1827 if ($date_end_real > 0) {
1828 $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1829 } else {
1830 $sql .= ",date_cloture = null";
1831 }
1832 $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1833 $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1834 $sql .= " WHERE rowid = ".((int) $rowid);
1835
1836 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1837 $result = $this->db->query($sql);
1838 if ($result) {
1839 if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1840 $contractline = new ContratLigne($this->db);
1841 $contractline->fetch($rowid);
1842
1843 // We replace values in $contractline->array_options only for entries defined into $array_options
1844 foreach ($array_options as $key => $value) {
1845 $contractline->array_options[$key] = $array_options[$key];
1846 }
1847
1848 $result = $contractline->insertExtraFields();
1849 if ($result < 0) {
1850 $this->error[] = $contractline->error;
1851 $error++;
1852 }
1853 }
1854
1855 if (empty($error)) {
1856 // Call trigger
1857 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1858 if ($result < 0) {
1859 $this->db->rollback();
1860 return -3;
1861 }
1862 // End call triggers
1863
1864 $this->db->commit();
1865 return 1;
1866 } else {
1867 $this->db->rollback();
1868 return -1;
1869 }
1870 } else {
1871 $this->db->rollback();
1872 $this->error = $this->db->error();
1873 dol_syslog(get_class($this)."::updateline Erreur -1");
1874 return -1;
1875 }
1876 }
1877
1885 public function deleteline($idline, User $user)
1886 {
1887 global $conf, $langs;
1888
1889 $error = 0;
1890
1891 if ($this->statut >= 0) {
1892 // Call trigger
1893 $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1894 if ($result < 0) {
1895 return -1;
1896 }
1897 // End call triggers
1898
1899 $this->db->begin();
1900
1901 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1902 $sql .= " WHERE rowid = ".((int) $idline);
1903
1904 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
1905 $resql = $this->db->query($sql);
1906 if (!$resql) {
1907 $this->error = "Error ".$this->db->lasterror();
1908 $error++;
1909 }
1910
1911 if (!$error) {
1912 // Remove extrafields
1913 $contractline = new ContratLigne($this->db);
1914 $contractline->id = $idline;
1915 $result = $contractline->deleteExtraFields();
1916 if ($result < 0) {
1917 $error++;
1918 $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
1919 }
1920 }
1921
1922 if (empty($error)) {
1923 $this->db->commit();
1924 return 1;
1925 } else {
1926 dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
1927 $this->db->rollback();
1928 return -1;
1929 }
1930 } else {
1931 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1932 return -2;
1933 }
1934 }
1935
1936
1937 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1945 public function update_statut($user)
1946 {
1947 // phpcs:enable
1948 dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1949
1950 // If draft, we keep it (should not happen)
1951 if ($this->statut == 0) {
1952 return 1;
1953 }
1954
1955 // Load $this->lines array
1956 // $this->fetch_lines();
1957
1958 // $newstatut=1;
1959 // foreach($this->lines as $key => $contractline)
1960 // {
1961 // // if ($contractline) // Loop on each service
1962 // }
1963
1964 return 1;
1965 }
1966
1967
1974 public function getLibStatut($mode)
1975 {
1976 return $this->LibStatut($this->statut, $mode);
1977 }
1978
1979 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1987 public function LibStatut($status, $mode)
1988 {
1989 // phpcs:enable
1990 global $langs;
1991
1992 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1993 global $langs;
1994 $langs->load("contracts");
1995 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1996 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
1997 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
1998 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
1999 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
2000 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
2001 }
2002
2003 $statusType = 'status'.$status;
2004 if ($status == self::STATUS_VALIDATED) {
2005 $statusType = 'status6';
2006 }
2007
2008 if ($mode == 4 || $mode == 6 || $mode == 7) {
2009 $text = '';
2010 if ($mode == 4) {
2011 $text = '<span class="hideonsmartphone">';
2012 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2013 $text .= ' '.$langs->trans("Services");
2014 $text .= ': &nbsp; &nbsp; ';
2015 $text .= '</span>';
2016 }
2017 $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
2018 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2019 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2020 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2021 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2022 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2023 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2024 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
2025 $text .= ($mode == 7 ? '</span>' : '');
2026 return $text;
2027 } else {
2028 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2029 }
2030 }
2031
2038 public function getTooltipContentArray($params)
2039 {
2040 global $conf, $langs, $user;
2041
2042 $langs->load('contracts');
2043
2044 $datas = [];
2045 $nofetch = !empty($params['nofetch']);
2046
2047 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2048 return ['optimize' => $langs->trans("ShowContract")];
2049 }
2050 if ($user->hasRight('contrat', 'lire')) {
2051 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2052 /* Status of a contract is status of all services, so disabled
2053 if (isset($this->statut)) {
2054 $label .= ' '.$this->getLibStatut(5);
2055 }*/
2056 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2057 if (!$nofetch) {
2058 $langs->load('companies');
2059 if (empty($this->thirdparty)) {
2060 $this->fetch_thirdparty();
2061 }
2062 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2063 }
2064 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2065 if (!$nofetch) {
2066 $langs->load('project');
2067 if (empty($this->project)) {
2068 $res = $this->fetch_project();
2069 if ($res > 0) {
2070 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
2071 }
2072 }
2073 }
2074 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2075 if (!empty($this->total_ht)) {
2076 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2077 }
2078 if (!empty($this->total_tva)) {
2079 $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2080 }
2081 if (!empty($this->total_ttc)) {
2082 $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2083 }
2084 }
2085 return $datas;
2086 }
2087
2097 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2098 {
2099 global $conf, $langs, $user, $hookmanager;
2100
2101 $result = '';
2102
2103 $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
2104
2105 //if ($option !== 'nolink')
2106 //{
2107 // Add param to save lastsearch_values or not
2108 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2109 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2110 $add_save_lastsearch_values = 1;
2111 }
2112 if ($add_save_lastsearch_values) {
2113 $url .= '&save_lastsearch_values=1';
2114 }
2115 //}
2116 $params = [
2117 'id' => $this->id,
2118 'objecttype' => $this->element,
2119 'nofetch' => 1,
2120 ];
2121 $classfortooltip = 'classfortooltip';
2122 $dataparams = '';
2123 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2124 $classfortooltip = 'classforajaxtooltip';
2125 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2126 $label = '';
2127 } else {
2128 $label = implode($this->getTooltipContentArray($params));
2129 }
2130
2131 $linkclose = '';
2132 if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2133 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2134 $label = $langs->trans("ShowContract");
2135 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2136 }
2137 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2138 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2139 }
2140 $linkstart = '<a href="'.$url.'"';
2141 $linkstart .= $linkclose.'>';
2142 $linkend = '</a>';
2143
2144 $result .= $linkstart;
2145 if ($withpicto) {
2146 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2147 }
2148 if ($withpicto != 2) {
2149 $result .= ($this->ref ? $this->ref : $this->id);
2150 }
2151 $result .= $linkend;
2152
2153 global $action;
2154 $hookmanager->initHooks(array('contractdao'));
2155 $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
2156 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2157 if ($reshook > 0) {
2158 $result = $hookmanager->resPrint;
2159 } else {
2160 $result .= $hookmanager->resPrint;
2161 }
2162
2163 return $result;
2164 }
2165
2172 public function info($id)
2173 {
2174 $sql = "SELECT c.rowid, c.ref, c.datec,";
2175 $sql .= " c.tms as date_modification,";
2176 $sql .= " fk_user_author";
2177 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2178 $sql .= " WHERE c.rowid = ".((int) $id);
2179
2180 $result = $this->db->query($sql);
2181 if ($result) {
2182 if ($this->db->num_rows($result)) {
2183 $obj = $this->db->fetch_object($result);
2184
2185 $this->id = $obj->rowid;
2186 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2187
2188 $this->user_creation_id = $obj->fk_user_author;
2189 $this->date_creation = $this->db->jdate($obj->datec);
2190 $this->date_modification = $this->db->jdate($obj->date_modification);
2191 }
2192
2193 $this->db->free($result);
2194 } else {
2195 dol_print_error($this->db);
2196 }
2197 }
2198
2199 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2206 public function array_detail($status = -1)
2207 {
2208 // phpcs:enable
2209 $tab = array();
2210
2211 $sql = "SELECT cd.rowid";
2212 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2213 $sql .= " WHERE fk_contrat =".((int) $this->id);
2214 if ($status >= 0) {
2215 $sql .= " AND statut = ".((int) $status);
2216 }
2217
2218 dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2219 $resql = $this->db->query($sql);
2220 if ($resql) {
2221 $num = $this->db->num_rows($resql);
2222 $i = 0;
2223 while ($i < $num) {
2224 $obj = $this->db->fetch_object($resql);
2225 $tab[$i] = $obj->rowid;
2226 $i++;
2227 }
2228 return $tab;
2229 } else {
2230 $this->error = $this->db->error();
2231 return -1;
2232 }
2233 }
2234
2244 public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2245 {
2246 $tab = array();
2247
2248 $sql = "SELECT c.rowid";
2249 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2250 if (!empty($product_categories)) {
2251 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2252 $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)).")";
2253 }
2254 $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2255 $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2256 $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2257 $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2258 $sql .= " GROUP BY c.rowid";
2259
2260 dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2261 $resql = $this->db->query($sql);
2262 if ($resql) {
2263 $num = $this->db->num_rows($resql);
2264 $i = 0;
2265 while ($i < $num) {
2266 $obj = $this->db->fetch_object($resql);
2267 $contrat = new Contrat($this->db);
2268 $contrat->fetch($obj->rowid);
2269 $tab[$contrat->id] = $contrat;
2270 $i++;
2271 }
2272 return $tab;
2273 } else {
2274 $this->error = $this->db->lasterror();
2275 return -1;
2276 }
2277 }
2278
2279
2280 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2288 public function load_board($user, $mode)
2289 {
2290 // phpcs:enable
2291 global $conf, $langs;
2292
2293 $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2294 $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2295 $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2296 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
2297 $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2298 }
2299
2300 if ($mode == 'inactive') {
2301 $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2302 $sql .= $this->from;
2303 $sql .= " WHERE c.statut = 1";
2304 $sql .= " AND c.rowid = cd.fk_contrat";
2305 $sql .= " AND cd.statut = 0";
2306 } elseif ($mode == 'expired') {
2307 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2308 $sql .= $this->from;
2309 $sql .= " WHERE c.statut = 1";
2310 $sql .= " AND c.rowid = cd.fk_contrat";
2311 $sql .= " AND cd.statut = 4";
2312 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
2313 } elseif ($mode == 'active') {
2314 $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2315 $sql .= $this->from;
2316 $sql .= " WHERE c.statut = 1";
2317 $sql .= " AND c.rowid = cd.fk_contrat";
2318 $sql .= " AND cd.statut = 4";
2319 //$datetouse = dol_now();
2320 //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
2321 }
2322 $sql .= " AND c.fk_soc = s.rowid";
2323 $sql .= " AND c.entity = ".((int) $conf->entity);
2324 if ($user->socid) {
2325 $sql .= " AND c.fk_soc = ".((int) $user->socid);
2326 }
2327 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
2328 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2329 }
2330
2331 $resql = $this->db->query($sql);
2332 if ($resql) {
2333 $langs->load("contracts");
2334 $now = dol_now();
2335
2336 if ($mode == 'inactive') {
2337 $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2338 $label = $langs->trans("BoardNotActivatedServices");
2339 $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2340 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2341 } elseif ($mode == 'expired') {
2342 $warning_delay = $conf->contrat->services->expires->warning_delay;
2343 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2344 $label = $langs->trans("BoardExpiredServices");
2345 $labelShort = $langs->trans("BoardExpiredServicesShort");
2346 } else {
2347 $warning_delay = $conf->contrat->services->expires->warning_delay;
2348 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2349 //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
2350 //if ($warning_delay >= 0) $url.='&amp;filter=expired';
2351 $label = $langs->trans("BoardRunningServices");
2352 $labelShort = $langs->trans("BoardRunningServicesShort");
2353 }
2354
2355 $response = new WorkboardResponse();
2356 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2357 $response->label = $label;
2358 $response->labelShort = $labelShort;
2359 $response->url = $url;
2360 $response->img = img_object('', "contract");
2361
2362 while ($obj = $this->db->fetch_object($resql)) {
2363 $response->nbtodo++;
2364
2365 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2366 $response->nbtodolate++;
2367 }
2368 }
2369
2370 return $response;
2371 } else {
2372 dol_print_error($this->db);
2373 $this->error = $this->db->error();
2374 return -1;
2375 }
2376 }
2377
2378 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2384 public function load_state_board()
2385 {
2386 // phpcs:enable
2387 global $conf, $user;
2388
2389 $this->nb = array();
2390 $clause = "WHERE";
2391
2392 $sql = "SELECT count(c.rowid) as nb";
2393 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2394 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2395 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
2396 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2397 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2398 $clause = "AND";
2399 }
2400 $sql .= " ".$clause." c.entity = ".$conf->entity;
2401
2402 $resql = $this->db->query($sql);
2403 if ($resql) {
2404 while ($obj = $this->db->fetch_object($resql)) {
2405 $this->nb["contracts"] = $obj->nb;
2406 }
2407 $this->db->free($resql);
2408 return 1;
2409 } else {
2410 dol_print_error($this->db);
2411 $this->error = $this->db->error();
2412 return -1;
2413 }
2414 }
2415
2416
2417 /* gestion des contacts d'un contrat */
2418
2424 public function getIdBillingContact()
2425 {
2426 return $this->getIdContact('external', 'BILLING');
2427 }
2428
2434 public function getIdServiceContact()
2435 {
2436 return $this->getIdContact('external', 'SERVICE');
2437 }
2438
2439
2447 public function initAsSpecimen()
2448 {
2449 global $user, $langs, $conf;
2450
2451 // Load array of products prodids
2452 $num_prods = 0;
2453 $prodids = array();
2454 $sql = "SELECT rowid";
2455 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2456 $sql .= " WHERE entity IN (".getEntity('product').")";
2457 $sql .= " AND tosell = 1";
2458 $sql .= $this->db->plimit(100);
2459
2460 $resql = $this->db->query($sql);
2461 if ($resql) {
2462 $num_prods = $this->db->num_rows($resql);
2463 $i = 0;
2464 while ($i < $num_prods) {
2465 $i++;
2466 $row = $this->db->fetch_row($resql);
2467 $prodids[$i] = $row[0];
2468 }
2469 }
2470
2471 // Initialise parametres
2472 $this->id = 0;
2473 $this->specimen = 1;
2474
2475 $this->ref = 'SPECIMEN';
2476 $this->ref_customer = 'SPECIMENCUST';
2477 $this->ref_supplier = 'SPECIMENSUPP';
2478 $this->socid = 1;
2479 $this->status = 0;
2480 $this->date_creation = (dol_now() - 3600 * 24 * 7);
2481 $this->date_contrat = dol_now();
2482 $this->commercial_signature_id = 1;
2483 $this->commercial_suivi_id = 1;
2484 $this->note_private = 'This is a comment (private)';
2485 $this->note_public = 'This is a comment (public)';
2486 $this->fk_project = 0;
2487 // Lines
2488 $nbp = 5;
2489 $xnbp = 0;
2490 while ($xnbp < $nbp) {
2491 $line = new ContratLigne($this->db);
2492 $line->qty = 1;
2493 $line->subprice = 100;
2494 $line->tva_tx = 19.6;
2495 $line->remise_percent = 10;
2496 $line->total_ht = 90;
2497 $line->total_ttc = 107.64; // 90 * 1.196
2498 $line->total_tva = 17.64;
2499 $line->date_start = dol_now() - 500000;
2500 $line->date_start_real = dol_now() - 200000;
2501 $line->date_end = dol_now() + 500000;
2502 $line->date_end_real = dol_now() - 100000;
2503 if ($num_prods > 0) {
2504 $prodid = mt_rand(1, $num_prods);
2505 $line->fk_product = $prodids[$prodid];
2506 }
2507 $this->lines[$xnbp] = $line;
2508 $xnbp++;
2509 }
2510 }
2511
2517 public function getLinesArray()
2518 {
2519 return $this->fetch_lines();
2520 }
2521
2527 public function getTicketsArray()
2528 {
2529 global $user;
2530
2531 $ticket = new Ticket($this->db);
2532 $nbTicket = $ticket->fetchAll($user, 'ASC', 't.datec', '', 0, '', array('t.fk_contract' => $this->id));
2533
2534 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2535 }
2536
2537
2549 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2550 {
2551 global $conf, $langs;
2552
2553 if (!dol_strlen($modele)) {
2554 $modele = ''; // No doc template/generation by default
2555
2556 if (!empty($this->model_pdf)) {
2557 $modele = $this->model_pdf;
2558 } elseif (getDolGlobalString('CONTRACT_ADDON_PDF')) {
2559 $modele = $conf->global->CONTRACT_ADDON_PDF;
2560 }
2561 }
2562
2563 if (empty($modele)) {
2564 return 0;
2565 } else {
2566 $langs->load("contracts");
2567 $outputlangs->load("products");
2568
2569 $modelpath = "core/modules/contract/doc/";
2570 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2571 }
2572 }
2573
2582 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2583 {
2584 $tables = array(
2585 'contrat'
2586 );
2587
2588 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2589 }
2590
2599 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2600 {
2601 $tables = array(
2602 'contratdet'
2603 );
2604
2605 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2606 }
2607
2616 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2617 {
2618 global $db, $langs, $conf, $hookmanager, $extrafields;
2619
2620 dol_include_once('/projet/class/project.class.php');
2621
2622 $error = 0;
2623
2624 $this->fetch($this->id);
2625
2626 // Load dest object
2627 $clonedObj = clone $this;
2628 $clonedObj->socid = $socid;
2629
2630 $this->db->begin();
2631
2632 $objsoc = new Societe($this->db);
2633
2634 $objsoc->fetch($clonedObj->socid);
2635
2636 // Clean data
2637 $clonedObj->statut = 0;
2638 // Clean extrafields
2639 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2640 $extrafields->fetch_name_optionals_label($this->table_element);
2641 foreach ($clonedObj->array_options as $key => $option) {
2642 $shortkey = preg_replace('/options_/', '', $key);
2643 //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2644 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2645 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2646 unset($clonedObj->array_options[$key]);
2647 }
2648 }
2649 }
2650
2651 if (!getDolGlobalString('CONTRACT_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').".php")) {
2652 $this->error = 'ErrorSetupNotComplete';
2653 dol_syslog($this->error);
2654 return -1;
2655 }
2656
2657 // Set ref
2658 require_once DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').'.php';
2659 $obj = $conf->global->CONTRACT_ADDON;
2660 $modContract = new $obj();
2661 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2662
2663 // get extrafields so they will be clone
2664 foreach ($this->lines as $line) {
2665 $line->fetch_optionals($line->id);
2666 }
2667
2668 // Create clone
2669 $clonedObj->context['createfromclone'] = 'createfromclone';
2670 $result = $clonedObj->create($user);
2671 if ($result < 0) {
2672 $error++;
2673 $this->error = $clonedObj->error;
2674 $this->errors[] = $clonedObj->error;
2675 } else {
2676 // copy external contacts if same company
2677 if ($this->socid == $clonedObj->socid) {
2678 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2679 $error++;
2680 }
2681 }
2682 }
2683
2684 if (!$error) {
2685 foreach ($this->lines as $line) {
2686 $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);
2687 if ($result < 0) {
2688 $error++;
2689 $this->error = $clonedObj->error;
2690 $this->errors[] = $clonedObj->error;
2691 }
2692 }
2693 }
2694
2695 if (!$error) {
2696 // Hook of thirdparty module
2697 if (is_object($hookmanager)) {
2698 $parameters = array(
2699 'objFrom' => $this,
2700 'clonedObj' => $clonedObj
2701 );
2702 $action = '';
2703 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2704 if ($reshook < 0) {
2705 $this->setErrorsFromObject($hookmanager);
2706 $error++;
2707 }
2708 }
2709 }
2710
2711 unset($clonedObj->context['createfromclone']);
2712
2713 // End
2714 if (!$error) {
2715 $this->db->commit();
2716 return $clonedObj->id;
2717 } else {
2718 $this->db->rollback();
2719 return -1;
2720 }
2721 }
2722
2723
2733 public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2734 {
2735 global $langs, $user;
2736
2737 $langs->load("agenda");
2738
2739 $now = dol_now();
2740
2741 $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2742
2743 $error = 0;
2744 $this->output = '';
2745 $this->error='';
2746
2747 $contractlineprocessed = array();
2748 $contractignored = array();
2749 $contracterror = array();
2750
2751 dol_syslog(__METHOD__, LOG_DEBUG);
2752
2753 $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2754 $sql.= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2755 $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2756 $sql.= ' WHERE cd.fk_contrat = c.rowid';
2757 $sql.= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2758 $sql.= " AND cd.statut = 4";
2759 if ($thirdparty_id > 0) {
2760 $sql.=" AND c.fk_soc = ".((int) $thirdparty_id);
2761 }
2762 //print $sql;
2763
2764 $resql = $this->db->query($sql);
2765 if ($resql) {
2766 $num = $this->db->num_rows($resql);
2767
2768 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2769
2770 $i=0;
2771 while ($i < $num) {
2772 $obj = $this->db->fetch_object($resql);
2773 if ($obj) {
2774 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2775 continue;
2776 }
2777
2778 // Load contract
2779 $object = new Contrat($this->db);
2780 $object->fetch($obj->rowid); // fetch also lines
2781 //$object->fetch_thirdparty();
2782
2783 if ($object->id <= 0) {
2784 $error++;
2785 $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2786 continue;
2787 }
2788
2789 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);
2790
2791 // Update expiration date of line
2792 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2793 $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2794 $duration_unit = preg_replace('/\d/', '', $obj->duration);
2795 //var_dump($expirationdate.' '.$enddatetoscan);
2796
2797 // Load linked ->linkedObjects (objects linked)
2798 // @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.
2799 $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2800
2801 // Test if there is at least 1 open invoice
2802 if (isset($object->linkedObjects['facture']) && is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2803 // Sort array of linked invoices by ascending date
2804 usort($object->linkedObjects['facture'], array('Contrat', 'contractCmpDate'));
2805 //dol_sort_array($object->linkedObjects['facture'], 'date');
2806
2807 $someinvoicenotpaid=0;
2808 foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2809 if ($invoice->statut == Facture::STATUS_DRAFT) {
2810 continue;
2811 } // Draft invoice are not invoice not paid
2812
2813 if (empty($invoice->paye)) {
2814 $someinvoicenotpaid++;
2815 }
2816 }
2817 if ($someinvoicenotpaid) {
2818 $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2819 $contractignored[$object->id] = $object->ref;
2820 continue;
2821 }
2822 }
2823
2824 if ($expirationdate && $expirationdate < $enddatetoscan) {
2825 dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2826 $newdate = $expirationdate;
2827 $protecti=0; //$protecti is to avoid infinite loop
2828 while ($newdate < $enddatetoscan && $protecti < 1000) {
2829 $newdate = dol_time_plus_duree($newdate, $duration_value, $duration_unit);
2830 $protecti++;
2831 }
2832
2833 if ($protecti < 1000) { // If not, there is a pb
2834 // We will update the end of date of contrat, so first we refresh contract data
2835 dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2836
2837 $this->db->begin();
2838
2839 $errorforlocaltransaction = 0;
2840
2841 $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2842 $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2843
2844 $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2845 $sqlupdate.= ' WHERE rowid = '.((int) $obj->lid);
2846 $resqlupdate = $this->db->query($sqlupdate);
2847 if ($resqlupdate) {
2848 $contractlineprocessed[$obj->lid]=$object->ref;
2849
2850 $actioncode = 'RENEW_CONTRACT';
2851 $now = dol_now();
2852
2853 // Create an event
2854 $actioncomm = new ActionComm($this->db);
2855 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2856 $actioncomm->code = 'AC_'.$actioncode;
2857 $actioncomm->label = $label;
2858 $actioncomm->datep = $now;
2859 $actioncomm->datef = $now;
2860 $actioncomm->percentage = -1; // Not applicable
2861 $actioncomm->socid = $object->socid;
2862 $actioncomm->authorid = $user->id; // User saving action
2863 $actioncomm->userownerid = $user->id; // Owner of action
2864 $actioncomm->fk_element = $object->id;
2865 $actioncomm->elementtype = 'contract';
2866 $actioncomm->note_private = $comment;
2867
2868 $ret = $actioncomm->create($user); // User creating action
2869 } else {
2870 $contracterror[$object->id]=$object->ref;
2871
2872 $error++;
2873 $errorforlocaltransaction++;
2874 $this->error = $this->db->lasterror();
2875 }
2876
2877 if (! $errorforlocaltransaction) {
2878 $this->db->commit();
2879 } else {
2880 $this->db->rollback();
2881 }
2882 } else {
2883 $error++;
2884 $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
2885 dol_syslog($this->error, LOG_ERR);
2886 }
2887 }
2888 }
2889 $i++;
2890 }
2891 } else {
2892 $error++;
2893 $this->error = $this->db->lasterror();
2894 }
2895
2896 $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed)>0 ? ' : '.join(',', $contractlineprocessed) : '');
2897
2898 return ($error ? 1 : 0);
2899 }
2900
2908 public static function contractCmpDate($a, $b)
2909 {
2910 if ($a->date == $b->date) {
2911 return strcmp((string) $a->id, (string) $b->id);
2912 }
2913 return ($a->date < $b->date) ? -1 : 1;
2914 }
2915
2923 public function getKanbanView($option = '', $arraydata = null)
2924 {
2925 global $langs;
2926
2927 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2928
2929 $return = '<div class="box-flex-item box-flex-grow-zero">';
2930 $return .= '<div class="info-box info-box-sm">';
2931 $return .= '<span class="info-box-icon bg-infobox-action">';
2932 $return .= img_picto('', $this->picto);
2933 $return .= '</span>';
2934 $return .= '<div class="info-box-content">';
2935 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2936 if ($selected >= 0) {
2937 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2938 }
2939 if (!empty($arraydata['thirdparty'])) {
2940 $tmpthirdparty = $arraydata['thirdparty'];
2941 $return .= '<br><div class="info-box-label inline-block">'.$tmpthirdparty->getNomUrl(1).'</div>';
2942 }
2943 if (property_exists($this, 'date_contrat')) {
2944 $return .= '<br><span class="opacitymedium">'.$langs->trans("DateContract").' : </span><span class="info-box-label">'.dol_print_date($this->date_contrat, 'day').'</span>';
2945 }
2946 if (method_exists($this, 'getLibStatut')) {
2947 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(7).'</div>';
2948 }
2949 $return .= '</div>';
2950 $return .= '</div>';
2951 $return .= '</div>';
2952 return $return;
2953 }
2954}
2955
2956
2961{
2965 public $element = 'contratdet';
2966
2970 public $table_element = 'contratdet';
2971
2976 public $element_for_permission = 'contrat';
2977
2981 public $id;
2982
2986 public $ref;
2987
2988 public $tms;
2989
2993 public $fk_contrat;
2994
2998 public $fk_product;
2999
3000 public $statut; // 0 inactive, 4 active, 5 closed
3001 public $type; // 0 for product, 1 for service
3002
3007 public $label;
3008
3013 public $libelle;
3014
3018 public $description;
3019
3020 public $product_type; // 0 for product, 1 for service
3021 public $product_ref;
3022 public $product_label;
3023
3024 public $date_commande;
3025
3026 public $date_start; // date start planned
3027 public $date_start_real; // date start real
3028 public $date_end; // date end planned
3029 public $date_end_real; // date end real
3030
3031 public $tva_tx;
3032 public $vat_src_code;
3033 public $localtax1_tx;
3034 public $localtax2_tx;
3035 public $localtax1_type; // Local tax 1 type
3036 public $localtax2_type; // Local tax 2 type
3037 public $qty;
3038 public $remise_percent;
3039 public $remise;
3040
3044 public $fk_remise_except;
3045
3046 public $subprice; // Unit price HT
3047
3053 public $price;
3054
3055 public $price_ht;
3056
3057 public $total_ht;
3058 public $total_tva;
3059 public $total_localtax1;
3060 public $total_localtax2;
3061 public $total_ttc;
3062
3066 public $fk_fournprice;
3067
3068 public $pa_ht;
3069
3070 public $info_bits;
3071
3075 public $fk_user_author;
3076
3080 public $fk_user_ouverture;
3081
3085 public $fk_user_cloture;
3086
3087 public $commentaire;
3088
3089
3093 public $rang = 0;
3094
3095
3096 const STATUS_INITIAL = 0;
3097 const STATUS_OPEN = 4;
3098 const STATUS_CLOSED = 5;
3099
3100
3101 // BEGIN MODULEBUILDER PROPERTIES
3105 public $fields = array(
3106 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
3107 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
3108 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
3109 'qty' =>array('type'=>'integer', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>35, 'isameasure'=>1),
3110 'total_ht' =>array('type'=>'integer', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>36, 'isameasure'=>1),
3111 'total_tva' =>array('type'=>'integer', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>37, 'isameasure'=>1),
3112 'total_ttc' =>array('type'=>'integer', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>38, 'isameasure'=>1),
3113 //'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
3114 //'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3115 'fk_contrat' =>array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'Contract', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
3116 'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
3117 //'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
3118 'note_private' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
3119 'note_public' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
3120 //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
3121 //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
3122 //'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
3123 'fk_user_ouverture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserStartingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3124 'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosingService', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
3125 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 4=>'Open', 5=>'Closed')),
3126 'rang' =>array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'position'=>500, 'default' =>0)
3127 );
3128 // END MODULEBUILDER PROPERTIES
3129
3130
3136 public function __construct($db)
3137 {
3138 $this->db = $db;
3139 }
3140
3141
3148 public function getLibStatut($mode)
3149 {
3150 return $this->LibStatut($this->statut, $mode, ((!empty($this->date_end)) ? ($this->date_end < dol_now() ? 1 : 0) : -1));
3151 }
3152
3153 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3163 public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
3164 {
3165 // phpcs:enable
3166 global $langs;
3167 $langs->load("contracts");
3168
3169 if ($status == self::STATUS_INITIAL) {
3170 $labelStatus = $langs->transnoentities("ServiceStatusInitial");
3171 $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
3172 } elseif ($status == self::STATUS_OPEN && $expired == -1) {
3173 $labelStatus = $langs->transnoentities("ServiceStatusRunning");
3174 $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
3175 } elseif ($status == self::STATUS_OPEN && $expired == 0) {
3176 $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
3177 $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
3178 } elseif ($status == self::STATUS_OPEN && $expired == 1) {
3179 $labelStatus = $langs->transnoentities("ServiceStatusLate");
3180 $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
3181 } elseif ($status == self::STATUS_CLOSED) {
3182 $labelStatus = $langs->transnoentities("ServiceStatusClosed");
3183 $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
3184 }
3185
3186 $statusType = 'status'.$status;
3187 if ($status == self::STATUS_OPEN && $expired == 1) {
3188 $statusType = 'status1';
3189 }
3190 if ($status == self::STATUS_CLOSED) {
3191 $statusType = 'status6';
3192 }
3193
3194 $params = array();
3195 $reg = array();
3196 if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
3197 $params = array('badgeParams'=>array('css' => $reg[1]));
3198 }
3199 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
3200 }
3201
3208 public function getTooltipContentArray($params)
3209 {
3210 global $conf, $langs, $user;
3211
3212 $datas = [];
3213 $datas['label'] = $langs->trans("ShowContractOfService").': '.$this->label;
3214 if (empty($datas['label'])) {
3215 $datas['label'] = $this->description;
3216 }
3217
3218 return $datas;
3219 }
3220
3228 public function getNomUrl($withpicto = 0, $maxlength = 0)
3229 {
3230 global $langs;
3231
3232 $result = '';
3233 $label = $langs->trans("ShowContractOfService").': '.$this->label;
3234 if (empty($label)) {
3235 $label = $this->description;
3236 }
3237 $classfortooltip = 'classfortooltip';
3238 $dataparams = '';
3239 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3240 $params = [
3241 'id' => $this->fk_contrat,
3242 'objecttype' => $this->element,
3243 ];
3244 $classfortooltip = 'classforajaxtooltip';
3245 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3246 $label = '';
3247 }
3248
3249 $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'"';
3250 $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3251 $link .= $dataparams.' class="'.$classfortooltip.'">';
3252 $linkend = '</a>';
3253
3254 $picto = 'service';
3255 if ($this->type == 0) {
3256 $picto = 'product';
3257 }
3258
3259 if ($withpicto) {
3260 $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
3261 }
3262 if ($withpicto && $withpicto != 2) {
3263 $result .= ' ';
3264 }
3265 if ($withpicto != 2) {
3266 $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
3267 }
3268 return $result;
3269 }
3270
3278 public function fetch($id, $ref = '')
3279 {
3280 // Check parameters
3281 if (empty($id) && empty($ref)) {
3282 return -1;
3283 }
3284
3285 $sql = "SELECT";
3286 $sql .= " t.rowid,";
3287 $sql .= " t.tms,";
3288 $sql .= " t.fk_contrat,";
3289 $sql .= " t.fk_product,";
3290 $sql .= " t.statut,";
3291 $sql .= " t.label,"; // This field is not used. Only label of product
3292 $sql .= " p.ref as product_ref,";
3293 $sql .= " p.label as product_label,";
3294 $sql .= " p.description as product_desc,";
3295 $sql .= " p.fk_product_type as product_type,";
3296 $sql .= " t.description,";
3297 $sql .= " t.date_commande,";
3298 $sql .= " t.date_ouverture_prevue as date_start,";
3299 $sql .= " t.date_ouverture as date_start_real,";
3300 $sql .= " t.date_fin_validite as date_end,";
3301 $sql .= " t.date_cloture as date_end_real,";
3302 $sql .= " t.tva_tx,";
3303 $sql .= " t.vat_src_code,";
3304 $sql .= " t.localtax1_tx,";
3305 $sql .= " t.localtax2_tx,";
3306 $sql .= " t.localtax1_type,";
3307 $sql .= " t.localtax2_type,";
3308 $sql .= " t.qty,";
3309 $sql .= " t.remise_percent,";
3310 $sql .= " t.remise,";
3311 $sql .= " t.fk_remise_except,";
3312 $sql .= " t.subprice,";
3313 $sql .= " t.price_ht,";
3314 $sql .= " t.total_ht,";
3315 $sql .= " t.total_tva,";
3316 $sql .= " t.total_localtax1,";
3317 $sql .= " t.total_localtax2,";
3318 $sql .= " t.total_ttc,";
3319 $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
3320 $sql .= " t.buy_price_ht as pa_ht,";
3321 $sql .= " t.info_bits,";
3322 $sql .= " t.fk_user_author,";
3323 $sql .= " t.fk_user_ouverture,";
3324 $sql .= " t.fk_user_cloture,";
3325 $sql .= " t.commentaire,";
3326 $sql .= " t.fk_unit,";
3327 $sql .= " t.rang";
3328 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
3329 if ($id) {
3330 $sql .= " WHERE t.rowid = ".((int) $id);
3331 }
3332 if ($ref) {
3333 $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
3334 }
3335
3336 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
3337 $resql = $this->db->query($sql);
3338 if ($resql) {
3339 if ($this->db->num_rows($resql)) {
3340 $obj = $this->db->fetch_object($resql);
3341
3342 $this->id = $obj->rowid;
3343 $this->ref = $obj->rowid;
3344
3345 $this->tms = $this->db->jdate($obj->tms);
3346 $this->fk_contrat = $obj->fk_contrat;
3347 $this->fk_product = $obj->fk_product;
3348 $this->statut = $obj->statut;
3349 $this->product_ref = $obj->product_ref;
3350 $this->product_label = $obj->product_label;
3351 $this->product_type = $obj->product_type;
3352 $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
3353 $this->description = $obj->description;
3354 $this->date_commande = $this->db->jdate($obj->date_commande);
3355
3356 $this->date_start = $this->db->jdate($obj->date_start);
3357 $this->date_start_real = $this->db->jdate($obj->date_start_real);
3358 $this->date_end = $this->db->jdate($obj->date_end);
3359 $this->date_end_real = $this->db->jdate($obj->date_end_real);
3360 // For backward compatibility
3361 //$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
3362 //$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
3363 //$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
3364 //$this->date_cloture = $this->db->jdate($obj->date_cloture);
3365
3366 $this->tva_tx = $obj->tva_tx;
3367 $this->vat_src_code = $obj->vat_src_code;
3368 $this->localtax1_tx = $obj->localtax1_tx;
3369 $this->localtax2_tx = $obj->localtax2_tx;
3370 $this->localtax1_type = $obj->localtax1_type;
3371 $this->localtax2_type = $obj->localtax2_type;
3372 $this->qty = $obj->qty;
3373 $this->remise_percent = $obj->remise_percent;
3374 $this->fk_remise_except = $obj->fk_remise_except;
3375 $this->subprice = $obj->subprice;
3376 $this->price_ht = $obj->price_ht;
3377 $this->total_ht = $obj->total_ht;
3378 $this->total_tva = $obj->total_tva;
3379 $this->total_localtax1 = $obj->total_localtax1;
3380 $this->total_localtax2 = $obj->total_localtax2;
3381 $this->total_ttc = $obj->total_ttc;
3382 $this->info_bits = $obj->info_bits;
3383 $this->fk_user_author = $obj->fk_user_author;
3384 $this->fk_user_ouverture = $obj->fk_user_ouverture;
3385 $this->fk_user_cloture = $obj->fk_user_cloture;
3386 $this->commentaire = $obj->commentaire;
3387 $this->fk_fournprice = $obj->fk_fournprice;
3388
3389 $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
3390 $this->pa_ht = $marginInfos[0];
3391 $this->fk_unit = $obj->fk_unit;
3392
3393 $this->rang = $obj->rang;
3394
3395 $this->fetch_optionals();
3396 }
3397
3398 $this->db->free($resql);
3399
3400 return 1;
3401 } else {
3402 $this->error = "Error ".$this->db->lasterror();
3403 return -1;
3404 }
3405 }
3406
3407
3415 public function update($user, $notrigger = 0)
3416 {
3417 global $mysoc;
3418
3419 $error = 0;
3420
3421 // Clean parameters
3422 $this->fk_contrat = (int) $this->fk_contrat;
3423 $this->fk_product = (int) $this->fk_product;
3424 $this->statut = (int) $this->statut;
3425 $this->label = trim($this->label);
3426 $this->description = trim($this->description);
3427 $this->vat_src_code = trim($this->vat_src_code);
3428 $this->tva_tx = trim($this->tva_tx);
3429 $this->localtax1_tx = trim($this->localtax1_tx);
3430 $this->localtax2_tx = trim($this->localtax2_tx);
3431 $this->qty = trim($this->qty);
3432 $this->remise_percent = trim($this->remise_percent);
3433 $this->fk_remise_except = (int) $this->fk_remise_except;
3434 $this->subprice = price2num($this->subprice);
3435 $this->price_ht = price2num($this->price_ht);
3436 $this->total_ht = trim($this->total_ht);
3437 $this->total_tva = trim($this->total_tva);
3438 $this->total_localtax1 = trim($this->total_localtax1);
3439 $this->total_localtax2 = trim($this->total_localtax2);
3440 $this->total_ttc = trim($this->total_ttc);
3441 $this->info_bits = trim($this->info_bits);
3442 $this->fk_user_author = (int) $this->fk_user_author;
3443 $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
3444 $this->fk_user_cloture = (int) $this->fk_user_cloture;
3445 $this->commentaire = trim($this->commentaire);
3446 $this->rang = (int) $this->rang;
3447 //if (empty($this->subprice)) $this->subprice = 0;
3448 if (empty($this->price_ht)) {
3449 $this->price_ht = 0;
3450 }
3451 if (empty($this->total_ht)) {
3452 $this->total_ht = 0;
3453 }
3454 if (empty($this->total_tva)) {
3455 $this->total_tva = 0;
3456 }
3457 if (empty($this->total_ttc)) {
3458 $this->total_ttc = 0;
3459 }
3460 if (empty($this->localtax1_tx)) {
3461 $this->localtax1_tx = 0;
3462 }
3463 if (empty($this->localtax2_tx)) {
3464 $this->localtax2_tx = 0;
3465 }
3466 if (empty($this->remise_percent)) {
3467 $this->remise_percent = 0;
3468 }
3469 // For backward compatibility
3470 if (empty($this->date_start)) {
3471 $this->date_start = $this->date_start;
3472 }
3473 if (empty($this->date_start_real)) {
3474 $this->date_start_real = $this->date_start_real;
3475 }
3476 if (empty($this->date_end)) {
3477 $this->date_end = $this->date_end;
3478 }
3479 if (empty($this->date_end_real)) {
3480 $this->date_end_real = $this->date_end_real;
3481 }
3482
3483 // Calcul du total TTC et de la TVA pour la ligne a partir de
3484 // qty, pu, remise_percent et txtva
3485 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3486 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3487 $localtaxes_type = getLocalTaxesFromRate($this->tva_tx, 0, $this->thirdparty, $mysoc);
3488
3489 $tabprice = calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
3490 $this->total_ht = $tabprice[0];
3491 $this->total_tva = $tabprice[1];
3492 $this->total_ttc = $tabprice[2];
3493 $this->total_localtax1 = $tabprice[9];
3494 $this->total_localtax2 = $tabprice[10];
3495
3496 if (empty($this->pa_ht)) {
3497 $this->pa_ht = 0;
3498 }
3499
3500 // if buy price not defined, define buyprice as configured in margin admin
3501 if ($this->pa_ht == 0) {
3502 if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
3503 return $result;
3504 } else {
3505 $this->pa_ht = $result;
3506 }
3507 }
3508
3509 // $this->oldcopy should have been set by the caller of update (here properties were already modified)
3510 if (empty($this->oldcopy)) {
3511 $this->oldcopy = dol_clone($this);
3512 }
3513
3514 $this->db->begin();
3515
3516 // Update request
3517 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3518 $sql .= " fk_contrat = ".((int) $this->fk_contrat).",";
3519 $sql .= " fk_product = ".($this->fk_product ? ((int) $this->fk_product) : 'null').",";
3520 $sql .= " statut = ".((int) $this->statut).",";
3521 $sql .= " label = '".$this->db->escape($this->label)."',";
3522 $sql .= " description = '".$this->db->escape($this->description)."',";
3523 $sql .= " date_commande = ".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
3524 $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3525 $sql .= " date_ouverture = ".($this->date_start_real != '' ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3526 $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3527 $sql .= " date_cloture = ".($this->date_end_real != '' ? "'".$this->db->idate($this->date_end_real)."'" : "null").",";
3528 $sql .= " vat_src_code = '".$this->db->escape($this->vat_src_code)."',";
3529 $sql .= " tva_tx = ".price2num($this->tva_tx).",";
3530 $sql .= " localtax1_tx = ".price2num($this->localtax1_tx).",";
3531 $sql .= " localtax2_tx = ".price2num($this->localtax2_tx).",";
3532 $sql .= " qty = ".price2num($this->qty).",";
3533 $sql .= " remise_percent = ".price2num($this->remise_percent).",";
3534 $sql .= " remise = ".($this->remise ? price2num($this->remise) : "null").",";
3535 $sql .= " fk_remise_except = ".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
3536 $sql .= " subprice = ".($this->subprice != '' ? $this->subprice : "null").",";
3537 $sql .= " price_ht = ".($this->price_ht != '' ? $this->price_ht : "null").",";
3538 $sql .= " total_ht = ".$this->total_ht.",";
3539 $sql .= " total_tva = ".$this->total_tva.",";
3540 $sql .= " total_localtax1 = ".$this->total_localtax1.",";
3541 $sql .= " total_localtax2 = ".$this->total_localtax2.",";
3542 $sql .= " total_ttc = ".$this->total_ttc.",";
3543 $sql .= " fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
3544 $sql .= " buy_price_ht = '".price2num($this->pa_ht)."',";
3545 $sql .= " info_bits = '".$this->db->escape($this->info_bits)."',";
3546 $sql .= " fk_user_author = ".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
3547 $sql .= " fk_user_ouverture = ".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
3548 $sql .= " fk_user_cloture = ".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3549 $sql .= " commentaire = '".$this->db->escape($this->commentaire)."',";
3550 $sql .= " fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit).",";
3551 $sql .= " rang = ".(empty($this->rang) ? '0' : (int) $this->rang);
3552 $sql .= " WHERE rowid = ".((int) $this->id);
3553
3554 dol_syslog(get_class($this)."::update", LOG_DEBUG);
3555 $resql = $this->db->query($sql);
3556 if (!$resql) {
3557 $this->error = "Error ".$this->db->lasterror();
3558 $error++;
3559 }
3560
3561 if (!$error) { // For avoid conflicts if trigger used
3562 $result = $this->insertExtraFields();
3563 if ($result < 0) {
3564 $error++;
3565 }
3566 }
3567
3568 // If we change a planned date (start or end) of one contract line, sync dates for all other services too
3569 if (!$error && getDolGlobalString('CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES')) {
3570 dol_syslog(get_class($this)."::update CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES is on so we update date for all lines", LOG_DEBUG);
3571
3572 if ($this->date_start != $this->oldcopy->date_start) {
3573 $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3574 $sql .= " date_ouverture_prevue = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null");
3575 $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3576
3577 $resql = $this->db->query($sql);
3578 if (!$resql) {
3579 $error++;
3580 $this->error = "Error ".$this->db->lasterror();
3581 }
3582 }
3583 if ($this->date_end != $this->oldcopy->date_end) {
3584 $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3585 $sql .= " date_fin_validite = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null");
3586 $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
3587
3588 $resql = $this->db->query($sql);
3589 if (!$resql) {
3590 $error++;
3591 $this->error = "Error ".$this->db->lasterror();
3592 }
3593 }
3594 }
3595
3596 if (!$error && !$notrigger) {
3597 // Call trigger
3598 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
3599 if ($result < 0) {
3600 $error++;
3601 $this->db->rollback();
3602 }
3603 // End call triggers
3604 }
3605
3606 if (!$error) {
3607 $this->db->commit();
3608 return 1;
3609 } else {
3610 $this->db->rollback();
3611 $this->errors[] = $this->error;
3612 return -1;
3613 }
3614 }
3615
3616
3617 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3624 public function update_total()
3625 {
3626 // phpcs:enable
3627 $this->db->begin();
3628
3629 // Mise a jour ligne en base
3630 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3631 $sql .= " total_ht=".price2num($this->total_ht, 'MT');
3632 $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
3633 $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT');
3634 $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT');
3635 $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
3636 $sql .= " WHERE rowid = ".((int) $this->id);
3637
3638 dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3639
3640 $resql = $this->db->query($sql);
3641 if ($resql) {
3642 $this->db->commit();
3643 return 1;
3644 } else {
3645 $this->error = $this->db->error();
3646 $this->db->rollback();
3647 return -2;
3648 }
3649 }
3650
3651
3658 public function insert($notrigger = 0)
3659 {
3660 global $user;
3661
3662 $error = 0;
3663
3664 // Insertion dans la base
3665 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3666 $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3667 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3668 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3669 $sql .= " info_bits,";
3670 $sql .= " rang,";
3671 $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3672 if ($this->date_start > 0) {
3673 $sql .= ",date_ouverture_prevue";
3674 }
3675 if ($this->date_end > 0) {
3676 $sql .= ",date_fin_validite";
3677 }
3678 $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3679 $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3680 $sql .= " '".$this->db->escape($this->qty)."',";
3681 $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3682 $sql .= " '".$this->db->escape($this->tva_tx)."',";
3683 $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3684 $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3685 $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3686 $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3687 $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3688 $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3689 $sql .= " '".$this->db->escape($this->info_bits)."',";
3690 $sql .= " ".(empty($this->rang) ? '0' : (int) $this->rang).",";
3691 $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3692 if ($this->fk_fournprice > 0) {
3693 $sql .= ' '.((int) $this->fk_fournprice).',';
3694 } else {
3695 $sql .= ' null,';
3696 }
3697 if ($this->pa_ht > 0) {
3698 $sql .= ' '.((float) price2num($this->pa_ht));
3699 } else {
3700 $sql .= ' null';
3701 }
3702 if ($this->date_start > 0) {
3703 $sql .= ",'".$this->db->idate($this->date_start)."'";
3704 }
3705 if ($this->date_end > 0) {
3706 $sql .= ",'".$this->db->idate($this->date_end)."'";
3707 }
3708 $sql .= ")";
3709
3710 dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3711
3712 $resql = $this->db->query($sql);
3713 if ($resql) {
3714 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3715
3716 // Insert of extrafields
3717 if (!$error) {
3718 $result = $this->insertExtraFields();
3719 if ($result < 0) {
3720 $this->db->rollback();
3721 return -1;
3722 }
3723 }
3724
3725 if (!$notrigger) {
3726 // Call trigger
3727 $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3728 if ($result < 0) {
3729 $this->db->rollback();
3730 return -1;
3731 }
3732 // End call triggers
3733 }
3734
3735 $this->db->commit();
3736 return 1;
3737 } else {
3738 $this->db->rollback();
3739 $this->error = $this->db->error()." sql=".$sql;
3740 return -1;
3741 }
3742 }
3743
3744 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3754 public function active_line($user, $date, $date_end = '', $comment = '')
3755 {
3756 // phpcs:enable
3757 $error = 0;
3758
3759 $this->db->begin();
3760
3761 $this->statut = ContratLigne::STATUS_OPEN;
3762 $this->date_start_real = $date;
3763 $this->date_end = $date_end;
3764 $this->fk_user_ouverture = $user->id;
3765 $this->date_end_real = null;
3766 $this->commentaire = $comment;
3767
3768 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) $this->statut).",";
3769 $sql .= " date_ouverture = ".(dol_strlen($this->date_start_real) != 0 ? "'".$this->db->idate($this->date_start_real)."'" : "null").",";
3770 if ($date_end >= 0) {
3771 $sql .= " date_fin_validite = ".(dol_strlen($this->date_end) != 0 ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3772 }
3773 $sql .= " fk_user_ouverture = ".((int) $this->fk_user_ouverture).",";
3774 $sql .= " date_cloture = null,";
3775 $sql .= " commentaire = '".$this->db->escape($comment)."'";
3776 $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3777
3778 dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3779 $resql = $this->db->query($sql);
3780 if ($resql) {
3781 // Call trigger
3782 $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3783 if ($result < 0) {
3784 $error++;
3785 }
3786 // End call triggers
3787
3788 if (!$error) {
3789 $this->db->commit();
3790 return 1;
3791 } else {
3792 $this->db->rollback();
3793 return -1;
3794 }
3795 } else {
3796 $this->error = $this->db->lasterror();
3797 $this->db->rollback();
3798 return -1;
3799 }
3800 }
3801
3802 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3812 public function close_line($user, $date_end_real, $comment = '', $notrigger = 0)
3813 {
3814 // phpcs:enable
3815 $this->date_cloture = $date_end_real;
3816 $this->date_end_real = $date_end_real;
3817 $this->user_closing_id = $user->id;
3818 $this->commentaire = $comment;
3819
3820 $error = 0;
3821
3822 // statut actif : 4
3823
3824 $this->db->begin();
3825
3826 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
3827 $sql .= " date_cloture = '".$this->db->idate($date_end_real)."',";
3828 $sql .= " fk_user_cloture = ".((int) $user->id).",";
3829 $sql .= " commentaire = '".$this->db->escape($comment)."'";
3830 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
3831
3832 $resql = $this->db->query($sql);
3833 if ($resql) {
3834 if (!$notrigger) {
3835 // Call trigger
3836 $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3837 if ($result < 0) {
3838 $error++;
3839 $this->db->rollback();
3840 return -1;
3841 }
3842 // End call triggers
3843 }
3844
3845 $this->db->commit();
3846 return 1;
3847 } else {
3848 $this->error = $this->db->lasterror();
3849 $this->db->rollback();
3850 return -1;
3851 }
3852 }
3853}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Definition security.php:604
$object ref
Definition info.php:79
Class to manage agenda events (actions)
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
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
fetch_project()
Load the project with id $this->fk_project into this->project.
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage contracts.
static contractCmpDate($a, $b)
Used to sort lines by date.
createFromClone(User $user, $socid=0, $notrigger=0)
Load an object from its id and create a new one in database.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
update_statut($user)
Update statut of contract according to services.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_start_real='', $date_end_real='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Mets a jour une ligne de contrat.
getTicketsArray()
Create an array of associated tickets.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
create($user)
Create a contract into database.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
array_detail($status=-1)
Return list of line rowid.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Ajoute une ligne de contrat en base.
update($user, $notrigger=0)
Update object into database.
closeAll(User $user, $notrigger=0, $comment='')
Close all lines of a contract.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
deleteline($idline, User $user)
Delete a contract line.
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 clicable name (with picto eventually)
info($id)
Charge les informations 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.
load_state_board()
Charge indicateurs this->nb de tableau de bord.
getNextNumRef($soc)
Return next contract ref.
Class to manage lines of contracts.
active_line($user, $date, $date_end='', $comment='')
Activate a contract line.
getLibStatut($mode)
Return label of this contract line status.
insert($notrigger=0)
Inserts a contrat line into database.
fetch($id, $ref='')
Load object in memory from database.
close_line($user, $date_end_real, $comment='', $notrigger=0)
Close a contract line.
update($user, $notrigger=0)
Update database for contract line.
update_total()
Update in database the fields total_xxx of lines Used by migration process.
static LibStatut($status, $mode, $expired=-1, $moreatt='')
Return label of a contract line status.
__construct($db)
Constructor.
getTooltipContentArray($params)
getTooltipContentArray
getNomUrl($withpicto=0, $maxlength=0)
Return clicable name (with picto eventually) for ContratLigne.
Class to manage Dolibarr database access.
Class to manage shipments.
const STATUS_DRAFT
Draft status.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($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:62
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall right right takeposterminal SELECT e e e e e statut
Definition invoice.php:1926
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:86
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:121