37require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobject.class.php';
38require_once DOL_DOCUMENT_ROOT.
'/contrat/class/contratligne.class.php';
39require_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
40require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
41require_once DOL_DOCUMENT_ROOT.
'/core/class/commonsignedobject.class.php';
51 use CommonSignedObject;
56 public $element =
'contrat';
61 public $table_element =
'contrat';
66 public $table_element_line =
'contratdet';
71 public $fk_element =
'fk_contrat';
76 public $picto =
'contract';
82 public $restrictiononfksoc = 1;
104 public $ref_supplier;
145 public $fk_user_author;
152 public $user_author_id;
159 public $user_creation;
164 public $user_cloture;
169 public $date_contrat;
174 public $commercial_signature_id;
180 public $fk_commercial_signature;
185 public $commercial_suivi_id;
192 public $fk_commercial_suivi;
197 public $extraparams = array();
202 public $lines = array();
207 public $nbofservices;
211 public $nbofserviceswait;
215 public $nbofservicesopened;
219 public $nbofservicesexpired;
223 public $nbofservicesclosed;
231 protected $lines_id_index_mapper = array();
262 public $fields = array(
263 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 10),
264 'ref' => array(
'type' =>
'varchar(50)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => -1,
'showoncombobox' => 1,
'position' => 15,
'searchall' => 1),
265 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 20),
266 'ref_customer' => array(
'type' =>
'varchar(50)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 25,
'searchall' => 1),
267 'ref_supplier' => array(
'type' =>
'varchar(50)',
'label' =>
'RefSupplier',
'enabled' => 1,
'visible' => -1,
'position' => 26,
'searchall' => 1),
268 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 30,
'index' => 1),
269 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 35),
270 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 40),
271 'date_contrat' => array(
'type' =>
'datetime',
'label' =>
'Date contrat',
'enabled' => 1,
'visible' => -1,
'position' => 45),
272 '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')),
273 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' =>
'isModEnabled("societe")',
'visible' => -1,
'notnull' => 1,
'position' => 70),
274 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' =>
"isModEnabled('project')",
'visible' => -1,
'position' => 75),
275 'fk_commercial_signature' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'SaleRepresentative Signature',
'enabled' => 1,
'visible' => -1,
'position' => 80),
276 'fk_commercial_suivi' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'SaleRepresentative follower',
'enabled' => 1,
'visible' => -1,
'position' => 85),
277 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 90),
278 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 105,
'searchall' => 1),
279 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 110,
'searchall' => 1),
280 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 115),
281 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 120),
282 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 125),
283 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'enabled' => 1,
'visible' => -2,
'notnull' => -1,
'position' => 135),
284 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'Last main doc',
'enabled' => 1,
'visible' => -1,
'position' => 140),
285 'statut' => array(
'type' =>
'smallint(6)',
'label' =>
'Statut',
'enabled' => 1,
'visible' => -1,
'position' => 500,
'notnull' => 1,
'arrayofkeyval' => array(0 =>
'Draft', 1 =>
'Validated', 2 =>
'Closed'))
289 const STATUS_DRAFT = 0;
290 const STATUS_VALIDATED = 1;
291 const STATUS_CLOSED = 2;
302 $this->ismultientitymanaged = 1;
303 $this->isextrafieldmanaged = 1;
312 public function getNextNumRef($soc)
314 global $db, $langs, $conf;
315 $langs->load(
"contracts");
324 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
326 foreach ($dirmodels as $reldir) {
330 $mybool = ((bool) @include_once $dir.$file) || $mybool;
338 $obj =
new $classname();
339 '@phan-var-force ModelNumRefContracts $obj';
341 $numref = $obj->getNextValue($soc, $this);
346 $this->error = $obj->error;
351 $langs->load(
"errors");
352 print $langs->trans(
"Error").
" ".$langs->trans(
"ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv(
"Contract"));
368 public function active_line($user, $line_id, $date_start, $date_end =
'', $comment =
'')
371 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date_start, $date_end, $comment);
373 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
374 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
390 public function close_line($user, $line_id, $date_end, $comment =
'')
393 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
395 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
396 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
413 public function activateAll($user, $date_start =
'', $notrigger = 0, $comment =
'', $date_end =
'')
415 if (empty($date_start)) {
426 foreach ($this->lines as $contratline) {
428 if ($contratline->statut != ContratLigne::STATUS_OPEN) {
429 $contratline->context = $this->context;
431 $result = $contratline->active_line($user, $date_start, !empty($date_end) ? $date_end : -1, $comment);
440 if (!$error && $this->statut == 0) {
441 $result = $this->
validate($user,
'', $notrigger);
451 $this->db->rollback();
466 public function closeAll(
User $user, $notrigger = 0, $comment =
'', $nofetchlines = 0)
473 if (empty($nofetchlines)) {
481 foreach ($this->lines as $contratline) {
483 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
484 $contratline->date_end_real = $now;
485 $contratline->date_cloture = $now;
486 $contratline->user_closing_id = $user->id;
487 $contratline->statut = ContratLigne::STATUS_CLOSED;
489 $result = $contratline->close_line($user, $now, $comment, $notrigger);
493 $this->error = $contratline->error.($contratline->error ?
' ('.$this->ref.
')' :
'');
494 $this->errors = $contratline->errors;
500 if (!$error && $this->
status == 0) {
501 $result = $this->
validate($user,
'', $notrigger);
514 $this->db->rollback();
530 public function validate(
User $user, $force_number =
'', $notrigger = 0)
532 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
538 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number);
546 if (!
getDolGlobalString(
'CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
547 $result = $this->thirdparty->setAsCustomer();
552 $num = $force_number;
553 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
554 $num = $this->getNextNumRef($this->thirdparty);
556 $num = (string) $this->
ref;
561 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET ref = '".$this->db->escape($num).
"', statut = 1";
562 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND statut = 0";
564 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
565 $resql = $this->db->query($sql);
569 $this->error = $this->db->lasterror();
573 if (!$error && !$notrigger) {
575 $result = $this->call_trigger(
'CONTRACT_VALIDATE', $user);
583 $this->oldref = $this->ref;
586 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
588 $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).
"'";
589 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'contract/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
590 $resql = $this->db->query($sql);
593 $this->error = $this->db->lasterror();
595 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files SET filepath = 'contract/".$this->db->escape($this->newref).
"'";
596 $sql .=
" WHERE filepath = 'contract/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
597 $resql = $this->db->query($sql);
600 $this->error = $this->db->lasterror();
606 $dirsource = $conf->contract->dir_output.
'/'.$oldref;
607 $dirdest = $conf->contract->dir_output.
'/'.$newref;
608 if (!$error && file_exists($dirsource)) {
609 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
611 if (@rename($dirsource, $dirdest)) {
614 $listoffiles =
dol_dir_list($conf->contract->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
615 foreach ($listoffiles as $fileentry) {
616 $dirsource = $fileentry[
'name'];
617 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
618 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
619 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
620 @rename($dirsource, $dirdest);
630 $this->
status = self::STATUS_VALIDATED;
631 $this->statut = self::STATUS_VALIDATED;
632 $this->date_validation = $now;
642 $this->db->rollback();
654 public function reopen($user, $notrigger = 0)
656 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
661 dol_syslog(get_class($this).
'::reopen user='.$user->id);
667 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET statut = 0";
669 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND statut = 1";
671 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
672 $resql = $this->db->query($sql);
676 $this->error = $this->db->lasterror();
680 if (!$error && !$notrigger) {
682 $result = $this->call_trigger(
'CONTRACT_REOPEN', $user);
691 $this->statut = self::STATUS_DRAFT;
692 $this->
status = self::STATUS_DRAFT;
693 $this->date_validation = $now;
700 $this->db->rollback();
716 public function fetch($id, $ref =
'', $ref_customer =
'', $ref_supplier =
'', $noextrafields = 0, $nolines = 0)
720 $sql =
"SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
721 $sql .=
" ref_supplier, ref_customer,";
724 $sql .=
" signed_status,";
725 $sql .=
" date_contrat as datecontrat,";
726 $sql .=
" fk_user_author,";
727 $sql .=
" fk_projet as fk_project,";
728 $sql .=
" fk_commercial_signature, fk_commercial_suivi,";
729 $sql .=
" note_private, note_public, model_pdf, last_main_doc, extraparams";
730 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat";
732 $sql .=
" WHERE entity IN (".getEntity(
'contract').
")";
734 $sql .=
" WHERE rowid = ".(int) $id;
737 $sql .=
" AND ref_customer = '".$this->db->escape($ref_customer).
"'";
740 $sql .=
" AND ref_supplier = '".$this->db->escape($ref_supplier).
"'";
743 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
746 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
748 $resql = $this->db->query($sql);
750 $num = $this->db->num_rows($resql);
752 $this->error =
'Fetch found several records.';
757 $obj = $this->db->fetch_object($resql);
759 $this->
id = $obj->rowid;
760 $this->
ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
761 $this->ref_customer = $obj->ref_customer;
762 $this->ref_supplier = $obj->ref_supplier;
763 $this->ref_ext = $obj->ref_ext;
764 $this->entity = $obj->entity;
765 $this->statut = $obj->status;
766 $this->
status = $obj->status;
767 $this->signed_status = $obj->signed_status;
769 $this->date_contrat = $this->db->jdate($obj->datecontrat);
770 $this->date_creation = $this->db->jdate($obj->datecontrat);
772 $this->user_author_id = $obj->fk_user_author;
774 $this->commercial_signature_id = $obj->fk_commercial_signature;
775 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
777 $this->note_private = $obj->note_private;
778 $this->note_public = $obj->note_public;
779 $this->model_pdf = $obj->model_pdf;
781 $this->fk_projet = $obj->fk_project;
782 $this->fk_project = $obj->fk_project;
784 $this->socid = $obj->thirdpartyid;
785 $this->fk_soc = $obj->thirdpartyid;
786 $this->last_main_doc = $obj->last_main_doc;
787 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) :
null);
789 $this->db->free($resql);
793 if (empty($noextrafields)) {
796 $this->error = $this->db->lasterror();
802 if (empty($nolines)) {
803 if ($result >= 0 && !empty($this->table_element_line)) {
806 $this->error = $this->db->lasterror();
814 dol_syslog(get_class($this).
"::fetch Contract failed");
815 $this->error =
"Fetch contract failed";
819 dol_syslog(get_class($this).
"::fetch Contract not found");
820 $this->error =
"Contract not found";
824 dol_syslog(get_class($this).
"::fetch Error searching contract");
825 $this->error = $this->db->error();
840 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
843 $this->nbofservices = 0;
844 $this->nbofserviceswait = 0;
845 $this->nbofservicesopened = 0;
846 $this->nbofservicesexpired = 0;
847 $this->nbofservicesclosed = 0;
855 $this->lines = array();
859 $sql =
"SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
860 $sql .=
" d.rowid, d.fk_contrat, d.statut as status, d.description, d.subprice, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
861 $sql .=
" d.total_ht,";
862 $sql .=
" d.total_tva,";
863 $sql .=
" d.total_localtax1,";
864 $sql .=
" d.total_localtax2,";
865 $sql .=
" d.total_ttc,";
866 $sql .=
" d.info_bits, d.fk_product,";
867 $sql .=
" d.date_ouverture_prevue as date_start,";
868 $sql .=
" d.date_ouverture as date_start_real,";
869 $sql .=
" d.date_fin_validite as date_end,";
870 $sql .=
" d.date_cloture as date_end_real,";
871 $sql .=
" d.fk_user_author,";
872 $sql .=
" d.fk_user_ouverture,";
873 $sql .=
" d.fk_user_cloture,";
874 $sql .=
" d.fk_unit,";
875 $sql .=
" d.extraparams,";
876 $sql .=
" d.product_type as type,";
878 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contratdet as d LEFT JOIN ".MAIN_DB_PREFIX.
"product as p ON d.fk_product = p.rowid";
879 $sql .=
" WHERE d.fk_contrat = ".((int) $this->
id);
880 if ($only_services == 1) {
881 $sql .=
" AND d.product_type = 1";
883 $sql .=
" ORDER by d.rang ASC";
885 dol_syslog(get_class($this).
"::fetch_lines", LOG_DEBUG);
886 $result = $this->db->query($sql);
888 $num = $this->db->num_rows($result);
892 $objp = $this->db->fetch_object($result);
896 $line->id = $objp->rowid;
897 $line->ref = $objp->rowid;
898 $line->fk_contrat = $objp->fk_contrat;
899 $line->desc = $objp->description;
900 $line->qty = $objp->qty;
901 $line->vat_src_code = $objp->vat_src_code;
902 $line->tva_tx = $objp->tva_tx;
903 $line->localtax1_tx = $objp->localtax1_tx;
904 $line->localtax2_tx = $objp->localtax2_tx;
905 $line->localtax1_type = $objp->localtax1_type;
906 $line->localtax2_type = $objp->localtax2_type;
907 $line->subprice = $objp->subprice;
908 $line->statut = $objp->status;
909 $line->status = $objp->status;
910 $line->remise_percent = $objp->remise_percent;
911 $line->total_ht = $objp->total_ht;
912 $line->total_tva = $objp->total_tva;
913 $line->total_localtax1 = $objp->total_localtax1;
914 $line->total_localtax2 = $objp->total_localtax2;
915 $line->total_ttc = $objp->total_ttc;
916 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
917 $line->info_bits = $objp->info_bits;
918 $line->type = $objp->type;
920 $line->fk_fournprice = $objp->fk_fournprice;
921 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
922 $line->pa_ht = $marginInfos[0];
924 $line->fk_user_author = $objp->fk_user_author;
925 $line->fk_user_ouverture = $objp->fk_user_ouverture;
926 $line->fk_user_cloture = $objp->fk_user_cloture;
927 $line->fk_unit = $objp->fk_unit;
929 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
931 $line->ref = $objp->product_ref;
932 $line->product_ref = $objp->product_ref;
933 $line->product_type = $objp->product_type;
934 $line->product_desc = $objp->product_desc;
935 $line->product_label = $objp->product_label;
937 $line->description = $objp->description;
939 $line->date_start = $this->db->jdate($objp->date_start);
940 $line->date_start_real = $this->db->jdate($objp->date_start_real);
941 $line->date_end = $this->db->jdate($objp->date_end);
942 $line->date_end_real = $this->db->jdate($objp->date_end_real);
953 $line->rang = $objp->rang;
957 if (empty($noextrafields)) {
958 $line->fetch_optionals();
962 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
963 $tmpproduct =
new Product($this->db);
964 $tmpproduct->fetch($objp->fk_product);
965 $tmpproduct->getMultiLangs();
967 $line->multilangs = $tmpproduct->multilangs;
970 $this->lines[$pos] = $line;
972 $this->lines_id_index_mapper[$line->id] = $pos;
977 if ($line->statut == ContratLigne::STATUS_INITIAL) {
978 $this->nbofserviceswait++;
980 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
981 $this->nbofservicesopened++;
983 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
984 $this->nbofservicesexpired++;
986 if ($line->statut == ContratLigne::STATUS_CLOSED) {
987 $this->nbofservicesclosed++;
991 $total_ttc += $objp->total_ttc;
992 $total_vat += $objp->total_tva;
993 $total_ht += $objp->total_ht;
998 $this->db->free($result);
1000 dol_syslog(get_class($this).
"::Fetch Error when reading lines of contracts linked to products");
1005 $this->nbofservices = count($this->lines);
1006 $this->total_ttc = (float)
price2num($total_ttc);
1007 $this->total_tva = (float)
price2num($total_vat);
1008 $this->total_ht = (float)
price2num($total_ht);
1010 return $this->lines;
1020 public function create($user, $notrigger = 0)
1022 global $conf, $langs;
1026 if ($this->commercial_signature_id <= 0) {
1027 $langs->load(
"commercial");
1028 $this->error .= $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"SalesRepresentativeSignature"));
1031 if ($this->commercial_suivi_id <= 0) {
1032 $langs->load(
"commercial");
1033 $this->error .= ($this->error ?
"<br>" :
'');
1034 $this->error .= $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"SalesRepresentativeFollowUp"));
1048 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"contrat (datec, fk_soc, fk_user_author, date_contrat,";
1049 $sql .=
" fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1050 $sql .=
" ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1051 $sql .=
" VALUES ('".$this->db->idate($now).
"', ".((int) $this->socid).
", ".((int) $user->id);
1052 $sql .=
", ".(dol_strlen($this->date_contrat) != 0 ?
"'".$this->db->idate($this->date_contrat).
"'" :
"NULL");
1053 $sql .=
",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) :
"NULL");
1054 $sql .=
",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) :
"NULL");
1055 $sql .=
",".($this->fk_project > 0 ? ((int) $this->fk_project) :
"NULL");
1056 $sql .=
", ".(dol_strlen($this->
ref) <= 0 ?
"null" :
"'".$this->db->escape($this->
ref).
"'");
1057 $sql .=
", ".((int) $this->entity);
1058 $sql .=
", ".((int) $this->signed_status);
1059 $sql .=
", ".(!empty($this->note_private) ? (
"'".$this->db->escape($this->note_private).
"'") :
"NULL");
1060 $sql .=
", ".(!empty($this->note_public) ? (
"'".$this->db->escape($this->note_public).
"'") :
"NULL");
1061 $sql .=
", ".(!empty($this->ref_customer) ? (
"'".$this->db->escape($this->ref_customer).
"'") :
"NULL");
1062 $sql .=
", ".(!empty($this->ref_supplier) ? (
"'".$this->db->escape($this->ref_supplier).
"'") :
"NULL");
1063 $sql .=
", ".(!empty($this->ref_ext) ? (
"'".$this->db->escape($this->ref_ext).
"'") :
"NULL");
1065 $resql = $this->db->query($sql);
1070 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
"contrat");
1074 if (substr($module, 0, 13) ==
'mod_contract_' && substr($module, -3) ==
'php') {
1075 $module = substr($module, 0,
dol_strlen($module) - 4);
1079 $modCodeContract =
new $module();
1080 '@phan-var-force ModelNumRefContracts $modCodeContract';
1083 if (!empty($modCodeContract->code_auto)) {
1085 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"contrat SET ref='(PROV".$this->
id.
")' WHERE rowid=".((int) $this->
id);
1086 if ($this->db->query($sql)) {
1088 $this->
ref =
"(PROV".$this->id.
")";
1100 if (!$error && !empty($this->commercial_signature_id)) {
1101 $result = $this->
add_contact($this->commercial_signature_id,
'SALESREPSIGN',
'internal');
1108 if (!$error && !empty($this->commercial_suivi_id)) {
1109 $result = $this->
add_contact($this->commercial_suivi_id,
'SALESREPFOLL',
'internal');
1116 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
1117 $this->linked_objects = $this->linkedObjectsIds;
1121 if ($this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1122 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1123 if (is_array($tmp_origin_id)) {
1124 foreach ($tmp_origin_id as $origin_id) {
1127 $this->error = $this->db->lasterror();
1132 $origin_id = $tmp_origin_id;
1135 $this->error = $this->db->lasterror();
1142 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
1143 $originforcontact = $this->origin;
1144 $originidforcontact = $this->origin_id;
1145 if ($originforcontact ==
'shipping') {
1146 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
1148 $exp->fetch($this->origin_id);
1149 $exp->fetchObjectLinked();
1150 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
1151 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
1152 $originforcontact =
'commande';
1153 $originidforcontact = $value;
1159 $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";
1160 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
1162 $resqlcontact = $this->db->query($sqlcontact);
1163 if ($resqlcontact) {
1164 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1165 if ($objcontact->source ==
'internal' && in_array($objcontact->code, array(
'SALESREPSIGN',
'SALESREPFOLL'))) {
1169 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
1177 if (!$error && !$notrigger) {
1179 $result = $this->call_trigger(
'CONTRACT_CREATE', $user);
1187 $this->db->commit();
1192 if (empty($this->error) && empty($this->errors)) {
1193 $this->error =
"Failed to add contract";
1195 dol_syslog(get_class($this).
"::create - 20 - ".$this->error, LOG_ERR);
1196 $this->db->rollback();
1200 $this->error = $langs->trans(
"UnknownError").
": ".$this->db->error();
1201 dol_syslog(get_class($this).
"::create - 10 - ".$this->error, LOG_ERR);
1203 $this->db->rollback();
1215 public function delete($user)
1219 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1226 $result = $this->call_trigger(
'CONTRACT_DELETE', $user);
1236 dol_syslog(get_class($this).
"::delete error", LOG_ERR);
1252 $main = MAIN_DB_PREFIX.
'contratdet';
1253 $ef = $main.
"_extrafields";
1254 $sql =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_contrat = ".((int) $this->
id).
")";
1256 dol_syslog(get_class($this).
"::delete contratdet_extrafields", LOG_DEBUG);
1257 $resql = $this->db->query($sql);
1259 $this->error = $this->db->error();
1266 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"contratdet";
1267 $sql .=
" WHERE fk_contrat=".((int) $this->
id);
1269 dol_syslog(get_class($this).
"::delete contratdet", LOG_DEBUG);
1270 $resql = $this->db->query($sql);
1272 $this->error = $this->db->error();
1290 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"contrat";
1291 $sql .=
" WHERE rowid=".((int) $this->
id);
1293 dol_syslog(get_class($this).
"::delete contrat", LOG_DEBUG);
1294 $resql = $this->db->query($sql);
1296 $this->error = $this->db->error();
1306 dol_syslog(get_class($this).
"::delete error -3 ".$this->error, LOG_ERR);
1313 if ($conf->contrat->dir_output && !empty($ref)) {
1314 $dir = $conf->contrat->multidir_output[$this->entity].
"/".$ref;
1315 if (file_exists($dir)) {
1318 $this->error =
'ErrorFailToDeleteDir';
1326 $this->db->commit();
1329 $this->error = $this->db->lasterror();
1330 $this->db->rollback();
1342 public function update($user, $notrigger = 0)
1348 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1349 $this->fk_commercial_signature = $this->commercial_signature_id;
1351 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1352 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1354 if (empty($this->socid) && $this->fk_soc > 0) {
1355 $this->socid = (int) $this->fk_soc;
1358 if (isset($this->
ref)) {
1359 $this->
ref = trim($this->
ref);
1361 if (isset($this->ref_customer)) {
1362 $this->ref_customer = trim($this->ref_customer);
1364 if (isset($this->ref_supplier)) {
1365 $this->ref_supplier = trim($this->ref_supplier);
1367 if (isset($this->ref_ext)) {
1368 $this->ref_ext = trim($this->ref_ext);
1370 if (isset($this->entity)) {
1371 $this->entity = (int) $this->entity;
1373 if (isset($this->
status)) {
1376 if ((
int) $this->socid > 0) {
1377 $this->socid = (int) $this->socid;
1379 if (isset($this->fk_commercial_signature)) {
1380 $this->fk_commercial_signature = (int) $this->fk_commercial_signature;
1382 if (isset($this->fk_commercial_suivi)) {
1383 $this->fk_commercial_suivi = (int) $this->fk_commercial_suivi;
1385 if (isset($this->note_private)) {
1386 $this->note_private = trim($this->note_private);
1388 if (isset($this->note_public)) {
1389 $this->note_public = trim($this->note_public);
1391 if (isset($this->import_key)) {
1392 $this->import_key = trim($this->import_key);
1395 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
1396 $extraparams =
dol_trunc($extraparams, 250);
1401 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET";
1402 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
1403 $sql .=
" ref_customer=".(isset($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" :
"null").
",";
1404 $sql .=
" ref_supplier=".(isset($this->ref_supplier) ?
"'".$this->db->escape($this->ref_supplier).
"'" :
"null").
",";
1405 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
1406 $sql .=
" entity=".((int) $conf->entity).
",";
1407 $sql .=
" date_contrat=".(dol_strlen($this->date_contrat) != 0 ?
"'".$this->db->idate($this->date_contrat).
"'" :
'null').
",";
1408 $sql .=
" statut=".(isset($this->statut) ? $this->statut : (isset($this->
status) ? $this->
status :
"null")).
",";
1409 $sql .=
" fk_soc=".($this->socid > 0 ? $this->socid :
"null").
",";
1410 $sql .=
" fk_projet=".($this->fk_project > 0 ? $this->fk_project :
"null").
",";
1411 $sql .=
" fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature :
"null").
",";
1412 $sql .=
" fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi :
"null").
",";
1413 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
1414 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
1415 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
1416 $sql .=
" fk_user_modif=".(isset($user->id) ? ((int) $user->id) :
"null").
",";
1417 $sql .=
" extraparams=".(isset($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
1418 $sql .=
" WHERE rowid=".((int) $this->
id);
1422 $resql = $this->db->query($sql);
1425 $this->errors[] =
"Error ".$this->db->lasterror();
1435 if (!$error && !$notrigger) {
1437 $result = $this->call_trigger(
'CONTRACT_MODIFY', $user);
1446 foreach ($this->errors as $errmsg) {
1447 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
1448 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
1450 $this->db->rollback();
1453 if (isset($user->id)) {
1454 $this->fk_user_modif = (int) $user->id;
1456 $this->db->commit();
1485 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type =
'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice =
null, $pa_ht = 0, $array_options = array(), $fk_unit =
null, $rang = 0)
1487 global $user, $langs,
$mysoc;
1490 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");
1493 if ($fk_product <= 0 && empty($desc)) {
1494 $this->error =
"ErrorDescRequiredForFreeProductLines";
1498 if ($this->
status >= 0) {
1507 if (preg_match(
'/\((.*)\)/', (
string) $txtva, $reg)) {
1508 $vat_src_code = $reg[1];
1509 $txtva = preg_replace(
'/\s*\(.*\)/',
'', (
string) $txtva);
1515 $remise_percent =
price2num($remise_percent);
1520 if (empty($info_bits)) {
1523 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1526 if (empty($pu_ttc)) {
1529 if (empty($txtva) || !is_numeric($txtva)) {
1532 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1535 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1539 if ($price_base_type ==
'HT') {
1546 if (empty($remise_percent)) {
1547 $remise_percent = 0;
1553 if ($date_start && $date_end && $date_start > $date_end) {
1554 $langs->load(
"errors");
1555 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
1568 $tabprice =
calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,
$mysoc, $localtaxes_type);
1569 $total_ht = $tabprice[0];
1570 $total_tva = $tabprice[1];
1571 $total_ttc = $tabprice[2];
1572 $total_localtax1 = $tabprice[9];
1573 $total_localtax2 = $tabprice[10];
1575 if (count($localtaxes_type) > 0) {
1576 $localtax1_type = $localtaxes_type[0];
1577 $localtax2_type = $localtaxes_type[2];
1579 $localtax1_type =
"";
1580 $localtax2_type =
"";
1583 if (empty($pa_ht)) {
1590 $result = $this->
defineBuyPrice($pu_ht, $remise_percent, $fk_product);
1599 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"contratdet";
1600 $sql .=
" (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1601 $sql .=
" localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1602 $sql .=
" total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1603 $sql .=
" info_bits,";
1604 $sql .=
" fk_product_fournisseur_price, buy_price_ht";
1605 if ($date_start > 0) {
1606 $sql .=
",date_ouverture_prevue";
1608 if ($date_end > 0) {
1609 $sql .=
",date_fin_validite";
1611 $sql .=
", fk_unit";
1613 $sql .=
") VALUES (";
1614 $sql .= $this->
id.
", '', '".$this->db->escape($desc).
"',";
1615 $sql .= ($fk_product > 0 ? $fk_product :
"null").
",";
1616 $sql .=
" ".((float) $qty).
",";
1617 $sql .=
" ".((float) $txtva).
",";
1618 $sql .=
" ".($vat_src_code ?
"'".$this->db->escape($vat_src_code).
"'" :
"null").
",";
1619 $sql .=
" ".((float) $txlocaltax1).
",";
1620 $sql .=
" ".((float) $txlocaltax2).
",";
1621 $sql .=
" '".$this->db->escape($localtax1_type).
"',";
1622 $sql .=
" '".$this->db->escape($localtax2_type).
"',";
1623 $sql .=
" ".price2num($remise_percent).
",";
1624 $sql .=
" ".price2num($pu_ht).
",";
1626 $sql .=
" ".((int) $info_bits).
",";
1627 if (isset($fk_fournprice)) {
1628 $sql .=
' '.((int) $fk_fournprice).
',';
1632 if (isset($pa_ht)) {
1633 $sql .=
' '.price2num($pa_ht);
1637 if ($date_start > 0) {
1638 $sql .=
",'".$this->db->idate($date_start).
"'";
1640 if ($date_end > 0) {
1641 $sql .=
",'".$this->db->idate($date_end).
"'";
1643 $sql .=
", ".($fk_unit ?
"'".$this->db->escape((
string) $fk_unit).
"'" :
"null");
1644 $sql .=
", ".(!empty($rang) ? (int) $rang :
"0");
1647 $resql = $this->db->query($sql);
1649 $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX.
"contratdet");
1652 $contractline->array_options = $array_options;
1653 $contractline->id = $contractlineid;
1654 $result = $contractline->insertExtraFields();
1660 if (empty($error)) {
1662 $this->context[
'line_id'] = $contractlineid;
1663 $result = $this->call_trigger(
'LINECONTRACT_INSERT', $user);
1671 $this->db->rollback();
1674 $this->db->commit();
1675 return $contractlineid;
1678 $this->db->rollback();
1679 $this->error = $this->db->error().
" sql=".$sql;
1683 dol_syslog(get_class($this).
"::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1712 public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_start_real =
'', $date_end_real =
'', $price_base_type =
'HT', $info_bits = 0, $fk_fournprice =
null, $pa_ht = 0, $array_options = array(), $fk_unit =
null, $rang = 0)
1714 global $user, $langs,
$mysoc;
1717 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
1724 $qty = trim((
string) $qty);
1725 $desc = trim((
string) $desc);
1731 if (empty($fk_fournprice)) {
1738 if ($date_start && $date_end && $date_start > $date_end) {
1739 $langs->load(
"errors");
1740 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
1744 dol_syslog(get_class($this).
"::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_start_real, $date_end_real, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits, $rang");
1754 $tvatx = preg_replace(
'/\s*\(.*\)/',
'', $tvatx);
1756 $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);
1757 $total_ht = $tabprice[0];
1758 $total_tva = $tabprice[1];
1759 $total_ttc = $tabprice[2];
1760 $total_localtax1 = $tabprice[9];
1761 $total_localtax2 = $tabprice[10];
1763 $localtax1_type = (empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0]);
1764 $localtax2_type = (empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2]);
1766 if (empty($pa_ht)) {
1780 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contratdet SET description = '".$this->db->escape($desc).
"'";
1781 $sql .=
",subprice = ".((float)
price2num($subprice));
1782 $sql .=
",remise_percent = ".((float)
price2num($remise_percent));
1783 $sql .=
",qty = ".((float) $qty);
1784 $sql .=
",tva_tx = ".((float)
price2num($tvatx));
1785 $sql .=
",localtax1_tx = ".((float)
price2num($localtax1tx));
1786 $sql .=
",localtax2_tx = ".((float)
price2num($localtax2tx));
1787 $sql .=
",localtax1_type='".$this->db->escape($localtax1_type).
"'";
1788 $sql .=
",localtax2_type='".$this->db->escape($localtax2_type).
"'";
1789 $sql .=
", total_ht = ".((float)
price2num($total_ht));
1790 $sql .=
", total_tva = ".((float)
price2num($total_tva));
1791 $sql .=
", total_localtax1 = ".((float)
price2num($total_localtax1));
1792 $sql .=
", total_localtax2 = ".((float)
price2num($total_localtax2));
1793 $sql .=
", total_ttc = ".((float)
price2num($total_ttc));
1794 $sql .=
", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice :
"null");
1795 $sql .=
", buy_price_ht = ".((float)
price2num($pa_ht));
1796 if ($date_start > 0) {
1797 $sql .=
",date_ouverture_prevue = '".$this->db->idate($date_start).
"'";
1799 $sql .=
",date_ouverture_prevue = null";
1801 if ($date_end > 0) {
1802 $sql .=
",date_fin_validite = '".$this->db->idate($date_end).
"'";
1804 $sql .=
",date_fin_validite = null";
1806 if ($date_start_real > 0) {
1807 $sql .=
",date_ouverture = '".$this->db->idate($date_start_real).
"'";
1809 $sql .=
",date_ouverture = null";
1811 if ($date_end_real > 0) {
1812 $sql .=
",date_cloture = '".$this->db->idate($date_end_real).
"'";
1814 $sql .=
",date_cloture = null";
1816 $sql .=
", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) :
"null");
1817 $sql .=
", rang = ".(!empty($rang) ? ((int) $rang) :
"0");
1818 $sql .=
" WHERE rowid = ".((int) $rowid);
1820 dol_syslog(get_class($this).
"::updateline", LOG_DEBUG);
1821 $result = $this->db->query($sql);
1823 if (is_array($array_options) && count($array_options) > 0) {
1825 $contractline->fetch($rowid);
1828 foreach ($array_options as $key => $value) {
1829 $contractline->array_options[$key] = $array_options[$key];
1832 $result = $contractline->insertExtraFields();
1834 $this->errors[] = $contractline->error;
1840 $sqltoupdatecontract =
"UPDATE ".MAIN_DB_PREFIX.
"contrat";
1841 $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.
")";
1842 $sqltoupdatecontract .=
" WHERE rowid = ".((int) $this->
id);
1843 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
1844 if (!$resqltoupdatecontract) {
1845 $this->error = $this->db->lasterror();
1846 $this->db->rollback();
1850 if (empty($error)) {
1852 $this->context[
'line_id'] = $rowid;
1853 $result = $this->call_trigger(
'LINECONTRACT_MODIFY', $user);
1855 $this->db->rollback();
1860 $this->db->commit();
1863 $this->db->rollback();
1867 $this->db->rollback();
1868 $this->error = $this->db->error();
1869 dol_syslog(get_class($this).
"::updateline Erreur -1");
1885 if ($this->statut >= 0) {
1886 if ($this->
id > 0) {
1889 if ($contractline->fetch($idline) <= 0 || (
int) $contractline->fk_contrat !== (
int) $this->id) {
1890 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
1896 $this->context[
'line_id'] = $idline;
1897 $result = $this->call_trigger(
'LINECONTRACT_DELETE', $user);
1905 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1906 $sql .=
" WHERE rowid = ".((int) $idline);
1908 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
1909 $resql = $this->db->query($sql);
1911 $this->error =
"Error ".$this->db->lasterror();
1918 $contractline->id = $idline;
1919 $result = $contractline->deleteExtraFields();
1922 $this->error =
"Error ".get_class($this).
"::deleteline deleteExtraFields error -4 ".$contractline->error;
1931 $result = $this->
line_order(
true,
'ASC',
false);
1934 $this->error =
"Error ".get_class($this).
"::deleteline line_order error";
1938 if (empty($error)) {
1939 $this->db->commit();
1942 dol_syslog(get_class($this).
"::deleteline ERROR:".$this->error, LOG_ERR);
1943 $this->db->rollback();
1947 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
1964 dol_syslog(__METHOD__.
" is deprecated", LOG_WARNING);
1967 if ($this->statut == 0) {
1992 return $this->
LibStatut($this->statut, $mode);
2008 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2010 $langs->load(
"contracts");
2011 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv(
'ContractStatusDraft');
2012 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv(
'ContractStatusValidated');
2013 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv(
'ContractStatusClosed');
2014 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv(
'ContractStatusDraft');
2015 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv(
'ContractStatusValidated');
2016 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv(
'ContractStatusClosed');
2019 $statusType =
'status'.$status;
2020 if ($status == self::STATUS_VALIDATED) {
2021 $statusType =
'status6';
2024 if ($mode == 4 || $mode == 6 || $mode == 7) {
2027 $text =
'<span class="hideonsmartphone">';
2028 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2029 $text .=
' '.$langs->trans(
"Services");
2030 $text .=
': ';
2033 $text .= ($mode == 7 ?
'<span class="nowraponall">' :
'');
2034 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2035 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2036 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2037 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2038 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2039 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2040 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1,
'class="marginleft2"')) :
'';
2041 $text .= ($mode == 7 ?
'</span>' :
'');
2043 $text .= is_null($this->signed_status) ?
'' :
' '.$this->getLibSignedStatus(5);
2047 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
2059 global $conf, $langs, $user;
2061 $langs->load(
'contracts');
2064 $nofetch = !empty($params[
'nofetch']);
2067 return [
'optimize' => $langs->trans(
"ShowContract")];
2069 if ($user->hasRight(
'contrat',
'lire')) {
2070 $datas[
'picto'] =
img_picto(
'', $this->picto).
' <u class="paddingrightonly">'.$langs->trans(
"Contract").
'</u>';
2075 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.($this->
ref ? $this->
ref : $this->id);
2077 $langs->load(
'companies');
2078 if (empty($this->thirdparty)) {
2081 $datas[
'customer'] =
'<br><b>'.$langs->trans(
'Customer').
':</b> '.$this->thirdparty->getNomUrl(1,
'', 0, 1);
2083 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '. $this->ref_customer;
2085 $langs->load(
'project');
2086 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2088 if ($res > 0 && $this->project instanceof
Project) {
2089 $datas[
'project'] =
'<br><b>'.$langs->trans(
'Project').
':</b> '.$this->project->getNomUrl(1,
'', 0,
'1');
2093 $datas[
'refsupplier'] =
'<br><b>'.$langs->trans(
'RefSupplier').
':</b> '.$this->ref_supplier;
2094 if (!empty($this->total_ht)) {
2095 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2097 if (!empty($this->total_tva)) {
2098 $datas[
'vatamount'] =
'<br><b>'.$langs->trans(
'VAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2100 if (!empty($this->total_ttc)) {
2101 $datas[
'amounttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2116 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2118 global $langs, $user, $hookmanager;
2122 $baseurl = DOL_URL_ROOT .
'/contrat/card.php';
2123 $query = [
'id' => $this->id];
2128 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2129 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2130 $add_save_lastsearch_values = 1;
2132 if ($add_save_lastsearch_values) {
2133 $query = array_merge($query, [
'save_lastsearch_values' => 1]);
2139 'objecttype' => $this->element,
2142 $classfortooltip =
'classfortooltip';
2145 $classfortooltip =
'classforajaxtooltip';
2146 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2153 if (empty($notooltip) && $user->hasRight(
'contrat',
'lire')) {
2155 $label = $langs->trans(
"ShowContract");
2156 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2158 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2159 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2161 $linkstart =
'<a href="'.$url.
'"';
2162 $linkstart .= $linkclose.
'>';
2165 $result .= $linkstart;
2167 $result .=
img_object(($notooltip ?
'' : $label), ($this->picto ? $this->picto :
'generic'), (($withpicto != 2) ?
'class="paddingright"' :
''), 0, 0, $notooltip ? 0 : 1);
2169 if ($withpicto != 2) {
2170 $result .= ($this->
ref ? $this->
ref : $this->id);
2172 $result .= $linkend;
2175 $hookmanager->initHooks(array(
'contractdao'));
2176 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
2177 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2179 $result = $hookmanager->resPrint;
2181 $result .= $hookmanager->resPrint;
2195 $sql =
"SELECT c.rowid, c.ref, c.datec,";
2196 $sql .=
" c.tms as date_modification,";
2197 $sql .=
" fk_user_author";
2198 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2199 $sql .=
" WHERE c.rowid = ".((int) $id);
2201 $result = $this->db->query($sql);
2203 if ($this->db->num_rows($result)) {
2204 $obj = $this->db->fetch_object($result);
2206 $this->
id = $obj->rowid;
2207 $this->
ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2209 $this->user_creation_id = $obj->fk_user_author;
2210 $this->date_creation = $this->db->jdate($obj->datec);
2211 $this->date_modification = $this->db->jdate($obj->date_modification);
2214 $this->db->free($result);
2232 $sql =
"SELECT cd.rowid";
2233 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contratdet as cd";
2234 $sql .=
" WHERE fk_contrat =".((int) $this->
id);
2236 $sql .=
" AND statut = ".((int) $status);
2239 dol_syslog(get_class($this).
"::array_detail()", LOG_DEBUG);
2240 $resql = $this->db->query($sql);
2242 $num = $this->db->num_rows($resql);
2245 $obj = $this->db->fetch_object($resql);
2246 $tab[$i] = $obj->rowid;
2251 $this->error = $this->db->error();
2265 public function getListOfContracts($option =
'all', $status = [], $product_categories = [], $line_status = [])
2269 $sql =
"SELECT c.rowid";
2270 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2271 if (!empty($product_categories) || !empty($line_status)) {
2272 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"contratdet as cd ON cd.fk_contrat = c.rowid";
2274 if (!empty($product_categories)) {
2275 $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)).
")";
2277 $sql .=
" WHERE c.fk_soc =".((int) $this->socid);
2278 $sql .= ($option ==
'others') ?
" AND c.rowid <> ".((
int) $this->id) :
"";
2279 $sql .= (!empty($status)) ?
" AND c.statut IN (".$this->db->sanitize(implode(
', ', $status)).
")" :
"";
2280 $sql .= (!empty($line_status)) ?
" AND cd.statut IN (".$this->db->sanitize(implode(
', ', $line_status)).
")" :
"";
2281 $sql .=
" GROUP BY c.rowid";
2283 dol_syslog(get_class($this).
"::getOtherContracts()", LOG_DEBUG);
2284 $resql = $this->db->query($sql);
2286 $num = $this->db->num_rows($resql);
2289 $obj = $this->db->fetch_object($resql);
2290 $contrat =
new Contrat($this->db);
2291 $contrat->fetch($obj->rowid);
2292 $tab[$contrat->id] = $contrat;
2297 $this->error = $this->db->lasterror();
2314 global $conf, $langs;
2316 $this->from =
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2317 $this->from .=
", ".MAIN_DB_PREFIX.
"contratdet as cd";
2318 $this->from .=
", ".MAIN_DB_PREFIX.
"societe as s";
2319 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2320 $this->from .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
2323 if ($mode ==
'inactive') {
2324 $sql =
"SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2325 $sql .= $this->from;
2326 $sql .=
" WHERE c.statut = 1";
2327 $sql .=
" AND c.rowid = cd.fk_contrat";
2328 $sql .=
" AND cd.statut = 0";
2329 } elseif ($mode ==
'expired') {
2330 $sql =
"SELECT cd.rowid, cd.date_fin_validite as datefin";
2331 $sql .= $this->from;
2332 $sql .=
" WHERE c.statut = 1";
2333 $sql .=
" AND c.rowid = cd.fk_contrat";
2334 $sql .=
" AND cd.statut = 4";
2335 $sql .=
" AND cd.date_fin_validite < '".$this->db->idate(
dol_now()).
"'";
2336 } elseif ($mode ==
'active') {
2337 $sql =
"SELECT cd.rowid, cd.date_fin_validite as datefin";
2338 $sql .= $this->from;
2339 $sql .=
" WHERE c.statut = 1";
2340 $sql .=
" AND c.rowid = cd.fk_contrat";
2341 $sql .=
" AND cd.statut = 4";
2347 $sql .=
" AND c.fk_soc = s.rowid";
2348 $sql .=
" AND c.entity = ".((int) $conf->entity);
2350 $sql .=
" AND c.fk_soc = ".((int) $user->socid);
2352 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2353 $sql .=
" AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2356 $resql = $this->db->query($sql);
2358 $langs->load(
"contracts");
2361 if ($mode ==
'inactive') {
2362 $warning_delay = $conf->contract->services->inactifs->warning_delay;
2363 $label = $langs->trans(
"BoardNotActivatedServices");
2364 $labelShort = $langs->trans(
"BoardNotActivatedServicesShort");
2365 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2366 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2367 } elseif ($mode ==
'expired') {
2368 $warning_delay = $conf->contract->services->expires->warning_delay;
2369 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2370 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2371 $label = $langs->trans(
"BoardExpiredServices");
2372 $labelShort = $langs->trans(
"BoardExpiredServicesShort");
2374 $warning_delay = $conf->contract->services->expires->warning_delay;
2375 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2376 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2377 $label = $langs->trans(
"BoardRunningServices");
2378 $labelShort = $langs->trans(
"BoardRunningServicesShort");
2382 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2383 $response->label = $label;
2384 $response->labelShort = $labelShort;
2385 $response->url = $url;
2386 $response->url_late = $url_late;
2389 while ($obj = $this->db->fetch_object($resql)) {
2390 $response->nbtodo++;
2392 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2393 $response->nbtodolate++;
2400 $this->error = $this->db->error();
2412 global $conf, $user;
2414 $this->nb = array();
2417 $sql =
"SELECT count(c.rowid) as nb";
2418 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2419 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON c.fk_soc = s.rowid";
2420 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2421 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2422 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
2425 $sql .=
" ".$clause.
" c.entity = ".$conf->entity;
2427 $resql = $this->db->query($sql);
2429 while ($obj = $this->db->fetch_object($resql)) {
2430 $this->nb[
"contracts"] = $obj->nb;
2432 $this->db->free($resql);
2436 $this->error = $this->db->error();
2474 global $user, $langs, $conf;
2479 $sql =
"SELECT rowid";
2480 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
2481 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
2482 $sql .=
" AND tosell = 1";
2483 $sql .= $this->db->plimit(100);
2485 $resql = $this->db->query($sql);
2487 $num_prods = $this->db->num_rows($resql);
2489 while ($i < $num_prods) {
2491 $row = $this->db->fetch_row($resql);
2492 $prodids[$i] = $row[0];
2498 $this->specimen = 1;
2500 $this->
ref =
'SPECIMEN';
2501 $this->ref_customer =
'SPECIMENCUST';
2502 $this->ref_supplier =
'SPECIMENSUPP';
2505 $this->date_creation = (
dol_now() - 3600 * 24 * 7);
2506 $this->date_contrat =
dol_now();
2507 $this->commercial_signature_id = 1;
2508 $this->commercial_suivi_id = 1;
2509 $this->note_private =
'This is a comment (private)';
2510 $this->note_public =
'This is a comment (public)';
2511 $this->fk_project = 0;
2515 while ($xnbp < $nbp) {
2518 $line->subprice = 100;
2519 $line->tva_tx = 19.6;
2520 $line->remise_percent = 10;
2521 $line->total_ht = 90;
2522 $line->total_ttc = 107.64;
2523 $line->total_tva = 17.64;
2524 $line->date_start =
dol_now() - 500000;
2525 $line->date_start_real =
dol_now() - 200000;
2526 $line->date_end =
dol_now() + 500000;
2527 $line->date_end_real =
dol_now() - 100000;
2528 if ($num_prods > 0) {
2529 $prodid = mt_rand(1, $num_prods);
2530 $line->fk_product = $prodids[$prodid];
2532 $this->lines[$xnbp] = $line;
2558 $ticket =
new Ticket($this->db);
2559 $nbTicket = $ticket->fetchAll($user,
'ASC',
't.datec', 0, 0, 0, array(
't.fk_contract' => $this->
id));
2561 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2576 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
2578 global $conf, $langs;
2583 if (!empty($this->model_pdf)) {
2584 $modele = $this->model_pdf;
2590 if (empty($modele)) {
2593 $langs->load(
"contracts");
2594 $outputlangs->load(
"products");
2596 $modelpath =
"core/modules/contract/doc/";
2597 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2643 public function createFromClone(
User $user, $socid = 0, $notrigger = 0)
2645 global $db, $langs, $conf, $hookmanager, $extrafields;
2651 $this->
fetch($this->
id);
2654 $clonedObj = clone $this;
2655 $clonedObj->socid = $socid;
2659 $objsoc =
new Societe($this->db);
2661 $objsoc->fetch($clonedObj->socid);
2664 $clonedObj->statut = 0;
2665 $clonedObj->status = 0;
2667 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2668 $extrafields->fetch_name_optionals_label($this->table_element);
2669 foreach ($clonedObj->array_options as $key => $option) {
2670 $shortkey = preg_replace(
'/options_/',
'', $key);
2672 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
2674 unset($clonedObj->array_options[$key]);
2680 $this->error =
'ErrorSetupNotComplete';
2686 require_once DOL_DOCUMENT_ROOT.
"/core/modules/contract/" .
getDolGlobalString(
'CONTRACT_ADDON').
'.php';
2688 $modContract =
new $obj();
2689 '@phan-var-force ModelNumRefContracts $modContract';
2691 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2694 foreach ($this->lines as $line) {
2695 $line->fetch_optionals($line->id);
2699 $clonedObj->context[
'createfromclone'] =
'createfromclone';
2700 $result = $clonedObj->create($user);
2706 if ($this->socid == $clonedObj->socid) {
2707 if ($clonedObj->copy_linked_contact($this,
'external') < 0) {
2714 foreach ($this->lines as $line) {
2715 $result = $clonedObj->addline($line->description, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_start, $line->date_cloture,
'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit, $line->rang);
2725 if (is_object($hookmanager)) {
2726 $parameters = array(
2728 'clonedObj' => $clonedObj
2731 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $clonedObj, $action);
2739 unset($clonedObj->context[
'createfromclone']);
2743 $this->db->commit();
2744 return $clonedObj->id;
2746 $this->db->rollback();
2763 global $langs, $user;
2765 $langs->load(
"agenda");
2775 $contractlineprocessed = array();
2776 $contractignored = array();
2777 $contracterror = array();
2781 $sql =
'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2782 $sql .=
' FROM '.MAIN_DB_PREFIX.
'contrat as c, '.MAIN_DB_PREFIX.
'contratdet as cd';
2783 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON p.rowid = cd.fk_product';
2784 $sql .=
' WHERE cd.fk_contrat = c.rowid';
2785 $sql .=
" AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan).
"', '%Y-%m-%d')";
2786 $sql .=
" AND cd.statut = 4";
2787 if ($thirdparty_id > 0) {
2788 $sql .=
" AND c.fk_soc = ".((int) $thirdparty_id);
2792 $resql = $this->db->query($sql);
2794 $num = $this->db->num_rows($resql);
2796 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2797 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
2801 $obj = $this->db->fetch_object($resql);
2803 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2813 $this->errors[] =
'Failed to load contract with id='.$obj->rowid;
2817 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);
2820 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2821 $duration_value = preg_replace(
'/[^0-9]/',
'', $obj->duration);
2822 $duration_unit = preg_replace(
'/\d/',
'', $obj->duration);
2827 $object->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 1);
2830 if (isset(
$object->linkedObjects[
'facture']) && is_array(
$object->linkedObjects[
'facture']) && count(
$object->linkedObjects[
'facture']) > 0) {
2832 usort(
$object->linkedObjects[
'facture'], array(
'Contrat',
'contractCmpDate'));
2835 $someinvoicenotpaid = 0;
2836 foreach (
$object->linkedObjects[
'facture'] as $idinvoice => $invoice) {
2841 if (empty($invoice->paye)) {
2842 $someinvoicenotpaid++;
2845 if ($someinvoicenotpaid) {
2846 $this->output .=
'Contract '.$object->ref.
' is qualified for renewal but there is '.$someinvoicenotpaid.
' invoice(s) unpayed so we cancel renewal'.
"\n";
2852 if ($expirationdate && $expirationdate < $enddatetoscan) {
2853 dol_syslog(
"Define the newdate of end of services from expirationdate=".$expirationdate);
2854 $newdate = $expirationdate;
2856 while ($newdate < $enddatetoscan && $protecti < 1000) {
2861 if ($protecti < 1000) {
2867 $errorforlocaltransaction = 0;
2869 $label =
'Renewal of contrat '.$object->ref.
' line '.$obj->lid;
2870 $comment =
'Renew date of contract '.$object->ref.
' line '.$obj->lid.
' by doAutoRenewContracts';
2872 $sqlupdate =
'UPDATE '.MAIN_DB_PREFIX.
"contratdet SET date_fin_validite = '".$this->db->idate($newdate).
"'";
2873 $sqlupdate .=
' WHERE rowid = '.((int) $obj->lid);
2874 $resqlupdate = $this->db->query($sqlupdate);
2876 $contractlineprocessed[$obj->lid] =
$object->ref;
2879 $sqltoupdatecontract =
"UPDATE ".MAIN_DB_PREFIX.
"contrat";
2880 $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.
")";
2881 $sqltoupdatecontract .=
" WHERE rowid = ".((int)
$object->id);
2882 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
2883 if (!$resqltoupdatecontract) {
2884 $this->error = $this->db->lasterror();
2885 $this->db->rollback();
2889 $actioncode =
'RENEW_CONTRACT';
2894 $actioncomm->type_code =
'AC_OTH_AUTO';
2895 $actioncomm->code =
'AC_'.$actioncode;
2896 $actioncomm->label = $label;
2897 $actioncomm->datep = $now;
2898 $actioncomm->datef = $now;
2899 $actioncomm->percentage = -1;
2900 $actioncomm->socid =
$object->socid;
2901 $actioncomm->authorid = $user->id;
2902 $actioncomm->userownerid = $user->id;
2903 $actioncomm->fk_element =
$object->id;
2904 $actioncomm->elementid =
$object->id;
2905 $actioncomm->elementtype =
'contract';
2906 $actioncomm->note_private = $comment;
2908 $ret = $actioncomm->create($user);
2913 $errorforlocaltransaction++;
2914 $this->error = $this->db->lasterror();
2917 if (! $errorforlocaltransaction) {
2918 $this->db->commit();
2920 $this->db->rollback();
2924 $this->error =
"Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate.
" enddatetoscan=".$enddatetoscan.
" duration_value=".$duration_value.
" duration_unit=".$duration_value;
2933 $this->error = $this->db->lasterror();
2936 $this->output .= count($contractlineprocessed).
' contract line(s) with end date before '.
dol_print_date($enddatetoscan,
'day').
' were renewed'.(count($contractlineprocessed) > 0 ?
' : '.implode(
',', $contractlineprocessed) :
'');
2938 return ($error ? 1 : 0);
2950 if ($a->date == $b->date) {
2951 return strcmp((
string) $a->id, (
string) $b->id);
2953 return ($a->date < $b->date) ? -1 : 1;
2967 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
2969 $return =
'<div class="box-flex-item box-flex-grow-zero">';
2970 $return .=
'<div class="info-box info-box-sm">';
2971 $return .=
'<span class="info-box-icon bg-infobox-action">';
2973 $return .=
'</span>';
2974 $return .=
'<div class="info-box-content">';
2975 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->
getNomUrl() .
'</span>';
2976 if ($selected >= 0) {
2977 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
2979 if (!empty($arraydata[
'thirdparty']) && $arraydata[
'thirdparty'] instanceof
Societe) {
2980 $tmpthirdparty = $arraydata[
'thirdparty'];
2981 '@phan-var-force Societe $tmpthirdparty';
2982 $return .=
'<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).
'</div>';
2984 $return .=
'<br><span class="opacitymedium valignmiddle">'.$langs->trans(
"DateContract").
' : </span><span class="info-box-label valignmiddle">'.
dol_print_date($this->date_contrat,
'day').
'</span>';
2985 $return .=
'<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).
'</div>';
2986 $return .=
'</div>';
2987 $return .=
'</div>';
2988 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
Class to manage agenda events (actions)
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
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.
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.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
loadStateBoard()
Load the indicators this->nb for state board.
update_statut($user)
Update statut of contract according to services.
closeAll(User $user, $notrigger=0, $comment='', $nofetchlines=0)
Close all lines of a contract.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_start_real='', $date_end_real='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Update a contract line.
getTicketsArray()
Create an array of associated tickets.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
deleteLine($idline, User $user)
Delete a contract line.
array_detail($status=-1)
Return list of line rowid.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Ajoute une ligne de contrat en base.
update($user, $notrigger=0)
Update object into database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
__construct($db)
Constructor.
doAutoRenewContracts($thirdparty_id=0, $delayindaysshort=0)
Action executed by scheduler CAN BE A CRON TASK Loop on each contract lines and update the end of dat...
getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
info($id)
Charge les information d'ordre info dans l'objet contrat.
getLibStatut($mode)
Return label of a contract status.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetch_lines($only_services=0, $loadalsotranslation=0, $noextrafields=0)
Load lines array into this->lines.
getIdServiceContact()
Return id des contacts clients de prestation.
Class to manage lines of contracts.
Class to manage Dolibarr database access.
const STATUS_DRAFT
Draft status.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
setSignedStatusCommon(User $user, int $status, int $notrigger=0, string $triggercode='')
Set signed status & call trigger with context message.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
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.
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.