dolibarr 25.0.0-alpha
contrat.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Destailleur Laurent <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6 * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
7 * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
8 * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
9 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
12 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
15 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
16 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com
17 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 3 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <https://www.gnu.org/licenses/>.
31 */
32
39require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40require_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
41require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonsignedobject.class.php';
44require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
45
52class Contrat extends CommonObject
53{
54 use CommonSignedObject;
55
59 public $element = 'contrat';
60
64 public $table_element = 'contrat';
65
69 public $table_element_line = 'contratdet';
70
74 public $fk_element = 'fk_contrat';
75
79 public $picto = 'contract';
80
85 public $restrictiononfksoc = 1;
86
90 protected $table_ref_field = 'ref';
91
96 public $ref_customer;
97
101 public $from;
102
107 public $ref_supplier;
108
113 public $fk_contract_type = 0;
114
119 public $socid;
120
126 public $fk_soc;
127
131 public $societe;
132
138 public $statut = 0;
139
144 public $status = 0;
145
149 public $product;
150
154 public $fk_user_author;
155
161 public $user_author_id;
162
163
168 public $user_creation;
169
173 public $user_cloture;
174
178 public $date_contrat;
179
183 public $commercial_signature_id;
184
189 public $fk_commercial_signature;
190
194 public $commercial_suivi_id;
195
201 public $fk_commercial_suivi;
202
206 public $extraparams = array();
207
211 public $lines = array();
212
216 public $nbofservices;
220 public $nbofserviceswait;
224 public $nbofservicesopened;
228 public $nbofservicesexpired;
232 public $nbofservicesclosed;
233 //public $lower_planned_end_date;
234 //public $higher_planner_end_date;
235
240 protected $lines_id_index_mapper = array();
241
242
267 // BEGIN MODULEBUILDER PROPERTIES
271 public $fields = array(
272 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
273 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'showoncombobox' => 1, 'position' => 15, 'searchall' => 1),
274 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 20),
275 'ref_customer' => array('type' => 'varchar(50)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 25, 'searchall' => 1),
276 'ref_supplier' => array('type' => 'varchar(50)', 'label' => 'RefSupplier', 'enabled' => 1, 'visible' => -1, 'position' => 26, 'searchall' => 1),
277 'fk_contract_type' => array('type' => 'smallint(6)', 'label' => 'ContractType', 'enabled' => 1, 'visible' => -1, 'position' => 27, 'default' => '0', 'arrayofkeyval' => array(0 => 'CustomerContract', 1 => 'SupplierContract')),
278 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 30, 'index' => 1),
279 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 35),
280 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 40),
281 'date_contrat' => array('type' => 'datetime', 'label' => 'Date contrat', 'enabled' => 1, 'visible' => -1, 'position' => 45),
282 'signed_status' => array('type' => 'smallint(6)', 'label' => 'SignedStatus', 'enabled' => 1, 'visible' => -1, 'position' => 50, 'arrayofkeyval' => array(0 => 'NoSignature', 1 => 'SignedSender', 2 => 'SignedReceiver', 3 => 'SignedReceiverOnline', 9 => 'SignedAll')),
283 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 70),
284 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 75),
285 'fk_commercial_signature' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative Signature', 'enabled' => 1, 'visible' => -1, 'position' => 80),
286 'fk_commercial_suivi' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'SaleRepresentative follower', 'enabled' => 1, 'visible' => -1, 'position' => 85),
287 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 90),
288 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 105, 'searchall' => 1),
289 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 110, 'searchall' => 1),
290 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 115),
291 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 120),
292 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 125),
293 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 135),
294 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'Last main doc', 'enabled' => 1, 'visible' => -1, 'position' => 140),
295 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
296 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245),
297 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
298 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
299 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 260, 'isameasure' => 1),
300 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 265, 'isameasure' => 1),
301 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => -1, 'position' => 500, 'notnull' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 2 => 'Closed'))
302 );
303 // END MODULEBUILDER PROPERTIES
304
305 const STATUS_DRAFT = 0;
306 const STATUS_VALIDATED = 1;
307 const STATUS_CLOSED = 2;
308
314 public function __construct($db)
315 {
316 $this->db = $db;
317
318 $this->ismultientitymanaged = 1;
319 $this->isextrafieldmanaged = 1;
320 }
321
328 public function getNextNumRef($soc)
329 {
330 global $db, $langs, $conf;
331 $langs->load("contracts");
332
333 if (getDolGlobalString('CONTRACT_ADDON')) {
334 $mybool = false;
335
336 $file = getDolGlobalString('CONTRACT_ADDON') . ".php";
337 $classname = getDolGlobalString('CONTRACT_ADDON');
338
339 // Include file with class
340 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
341
342 foreach ($dirmodels as $reldir) {
343 $dir = dol_buildpath($reldir."core/modules/contract/");
344
345 // Load file with numbering class (if found)
346 $mybool = ((bool) @include_once $dir.$file) || $mybool;
347 }
348
349 if (!$mybool) {
350 dol_print_error(null, "Failed to include file ".$file);
351 return '';
352 }
353
354 $obj = new $classname();
355 '@phan-var-force ModelNumRefContracts $obj';
357 $numref = $obj->getNextValue($soc, $this);
358
359 if ($numref != "") {
360 return $numref;
361 } else {
362 $this->error = $obj->error;
363 dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
364 return "";
365 }
366 } else {
367 $langs->load("errors");
368 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
369 return "";
370 }
371 }
372
373 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
384 public function active_line($user, $line_id, $date_start, $date_end = '', $comment = '')
385 {
386 // phpcs:enable
387 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
388 if ($result < 0) {
389 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
390 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
391 }
392 return $result;
393 }
394
395
396 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
406 public function close_line($user, $line_id, $date_end, $comment = '')
407 {
408 // phpcs:enable
409 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
410 if ($result < 0) {
411 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
412 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
413 }
414 return $result;
415 }
416
417
429 public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '', $date_end = '')
430 {
431 if (empty($date_start)) {
433 }
434
435 $this->db->begin();
436
437 $error = 0;
438
439 // Load lines
440 $this->fetch_lines();
441
442 foreach ($this->lines as $contratline) {
443 // Open lines not already open
444 if ($contratline->status != ContratLigne::STATUS_OPEN) {
445 $contratline->context = $this->context;
446
447 $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
448 if ($result < 0) {
449 $error++;
450 $this->setErrorsFromObject($contratline);
451 break;
452 }
453 }
454 }
455
456 if (!$error && $this->status == 0) {
457 $result = $this->validate($user, '', $notrigger);
458 if ($result < 0) {
459 $error++;
460 }
461 }
462
463 if (!$error) {
464 $this->db->commit();
465 return 1;
466 } else {
467 $this->db->rollback();
468 return -1;
469 }
470 }
471
482 public function closeAll(User $user, $notrigger = 0, $comment = '', $nofetchlines = 0)
483 {
484 dol_syslog("closeAll begin", LOG_DEBUG, 1);
485
486 $this->db->begin();
487
488 // Load lines
489 if (empty($nofetchlines)) {
490 $this->fetch_lines();
491 }
492
493 $now = dol_now();
494
495 $error = 0;
496
497 foreach ($this->lines as $contratline) {
498 // Close lines not already closed
499 if ($contratline->status != ContratLigne::STATUS_CLOSED) {
500 $contratline->date_end_real = $now;
501 $contratline->date_cloture = $now; // For backward compatibility
502 $contratline->user_closing_id = $user->id;
503 $contratline->status = ContratLigne::STATUS_CLOSED;
504
505 $result = $contratline->close_line($user, $now, $comment, $notrigger);
506
507 if ($result < 0) {
508 $error++;
509 $this->error = $contratline->error.($contratline->error ? ' ('.$this->ref.')' : '');
510 $this->errors = $contratline->errors;
511 break;
512 }
513 }
514 }
515
516 if (!$error && $this->status == 0) {
517 $result = $this->validate($user, '', $notrigger);
518 if ($result < 0) {
519 $error++;
520 }
521 }
522
523 if (!$error) {
524 $this->db->commit();
525
526 dol_syslog("closeAll end", LOG_DEBUG, -1);
527
528 return 1;
529 } else {
530 $this->db->rollback();
531
532 dol_syslog("closeAll end", LOG_DEBUG, -1);
533
534 return -1;
535 }
536 }
537
546 public function validate(User $user, $force_number = '', $notrigger = 0)
547 {
548 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
549 global $conf;
550
551 $now = dol_now();
552
553 $error = 0;
554 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
555
556
557 $this->db->begin();
558
559 $this->fetch_thirdparty();
560
561 // A contract is validated so we can move thirdparty to status customer
562 if (!getDolGlobalString('CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
563 $result = $this->thirdparty->setAsCustomer();
564 }
565
566 // Define new ref
567 if ($force_number) {
568 $num = $force_number;
569 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
570 $num = $this->getNextNumRef($this->thirdparty);
571 } else {
572 $num = (string) $this->ref;
573 }
574 $this->newref = dol_sanitizeFileName($num);
575
576 if ($num) {
577 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
578 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
579
580 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
581 $resql = $this->db->query($sql);
582 if (!$resql) {
583 dol_print_error($this->db);
584 $error++;
585 $this->error = $this->db->lasterror();
586 }
587
588 // Trigger calls
589 if (!$error && !$notrigger) {
590 // Call trigger
591 $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
592 if ($result < 0) {
593 $error++;
594 }
595 // End call triggers
596 }
597
598 if (!$error) {
599 $this->oldref = $this->ref;
600
601 // Rename directory if dir was a temporary ref
602 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
603 // Now we rename also files into index
604 $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)."'";
605 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
606 $resql = $this->db->query($sql);
607 if (!$resql) {
608 $error++;
609 $this->error = $this->db->lasterror();
610 }
611 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files SET filepath = 'contract/".$this->db->escape($this->newref)."'";
612 $sql .= " WHERE filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
613 $resql = $this->db->query($sql);
614 if (!$resql) {
615 $error++;
616 $this->error = $this->db->lasterror();
617 }
618
619 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
620 $oldref = dol_sanitizeFileName($this->ref);
621 $newref = dol_sanitizeFileName($num);
622 $dirsource = $conf->contract->dir_output.'/'.$oldref;
623 $dirdest = $conf->contract->dir_output.'/'.$newref;
624 if (!$error && file_exists($dirsource)) {
625 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
626
627 if (@rename($dirsource, $dirdest)) {
628 dol_syslog("Rename ok");
629 // Rename docs starting with $oldref with $newref
630 $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
631 foreach ($listoffiles as $fileentry) {
632 $dirsource = $fileentry['name'];
633 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
634 $dirsource = $fileentry['path'].'/'.$dirsource;
635 $dirdest = $fileentry['path'].'/'.$dirdest;
636 @rename($dirsource, $dirdest);
637 }
638 }
639 }
640 }
641 }
642
643 // Set new ref and define current status
644 if (!$error) {
645 $this->ref = $num;
646 $this->status = self::STATUS_VALIDATED;
647 $this->statut = self::STATUS_VALIDATED; // deprecated
648 $this->date_validation = $now;
649 }
650 } else {
651 $error++;
652 }
653
654 if (!$error) {
655 $this->db->commit();
656 return 1;
657 } else {
658 $this->db->rollback();
659 return -1;
660 }
661 }
662
670 public function reopen($user, $notrigger = 0)
671 {
672 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
673
674 $now = dol_now();
675
676 $error = 0;
677 dol_syslog(get_class($this).'::reopen user='.$user->id);
678
679 $this->db->begin();
680
681 $this->fetch_thirdparty();
682
683 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
684 //$sql.= ", fk_user_valid = null, date_valid = null";
685 $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
686
687 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
688 $resql = $this->db->query($sql);
689 if (!$resql) {
690 dol_print_error($this->db);
691 $error++;
692 $this->error = $this->db->lasterror();
693 }
694
695 // Trigger calls
696 if (!$error && !$notrigger) {
697 // Call trigger
698 $result = $this->call_trigger('CONTRACT_REOPEN', $user);
699 if ($result < 0) {
700 $error++;
701 }
702 // End call triggers
703 }
704
705 // Set new ref and define current status
706 if (!$error) {
707 $this->statut = self::STATUS_DRAFT;
708 $this->status = self::STATUS_DRAFT;
709 $this->date_validation = $now;
710 }
711
712 if (!$error) {
713 $this->db->commit();
714 return 1;
715 } else {
716 $this->db->rollback();
717 return -1;
718 }
719 }
720
732 public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '', $noextrafields = 0, $nolines = 0)
733 {
734 $result = -10;
735
736 $sql = "SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
737 $sql .= " ref_supplier, ref_customer,";
738 $sql .= " ref_ext,";
739 $sql .= " entity,";
740 $sql .= " signed_status,";
741 $sql .= " date_contrat as datecontrat,";
742 $sql .= " fk_user_author,";
743 $sql .= " fk_projet as fk_project,";
744 $sql .= " fk_commercial_signature, fk_commercial_suivi,";
745 $sql .= " note_private, note_public, model_pdf, last_main_doc, extraparams, fk_contract_type,";
746 $sql .= " fk_multicurrency, multicurrency_code, multicurrency_tx, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
747 $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
748 if (!$id) {
749 $sql .= " WHERE entity IN (".getEntity('contract').")";
750 } else {
751 $sql .= " WHERE rowid = ".(int) $id;
752 }
753 if ($ref_customer) {
754 $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
755 }
756 if ($ref_supplier) {
757 $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
758 }
759 if ($ref) {
760 $sql .= " AND ref = '".$this->db->escape($ref)."'";
761 }
762
763 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
764
765 $resql = $this->db->query($sql);
766 if ($resql) {
767 $num = $this->db->num_rows($resql);
768 if ($num > 1) {
769 $this->error = 'Fetch found several records.';
770 dol_syslog($this->error, LOG_ERR);
771 $result = -2;
772 return 0;
773 } elseif ($num) { // $num = 1
774 $obj = $this->db->fetch_object($resql);
775 if ($obj) {
776 $this->id = $obj->rowid;
777 $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
778 $this->ref_customer = $obj->ref_customer;
779 $this->ref_supplier = $obj->ref_supplier;
780 $this->ref_ext = $obj->ref_ext;
781 $this->entity = $obj->entity;
782 $this->statut = $obj->status;
783 $this->status = $obj->status;
784 $this->signed_status = $obj->signed_status;
785
786 $this->date_contrat = $this->db->jdate($obj->datecontrat);
787 $this->date_creation = $this->db->jdate($obj->datecontrat);
788
789 $this->user_author_id = $obj->fk_user_author;
790
791 $this->commercial_signature_id = $obj->fk_commercial_signature;
792 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
793
794 $this->note_private = $obj->note_private;
795 $this->note_public = $obj->note_public;
796 $this->model_pdf = $obj->model_pdf;
797
798 $this->fk_projet = $obj->fk_project; // deprecated
799 $this->fk_project = $obj->fk_project;
800
801 $this->socid = $obj->thirdpartyid;
802 $this->fk_soc = $obj->thirdpartyid;
803 $this->last_main_doc = $obj->last_main_doc;
804 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : null);
805 $this->fk_contract_type = (int) $obj->fk_contract_type;
806
807 $this->fk_multicurrency = $obj->fk_multicurrency;
808 $this->multicurrency_code = $obj->multicurrency_code;
809 $this->multicurrency_tx = $obj->multicurrency_tx;
810 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
811 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
812 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
813
814 $this->db->free($resql);
815
816 // Retrieve all extrafields
817 // fetch optionals attributes and labels
818 if (empty($noextrafields)) {
819 $result = $this->fetch_optionals();
820 if ($result < 0) {
821 $this->error = $this->db->lasterror();
822 return -4;
823 }
824 }
825
826 // Lines
827 if (empty($nolines)) {
828 if ($result >= 0 && !empty($this->table_element_line)) {
829 $result = $this->fetch_lines();
830 if ($result < 0) {
831 $this->error = $this->db->lasterror();
832 return -3;
833 }
834 }
835 }
836
837 return $this->id;
838 } else {
839 dol_syslog(get_class($this)."::fetch Contract failed");
840 $this->error = "Fetch contract failed";
841 return -1;
842 }
843 } else {
844 dol_syslog(get_class($this)."::fetch Contract not found");
845 $this->error = "Contract not found";
846 return 0;
847 }
848 } else {
849 dol_syslog(get_class($this)."::fetch Error searching contract");
850 $this->error = $this->db->error();
851 return -1;
852 }
853 }
854
855 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
865 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
866 {
867 // phpcs:enable
868 $this->nbofservices = 0;
869 $this->nbofserviceswait = 0;
870 $this->nbofservicesopened = 0;
871 $this->nbofservicesexpired = 0;
872 $this->nbofservicesclosed = 0;
873
874 $total_ttc = 0;
875 $total_vat = 0;
876 $total_ht = 0;
877 $multicurrency_total_ttc = 0;
878 $multicurrency_total_vat = 0;
879 $multicurrency_total_ht = 0;
880
881 $now = dol_now();
882
883 $this->lines = array();
884 $pos = 0;
885
886 // Selects contract lines related to a product
887 $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
888 $sql .= " d.rowid, d.fk_contrat, d.statut as status, d.description, d.subprice, d.subprice_ttc, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
889 $sql .= " d.total_ht,";
890 $sql .= " d.total_tva,";
891 $sql .= " d.total_localtax1,";
892 $sql .= " d.total_localtax2,";
893 $sql .= " d.total_ttc,";
894 $sql .= " d.info_bits, d.fk_product,";
895 $sql .= " d.date_ouverture_prevue as date_start,";
896 $sql .= " d.date_ouverture as date_start_real,";
897 $sql .= " d.date_fin_validite as date_end,";
898 $sql .= " d.date_cloture as date_end_real,";
899 $sql .= " d.fk_user_author,";
900 $sql .= " d.fk_user_ouverture,";
901 $sql .= " d.fk_user_cloture,";
902 $sql .= " d.fk_unit,";
903 $sql .= " d.extraparams,";
904 $sql .= " d.product_type as type,";
905 $sql .= " d.rang,";
906 $sql .= " d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_subprice_ttc, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc";
907 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
908 $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
909 if ($only_services == 1) {
910 $sql .= " AND d.product_type = 1";
911 }
912 $sql .= " ORDER by d.rang ASC";
913
914 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
915 $result = $this->db->query($sql);
916 if ($result) {
917 $num = $this->db->num_rows($result);
918 $i = 0;
919
920 while ($i < $num) {
921 $objp = $this->db->fetch_object($result);
922
923 $line = new ContratLigne($this->db);
924
925 $line->id = $objp->rowid;
926 $line->ref = $objp->rowid;
927 $line->fk_contrat = $objp->fk_contrat;
928 $line->desc = $objp->description; // Description line
929 $line->qty = $objp->qty;
930 $line->vat_src_code = $objp->vat_src_code;
931 $line->tva_tx = $objp->tva_tx;
932 $line->localtax1_tx = $objp->localtax1_tx;
933 $line->localtax2_tx = $objp->localtax2_tx;
934 $line->localtax1_type = $objp->localtax1_type;
935 $line->localtax2_type = $objp->localtax2_type;
936 $line->subprice = $objp->subprice;
937 $line->subprice_ttc = $objp->subprice_ttc;
938 $line->statut = $objp->status; // For backward compatibility
939 $line->status = $objp->status;
940 $line->remise_percent = $objp->remise_percent;
941 $line->total_ht = $objp->total_ht;
942 $line->total_tva = $objp->total_tva;
943 $line->total_localtax1 = $objp->total_localtax1;
944 $line->total_localtax2 = $objp->total_localtax2;
945 $line->total_ttc = $objp->total_ttc;
946 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
947 $line->info_bits = $objp->info_bits;
948 $line->type = $objp->type;
949
950 $line->fk_fournprice = $objp->fk_fournprice;
951 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
952 $line->pa_ht = $marginInfos[0];
953
954 $line->fk_user_author = $objp->fk_user_author;
955 $line->fk_user_ouverture = $objp->fk_user_ouverture;
956 $line->fk_user_cloture = $objp->fk_user_cloture;
957 $line->fk_unit = $objp->fk_unit;
958
959 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
960
961 $line->ref = $objp->product_ref; // deprecated
962 $line->product_ref = $objp->product_ref; // Product Ref
963 $line->product_type = $objp->product_type; // Product Type
964 $line->product_desc = $objp->product_desc; // Product Description
965 $line->product_label = $objp->product_label; // Product Label
966
967 $line->description = $objp->description;
968
969 $line->date_start = $this->db->jdate($objp->date_start);
970 $line->date_start_real = $this->db->jdate($objp->date_start_real);
971 $line->date_end = $this->db->jdate($objp->date_end);
972 $line->date_end_real = $this->db->jdate($objp->date_end_real);
973 // For backward compatibility
974 //$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
975 //$line->date_ouverture = $this->db->jdate($objp->date_ouverture);
976 //$line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
977 //$line->date_cloture = $this->db->jdate($objp->date_cloture);
978 //$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
979 //$line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
980 //$line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
981 //$line->date_fin_reel = $this->db->jdate($objp->date_cloture);
982
983 $line->rang = $objp->rang;
984
985 $line->fk_multicurrency = $objp->fk_multicurrency;
986 $line->multicurrency_code = $objp->multicurrency_code;
987 $line->multicurrency_subprice = $objp->multicurrency_subprice;
988 $line->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
989 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
990 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
991 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
992
993 // Retrieve all extrafields for contract line
994 // fetch optionals attributes and labels
995 if (empty($noextrafields)) {
996 $line->fetch_optionals();
997 }
998
999 // multilangs
1000 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
1001 $tmpproduct = new Product($this->db);
1002 $tmpproduct->fetch($objp->fk_product);
1003 $tmpproduct->getMultiLangs();
1004
1005 $line->multilangs = $tmpproduct->multilangs;
1006 }
1007
1008 $this->lines[$pos] = $line;
1009
1010 $this->lines_id_index_mapper[$line->id] = $pos;
1011
1012 //dol_syslog("1 ".$line->desc);
1013 //dol_syslog("2 ".$line->product_desc);
1014
1015 if ($line->statut == ContratLigne::STATUS_INITIAL) {
1016 $this->nbofserviceswait++;
1017 }
1018 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
1019 $this->nbofservicesopened++;
1020 }
1021 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
1022 $this->nbofservicesexpired++;
1023 }
1024 if ($line->statut == ContratLigne::STATUS_CLOSED) {
1025 $this->nbofservicesclosed++;
1026 }
1027
1028 // TODO Not saved into database
1029 $total_ttc += $objp->total_ttc;
1030 $total_vat += $objp->total_tva;
1031 $total_ht += $objp->total_ht;
1032 $multicurrency_total_ttc += $objp->multicurrency_total_ttc;
1033 $multicurrency_total_vat += $objp->multicurrency_total_tva;
1034 $multicurrency_total_ht += $objp->multicurrency_total_ht;
1035
1036 $i++;
1037 $pos++;
1038 }
1039 $this->db->free($result);
1040 } else {
1041 dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
1042 return -3;
1043 }
1044
1045 // Now set the global properties on contract not stored into database.
1046 $this->nbofservices = count($this->lines);
1047 $this->total_ttc = (float) price2num($total_ttc);
1048 $this->total_tva = (float) price2num($total_vat);
1049 $this->total_ht = (float) price2num($total_ht);
1050 $this->multicurrency_total_ttc = (float) price2num($multicurrency_total_ttc);
1051 $this->multicurrency_total_tva = (float) price2num($multicurrency_total_vat);
1052 $this->multicurrency_total_ht = (float) price2num($multicurrency_total_ht);
1053
1054 return $this->lines;
1055 }
1056
1064 public function create($user, $notrigger = 0)
1065 {
1066 global $conf, $langs;
1067
1068 // Check parameters
1069 $paramsok = 1;
1070 if ($this->commercial_signature_id <= 0) {
1071 $langs->load("commercial");
1072 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
1073 $paramsok = 0;
1074 }
1075 if ($this->commercial_suivi_id <= 0) {
1076 $langs->load("commercial");
1077 $this->error .= ($this->error ? "<br>" : '');
1078 $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
1079 $paramsok = 0;
1080 }
1081 $this->entity = setEntity($this);
1082 if (!$paramsok) {
1083 return -1;
1084 }
1085
1086
1087 $this->db->begin();
1088
1089 $now = dol_now();
1090
1091 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1092 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1093 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date_contrat);
1094 } else {
1095 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1096 }
1097 if (empty($this->fk_multicurrency)) {
1098 $this->multicurrency_code = $conf->currency;
1099 $this->fk_multicurrency = 0;
1100 $this->multicurrency_tx = 1;
1101 }
1102
1103 // Insert contract
1104 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
1105 $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1106 $sql .= " ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext, fk_contract_type,";
1107 $sql .= " fk_multicurrency, multicurrency_code, multicurrency_tx)";
1108 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
1109 $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
1110 $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
1111 $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
1112 $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
1113 $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
1114 $sql .= ", ".((int) $this->entity);
1115 $sql .= ", ".((int) $this->signed_status);
1116 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
1117 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
1118 $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
1119 $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
1120 $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
1121 $sql .= ", ".((int) $this->fk_contract_type);
1122 $sql .= ", ".(int) $this->fk_multicurrency;
1123 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1124 $sql .= ", ".(float) $this->multicurrency_tx;
1125 $sql .= ")";
1126 $resql = $this->db->query($sql);
1127
1128 if ($resql) {
1129 $error = 0;
1130
1131 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
1132
1133 // Load object modContract
1134 $module = getDolGlobalString('CONTRACT_ADDON', 'mod_contract_serpis');
1135 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1136 $module = substr($module, 0, dol_strlen($module) - 4);
1137 }
1138 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1139 if ($result > 0) {
1140 $modCodeContract = new $module();
1141 '@phan-var-force ModelNumRefContracts $modCodeContract';
1144 if (!empty($modCodeContract->code_auto)) {
1145 // Force the ref to a draft value if numbering module is an automatic numbering
1146 $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".((int) $this->id).")' WHERE rowid=".((int) $this->id);
1147 if ($this->db->query($sql)) {
1148 if ($this->id) {
1149 $this->ref = "(PROV".$this->id.")";
1150 }
1151 }
1152 }
1153 }
1154
1155 $result = $this->insertExtraFields();
1156 if ($result < 0) {
1157 $error++;
1158 }
1159
1160 // Insert business contacts ('SALESREPSIGN','contrat')
1161 if (!$error && !empty($this->commercial_signature_id)) {
1162 $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
1163 if ($result < 0) {
1164 $error++;
1165 }
1166 }
1167
1168 // Insert business contacts ('SALESREPFOLL','contrat')
1169 if (!$error && !empty($this->commercial_suivi_id)) {
1170 $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
1171 if ($result < 0) {
1172 $error++;
1173 }
1174 }
1175
1176 if (!$error) {
1177 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1178 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1179 }
1180
1181 // Add object linked
1182 if ($this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1183 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1184 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, ...))
1185 foreach ($tmp_origin_id as $origin_id) {
1186 $ret = $this->add_object_linked($origin, $origin_id);
1187 if (!$ret) {
1188 $this->error = $this->db->lasterror();
1189 $error++;
1190 }
1191 }
1192 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1193 $origin_id = $tmp_origin_id;
1194 $ret = $this->add_object_linked($origin, $origin_id);
1195 if (!$ret) {
1196 $this->error = $this->db->lasterror();
1197 $error++;
1198 }
1199 }
1200 }
1201 }
1202
1203 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1204 $originforcontact = $this->origin;
1205 $originidforcontact = $this->origin_id;
1206 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1207 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1208 $exp = new Expedition($this->db);
1209 $exp->fetch($this->origin_id);
1210 $exp->fetchObjectLinked();
1211 if (count($exp->linkedObjectsIds['commande']) > 0) {
1212 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1213 $originforcontact = 'commande';
1214 $originidforcontact = $value;
1215 break; // We take first one
1216 }
1217 }
1218 }
1219
1220 $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";
1221 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1222
1223 $resqlcontact = $this->db->query($sqlcontact);
1224 if ($resqlcontact) {
1225 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1226 if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1227 continue; // ignore this, already forced previously
1228 }
1229
1230 $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
1231 }
1232 } else {
1233 dol_print_error($this->db);
1234 }
1235 }
1236 }
1237
1238 if (!$error && !$notrigger) {
1239 // Call trigger
1240 $result = $this->call_trigger('CONTRACT_CREATE', $user);
1241 if ($result < 0) {
1242 $error++;
1243 }
1244 // End call triggers
1245 }
1246
1247 if (!$error) {
1248 $this->db->commit();
1249 return $this->id;
1250 } else {
1251 // Keep the error reported by the failing step, it is the only actionable one.
1252 // Only fall back to a generic message when nothing was set, as propal.class.php does.
1253 if (empty($this->error) && empty($this->errors)) {
1254 $this->error = "Failed to add contract";
1255 }
1256 dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1257 $this->db->rollback();
1258 return -2;
1259 }
1260 } else {
1261 $this->error = $langs->trans("UnknownError").": ".$this->db->error();
1262 dol_syslog(get_class($this)."::create - 10 - ".$this->error, LOG_ERR);
1263
1264 $this->db->rollback();
1265 return -1;
1266 }
1267 }
1268
1269
1276 public function delete($user)
1277 {
1278 global $conf;
1279
1280 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1281
1282 $error = 0;
1283
1284 $this->db->begin();
1285
1286 // Call trigger
1287 $result = $this->call_trigger('CONTRACT_DELETE', $user);
1288 if ($result < 0) {
1289 $error++;
1290 }
1291 // End call triggers
1292
1293 if (!$error) {
1294 // Delete linked contacts
1295 $res = $this->delete_linked_contact();
1296 if ($res < 0) {
1297 dol_syslog(get_class($this)."::delete error", LOG_ERR);
1298 $error++;
1299 }
1300 }
1301
1302 if (!$error) {
1303 // Delete linked object
1304 $res = $this->deleteObjectLinked();
1305 if ($res < 0) {
1306 $error++;
1307 }
1308 }
1309
1310 // Delete lines
1311 if (!$error) {
1312 // Delete contratdet extrafields
1313 $sql_main_table = MAIN_DB_PREFIX.'contratdet';
1314 $ef = $sql_main_table."_extrafields";
1315 $sql = "DELETE FROM ".$this->db->sanitize($ef)." WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_contrat = ".((int) $this->id).")";
1316
1317 dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
1318 $resql = $this->db->query($sql);
1319 if (!$resql) {
1320 $this->error = $this->db->error();
1321 $error++;
1322 }
1323 }
1324
1325 if (!$error) {
1326 // Delete contratdet
1327 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1328 $sql .= " WHERE fk_contrat = ".((int) $this->id);
1329
1330 dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1331 $resql = $this->db->query($sql);
1332 if (!$resql) {
1333 $this->error = $this->db->error();
1334 $error++;
1335 }
1336 }
1337
1338 // Delete record into ECM index and physically
1339 if (!$error) {
1340 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1341 if ($res) {
1342 $res = $this->deleteEcmFiles(1);
1343 } // Deleting files physically is done later with the dol_delete_dir_recursive
1344 if (!$res) {
1345 $error++;
1346 }
1347 }
1348
1349 // Delete contract
1350 if (!$error) {
1351 $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1352 $sql .= " WHERE rowid=".((int) $this->id);
1353
1354 dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1355 $resql = $this->db->query($sql);
1356 if (!$resql) {
1357 $this->error = $this->db->error();
1358 $error++;
1359 }
1360 }
1361
1362 // Removed extrafields
1363 if (!$error) {
1364 $result = $this->deleteExtraFields();
1365 if ($result < 0) {
1366 $error++;
1367 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1368 }
1369 }
1370
1371 if (!$error) {
1372 // We remove directory
1373 $ref = dol_sanitizeFileName($this->ref);
1374 if ($conf->contrat->dir_output && !empty($ref)) {
1375 $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
1376 if (file_exists($dir)) {
1377 $res = @dol_delete_dir_recursive($dir);
1378 if (!$res) {
1379 $this->error = 'ErrorFailToDeleteDir';
1380 $error++;
1381 }
1382 }
1383 }
1384 }
1385
1386 if (!$error) {
1387 $this->db->commit();
1388 return 1;
1389 } else {
1390 $this->error = $this->db->lasterror();
1391 $this->db->rollback();
1392 return -1;
1393 }
1394 }
1395
1403 public function update($user, $notrigger = 0)
1404 {
1405 global $conf;
1406 $error = 0;
1407
1408 // Clean parameters
1409 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1410 $this->fk_commercial_signature = $this->commercial_signature_id;
1411 }
1412 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1413 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1414 }
1415 if (empty($this->socid) && $this->fk_soc > 0) {
1416 $this->socid = (int) $this->fk_soc;
1417 }
1418
1419 if (isset($this->ref)) {
1420 $this->ref = trim($this->ref);
1421 }
1422 if (isset($this->ref_customer)) {
1423 $this->ref_customer = trim($this->ref_customer);
1424 }
1425 if (isset($this->ref_supplier)) {
1426 $this->ref_supplier = trim($this->ref_supplier);
1427 }
1428 if (isset($this->ref_ext)) {
1429 $this->ref_ext = trim($this->ref_ext);
1430 }
1431 if (isset($this->entity)) {
1432 $this->entity = (int) $this->entity;
1433 }
1434 if (isset($this->status)) {
1435 $this->status = (int) $this->status;
1436 }
1437 if ((int) $this->socid > 0) {
1438 $this->socid = (int) $this->socid;
1439 }
1440 if (isset($this->fk_commercial_signature)) {
1441 $this->fk_commercial_signature = (int) $this->fk_commercial_signature;
1442 }
1443 if (isset($this->fk_commercial_suivi)) {
1444 $this->fk_commercial_suivi = (int) $this->fk_commercial_suivi;
1445 }
1446 if (isset($this->note_private)) {
1447 $this->note_private = trim($this->note_private);
1448 }
1449 if (isset($this->note_public)) {
1450 $this->note_public = trim($this->note_public);
1451 }
1452 if (isset($this->import_key)) {
1453 $this->import_key = trim($this->import_key);
1454 }
1455
1456 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
1457 $extraparams = dol_trunc($extraparams, 250);
1458
1459 // $this->oldcopy must have been set by the caller of update
1460
1461 // Update request
1462 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1463 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1464 $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1465 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1466 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1467 $sql .= " entity=".((int) $conf->entity).",";
1468 $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1469 $sql .= " statut=".(isset($this->statut) ? ((int) $this->statut) : (isset($this->status) ? ((int) $this->status) : "null")).",";
1470 $sql .= " fk_soc=".($this->socid > 0 ? ((int) $this->socid) : "null").",";
1471 $sql .= " fk_projet=".($this->fk_project > 0 ? ((int) $this->fk_project) : "null").",";
1472 $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? ((int) $this->fk_commercial_signature) : "null").",";
1473 $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? ((int) $this->fk_commercial_suivi) : "null").",";
1474 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1475 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1476 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
1477 $sql .= " fk_user_modif=".(isset($user->id) ? ((int) $user->id) : "null").",";
1478 $sql .= " extraparams=".(isset($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
1479 $sql .= " WHERE rowid=".((int) $this->id);
1480
1481 $this->db->begin();
1482
1483 $resql = $this->db->query($sql);
1484 if (!$resql) {
1485 $error++;
1486 $this->errors[] = "Error ".$this->db->lasterror();
1487 }
1488
1489 if (!$error) {
1490 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
1491 if ($result < 0) {
1492 $error++;
1493 }
1494 }
1495
1496 if (!$error && !$notrigger) {
1497 // Call triggers
1498 $result = $this->call_trigger('CONTRACT_MODIFY', $user);
1499 if ($result < 0) {
1500 $error++;
1501 }
1502 // End call triggers
1503 }
1504
1505 // Commit or rollback
1506 if ($error) {
1507 foreach ($this->errors as $errmsg) {
1508 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1509 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1510 }
1511 $this->db->rollback();
1512 return -1 * $error;
1513 } else {
1514 if (isset($user->id)) {
1515 $this->fk_user_modif = (int) $user->id;
1516 }
1517 $this->db->commit();
1518 return 1;
1519 }
1520 }
1521
1522
1547 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, $pu_ht_devise = 0.0)
1548 {
1549 global $user, $langs, $mysoc;
1550 $error = 0;
1551
1552 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");
1553
1554 // Check parameters
1555 if ($fk_product <= 0 && empty($desc)) {
1556 $this->error = "ErrorDescRequiredForFreeProductLines";
1557 return -1;
1558 }
1559
1560 if ($this->status >= 0) {
1561 // Clean parameters
1562 $pu_ht = price2num($pu_ht);
1563 $pu_ttc = price2num($pu_ttc);
1564 $pa_ht = price2num($pa_ht);
1565 $pu_ht_devise = price2num($pu_ht_devise);
1566
1567 // Clean vat code
1568 $reg = array();
1569 $vat_src_code = '';
1570 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1571 $vat_src_code = $reg[1];
1572 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code into vatrate.
1573 }
1574 $txtva = price2num($txtva);
1575 $txlocaltax1 = price2num($txlocaltax1);
1576 $txlocaltax2 = price2num($txlocaltax2);
1577
1578 $remise_percent = price2num($remise_percent);
1579 $qty = price2num($qty);
1580 if (empty($qty)) {
1581 $qty = 1;
1582 }
1583 if (empty($info_bits)) {
1584 $info_bits = 0;
1585 }
1586 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1587 $pu_ht = 0;
1588 }
1589 if (empty($pu_ttc)) {
1590 $pu_ttc = 0;
1591 }
1592 if (empty($txtva) || !is_numeric($txtva)) {
1593 $txtva = 0;
1594 }
1595 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1596 $txlocaltax1 = 0;
1597 }
1598 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1599 $txlocaltax2 = 0;
1600 }
1601
1602 if ($price_base_type == 'HT') {
1603 $pu = $pu_ht;
1604 } else {
1605 $pu = $pu_ttc;
1606 }
1607
1608 // Check parameters
1609 if (empty($remise_percent)) {
1610 $remise_percent = 0;
1611 }
1612 if (empty($rang)) {
1613 $rang = 0;
1614 }
1615
1616 if ($date_start && $date_end && $date_start > $date_end) {
1617 $langs->load("errors");
1618 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1619 return -1;
1620 }
1621
1622 $this->db->begin();
1623
1624 $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
1625
1626 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1627 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1628 // and this is done at the line level, which has its own VAT rate
1629
1630 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise, $this->multicurrency_code);
1631 $total_ht = $tabprice[0];
1632 $total_tva = $tabprice[1];
1633 $total_ttc = $tabprice[2];
1634 $total_localtax1 = $tabprice[9];
1635 $total_localtax2 = $tabprice[10];
1636 $pu_ht = $tabprice[3];
1637 $pu_ttc = $tabprice[5];
1638
1639 // Multicurrency
1640 $multicurrency_total_ht = $tabprice[16];
1641 $multicurrency_total_tva = $tabprice[17];
1642 $multicurrency_total_ttc = $tabprice[18];
1643 $pu_ht_devise = $tabprice[19];
1644
1645 if (count($localtaxes_type) > 0) {
1646 $localtax1_type = $localtaxes_type[0];
1647 $localtax2_type = $localtaxes_type[2];
1648 } else {
1649 $localtax1_type = "";
1650 $localtax2_type = "";
1651 }
1652
1653 if (empty($pa_ht)) {
1654 $pa_ht = 0;
1655 }
1656
1657
1658 // if buy price not defined, define buyprice as configured in margin admin
1659 if ($pa_ht == 0) {
1660 $result = $this->defineBuyPrice((float) $pu_ht, $remise_percent, $fk_product, $qty);
1661 if ($result < 0) {
1662 return -1;
1663 } else {
1664 $pa_ht = $result;
1665 }
1666 }
1667
1668 // Insert into database
1669 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1670 $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1671 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, subprice_ttc,";
1672 $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1673 $sql .= " info_bits,";
1674 $sql .= " fk_product_fournisseur_price, buy_price_ht,";
1675 $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_subprice_ttc, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
1676 if ($date_start > 0) {
1677 $sql .= ",date_ouverture_prevue";
1678 }
1679 if ($date_end > 0) {
1680 $sql .= ",date_fin_validite";
1681 }
1682 $sql .= ", fk_unit";
1683 $sql .= ", rang";
1684 $sql .= ") VALUES (";
1685 $sql .= ((int) $this->id).", '', '".$this->db->escape($desc)."',";
1686 $sql .= ($fk_product > 0 ? ((int) $fk_product) : "null").",";
1687 $sql .= " ".((float) $qty).",";
1688 $sql .= " ".((float) $txtva).",";
1689 $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
1690 $sql .= " ".((float) $txlocaltax1).",";
1691 $sql .= " ".((float) $txlocaltax2).",";
1692 $sql .= " '".$this->db->escape($localtax1_type)."',";
1693 $sql .= " '".$this->db->escape($localtax2_type)."',";
1694 $sql .= " ".price2num($remise_percent).",";
1695 $sql .= " ".price2num($pu_ht).",";
1696 $sql .= " ".($price_base_type === 'TTC' ? (float) price2num($pu_ttc) : 0).",";
1697 $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1698 $sql .= " ".((int) $info_bits).",";
1699 if (isset($fk_fournprice)) {
1700 $sql .= ' '.((int) $fk_fournprice).',';
1701 } else {
1702 $sql .= ' null,';
1703 }
1704 if (isset($pa_ht)) {
1705 $sql .= ' '.price2num($pa_ht).',';
1706 } else {
1707 $sql .= ' null,';
1708 }
1709 $sql .= " ".(int) $this->fk_multicurrency.",";
1710 $sql .= " '".$this->db->escape((string) $this->multicurrency_code)."',";
1711 $sql .= " ".(float) $pu_ht_devise.",";
1712 $sql .= " ".($price_base_type === 'TTC' ? (float) price2num((float) $pu_ht_devise * (1 + ((float) $txtva / 100))) : 0).",";
1713 $sql .= " ".(float) $multicurrency_total_ht.",".(float) $multicurrency_total_tva.",".(float) $multicurrency_total_ttc;
1714 if ($date_start > 0) {
1715 $sql .= ",'".$this->db->idate($date_start)."'";
1716 }
1717 if ($date_end > 0) {
1718 $sql .= ",'".$this->db->idate($date_end)."'";
1719 }
1720 $sql .= ", ".($fk_unit ? "'".$this->db->escape((string) $fk_unit)."'" : "null");
1721 $sql .= ", ".(!empty($rang) ? (int) $rang : "0");
1722 $sql .= ")";
1723
1724 $resql = $this->db->query($sql);
1725 if ($resql) {
1726 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1727
1728 $contractline = new ContratLigne($this->db);
1729 $contractline->array_options = $array_options;
1730 $contractline->id = $contractlineid;
1731 $result = $contractline->insertExtraFields();
1732 if ($result < 0) {
1733 $this->setErrorsFromObject($contractline);
1734 $error++;
1735 }
1736
1737 if (empty($error)) {
1738 // Call trigger
1739 $this->context['line_id'] = $contractlineid;
1740 $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1741 if ($result < 0) {
1742 $error++;
1743 }
1744 // End call triggers
1745 }
1746
1747 if ($error) {
1748 $this->db->rollback();
1749 return -1;
1750 } else {
1751 $this->db->commit();
1752 return $contractlineid;
1753 }
1754 } else {
1755 $this->db->rollback();
1756 $this->error = $this->db->error()." sql=".$sql;
1757 return -1;
1758 }
1759 } else {
1760 dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1761 return -2;
1762 }
1763 }
1764
1790 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, $pu_ht_devise = 0.0)
1791 {
1792 global $user, $langs, $mysoc;
1793
1794 if (!$this->isLineOfObject($rowid)) {
1795 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1796 return -1;
1797 }
1798
1799 $error = 0;
1800
1801 // Clean parameters
1802 $qty = trim((string) $qty);
1803 $desc = trim($desc);
1804
1805 $tvatx = price2num($tvatx);
1806 $localtax1tx = price2num($localtax1tx);
1807 $localtax2tx = price2num($localtax2tx);
1808 $pa_ht = price2num($pa_ht);
1809 $pu_ht_devise = price2num($pu_ht_devise);
1810 if (empty($fk_fournprice)) {
1811 $fk_fournprice = 0;
1812 }
1813 if (empty($rang)) {
1814 $rang = 0;
1815 }
1816
1817 if ($date_start && $date_end && $date_start > $date_end) {
1818 $langs->load("errors");
1819 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1820 return -1;
1821 }
1822
1823 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");
1824
1825 $this->db->begin();
1826
1827 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1828 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1829 // and this is done at the line level, which has its own VAT rate
1830
1831 $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1832 $tvatx = preg_replace('/\s*\‍(.*\‍)/', '', $tvatx); // Remove code into vatrate.
1833
1834 $tabprice = calcul_price_total((float) $qty, $pu, $remise_percent, (float) price2num($tvatx), (float) $localtax1tx, (float) $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise, $this->multicurrency_code);
1835 $total_ht = $tabprice[0];
1836 $total_tva = $tabprice[1];
1837 $total_ttc = $tabprice[2];
1838 $total_localtax1 = $tabprice[9];
1839 $total_localtax2 = $tabprice[10];
1840 $pu_ht = $tabprice[3];
1841 $pu_ttc = $tabprice[5];
1842
1843 // Multicurrency
1844 $multicurrency_total_ht = $tabprice[16];
1845 $multicurrency_total_tva = $tabprice[17];
1846 $multicurrency_total_ttc = $tabprice[18];
1847 $pu_ht_devise = $tabprice[19];
1848
1849 $localtax1_type = (empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]);
1850 $localtax2_type = (empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]);
1851
1852 if (empty($pa_ht)) {
1853 $pa_ht = 0;
1854 }
1855
1856 // if buy price not defined, define buyprice as configured in margin admin
1857 if ($pa_ht == 0) {
1858 $result = $this->defineBuyPrice($pu, $remise_percent);
1859 if ($result < 0) {
1860 return -1;
1861 } else {
1862 $pa_ht = $result;
1863 }
1864 }
1865
1866 $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET description = '".$this->db->escape($desc)."'";
1867 $sql .= ",subprice = ".((float) price2num($pu_ht));
1868 // Persist the original entry mode of the line so a no-op edit can preserve it later.
1869 $sql .= ",subprice_ttc = ".($price_base_type === 'TTC' ? (float) price2num($pu_ttc) : 0);
1870 $sql .= ",remise_percent = ".((float) price2num($remise_percent));
1871 $sql .= ",qty = ".((float) $qty);
1872 $sql .= ",tva_tx = ".((float) price2num($tvatx));
1873 $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
1874 $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
1875 $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'";
1876 $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'";
1877 $sql .= ", total_ht = ".((float) price2num($total_ht));
1878 $sql .= ", total_tva = ".((float) price2num($total_tva));
1879 $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
1880 $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
1881 $sql .= ", total_ttc = ".((float) price2num($total_ttc));
1882 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? ((int) $fk_fournprice) : "null");
1883 $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
1884 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1885 $sql .= ", multicurrency_code = '".$this->db->escape((string) $this->multicurrency_code)."'";
1886 $sql .= ", multicurrency_subprice = ".(float) $pu_ht_devise;
1887 $sql .= ", multicurrency_subprice_ttc = ".($price_base_type === 'TTC' ? (float) price2num((float) $pu_ht_devise * (1 + ((float) $tvatx / 100))) : 0);
1888 $sql .= ", multicurrency_total_ht = ".(float) $multicurrency_total_ht;
1889 $sql .= ", multicurrency_total_tva = ".(float) $multicurrency_total_tva;
1890 $sql .= ", multicurrency_total_ttc = ".(float) $multicurrency_total_ttc;
1891 if ($date_start > 0) {
1892 $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
1893 } else {
1894 $sql .= ",date_ouverture_prevue = null";
1895 }
1896 if ($date_end > 0) {
1897 $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
1898 } else {
1899 $sql .= ",date_fin_validite = null";
1900 }
1901 if ($date_start_real > 0) {
1902 $sql .= ",date_ouverture = '".$this->db->idate($date_start_real)."'";
1903 } else {
1904 $sql .= ",date_ouverture = null";
1905 }
1906 if ($date_end_real > 0) {
1907 $sql .= ",date_cloture = '".$this->db->idate($date_end_real)."'";
1908 } else {
1909 $sql .= ",date_cloture = null";
1910 }
1911 $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
1912 $sql .= ", rang = ".(!empty($rang) ? ((int) $rang) : "0");
1913 $sql .= " WHERE rowid = ".((int) $rowid);
1914
1915 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1916 $result = $this->db->query($sql);
1917 if ($result) {
1918 if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1919 $contractline = new ContratLigne($this->db);
1920 $contractline->fetch($rowid);
1921
1922 // We replace values in $contractline->array_options only for entries defined into $array_options
1923 foreach ($array_options as $key => $value) {
1924 $contractline->array_options[$key] = $array_options[$key];
1925 }
1926
1927 $result = $contractline->insertExtraFields();
1928 if ($result < 0) {
1929 $this->errors[] = $contractline->error;
1930 $error++;
1931 }
1932 }
1933
1934 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
1935 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
1936 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $this->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
1937 $sqltoupdatecontract .= " WHERE rowid = ".((int) $this->id);
1938 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
1939 if (!$resqltoupdatecontract) {
1940 $this->error = $this->db->lasterror();
1941 $this->db->rollback();
1942 return -1;
1943 }
1944
1945 if (empty($error)) {
1946 // Call trigger
1947 $this->context['line_id'] = $rowid;
1948 $result = $this->call_trigger('LINECONTRACT_MODIFY', $user);
1949 if ($result < 0) {
1950 $this->db->rollback();
1951 return -3;
1952 }
1953 // End call triggers
1954
1955 $this->db->commit();
1956 return 1;
1957 } else {
1958 $this->db->rollback();
1959 return -1;
1960 }
1961 } else {
1962 $this->db->rollback();
1963 $this->error = $this->db->error();
1964 dol_syslog(get_class($this)."::updateline Erreur -1");
1965 return -1;
1966 }
1967 }
1968
1976 public function deleteLine($idline, User $user)
1977 {
1978 $error = 0;
1979
1980 if ($this->statut >= 0) {
1981 if ($this->id > 0) {
1982 // The line must belong to this contract
1983 $contractline = new ContratLigne($this->db);
1984 if ($contractline->fetch($idline) <= 0 || (int) $contractline->fk_contrat !== (int) $this->id) {
1985 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1986 return -1;
1987 }
1988 }
1989
1990 // Call trigger
1991 $this->context['line_id'] = $idline;
1992 $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1993 if ($result < 0) {
1994 return -1;
1995 }
1996 // End call triggers
1997
1998 $this->db->begin();
1999
2000 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
2001 $sql .= " WHERE rowid = ".((int) $idline);
2002
2003 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
2004 $resql = $this->db->query($sql);
2005 if (!$resql) {
2006 $this->error = "Error ".$this->db->lasterror();
2007 $error++;
2008 }
2009
2010 if (!$error) {
2011 // Remove extrafields
2012 $contractline = new ContratLigne($this->db);
2013 $contractline->id = $idline;
2014 $result = $contractline->deleteExtraFields();
2015 if ($result < 0) {
2016 $error++;
2017 $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
2018 }
2019 }
2020
2021 if (!$error) {
2022 // Renumber remaining lines so rang stays a contiguous 1..N sequence.
2023 // Without this, a deleted line leaves a permanent gap that breaks
2024 // the up/down swap logic (updateLineUp/updateLineDown) for any pair
2025 // of lines that no longer sit at an exact rang+/-1 from each other.
2026 $result = $this->line_order(true, 'ASC', false);
2027 if ($result < 0) {
2028 $error++;
2029 $this->error = "Error ".get_class($this)."::deleteline line_order error";
2030 }
2031 }
2032
2033 if (empty($error)) {
2034 $this->db->commit();
2035 return 1;
2036 } else {
2037 dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
2038 $this->db->rollback();
2039 return -1;
2040 }
2041 } else {
2042 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2043 return -2;
2044 }
2045 }
2046
2047
2048 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2056 public function update_statut($user)
2057 {
2058 // phpcs:enable
2059 dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
2060
2061 // If draft, we keep it (should not happen)
2062 if ($this->statut == 0) {
2063 return 1;
2064 }
2065
2066 // Load $this->lines array
2067 // $this->fetch_lines();
2068
2069 // $newstatut=1;
2070 // foreach($this->lines as $key => $contractline)
2071 // {
2072 // // if ($contractline) // Loop on each service
2073 // }
2074
2075 return 1;
2076 }
2077
2078
2085 public function getLibStatut($mode)
2086 {
2087 return $this->LibStatut($this->statut, $mode);
2088 }
2089
2090 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2098 public function LibStatut($status, $mode)
2099 {
2100 // phpcs:enable
2101 global $langs;
2102
2103 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2104 global $langs;
2105 $langs->load("contracts");
2106 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
2107 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
2108 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
2109 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
2110 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
2111 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
2112 }
2113
2114 $statusType = 'status'.$status;
2115 if ($status == self::STATUS_VALIDATED) {
2116 $statusType = 'status6';
2117 }
2118
2119 if ($mode == 4 || $mode == 6 || $mode == 7) {
2120 $text = '';
2121 if ($mode == 4) {
2122 $text = '<span class="hideonsmartphone">';
2123 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2124 $text .= ' '.$langs->trans("Services");
2125 $text .= ': &nbsp; &nbsp; ';
2126 $text .= '</span>';
2127 }
2128 $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
2129 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2130 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2131 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2132 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2133 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
2134 $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
2135 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
2136 $text .= ($mode == 7 ? '</span>' : '');
2137 if (getDolGlobalString('CONTRACT_SHOW_SIGNATURE_STATUS_WITH_SERVICE_STATUS')) {
2138 $text .= is_null($this->signed_status) ? '' : ' '.$this->getLibSignedStatus(5);
2139 }
2140 return $text;
2141 } else {
2142 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2143 }
2144 }
2145
2152 public function getTooltipContentArray($params)
2153 {
2154 global $conf, $langs, $user;
2155
2156 $langs->load('contracts');
2157
2158 $datas = [];
2159 $nofetch = !empty($params['nofetch']);
2160
2161 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2162 return ['optimize' => $langs->trans("ShowContract")];
2163 }
2164 if ($user->hasRight('contrat', 'lire')) {
2165 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
2166 /* Status of a contract is status of all services, so disabled
2167 if (isset($this->statut)) {
2168 $label .= ' '.$this->getLibStatut(5);
2169 }*/
2170 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
2171 if (!$nofetch) {
2172 $langs->load('companies');
2173 if (empty($this->thirdparty)) {
2174 $this->fetch_thirdparty();
2175 }
2176 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2177 }
2178 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '. $this->ref_customer;
2179 if (!$nofetch) {
2180 $langs->load('project');
2181 if (is_null($this->project) || (is_object($this->project) && empty($this->project->id))) {
2182 $res = $this->fetchProject();
2183 if ($res > 0 && $this->project instanceof Project) {
2184 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
2185 }
2186 }
2187 }
2188 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2189 if (!empty($this->total_ht)) {
2190 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2191 }
2192 if (!empty($this->total_tva)) {
2193 $datas['vatamount'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2194 }
2195 if (!empty($this->total_ttc)) {
2196 $datas['amounttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2197 }
2198 }
2199 return $datas;
2200 }
2201
2211 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2212 {
2213 global $langs, $user, $hookmanager;
2214
2215 $result = '';
2216
2217 $baseurl = DOL_URL_ROOT . '/contrat/card.php';
2218 $query = ['id' => $this->id];
2219
2220 //if ($option !== 'nolink')
2221 //{
2222 // Add param to save lastsearch_values or not
2223 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2224 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2225 $add_save_lastsearch_values = 1;
2226 }
2227 if ($add_save_lastsearch_values) {
2228 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2229 }
2230 //}
2231 $url = dolBuildUrl($baseurl, $query);
2232 $params = [
2233 'id' => $this->id,
2234 'objecttype' => $this->element,
2235 'nofetch' => 1,
2236 ];
2237 $classfortooltip = 'classfortooltip';
2238 $dataparams = '';
2239 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2240 $classfortooltip = 'classforajaxtooltip';
2241 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2242 $label = '';
2243 } else {
2244 $label = implode($this->getTooltipContentArray($params));
2245 }
2246
2247 $linkclose = '';
2248 if (empty($notooltip) && $user->hasRight('contrat', 'lire')) {
2249 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2250 $label = $langs->trans("ShowContract");
2251 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2252 }
2253 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2254 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2255 }
2256 $linkstart = '<a href="'.$url.'"';
2257 $linkstart .= $linkclose.'>';
2258 $linkend = '</a>';
2259
2260 $result .= $linkstart;
2261 if ($withpicto) {
2262 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2263 }
2264 if ($withpicto != 2) {
2265 $result .= ($this->ref ? $this->ref : $this->id);
2266 }
2267 $result .= $linkend;
2268
2269 global $action;
2270 $hookmanager->initHooks(array('contractdao'));
2271 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2272 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2273 if ($reshook > 0) {
2274 $result = $hookmanager->resPrint;
2275 } else {
2276 $result .= $hookmanager->resPrint;
2277 }
2278
2279 return $result;
2280 }
2281
2288 public function info($id)
2289 {
2290 $sql = "SELECT c.rowid, c.ref, c.datec,";
2291 $sql .= " c.tms as date_modification,";
2292 $sql .= " fk_user_author";
2293 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2294 $sql .= " WHERE c.rowid = ".((int) $id);
2295
2296 $result = $this->db->query($sql);
2297 if ($result) {
2298 if ($this->db->num_rows($result)) {
2299 $obj = $this->db->fetch_object($result);
2300
2301 $this->id = $obj->rowid;
2302 $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2303
2304 $this->user_creation_id = $obj->fk_user_author;
2305 $this->date_creation = $this->db->jdate($obj->datec);
2306 $this->date_modification = $this->db->jdate($obj->date_modification);
2307 }
2308
2309 $this->db->free($result);
2310 } else {
2311 dol_print_error($this->db);
2312 }
2313 }
2314
2315 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2322 public function array_detail($status = -1)
2323 {
2324 // phpcs:enable
2325 $tab = array();
2326
2327 $sql = "SELECT cd.rowid";
2328 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2329 $sql .= " WHERE fk_contrat =".((int) $this->id);
2330 if ($status >= 0) {
2331 $sql .= " AND statut = ".((int) $status);
2332 }
2333
2334 dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2335 $resql = $this->db->query($sql);
2336 if ($resql) {
2337 $num = $this->db->num_rows($resql);
2338 $i = 0;
2339 while ($i < $num) {
2340 $obj = $this->db->fetch_object($resql);
2341 $tab[$i] = $obj->rowid;
2342 $i++;
2343 }
2344 return $tab;
2345 } else {
2346 $this->error = $this->db->error();
2347 return -1;
2348 }
2349 }
2350
2360 public function getListOfContracts($option = 'all', $status = [], $product_categories = [], $line_status = [])
2361 {
2362 $tab = array();
2363
2364 $sql = "SELECT c.rowid";
2365 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2366 if (!empty($product_categories) || !empty($line_status)) {
2367 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid";
2368 }
2369 if (!empty($product_categories)) {
2370 $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)).")";
2371 }
2372 $sql .= " WHERE c.fk_soc =".((int) $this->socid);
2373 $sql .= ($option == 'others') ? " AND c.rowid <> ".((int) $this->id) : "";
2374 $sql .= (!empty($status)) ? " AND c.statut IN (".$this->db->sanitize(implode(', ', $status)).")" : "";
2375 $sql .= (!empty($line_status)) ? " AND cd.statut IN (".$this->db->sanitize(implode(', ', $line_status)).")" : "";
2376 $sql .= " GROUP BY c.rowid";
2377
2378 dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2379 $resql = $this->db->query($sql);
2380 if ($resql) {
2381 $num = $this->db->num_rows($resql);
2382 $i = 0;
2383 while ($i < $num) {
2384 $obj = $this->db->fetch_object($resql);
2385 $contrat = new Contrat($this->db);
2386 $contrat->fetch($obj->rowid);
2387 $tab[$contrat->id] = $contrat;
2388 $i++;
2389 }
2390 return $tab;
2391 } else {
2392 $this->error = $this->db->lasterror();
2393 return -1;
2394 }
2395 }
2396
2397
2398 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2406 public function load_board($user, $mode)
2407 {
2408 // phpcs:enable
2409 global $conf, $langs;
2410
2411 $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2412 $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2413 $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2414 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2415 $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2416 }
2417
2418 $now = dol_now();
2419 if ($mode == 'inactive') {
2420 $warning_delay = $conf->contract->services->inactifs->warning_delay;
2421 $datefield = 'cd.date_ouverture_prevue';
2422 } elseif ($mode == 'expired' || $mode == 'active') {
2423 $warning_delay = $conf->contract->services->expires->warning_delay;
2424 $datefield = 'cd.date_fin_validite';
2425 } else {
2426 return -1;
2427 }
2428
2429 // The count and the number of late services are computed by the database instead of reading every service. A service
2430 // is late when it has a date (planned start for inactive services, end of validity for the others) and that date is
2431 // before now minus the warning delay.
2432 $sql = "SELECT COUNT(cd.rowid) as nb,";
2433 $sql .= " SUM(CASE WHEN ".$this->db->sanitize($datefield)." IS NOT NULL AND ".$this->db->sanitize($datefield)." < '".$this->db->idate($now - $warning_delay)."' THEN 1 ELSE 0 END) as nblate";
2434 if ($mode == 'inactive') {
2435 $sql .= $this->from;
2436 $sql .= " WHERE c.statut = 1";
2437 $sql .= " AND c.rowid = cd.fk_contrat";
2438 $sql .= " AND cd.statut = 0";
2439 } elseif ($mode == 'expired') {
2440 $sql .= $this->from;
2441 $sql .= " WHERE c.statut = 1";
2442 $sql .= " AND c.rowid = cd.fk_contrat";
2443 $sql .= " AND cd.statut = 4";
2444 $sql .= " AND cd.date_fin_validite < '".$this->db->idate($now)."'";
2445 } else {
2446 $sql .= $this->from;
2447 $sql .= " WHERE c.statut = 1";
2448 $sql .= " AND c.rowid = cd.fk_contrat";
2449 $sql .= " AND cd.statut = 4";
2450 }
2451 $sql .= " AND c.fk_soc = s.rowid";
2452 $sql .= " AND c.entity = ".((int) $conf->entity);
2453 if ($user->socid) {
2454 $sql .= " AND c.fk_soc = ".((int) $user->socid);
2455 }
2456 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2457 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2458 }
2459
2460 $resql = $this->db->query($sql);
2461 if ($resql) {
2462 $langs->load("contracts");
2463
2464 if ($mode == 'inactive') {
2465 $label = $langs->trans("BoardNotActivatedServices");
2466 $labelShort = $langs->trans("BoardNotActivatedServicesShort");
2467 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2468 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2469 } elseif ($mode == 'expired') {
2470 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2471 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2472 $label = $langs->trans("BoardExpiredServices");
2473 $labelShort = $langs->trans("BoardExpiredServicesShort");
2474 } else {
2475 $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2476 $url_late = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2477 $label = $langs->trans("BoardRunningServices");
2478 $labelShort = $langs->trans("BoardRunningServicesShort");
2479 }
2480
2481 $response = new WorkboardResponse();
2482 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2483 $response->label = $label;
2484 $response->labelShort = $labelShort;
2485 $response->url = $url;
2486 $response->url_late = $url_late;
2487 $response->img = img_object('', "contract");
2488
2489 $obj = $this->db->fetch_object($resql);
2490 if ($obj) {
2491 $response->nbtodo = (int) $obj->nb;
2492 $response->nbtodolate = (int) $obj->nblate;
2493 }
2494
2495 return $response;
2496 } else {
2497 dol_print_error($this->db);
2498 $this->error = $this->db->error();
2499 return -1;
2500 }
2501 }
2502
2508 public function loadStateBoard()
2509 {
2510 global $conf, $user;
2511
2512 $this->nb = array();
2513 $sanitizedclause = "WHERE";
2514
2515 $sql = "SELECT count(c.rowid) as nb";
2516 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2517 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2518 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2519 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2520 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2521 $sanitizedclause = "AND";
2522 }
2523 $sql .= " ".$sanitizedclause." c.entity = ".((int) $conf->entity);
2524
2525 $resql = $this->db->query($sql);
2526 if ($resql) {
2527 while ($obj = $this->db->fetch_object($resql)) {
2528 $this->nb["contracts"] = $obj->nb;
2529 }
2530 $this->db->free($resql);
2531 return 1;
2532 } else {
2533 dol_print_error($this->db);
2534 $this->error = $this->db->error();
2535 return -1;
2536 }
2537 }
2538
2539
2540 /* gestion des contacts d'un contrat */
2541
2547 public function getIdBillingContact()
2548 {
2549 return $this->getIdContact('external', 'BILLING');
2550 }
2551
2557 public function getIdServiceContact()
2558 {
2559 return $this->getIdContact('external', 'SERVICE');
2560 }
2561
2562
2570 public function initAsSpecimen()
2571 {
2572 global $user, $langs, $conf;
2573
2574 // Load array of products prodids
2575 $num_prods = 0;
2576 $prodids = array();
2577 $sql = "SELECT rowid";
2578 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2579 $sql .= " WHERE entity IN (".getEntity('product').")";
2580 $sql .= " AND tosell = 1";
2581 $sql .= $this->db->plimit(100);
2582
2583 $resql = $this->db->query($sql);
2584 if ($resql) {
2585 $num_prods = $this->db->num_rows($resql);
2586 $i = 0;
2587 while ($i < $num_prods) {
2588 $i++;
2589 $row = $this->db->fetch_row($resql);
2590 $prodids[$i] = $row[0];
2591 }
2592 }
2593
2594 // Initialise parameters
2595 $this->id = 0;
2596 $this->specimen = 1;
2597
2598 $this->ref = 'SPECIMEN';
2599 $this->ref_customer = 'SPECIMENCUST';
2600 $this->ref_supplier = 'SPECIMENSUPP';
2601 $this->socid = 1;
2602 $this->status = 0;
2603 $this->date_creation = (dol_now() - 3600 * 24 * 7);
2604 $this->date_contrat = dol_now();
2605 $this->commercial_signature_id = 1;
2606 $this->commercial_suivi_id = 1;
2607 $this->note_private = 'This is a comment (private)';
2608 $this->note_public = 'This is a comment (public)';
2609 $this->fk_project = 0;
2610 // Lines
2611 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
2612 $xnbp = 0;
2613 while ($xnbp < $nbp) {
2614 $line = new ContratLigne($this->db);
2615 $line->qty = 1;
2616 $line->subprice = 100;
2617 $line->tva_tx = 19.6;
2618 $line->remise_percent = 10;
2619 $line->total_ht = 90;
2620 $line->total_ttc = 107.64; // 90 * 1.196
2621 $line->total_tva = 17.64;
2622 $line->date_start = dol_now() - 500000;
2623 $line->date_start_real = dol_now() - 200000;
2624 $line->date_end = dol_now() + 500000;
2625 $line->date_end_real = dol_now() - 100000;
2626 if ($num_prods > 0) {
2627 $prodid = mt_rand(1, $num_prods);
2628 $line->fk_product = $prodids[$prodid];
2629 }
2630 $this->lines[$xnbp] = $line;
2631 $xnbp++;
2632 }
2633
2634 return 1;
2635 }
2636
2642 public function getLinesArray()
2643 {
2644 return $this->fetch_lines();
2645 }
2646
2652 public function getTicketsArray()
2653 {
2654 global $user;
2655
2656 $ticket = new Ticket($this->db);
2657 $nbTicket = $ticket->fetchAll($user, 'ASC', 't.datec', 0, 0, 0, array('t.fk_contract' => $this->id));
2658
2659 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2660 }
2661
2662
2674 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2675 {
2676 global $langs;
2677
2678 if (!dol_strlen($modele)) {
2679 $modele = ''; // No doc template/generation by default
2680
2681 if (!empty($this->model_pdf)) {
2682 $modele = $this->model_pdf;
2683 } elseif (getDolGlobalString('CONTRACT_ADDON_PDF')) {
2684 $modele = getDolGlobalString('CONTRACT_ADDON_PDF');
2685 }
2686 }
2687
2688 if (empty($modele)) {
2689 return 0;
2690 } else {
2691 $langs->load("contracts");
2692 $outputlangs->load("products");
2693
2694 $modelpath = "core/modules/contract/doc/";
2695 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2696 }
2697 }
2698
2707 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2708 {
2709 $tables = array(
2710 'contrat'
2711 );
2712
2713 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2714 }
2715
2724 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2725 {
2726 $tables = array(
2727 'contratdet'
2728 );
2729
2730 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2731 }
2732
2741 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2742 {
2743 global $db, $langs, $conf, $hookmanager, $extrafields;
2744
2745 dol_include_once('/projet/class/project.class.php');
2746
2747 $error = 0;
2748
2749 $this->fetch($this->id);
2750
2751 // Load dest object
2752 $clonedObj = clone $this;
2753 $clonedObj->socid = $socid;
2754
2755 $this->db->begin();
2756
2757 $objsoc = new Societe($this->db);
2758
2759 $objsoc->fetch($clonedObj->socid);
2760
2761 // Clean data
2762 $clonedObj->statut = 0;
2763 $clonedObj->status = 0;
2764 // Clean extrafields
2765 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2766 $extrafields->fetch_name_optionals_label($this->table_element);
2767 foreach ($clonedObj->array_options as $key => $option) {
2768 $shortkey = preg_replace('/options_/', '', $key);
2769 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
2770 unset($clonedObj->array_options[$key]);
2771 }
2772 }
2773 }
2774
2775 if (!getDolGlobalString('CONTRACT_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').".php")) {
2776 $this->error = 'ErrorSetupNotComplete';
2777 dol_syslog($this->error);
2778 return -1;
2779 }
2780
2781 // Set ref
2782 require_once DOL_DOCUMENT_ROOT."/core/modules/contract/" . getDolGlobalString('CONTRACT_ADDON').'.php';
2783 $obj = getDolGlobalString('CONTRACT_ADDON');
2784 $modContract = new $obj();
2785 '@phan-var-force ModelNumRefContracts $modContract';
2787 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2788
2789 // get extrafields so they will be clone
2790 foreach ($this->lines as $line) {
2791 $line->fetch_optionals($line->id);
2792 }
2793
2794 // Create clone
2795 $clonedObj->context['createfromclone'] = 'createfromclone';
2796 $result = $clonedObj->create($user);
2797 if ($result < 0) {
2798 $error++;
2799 $this->setErrorsFromObject($clonedObj);
2800 } else {
2801 // copy external contacts if same company
2802 if ($this->socid == $clonedObj->socid) {
2803 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
2804 $error++;
2805 }
2806 }
2807 }
2808
2809 if (!$error) {
2810 foreach ($this->lines as $line) {
2811 // Preserve the original entry mode of the line. Contrat::addline() stores subprice from the
2812 // $pu_ht argument as-is (like the card, which pre-computes it), so we pass the stored HT and
2813 // flag TTC + subprice_ttc so the total is computed from the typed value (no rounding drift).
2814 $line_price_base_type = $line->getPriceBaseType();
2815 $result = $clonedObj->addline($line->description, (float) $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_start, $line->date_cloture, $line_price_base_type, (float) $line->subprice_ttc, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit, $line->rang, (float) $line->multicurrency_subprice);
2816 if ($result < 0) {
2817 $error++;
2818 $this->setErrorsFromObject($clonedObj);
2819 }
2820 }
2821 }
2822
2823 if (!$error) {
2824 // Hook of thirdparty module
2825 if (is_object($hookmanager)) {
2826 $parameters = array(
2827 'objFrom' => $this,
2828 'clonedObj' => $clonedObj
2829 );
2830 $action = '';
2831 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2832 if ($reshook < 0) {
2833 $this->setErrorsFromObject($hookmanager);
2834 $error++;
2835 }
2836 }
2837 }
2838
2839 unset($clonedObj->context['createfromclone']);
2840
2841 // End
2842 if (!$error) {
2843 $this->db->commit();
2844 return $clonedObj->id;
2845 } else {
2846 $this->db->rollback();
2847 return -1;
2848 }
2849 }
2850
2851
2861 public function doAutoRenewContracts($thirdparty_id = 0, $delayindaysshort = 0)
2862 {
2863 global $langs, $user;
2864
2865 $langs->load("agenda");
2866
2867 $now = dol_now();
2868
2869 $enddatetoscan = dol_time_plus_duree($now, -1 * abs($delayindaysshort), 'd');
2870
2871 $error = 0;
2872 $this->output = '';
2873 $this->error = '';
2874
2875 $contractlineprocessed = array();
2876 $contractignored = array();
2877 $contracterror = array();
2878
2879 dol_syslog(__METHOD__, LOG_DEBUG);
2880
2881 $sql = 'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2882 $sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c, '.MAIN_DB_PREFIX.'contratdet as cd';
2883 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON p.rowid = cd.fk_product';
2884 $sql .= ' WHERE cd.fk_contrat = c.rowid';
2885 $sql .= " AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan)."', '%Y-%m-%d')";
2886 $sql .= " AND cd.statut = 4";
2887 if ($thirdparty_id > 0) {
2888 $sql .= " AND c.fk_soc = ".((int) $thirdparty_id);
2889 }
2890 //print $sql;
2891
2892 $resql = $this->db->query($sql);
2893 if ($resql) {
2894 $num = $this->db->num_rows($resql);
2895
2896 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2897 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2898
2899 $i = 0;
2900 while ($i < $num) {
2901 $obj = $this->db->fetch_object($resql);
2902 if ($obj) {
2903 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2904 continue;
2905 }
2906
2907 // Load contract
2908 $object = new Contrat($this->db);
2909 $object->fetch($obj->rowid); // fetch also lines
2910
2911 if ($object->id <= 0) {
2912 $error++;
2913 $this->errors[] = 'Failed to load contract with id='.$obj->rowid;
2914 continue;
2915 }
2916
2917 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);
2918
2919 // Update expiration date of line
2920 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2921 $duration_value = preg_replace('/[^0-9]/', '', $obj->duration);
2922 $duration_unit = preg_replace('/\d/', '', $obj->duration);
2923
2924 // Load linked ->linkedObjects (objects linked)
2925 // @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.
2926 $object->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 1);
2927
2928 // Test if there is at least 1 open invoice
2929 if (isset($object->linkedObjects['facture']) && is_array($object->linkedObjects['facture']) && count($object->linkedObjects['facture']) > 0) {
2930 // Sort array of linked invoices by ascending date
2931 usort($object->linkedObjects['facture'], array('Contrat', 'contractCmpDate'));
2932 //dol_sort_array($object->linkedObjects['facture'], 'date');
2933
2934 $someinvoicenotpaid = 0;
2935 foreach ($object->linkedObjects['facture'] as $idinvoice => $invoice) {
2936 if ($invoice->statut == Facture::STATUS_DRAFT) {
2937 continue;
2938 } // Draft invoice are not invoice not paid
2939
2940 if (empty($invoice->paye)) {
2941 $someinvoicenotpaid++;
2942 }
2943 }
2944 if ($someinvoicenotpaid) {
2945 $this->output .= 'Contract '.$object->ref.' is qualified for renewal but there is '.$someinvoicenotpaid.' invoice(s) unpayed so we cancel renewal'."\n";
2946 $contractignored[$object->id] = $object->ref;
2947 continue;
2948 }
2949 }
2950
2951 if ($expirationdate && $expirationdate < $enddatetoscan) {
2952 dol_syslog("Define the newdate of end of services from expirationdate=".$expirationdate);
2953 $newdate = $expirationdate;
2954 $protecti = 0; // $protecti is to avoid infinite loop
2955 while ($newdate < $enddatetoscan && $protecti < 1000) {
2956 $newdate = dol_time_plus_duree($newdate, (int) $duration_value, $duration_unit);
2957 $protecti++;
2958 }
2959
2960 if ($protecti < 1000) { // If not, there is a pb
2961 // We will update the end of date of contrat, so first we refresh contract data
2962 dol_syslog("We will update the end of date of contract with newdate = ".dol_print_date($newdate, 'dayhourrfc'));
2963
2964 $this->db->begin();
2965
2966 $errorforlocaltransaction = 0;
2967
2968 $label = 'Renewal of contrat '.$object->ref.' line '.$obj->lid;
2969 $comment = 'Renew date of contract '.$object->ref.' line '.$obj->lid.' by doAutoRenewContracts';
2970
2971 $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."contratdet SET date_fin_validite = '".$this->db->idate($newdate)."'";
2972 $sqlupdate .= ' WHERE rowid = '.((int) $obj->lid);
2973 $resqlupdate = $this->db->query($sqlupdate);
2974 if ($resqlupdate) {
2975 $contractlineprocessed[$obj->lid] = $object->ref;
2976
2977 // Update column llx_contrat.denormalized_lower_panned_end_date with next expiration date of an open contract
2978 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
2979 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = ".((int) $object->id)." AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
2980 $sqltoupdatecontract .= " WHERE rowid = ".((int) $object->id);
2981 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
2982 if (!$resqltoupdatecontract) {
2983 $this->error = $this->db->lasterror();
2984 $this->db->rollback();
2985 return -1;
2986 }
2987
2988 $actioncode = 'RENEW_CONTRACT';
2989 $now = dol_now();
2990
2991 // Create an event
2992 $actioncomm = new ActionComm($this->db);
2993 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2994 $actioncomm->code = 'AC_'.$actioncode;
2995 $actioncomm->label = $label;
2996 $actioncomm->datep = $now;
2997 $actioncomm->datef = $now;
2998 $actioncomm->percentage = -1; // Not applicable
2999 $actioncomm->socid = $object->socid;
3000 $actioncomm->authorid = $user->id; // User saving action
3001 $actioncomm->userownerid = $user->id; // Owner of action
3002 $actioncomm->fk_element = $object->id;
3003 $actioncomm->elementid = $object->id;
3004 $actioncomm->elementtype = 'contract';
3005 $actioncomm->note_private = $comment;
3006
3007 $ret = $actioncomm->create($user); // User creating action
3008 } else {
3009 $contracterror[$object->id] = $object->ref;
3010
3011 $error++;
3012 $errorforlocaltransaction++;
3013 $this->error = $this->db->lasterror();
3014 }
3015
3016 if (! $errorforlocaltransaction) {
3017 $this->db->commit();
3018 } else {
3019 $this->db->rollback();
3020 }
3021 } else {
3022 $error++;
3023 $this->error = "Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate." enddatetoscan=".$enddatetoscan." duration_value=".$duration_value." duration_unit=".$duration_value;
3024 dol_syslog($this->error, LOG_ERR);
3025 }
3026 }
3027 }
3028 $i++;
3029 }
3030 } else {
3031 $error++;
3032 $this->error = $this->db->lasterror();
3033 }
3034
3035 $this->output .= count($contractlineprocessed).' contract line(s) with end date before '.dol_print_date($enddatetoscan, 'day').' were renewed'.(count($contractlineprocessed) > 0 ? ' : '.implode(',', $contractlineprocessed) : '');
3036
3037 return ($error ? 1 : 0);
3038 }
3039
3047 public static function contractCmpDate($a, $b)
3048 {
3049 if ($a->date == $b->date) {
3050 return strcmp((string) $a->id, (string) $b->id);
3051 }
3052 return ($a->date < $b->date) ? -1 : 1;
3053 }
3054
3062 public function getKanbanView($option = '', $arraydata = null)
3063 {
3064 global $langs;
3065
3066 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3067
3068 $return = '<div class="box-flex-item box-flex-grow-zero">';
3069 $return .= '<div class="info-box info-box-sm">';
3070 $return .= '<span class="info-box-icon bg-infobox-action">';
3071 $return .= img_picto('', $this->picto);
3072 $return .= '</span>';
3073 $return .= '<div class="info-box-content">';
3074 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
3075 if ($selected >= 0) {
3076 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3077 }
3078 if (!empty($arraydata['thirdparty']) && $arraydata['thirdparty'] instanceof Societe) {
3079 $tmpthirdparty = $arraydata['thirdparty'];
3080 '@phan-var-force Societe $tmpthirdparty';
3081 $return .= '<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).'</div>';
3082 }
3083 $return .= '<br><span class="opacitymedium valignmiddle">'.$langs->trans("DateContract").' : </span><span class="info-box-label valignmiddle">'.dol_print_date($this->date_contrat, 'day').'</span>';
3084 $return .= '<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).'</div>';
3085 $return .= '</div>';
3086 $return .= '</div>';
3087 $return .= '</div>';
3088
3089 return $return;
3090 }
3091
3099 public function getTotalizedLines($statut, int $expired)
3100 {
3101 $sql = "SELECT SUM(cd.qty) as total_qty, SUM(cd.total_ht) as total_ht, SUM(cd.total_tva) as total_tva, SUM(cd.total_ttc) as total_ttc,";
3102 $sql .= " SUM(cd.total_localtax1) as total_localtax1, SUM(cd.total_localtax2) as total_localtax2";
3103 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
3104 $sql .= " WHERE cd.fk_contrat =".((int) $this->id);
3105 if ($statut >= 0) {
3106 $sql .= " AND cd.statut = ".((int) $statut);
3107 if ($expired > 0) {
3108 $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
3109 } else {
3110 $sql .= " AND cd.date_fin_validite >= '".$this->db->idate(dol_now())."'";
3111 }
3112 }
3113 $ret = $this->db->query($sql);
3114 $response = array();
3115 if ($ret) {
3116 $obj = $this->db->fetch_object($ret);
3117 $response['total_qty'] = $obj->total_qty;
3118 $response['total_ht'] = $obj->total_ht;
3119 $response['total_tva'] = $obj->total_tva;
3120 $response['total_localtax1'] = $obj->total_localtax1;
3121 $response['total_localtax2'] = $obj->total_localtax2;
3122 $response['total_ttc'] = $obj->total_ttc;
3123 } else {
3124 dol_print_error($this->db);
3125 $this->error = $this->db->lasterror();
3126 return -1;
3127 }
3128 return $response;
3129 }
3130
3131 // @Todo getLibSignedStatus, LibSignedStatus
3132
3142 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
3143 {
3144 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
3145 }
3146
3161 public function sendReminderForExpiredServices($daysbeforeendlist = '10', $fk_product = 0)
3162 {
3163 global $conf, $langs, $mysoc, $user;
3164
3165 $error = 0;
3166 $this->output = '';
3167 $this->error = '';
3168
3169 $blockingerrormsg = '';
3170
3171 if (!isModEnabled('contract')) { // Should not happen. If module disabled, cron job should not be visible.
3172 $langs->load("agenda");
3173 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Contract"));
3174 return 0;
3175 }
3176
3177 $now = dol_now();
3178 $nbok = 0;
3179 $nbko = 0;
3180
3181 $listoflinesok = array();
3182 $listoflinesko = array();
3183
3184 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
3185 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
3186 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
3187
3188 if (!is_numeric($daysbeforeend)) {
3189 $blockingerrormsg = "Value for delta is not a numeric value";
3190 $nbko++;
3191 break;
3192 }
3193
3194 $tmp = dol_getdate($now);
3195 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3196 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3197
3198 $sql = "SELECT cd.rowid, cd.fk_contrat";
3199 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
3200 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."contrat as c ON c.rowid = cd.fk_contrat";
3201 $sql .= " WHERE c.entity = ".((int) $conf->entity); // Do not use getEntity('contract') here, we want the batch to be on its entity only
3202 $sql .= " AND cd.statut = ".((int) ContratLigne::STATUS_OPEN);
3203 $sql .= " AND cd.date_fin_validite >= '".$this->db->idate($datetosearchfor)."'";
3204 $sql .= " AND cd.date_fin_validite <= '".$this->db->idate($datetosearchforend)."'";
3205 if ((int) $fk_product > 0) {
3206 $sql .= " AND cd.fk_product = ".((int) $fk_product);
3207 }
3208
3209 $resql = $this->db->query($sql);
3210 if ($resql) {
3211 $num_rows = $this->db->num_rows($resql);
3212
3213 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3214 include_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
3215 $formmail = new FormMail($this->db);
3216
3217 $i = 0;
3218 while ($i < $num_rows) {
3219 $obj = $this->db->fetch_object($resql);
3220
3221 $contractline = new ContratLigne($this->db);
3222 $contractline->fetch($obj->rowid);
3223
3224 $contractstatic = new Contrat($this->db);
3225 $contractstatic->fetch($obj->fk_contrat);
3226 $thirdpartyres = $contractstatic->fetch_thirdparty();
3227
3228 if ($thirdpartyres <= 0 || empty($contractstatic->thirdparty->email)) {
3229 $nbko++;
3230 $listoflinesko[$contractline->id] = $contractline->id;
3231 } else {
3232 $languagefromcountrycode = getLanguageCodeFromCountryCode($contractstatic->thirdparty->country_code);
3233 $languagecodetouse = (empty($contractstatic->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $contractstatic->thirdparty->default_lang);
3234
3235 $outputlangs = new Translate('', $conf);
3236 $outputlangs->setDefaultLang($languagecodetouse);
3237 $outputlangs->loadLangs(array("main", "contracts"));
3238 dol_syslog("sendReminderForExpiredServices Language for thirdparty id ".$contractstatic->thirdparty->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang);
3239
3240 $arraydefaultmessage = null;
3241 $labeltouse = getDolGlobalString('CONTRACT_EMAIL_TEMPLATE_REMIND_EXPIRATION');
3242
3243 if (!empty($labeltouse)) {
3244 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'contrat', $user, $outputlangs, 0, 1, $labeltouse);
3245 }
3246
3247 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3248 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $contractstatic);
3249 complete_substitutions_array($substitutionarray, $outputlangs, $contractstatic);
3250 $substitutionarray['__CONTRACT_LINE_LABEL__'] = ($contractline->label ? $contractline->label : $contractline->description);
3251 $substitutionarray['__CONTRACT_LINE_DATE_END__'] = dol_print_date($contractline->date_end, 'day', 'tzuserrel', $outputlangs);
3252
3253 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
3254 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
3255 $email_from = getDolGlobalString('CONTRACT_MAIL_FROM', $conf->email_from);
3256 $to = (string) $contractstatic->thirdparty->email;
3257 $cc = getDolGlobalString('CONTRACT_CC_MAIL_FROM');
3258
3259 $trackid = 'con'.$contractstatic->id;
3260 $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredServices'."\r\n";
3261
3262 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3263 $cmail = new CMailFile($subject, $to, $email_from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
3264 $result = $cmail->sendfile();
3265 if (!$result) {
3266 $error++;
3267 $this->error .= $cmail->error.' ';
3268 if (!is_null($cmail->errors)) {
3269 $this->errors = array_merge($this->errors, $cmail->errors);
3270 }
3271 $nbko++;
3272 $listoflinesko[$contractline->id] = $contractline->id;
3273 } else {
3274 $nbok++;
3275 $listoflinesok[$contractline->id] = $contractline->id;
3276
3277 // Insert record of email sent, as an agenda event on the contract (same convention as other automated reminder emails)
3278 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3279
3280 $actioncomm = new ActionComm($this->db);
3281 $actioncomm->type_code = 'AC_OTH_AUTO';
3282 $actioncomm->code = 'AC_EMAIL';
3283 $actioncomm->label = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($email_from, 4, 0, 1), CMailFile::getValidAddress($to, 4, 0, 1));
3284 $actioncomm->note_private = $msg;
3285 $actioncomm->fk_project = 0;
3286 $actioncomm->datep = $now;
3287 $actioncomm->datef = $now;
3288 $actioncomm->percentage = -1; // Not applicable
3289 $actioncomm->socid = $contractstatic->thirdparty->id;
3290 $actioncomm->contact_id = 0;
3291 $actioncomm->authorid = $user->id;
3292 $actioncomm->userownerid = $user->id;
3293 $actioncomm->email_msgid = $cmail->msgid;
3294 $actioncomm->email_from = $email_from;
3295 $actioncomm->email_sender = '';
3296 $actioncomm->email_to = $to;
3297 $actioncomm->email_subject = $subject;
3298
3299 $actioncomm->fk_element = $contractstatic->id;
3300 $actioncomm->elementid = $contractstatic->id;
3301 $actioncomm->elementtype = $contractstatic->element;
3302
3303 $actioncomm->create($user);
3304 }
3305 } else {
3306 $error++;
3307 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
3308
3309 $nbko++;
3310 $listoflinesko[$contractline->id] = $contractline->id;
3311
3312 // Do not break here: a template issue for one contract line (ex: not found for its language) must not
3313 // prevent the reminder from being sent for the other contract lines due the same day.
3314 }
3315 }
3316
3317 $i++;
3318 }
3319 } else {
3320 $this->error = $this->db->lasterror();
3321 return 1;
3322 }
3323 }
3324
3325 if ($blockingerrormsg) {
3326 $this->error = $blockingerrormsg;
3327 return 1;
3328 } else {
3329 $this->output = 'Found '.($nbok + $nbko).' contract lines to send reminder for.';
3330 $this->output .= ' Sent email successfully for '.$nbok.' lines';
3331 if ($nbko) {
3332 $this->output .= ' - Canceled for '.$nbko.' line(s) (no thirdparty email, missing template, or send error)';
3333 }
3334 }
3335
3336 if ($error) {
3337 return 1;
3338 }
3339 return 0;
3340 }
3341}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
static contractCmpDate($a, $b)
Used to sort lines by date.
getTotalizedLines($statut, int $expired)
Return totalized lines.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
loadStateBoard()
Load the indicators this->nb for state board.
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, $pu_ht_devise=0.0)
Insert contract line into database.
update_statut($user)
Update statut of contract according to services.
closeAll(User $user, $notrigger=0, $comment='', $nofetchlines=0)
Close all lines of a contract.
getTicketsArray()
Create an array of associated tickets.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
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, $pu_ht_devise=0.0)
Update a contract line.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
deleteLine($idline, User $user)
Delete a contract line.
array_detail($status=-1)
Return list of line rowid.
update($user, $notrigger=0)
Update object into database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
__construct($db)
Constructor.
doAutoRenewContracts($thirdparty_id=0, $delayindaysshort=0)
Action executed by scheduler CAN BE A CRON TASK Loop on each contract lines and update the end of dat...
getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
info($id)
Charge les information d'ordre info dans l'objet contrat.
getLibStatut($mode)
Return label of a contract status.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetch_lines($only_services=0, $loadalsotranslation=0, $noextrafields=0)
Load lines array into this->lines.
getIdServiceContact()
Return id des contacts clients de prestation.
sendReminderForExpiredServices($daysbeforeendlist='10', $fk_product=0)
Send reminders by email before a running contract service expires.
Class to manage lines of contracts.
Class to manage Dolibarr database access.
const STATUS_DRAFT
Draft status.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
setSignedStatusCommon(User $user, int $status, int $notrigger=0, string $triggercode='')
Set signed status & call trigger with context message.
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90