38require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobject.class.php';
39require_once DOL_DOCUMENT_ROOT.
'/contrat/class/contratligne.class.php';
40require_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
41require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
42require_once DOL_DOCUMENT_ROOT.
'/core/class/commonsignedobject.class.php';
52 use CommonSignedObject;
57 public $element =
'contrat';
62 public $table_element =
'contrat';
67 public $table_element_line =
'contratdet';
72 public $fk_element =
'fk_contrat';
77 public $picto =
'contract';
83 public $restrictiononfksoc = 1;
105 public $ref_supplier;
146 public $fk_user_author;
153 public $user_author_id;
160 public $user_creation;
165 public $user_cloture;
170 public $date_contrat;
175 public $commercial_signature_id;
181 public $fk_commercial_signature;
186 public $commercial_suivi_id;
193 public $fk_commercial_suivi;
198 public $extraparams = array();
203 public $lines = array();
208 public $nbofservices;
212 public $nbofserviceswait;
216 public $nbofservicesopened;
220 public $nbofservicesexpired;
224 public $nbofservicesclosed;
232 protected $lines_id_index_mapper = array();
263 public $fields = array(
264 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 10),
265 'ref' => array(
'type' =>
'varchar(50)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => -1,
'showoncombobox' => 1,
'position' => 15,
'searchall' => 1),
266 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 20),
267 'ref_customer' => array(
'type' =>
'varchar(50)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 25,
'searchall' => 1),
268 'ref_supplier' => array(
'type' =>
'varchar(50)',
'label' =>
'RefSupplier',
'enabled' => 1,
'visible' => -1,
'position' => 26,
'searchall' => 1),
269 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 30,
'index' => 1),
270 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 35),
271 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 40),
272 'date_contrat' => array(
'type' =>
'datetime',
'label' =>
'Date contrat',
'enabled' => 1,
'visible' => -1,
'position' => 45),
273 'signed_status' => array(
'type' =>
'smallint(6)',
'label' =>
'SignedStatus',
'enabled' => 1,
'visible' => -1,
'position' => 50,
'arrayofkeyval' => array(0 =>
'NoSignature', 1 =>
'SignedSender', 2 =>
'SignedReceiver', 3 =>
'SignedReceiverOnline', 9 =>
'SignedAll')),
274 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' =>
'isModEnabled("societe")',
'visible' => -1,
'notnull' => 1,
'position' => 70),
275 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' =>
"isModEnabled('project')",
'visible' => -1,
'position' => 75),
276 'fk_commercial_signature' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'SaleRepresentative Signature',
'enabled' => 1,
'visible' => -1,
'position' => 80),
277 'fk_commercial_suivi' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'SaleRepresentative follower',
'enabled' => 1,
'visible' => -1,
'position' => 85),
278 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 90),
279 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 105,
'searchall' => 1),
280 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 110,
'searchall' => 1),
281 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 115),
282 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 120),
283 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 125),
284 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'enabled' => 1,
'visible' => -2,
'notnull' => -1,
'position' => 135),
285 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'Last main doc',
'enabled' => 1,
'visible' => -1,
'position' => 140),
286 'statut' => array(
'type' =>
'smallint(6)',
'label' =>
'Statut',
'enabled' => 1,
'visible' => -1,
'position' => 500,
'notnull' => 1,
'arrayofkeyval' => array(0 =>
'Draft', 1 =>
'Validated', 2 =>
'Closed'))
290 const STATUS_DRAFT = 0;
291 const STATUS_VALIDATED = 1;
292 const STATUS_CLOSED = 2;
303 $this->ismultientitymanaged = 1;
304 $this->isextrafieldmanaged = 1;
313 public function getNextNumRef($soc)
315 global $db, $langs,
$conf;
316 $langs->load(
"contracts");
325 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
327 foreach ($dirmodels as $reldir) {
331 $mybool = ((bool) @include_once $dir.$file) || $mybool;
339 $obj =
new $classname();
340 '@phan-var-force ModelNumRefContracts $obj';
342 $numref = $obj->getNextValue($soc, $this);
347 $this->error = $obj->error;
352 $langs->load(
"errors");
353 print $langs->trans(
"Error").
" ".$langs->trans(
"ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv(
"Contract"));
372 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user,
$date_start, $date_end, $comment);
374 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
375 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
391 public function close_line($user, $line_id, $date_end, $comment =
'')
394 $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
396 $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
397 $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
427 foreach ($this->lines as $contratline) {
429 if ($contratline->statut != ContratLigne::STATUS_OPEN) {
430 $contratline->context = $this->context;
432 $result = $contratline->active_line($user,
$date_start, !empty($date_end) ? $date_end : -1, $comment);
441 if (!$error && $this->statut == 0) {
442 $result = $this->
validate($user,
'', $notrigger);
452 $this->db->rollback();
467 public function closeAll(
User $user, $notrigger = 0, $comment =
'', $nofetchlines = 0)
474 if (empty($nofetchlines)) {
482 foreach ($this->lines as $contratline) {
484 if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
485 $contratline->date_end_real = $now;
486 $contratline->date_cloture = $now;
487 $contratline->user_closing_id = $user->id;
488 $contratline->statut = ContratLigne::STATUS_CLOSED;
490 $result = $contratline->close_line($user, $now, $comment, $notrigger);
494 $this->error = $contratline->error.($contratline->error ?
' ('.$this->ref.
')' :
'');
495 $this->errors = $contratline->errors;
501 if (!$error && $this->
status == 0) {
502 $result = $this->
validate($user,
'', $notrigger);
515 $this->db->rollback();
531 public function validate(
User $user, $force_number =
'', $notrigger = 0)
533 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
539 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number);
547 if (!
getDolGlobalString(
'CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION') && $this->thirdparty->fournisseur == 0) {
548 $result = $this->thirdparty->setAsCustomer();
553 $num = $force_number;
554 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
555 $num = $this->getNextNumRef($this->thirdparty);
562 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET ref = '".$this->db->escape($num).
"', statut = 1";
563 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND statut = 0";
565 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
566 $resql = $this->db->query($sql);
570 $this->error = $this->db->lasterror();
574 if (!$error && !$notrigger) {
576 $result = $this->call_trigger(
'CONTRACT_VALIDATE', $user);
584 $this->oldref = $this->ref;
587 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
589 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files SET filename = CONCAT('".$this->db->escape($this->newref).
"', SUBSTR(filename, ".(strlen($this->
ref) + 1).
")), filepath = 'contract/".$this->db->escape($this->newref).
"'";
590 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'contract/".$this->db->escape($this->
ref).
"' and entity = ".((int)
$conf->entity);
591 $resql = $this->db->query($sql);
594 $this->error = $this->db->lasterror();
596 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files SET filepath = 'contract/".$this->db->escape($this->newref).
"'";
597 $sql .=
" WHERE filepath = 'contract/".$this->db->escape($this->
ref).
"' and entity = ".((int)
$conf->entity);
598 $resql = $this->db->query($sql);
601 $this->error = $this->db->lasterror();
607 $dirsource =
$conf->contract->dir_output.
'/'.$oldref;
608 $dirdest =
$conf->contract->dir_output.
'/'.$newref;
609 if (!$error && file_exists($dirsource)) {
610 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
612 if (@rename($dirsource, $dirdest)) {
615 $listoffiles =
dol_dir_list(
$conf->contract->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
616 foreach ($listoffiles as $fileentry) {
617 $dirsource = $fileentry[
'name'];
618 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
619 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
620 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
621 @rename($dirsource, $dirdest);
631 $this->
status = self::STATUS_VALIDATED;
632 $this->statut = self::STATUS_VALIDATED;
633 $this->date_validation = $now;
643 $this->db->rollback();
655 public function reopen($user, $notrigger = 0)
657 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
662 dol_syslog(get_class($this).
'::reopen user='.$user->id);
668 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET statut = 0";
670 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND statut = 1";
672 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
673 $resql = $this->db->query($sql);
677 $this->error = $this->db->lasterror();
681 if (!$error && !$notrigger) {
683 $result = $this->call_trigger(
'CONTRACT_REOPEN', $user);
692 $this->statut = self::STATUS_DRAFT;
693 $this->
status = self::STATUS_DRAFT;
694 $this->date_validation = $now;
701 $this->db->rollback();
717 public function fetch($id, $ref =
'', $ref_customer =
'', $ref_supplier =
'', $noextrafields = 0, $nolines = 0)
721 $sql =
"SELECT rowid, statut as status, ref, fk_soc as thirdpartyid,";
722 $sql .=
" ref_supplier, ref_customer,";
725 $sql .=
" signed_status,";
726 $sql .=
" date_contrat as datecontrat,";
727 $sql .=
" fk_user_author,";
728 $sql .=
" fk_projet as fk_project,";
729 $sql .=
" fk_commercial_signature, fk_commercial_suivi,";
730 $sql .=
" note_private, note_public, model_pdf, last_main_doc, extraparams";
731 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat";
733 $sql .=
" WHERE entity IN (".getEntity(
'contract').
")";
735 $sql .=
" WHERE rowid = ".(int) $id;
738 $sql .=
" AND ref_customer = '".$this->db->escape($ref_customer).
"'";
741 $sql .=
" AND ref_supplier = '".$this->db->escape($ref_supplier).
"'";
744 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
747 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
749 $resql = $this->db->query($sql);
751 $num = $this->db->num_rows($resql);
753 $this->error =
'Fetch found several records.';
758 $obj = $this->db->fetch_object($resql);
760 $this->
id = $obj->rowid;
761 $this->
ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
762 $this->ref_customer = $obj->ref_customer;
763 $this->ref_supplier = $obj->ref_supplier;
764 $this->ref_ext = $obj->ref_ext;
765 $this->entity = $obj->entity;
766 $this->statut = $obj->status;
767 $this->
status = $obj->status;
768 $this->signed_status = $obj->signed_status;
770 $this->date_contrat = $this->db->jdate($obj->datecontrat);
771 $this->date_creation = $this->db->jdate($obj->datecontrat);
773 $this->user_author_id = $obj->fk_user_author;
775 $this->commercial_signature_id = $obj->fk_commercial_signature;
776 $this->commercial_suivi_id = $obj->fk_commercial_suivi;
778 $this->note_private = $obj->note_private;
779 $this->note_public = $obj->note_public;
780 $this->model_pdf = $obj->model_pdf;
782 $this->fk_projet = $obj->fk_project;
783 $this->fk_project = $obj->fk_project;
785 $this->socid = $obj->thirdpartyid;
786 $this->fk_soc = $obj->thirdpartyid;
787 $this->last_main_doc = $obj->last_main_doc;
788 $this->extraparams = (isset($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) :
null);
790 $this->db->free($resql);
794 if (empty($noextrafields)) {
797 $this->error = $this->db->lasterror();
803 if (empty($nolines)) {
804 if ($result >= 0 && !empty($this->table_element_line)) {
807 $this->error = $this->db->lasterror();
815 dol_syslog(get_class($this).
"::fetch Contract failed");
816 $this->error =
"Fetch contract failed";
820 dol_syslog(get_class($this).
"::fetch Contract not found");
821 $this->error =
"Contract not found";
825 dol_syslog(get_class($this).
"::fetch Error searching contract");
826 $this->error = $this->db->error();
841 public function fetch_lines($only_services = 0, $loadalsotranslation = 0, $noextrafields = 0)
844 $this->nbofservices = 0;
845 $this->nbofserviceswait = 0;
846 $this->nbofservicesopened = 0;
847 $this->nbofservicesexpired = 0;
848 $this->nbofservicesclosed = 0;
856 $this->lines = array();
860 $sql =
"SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
861 $sql .=
" d.rowid, d.fk_contrat, d.statut as status, d.description, d.subprice, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
862 $sql .=
" d.total_ht,";
863 $sql .=
" d.total_tva,";
864 $sql .=
" d.total_localtax1,";
865 $sql .=
" d.total_localtax2,";
866 $sql .=
" d.total_ttc,";
867 $sql .=
" d.info_bits, d.fk_product,";
868 $sql .=
" d.date_ouverture_prevue as date_start,";
869 $sql .=
" d.date_ouverture as date_start_real,";
870 $sql .=
" d.date_fin_validite as date_end,";
871 $sql .=
" d.date_cloture as date_end_real,";
872 $sql .=
" d.fk_user_author,";
873 $sql .=
" d.fk_user_ouverture,";
874 $sql .=
" d.fk_user_cloture,";
875 $sql .=
" d.fk_unit,";
876 $sql .=
" d.extraparams,";
877 $sql .=
" d.product_type as type,";
879 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contratdet as d LEFT JOIN ".MAIN_DB_PREFIX.
"product as p ON d.fk_product = p.rowid";
880 $sql .=
" WHERE d.fk_contrat = ".((int) $this->
id);
881 if ($only_services == 1) {
882 $sql .=
" AND d.product_type = 1";
884 $sql .=
" ORDER by d.rang ASC";
886 dol_syslog(get_class($this).
"::fetch_lines", LOG_DEBUG);
887 $result = $this->db->query($sql);
889 $num = $this->db->num_rows($result);
893 $objp = $this->db->fetch_object($result);
897 $line->id = $objp->rowid;
898 $line->ref = $objp->rowid;
899 $line->fk_contrat = $objp->fk_contrat;
900 $line->desc = $objp->description;
901 $line->qty = $objp->qty;
902 $line->vat_src_code = $objp->vat_src_code;
903 $line->tva_tx = $objp->tva_tx;
904 $line->localtax1_tx = $objp->localtax1_tx;
905 $line->localtax2_tx = $objp->localtax2_tx;
906 $line->localtax1_type = $objp->localtax1_type;
907 $line->localtax2_type = $objp->localtax2_type;
908 $line->subprice = $objp->subprice;
909 $line->statut = $objp->status;
910 $line->status = $objp->status;
911 $line->remise_percent = $objp->remise_percent;
912 $line->total_ht = $objp->total_ht;
913 $line->total_tva = $objp->total_tva;
914 $line->total_localtax1 = $objp->total_localtax1;
915 $line->total_localtax2 = $objp->total_localtax2;
916 $line->total_ttc = $objp->total_ttc;
917 $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
918 $line->info_bits = $objp->info_bits;
919 $line->type = $objp->type;
921 $line->fk_fournprice = $objp->fk_fournprice;
922 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_fournprice, $objp->pa_ht);
923 $line->pa_ht = $marginInfos[0];
925 $line->fk_user_author = $objp->fk_user_author;
926 $line->fk_user_ouverture = $objp->fk_user_ouverture;
927 $line->fk_user_cloture = $objp->fk_user_cloture;
928 $line->fk_unit = $objp->fk_unit;
930 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
932 $line->ref = $objp->product_ref;
933 $line->product_ref = $objp->product_ref;
934 $line->product_type = $objp->product_type;
935 $line->product_desc = $objp->product_desc;
936 $line->product_label = $objp->product_label;
938 $line->description = $objp->description;
940 $line->date_start = $this->db->jdate($objp->date_start);
941 $line->date_start_real = $this->db->jdate($objp->date_start_real);
942 $line->date_end = $this->db->jdate($objp->date_end);
943 $line->date_end_real = $this->db->jdate($objp->date_end_real);
954 $line->rang = $objp->rang;
958 if (empty($noextrafields)) {
959 $line->fetch_optionals();
963 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
964 $tmpproduct =
new Product($this->db);
965 $tmpproduct->fetch($objp->fk_product);
966 $tmpproduct->getMultiLangs();
968 $line->multilangs = $tmpproduct->multilangs;
971 $this->lines[$pos] = $line;
973 $this->lines_id_index_mapper[$line->id] = $pos;
978 if ($line->statut == ContratLigne::STATUS_INITIAL) {
979 $this->nbofserviceswait++;
981 if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_end) || $line->date_end >= $now)) {
982 $this->nbofservicesopened++;
984 if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_end) && $line->date_end < $now)) {
985 $this->nbofservicesexpired++;
987 if ($line->statut == ContratLigne::STATUS_CLOSED) {
988 $this->nbofservicesclosed++;
992 $total_ttc += $objp->total_ttc;
993 $total_vat += $objp->total_tva;
994 $total_ht += $objp->total_ht;
999 $this->db->free($result);
1001 dol_syslog(get_class($this).
"::Fetch Error when reading lines of contracts linked to products");
1006 $this->nbofservices = count($this->lines);
1007 $this->total_ttc = (float)
price2num($total_ttc);
1008 $this->total_tva = (float)
price2num($total_vat);
1009 $this->total_ht = (float)
price2num($total_ht);
1011 return $this->lines;
1021 public function create($user, $notrigger = 0)
1023 global
$conf, $langs;
1027 if ($this->commercial_signature_id <= 0) {
1028 $langs->load(
"commercial");
1029 $this->error .= $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"SalesRepresentativeSignature"));
1032 if ($this->commercial_suivi_id <= 0) {
1033 $langs->load(
"commercial");
1034 $this->error .= ($this->error ?
"<br>" :
'');
1035 $this->error .= $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"SalesRepresentativeFollowUp"));
1049 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"contrat (datec, fk_soc, fk_user_author, date_contrat,";
1050 $sql .=
" fk_commercial_signature, fk_commercial_suivi, fk_projet,";
1051 $sql .=
" ref, entity, signed_status, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
1052 $sql .=
" VALUES ('".$this->db->idate($now).
"', ".((int) $this->socid).
", ".((int) $user->id);
1053 $sql .=
", ".(dol_strlen($this->date_contrat) != 0 ?
"'".$this->db->idate($this->date_contrat).
"'" :
"NULL");
1054 $sql .=
",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) :
"NULL");
1055 $sql .=
",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) :
"NULL");
1056 $sql .=
",".($this->fk_project > 0 ? ((int) $this->fk_project) :
"NULL");
1057 $sql .=
", ".(dol_strlen($this->
ref) <= 0 ?
"null" :
"'".$this->db->escape($this->
ref).
"'");
1058 $sql .=
", ".((int) $this->entity);
1059 $sql .=
", ".((int) $this->signed_status);
1060 $sql .=
", ".(!empty($this->note_private) ? (
"'".$this->db->escape($this->note_private).
"'") :
"NULL");
1061 $sql .=
", ".(!empty($this->note_public) ? (
"'".$this->db->escape($this->note_public).
"'") :
"NULL");
1062 $sql .=
", ".(!empty($this->ref_customer) ? (
"'".$this->db->escape($this->ref_customer).
"'") :
"NULL");
1063 $sql .=
", ".(!empty($this->ref_supplier) ? (
"'".$this->db->escape($this->ref_supplier).
"'") :
"NULL");
1064 $sql .=
", ".(!empty($this->ref_ext) ? (
"'".$this->db->escape($this->ref_ext).
"'") :
"NULL");
1066 $resql = $this->db->query($sql);
1071 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
"contrat");
1075 if (substr($module, 0, 13) ==
'mod_contract_' && substr($module, -3) ==
'php') {
1076 $module = substr($module, 0,
dol_strlen($module) - 4);
1080 $modCodeContract =
new $module();
1081 '@phan-var-force ModelNumRefContracts $modCodeContract';
1084 if (!empty($modCodeContract->code_auto)) {
1086 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"contrat SET ref='(PROV".((int) $this->
id).
")' WHERE rowid=".((int) $this->
id);
1087 if ($this->db->query($sql)) {
1089 $this->
ref =
"(PROV".$this->id.
")";
1101 if (!$error && !empty($this->commercial_signature_id)) {
1102 $result = $this->
add_contact($this->commercial_signature_id,
'SALESREPSIGN',
'internal');
1109 if (!$error && !empty($this->commercial_suivi_id)) {
1110 $result = $this->
add_contact($this->commercial_suivi_id,
'SALESREPFOLL',
'internal');
1117 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
1118 $this->linked_objects = $this->linkedObjectsIds;
1122 if ($this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1123 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1124 if (is_array($tmp_origin_id)) {
1125 foreach ($tmp_origin_id as $origin_id) {
1128 $this->error = $this->db->lasterror();
1133 $origin_id = $tmp_origin_id;
1136 $this->error = $this->db->lasterror();
1143 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
1144 $originforcontact = $this->origin;
1145 $originidforcontact = $this->origin_id;
1146 if ($originforcontact ==
'shipping') {
1147 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
1149 $exp->fetch($this->origin_id);
1150 $exp->fetchObjectLinked();
1151 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
1152 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
1153 $originforcontact =
'commande';
1154 $originidforcontact = $value;
1160 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
1161 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
1163 $resqlcontact = $this->db->query($sqlcontact);
1164 if ($resqlcontact) {
1165 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1166 if ($objcontact->source ==
'internal' && in_array($objcontact->code, array(
'SALESREPSIGN',
'SALESREPFOLL'))) {
1170 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
1178 if (!$error && !$notrigger) {
1180 $result = $this->call_trigger(
'CONTRACT_CREATE', $user);
1188 $this->db->commit();
1193 if (empty($this->error) && empty($this->errors)) {
1194 $this->error =
"Failed to add contract";
1196 dol_syslog(get_class($this).
"::create - 20 - ".$this->error, LOG_ERR);
1197 $this->db->rollback();
1201 $this->error = $langs->trans(
"UnknownError").
": ".$this->db->error();
1202 dol_syslog(get_class($this).
"::create - 10 - ".$this->error, LOG_ERR);
1204 $this->db->rollback();
1216 public function delete($user)
1220 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1227 $result = $this->call_trigger(
'CONTRACT_DELETE', $user);
1237 dol_syslog(get_class($this).
"::delete error", LOG_ERR);
1253 $sql_main_table = MAIN_DB_PREFIX.
'contratdet';
1254 $ef = $sql_main_table.
"_extrafields";
1255 $sql =
"DELETE FROM ".$this->db->sanitize($ef).
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_contrat = ".((int) $this->
id).
")";
1257 dol_syslog(get_class($this).
"::delete contratdet_extrafields", LOG_DEBUG);
1258 $resql = $this->db->query($sql);
1260 $this->error = $this->db->error();
1267 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"contratdet";
1268 $sql .=
" WHERE fk_contrat = ".((int) $this->
id);
1270 dol_syslog(get_class($this).
"::delete contratdet", LOG_DEBUG);
1271 $resql = $this->db->query($sql);
1273 $this->error = $this->db->error();
1291 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"contrat";
1292 $sql .=
" WHERE rowid=".((int) $this->
id);
1294 dol_syslog(get_class($this).
"::delete contrat", LOG_DEBUG);
1295 $resql = $this->db->query($sql);
1297 $this->error = $this->db->error();
1307 dol_syslog(get_class($this).
"::delete error -3 ".$this->error, LOG_ERR);
1314 if ($conf->contrat->dir_output && !empty($ref)) {
1315 $dir =
$conf->contrat->multidir_output[$this->entity].
"/".$ref;
1316 if (file_exists($dir)) {
1319 $this->error =
'ErrorFailToDeleteDir';
1327 $this->db->commit();
1330 $this->error = $this->db->lasterror();
1331 $this->db->rollback();
1343 public function update($user, $notrigger = 0)
1349 if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1350 $this->fk_commercial_signature = $this->commercial_signature_id;
1352 if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1353 $this->fk_commercial_suivi = $this->commercial_suivi_id;
1355 if (empty($this->socid) && $this->fk_soc > 0) {
1356 $this->socid = (int) $this->fk_soc;
1359 if (isset($this->
ref)) {
1360 $this->
ref = trim($this->
ref);
1362 if (isset($this->ref_customer)) {
1363 $this->ref_customer = trim($this->ref_customer);
1365 if (isset($this->ref_supplier)) {
1366 $this->ref_supplier = trim($this->ref_supplier);
1368 if (isset($this->ref_ext)) {
1369 $this->ref_ext = trim($this->ref_ext);
1371 if (isset($this->entity)) {
1372 $this->entity = (int) $this->entity;
1374 if (isset($this->
status)) {
1377 if ((
int) $this->socid > 0) {
1378 $this->socid = (int) $this->socid;
1380 if (isset($this->fk_commercial_signature)) {
1381 $this->fk_commercial_signature = (int) $this->fk_commercial_signature;
1383 if (isset($this->fk_commercial_suivi)) {
1384 $this->fk_commercial_suivi = (int) $this->fk_commercial_suivi;
1386 if (isset($this->note_private)) {
1387 $this->note_private = trim($this->note_private);
1389 if (isset($this->note_public)) {
1390 $this->note_public = trim($this->note_public);
1392 if (isset($this->import_key)) {
1393 $this->import_key = trim($this->import_key);
1396 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
1397 $extraparams =
dol_trunc($extraparams, 250);
1402 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contrat SET";
1403 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
1404 $sql .=
" ref_customer=".(isset($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" :
"null").
",";
1405 $sql .=
" ref_supplier=".(isset($this->ref_supplier) ?
"'".$this->db->escape($this->ref_supplier).
"'" :
"null").
",";
1406 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
1407 $sql .=
" entity=".((int)
$conf->entity).
",";
1408 $sql .=
" date_contrat=".(dol_strlen($this->date_contrat) != 0 ?
"'".$this->db->idate($this->date_contrat).
"'" :
'null').
",";
1409 $sql .=
" statut=".(isset($this->statut) ? ((int) $this->statut) : (isset($this->
status) ? ((int) $this->
status) :
"null")).
",";
1410 $sql .=
" fk_soc=".($this->socid > 0 ? ((int) $this->socid) :
"null").
",";
1411 $sql .=
" fk_projet=".($this->fk_project > 0 ? ((int) $this->fk_project) :
"null").
",";
1412 $sql .=
" fk_commercial_signature=".(isset($this->fk_commercial_signature) ? ((int) $this->fk_commercial_signature) :
"null").
",";
1413 $sql .=
" fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? ((int) $this->fk_commercial_suivi) :
"null").
",";
1414 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
1415 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
1416 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
1417 $sql .=
" fk_user_modif=".(isset($user->id) ? ((int) $user->id) :
"null").
",";
1418 $sql .=
" extraparams=".(isset($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
1419 $sql .=
" WHERE rowid=".((int) $this->
id);
1423 $resql = $this->db->query($sql);
1426 $this->errors[] =
"Error ".$this->db->lasterror();
1436 if (!$error && !$notrigger) {
1438 $result = $this->call_trigger(
'CONTRACT_MODIFY', $user);
1447 foreach ($this->errors as $errmsg) {
1448 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
1449 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
1451 $this->db->rollback();
1454 if (isset($user->id)) {
1455 $this->fk_user_modif = (int) $user->id;
1457 $this->db->commit();
1486 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent,
$date_start, $date_end, $price_base_type =
'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice =
null, $pa_ht = 0, $array_options = array(), $fk_unit =
null, $rang = 0)
1488 global $user, $langs,
$mysoc;
1491 dol_syslog(get_class($this).
"::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1494 if ($fk_product <= 0 && empty($desc)) {
1495 $this->error =
"ErrorDescRequiredForFreeProductLines";
1499 if ($this->
status >= 0) {
1508 if (preg_match(
'/\((.*)\)/', (
string) $txtva, $reg)) {
1509 $vat_src_code = $reg[1];
1510 $txtva = preg_replace(
'/\s*\(.*\)/',
'', (
string) $txtva);
1516 $remise_percent =
price2num($remise_percent);
1521 if (empty($info_bits)) {
1524 if (empty($pu_ht) || !is_numeric($pu_ht)) {
1527 if (empty($pu_ttc)) {
1530 if (empty($txtva) || !is_numeric($txtva)) {
1533 if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
1536 if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
1540 if ($price_base_type ==
'HT') {
1547 if (empty($remise_percent)) {
1548 $remise_percent = 0;
1555 $langs->load(
"errors");
1556 $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";
1606 $sql .=
",date_ouverture_prevue";
1608 if ($date_end > 0) {
1609 $sql .=
",date_fin_validite";
1611 $sql .=
", fk_unit";
1613 $sql .=
") VALUES (";
1614 $sql .= ((int) $this->
id).
", '', '".$this->db->escape($desc).
"',";
1615 $sql .= ($fk_product > 0 ? ((int) $fk_product) :
"null").
",";
1616 $sql .=
" ".((float) $qty).
",";
1617 $sql .=
" ".((float) $txtva).
",";
1618 $sql .=
" ".($vat_src_code ?
"'".$this->db->escape($vat_src_code).
"'" :
"null").
",";
1619 $sql .=
" ".((float) $txlocaltax1).
",";
1620 $sql .=
" ".((float) $txlocaltax2).
",";
1621 $sql .=
" '".$this->db->escape($localtax1_type).
"',";
1622 $sql .=
" '".$this->db->escape($localtax2_type).
"',";
1623 $sql .=
" ".price2num($remise_percent).
",";
1624 $sql .=
" ".price2num($pu_ht).
",";
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);
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;
1719 $qty = trim((
string) $qty);
1720 $desc = trim((
string) $desc);
1726 if (empty($fk_fournprice)) {
1734 $langs->load(
"errors");
1735 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
1739 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");
1748 $tvatx = preg_replace(
'/\s*\(.*\)/',
'', $tvatx);
1750 $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);
1751 $total_ht = $tabprice[0];
1752 $total_tva = $tabprice[1];
1753 $total_ttc = $tabprice[2];
1754 $total_localtax1 = $tabprice[9];
1755 $total_localtax2 = $tabprice[10];
1757 $localtax1_type = (empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0]);
1758 $localtax2_type = (empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2]);
1760 if (empty($pa_ht)) {
1774 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"contratdet SET description = '".$this->db->escape($desc).
"'";
1775 $sql .=
",subprice = ".((float)
price2num($subprice));
1776 $sql .=
",remise_percent = ".((float)
price2num($remise_percent));
1777 $sql .=
",qty = ".((float) $qty);
1778 $sql .=
",tva_tx = ".((float)
price2num($tvatx));
1779 $sql .=
",localtax1_tx = ".((float)
price2num($localtax1tx));
1780 $sql .=
",localtax2_tx = ".((float)
price2num($localtax2tx));
1781 $sql .=
",localtax1_type='".$this->db->escape($localtax1_type).
"'";
1782 $sql .=
",localtax2_type='".$this->db->escape($localtax2_type).
"'";
1783 $sql .=
", total_ht = ".((float)
price2num($total_ht));
1784 $sql .=
", total_tva = ".((float)
price2num($total_tva));
1785 $sql .=
", total_localtax1 = ".((float)
price2num($total_localtax1));
1786 $sql .=
", total_localtax2 = ".((float)
price2num($total_localtax2));
1787 $sql .=
", total_ttc = ".((float)
price2num($total_ttc));
1788 $sql .=
", fk_product_fournisseur_price=".($fk_fournprice > 0 ? ((int) $fk_fournprice) :
"null");
1789 $sql .=
", buy_price_ht = ".((float)
price2num($pa_ht));
1791 $sql .=
",date_ouverture_prevue = '".$this->db->idate(
$date_start).
"'";
1793 $sql .=
",date_ouverture_prevue = null";
1795 if ($date_end > 0) {
1796 $sql .=
",date_fin_validite = '".$this->db->idate($date_end).
"'";
1798 $sql .=
",date_fin_validite = null";
1800 if ($date_start_real > 0) {
1801 $sql .=
",date_ouverture = '".$this->db->idate($date_start_real).
"'";
1803 $sql .=
",date_ouverture = null";
1805 if ($date_end_real > 0) {
1806 $sql .=
",date_cloture = '".$this->db->idate($date_end_real).
"'";
1808 $sql .=
",date_cloture = null";
1810 $sql .=
", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) :
"null");
1811 $sql .=
", rang = ".(!empty($rang) ? ((int) $rang) :
"0");
1812 $sql .=
" WHERE rowid = ".((int) $rowid);
1814 dol_syslog(get_class($this).
"::updateline", LOG_DEBUG);
1815 $result = $this->db->query($sql);
1817 if (is_array($array_options) && count($array_options) > 0) {
1819 $contractline->fetch($rowid);
1822 foreach ($array_options as $key => $value) {
1823 $contractline->array_options[$key] = $array_options[$key];
1826 $result = $contractline->insertExtraFields();
1828 $this->errors[] = $contractline->error;
1834 $sqltoupdatecontract =
"UPDATE ".MAIN_DB_PREFIX.
"contrat";
1835 $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.
")";
1836 $sqltoupdatecontract .=
" WHERE rowid = ".((int) $this->
id);
1837 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
1838 if (!$resqltoupdatecontract) {
1839 $this->error = $this->db->lasterror();
1840 $this->db->rollback();
1844 if (empty($error)) {
1846 $this->context[
'line_id'] = $rowid;
1847 $result = $this->call_trigger(
'LINECONTRACT_MODIFY', $user);
1849 $this->db->rollback();
1854 $this->db->commit();
1857 $this->db->rollback();
1861 $this->db->rollback();
1862 $this->error = $this->db->error();
1863 dol_syslog(get_class($this).
"::updateline Erreur -1");
1879 if ($this->statut >= 0) {
1881 $this->context[
'line_id'] = $idline;
1882 $result = $this->call_trigger(
'LINECONTRACT_DELETE', $user);
1890 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
1891 $sql .=
" WHERE rowid = ".((int) $idline);
1893 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
1894 $resql = $this->db->query($sql);
1896 $this->error =
"Error ".$this->db->lasterror();
1903 $contractline->id = $idline;
1904 $result = $contractline->deleteExtraFields();
1907 $this->error =
"Error ".get_class($this).
"::deleteline deleteExtraFields error -4 ".$contractline->error;
1916 $result = $this->
line_order(
true,
'ASC',
false);
1919 $this->error =
"Error ".get_class($this).
"::deleteline line_order error";
1923 if (empty($error)) {
1924 $this->db->commit();
1927 dol_syslog(get_class($this).
"::deleteline ERROR:".$this->error, LOG_ERR);
1928 $this->db->rollback();
1932 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
1949 dol_syslog(__METHOD__.
" is deprecated", LOG_WARNING);
1952 if ($this->statut == 0) {
1977 return $this->
LibStatut($this->statut, $mode);
1993 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1995 $langs->load(
"contracts");
1996 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv(
'ContractStatusDraft');
1997 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv(
'ContractStatusValidated');
1998 $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv(
'ContractStatusClosed');
1999 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv(
'ContractStatusDraft');
2000 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv(
'ContractStatusValidated');
2001 $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv(
'ContractStatusClosed');
2004 $statusType =
'status'.$status;
2005 if ($status == self::STATUS_VALIDATED) {
2006 $statusType =
'status6';
2009 if ($mode == 4 || $mode == 6 || $mode == 7) {
2012 $text =
'<span class="hideonsmartphone">';
2013 $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
2014 $text .=
' '.$langs->trans(
"Services");
2015 $text .=
': ';
2018 $text .= ($mode == 7 ?
'<span class="nowraponall">' :
'');
2019 $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2020 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2021 $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2022 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2023 $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1,
'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ?
' ' :
'') :
'';
2024 $text .= ($mode == 7 ?
'</span><span class="nowraponall">' :
'');
2025 $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1,
'class="marginleft2"')) :
'';
2026 $text .= ($mode == 7 ?
'</span>' :
'');
2028 $text .= is_null($this->signed_status) ?
'' :
' '.$this->getLibSignedStatus(5);
2032 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
2044 global
$conf, $langs, $user;
2046 $langs->load(
'contracts');
2049 $nofetch = !empty($params[
'nofetch']);
2052 return [
'optimize' => $langs->trans(
"ShowContract")];
2054 if ($user->hasRight(
'contrat',
'lire')) {
2055 $datas[
'picto'] =
img_picto(
'', $this->picto).
' <u class="paddingrightonly">'.$langs->trans(
"Contract").
'</u>';
2060 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.($this->
ref ? $this->
ref : $this->id);
2062 $langs->load(
'companies');
2063 if (empty($this->thirdparty)) {
2066 $datas[
'customer'] =
'<br><b>'.$langs->trans(
'Customer').
':</b> '.$this->thirdparty->getNomUrl(1,
'', 0, 1);
2068 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '. $this->ref_customer;
2070 $langs->load(
'project');
2071 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2073 if ($res > 0 && $this->project instanceof
Project) {
2074 $datas[
'project'] =
'<br><b>'.$langs->trans(
'Project').
':</b> '.$this->project->getNomUrl(1,
'', 0,
'1');
2078 $datas[
'refsupplier'] =
'<br><b>'.$langs->trans(
'RefSupplier').
':</b> '.$this->ref_supplier;
2079 if (!empty($this->total_ht)) {
2080 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2082 if (!empty($this->total_tva)) {
2083 $datas[
'vatamount'] =
'<br><b>'.$langs->trans(
'VAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2085 if (!empty($this->total_ttc)) {
2086 $datas[
'amounttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2101 public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
2103 global $langs, $user, $hookmanager;
2107 $baseurl = DOL_URL_ROOT .
'/contrat/card.php';
2108 $query = [
'id' => $this->id];
2113 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2114 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2115 $add_save_lastsearch_values = 1;
2117 if ($add_save_lastsearch_values) {
2118 $query = array_merge($query, [
'save_lastsearch_values' => 1]);
2124 'objecttype' => $this->element,
2127 $classfortooltip =
'classfortooltip';
2130 $classfortooltip =
'classforajaxtooltip';
2131 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2138 if (empty($notooltip) && $user->hasRight(
'contrat',
'lire')) {
2140 $label = $langs->trans(
"ShowContract");
2141 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2143 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2144 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2146 $linkstart =
'<a href="'.$url.
'"';
2147 $linkstart .= $linkclose.
'>';
2150 $result .= $linkstart;
2152 $result .=
img_object(($notooltip ?
'' : $label), ($this->picto ? $this->picto :
'generic'), (($withpicto != 2) ?
'class="paddingright"' :
''), 0, 0, $notooltip ? 0 : 1);
2154 if ($withpicto != 2) {
2155 $result .= ($this->
ref ? $this->
ref : $this->id);
2157 $result .= $linkend;
2160 $hookmanager->initHooks(array(
'contractdao'));
2161 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
2162 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2164 $result = $hookmanager->resPrint;
2166 $result .= $hookmanager->resPrint;
2180 $sql =
"SELECT c.rowid, c.ref, c.datec,";
2181 $sql .=
" c.tms as date_modification,";
2182 $sql .=
" fk_user_author";
2183 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2184 $sql .=
" WHERE c.rowid = ".((int) $id);
2186 $result = $this->db->query($sql);
2188 if ($this->db->num_rows($result)) {
2189 $obj = $this->db->fetch_object($result);
2191 $this->
id = $obj->rowid;
2192 $this->
ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2194 $this->user_creation_id = $obj->fk_user_author;
2195 $this->date_creation = $this->db->jdate($obj->datec);
2196 $this->date_modification = $this->db->jdate($obj->date_modification);
2199 $this->db->free($result);
2217 $sql =
"SELECT cd.rowid";
2218 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contratdet as cd";
2219 $sql .=
" WHERE fk_contrat =".((int) $this->
id);
2221 $sql .=
" AND statut = ".((int) $status);
2224 dol_syslog(get_class($this).
"::array_detail()", LOG_DEBUG);
2225 $resql = $this->db->query($sql);
2227 $num = $this->db->num_rows($resql);
2230 $obj = $this->db->fetch_object($resql);
2231 $tab[$i] = $obj->rowid;
2236 $this->error = $this->db->error();
2250 public function getListOfContracts($option =
'all', $status = [], $product_categories = [], $line_status = [])
2254 $sql =
"SELECT c.rowid";
2255 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2256 if (!empty($product_categories) || !empty($line_status)) {
2257 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"contratdet as cd ON cd.fk_contrat = c.rowid";
2259 if (!empty($product_categories)) {
2260 $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)).
")";
2262 $sql .=
" WHERE c.fk_soc =".((int) $this->socid);
2263 $sql .= ($option ==
'others') ?
" AND c.rowid <> ".((
int) $this->id) :
"";
2264 $sql .= (!empty($status)) ?
" AND c.statut IN (".$this->db->sanitize(implode(
', ', $status)).
")" :
"";
2265 $sql .= (!empty($line_status)) ?
" AND cd.statut IN (".$this->db->sanitize(implode(
', ', $line_status)).
")" :
"";
2266 $sql .=
" GROUP BY c.rowid";
2268 dol_syslog(get_class($this).
"::getOtherContracts()", LOG_DEBUG);
2269 $resql = $this->db->query($sql);
2271 $num = $this->db->num_rows($resql);
2274 $obj = $this->db->fetch_object($resql);
2275 $contrat =
new Contrat($this->db);
2276 $contrat->fetch($obj->rowid);
2277 $tab[$contrat->id] = $contrat;
2282 $this->error = $this->db->lasterror();
2299 global
$conf, $langs;
2301 $this->from =
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2302 $this->from .=
", ".MAIN_DB_PREFIX.
"contratdet as cd";
2303 $this->from .=
", ".MAIN_DB_PREFIX.
"societe as s";
2304 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2305 $this->from .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
2308 if ($mode ==
'inactive') {
2309 $sql =
"SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2310 $sql .= $this->from;
2311 $sql .=
" WHERE c.statut = 1";
2312 $sql .=
" AND c.rowid = cd.fk_contrat";
2313 $sql .=
" AND cd.statut = 0";
2314 } elseif ($mode ==
'expired') {
2315 $sql =
"SELECT cd.rowid, cd.date_fin_validite as datefin";
2316 $sql .= $this->from;
2317 $sql .=
" WHERE c.statut = 1";
2318 $sql .=
" AND c.rowid = cd.fk_contrat";
2319 $sql .=
" AND cd.statut = 4";
2320 $sql .=
" AND cd.date_fin_validite < '".$this->db->idate(
dol_now()).
"'";
2321 } elseif ($mode ==
'active') {
2322 $sql =
"SELECT cd.rowid, cd.date_fin_validite as datefin";
2323 $sql .= $this->from;
2324 $sql .=
" WHERE c.statut = 1";
2325 $sql .=
" AND c.rowid = cd.fk_contrat";
2326 $sql .=
" AND cd.statut = 4";
2332 $sql .=
" AND c.fk_soc = s.rowid";
2333 $sql .=
" AND c.entity = ".((int)
$conf->entity);
2335 $sql .=
" AND c.fk_soc = ".((int) $user->socid);
2337 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2338 $sql .=
" AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2341 $resql = $this->db->query($sql);
2343 $langs->load(
"contracts");
2346 if ($mode ==
'inactive') {
2347 $warning_delay =
$conf->contract->services->inactifs->warning_delay;
2348 $label = $langs->trans(
"BoardNotActivatedServices");
2349 $labelShort = $langs->trans(
"BoardNotActivatedServicesShort");
2350 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&sortfield=cd.date_fin_validite&sortorder=asc';
2351 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=0&search_option=late';
2352 } elseif ($mode ==
'expired') {
2353 $warning_delay =
$conf->contract->services->expires->warning_delay;
2354 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
2355 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&search_option=late';
2356 $label = $langs->trans(
"BoardExpiredServices");
2357 $labelShort = $langs->trans(
"BoardExpiredServicesShort");
2359 $warning_delay =
$conf->contract->services->expires->warning_delay;
2360 $url = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_status=4&sortfield=cd.date_fin_validite&sortorder=asc';
2361 $url_late = DOL_URL_ROOT.
'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&search_option=late';
2362 $label = $langs->trans(
"BoardRunningServices");
2363 $labelShort = $langs->trans(
"BoardRunningServicesShort");
2367 $response->warning_delay = $warning_delay / 60 / 60 / 24;
2368 $response->label = $label;
2369 $response->labelShort = $labelShort;
2370 $response->url = $url;
2371 $response->url_late = $url_late;
2374 while ($obj = $this->db->fetch_object($resql)) {
2375 $response->nbtodo++;
2377 if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2378 $response->nbtodolate++;
2385 $this->error = $this->db->error();
2397 global
$conf, $user;
2399 $this->nb = array();
2400 $sanitizedclause =
"WHERE";
2402 $sql =
"SELECT count(c.rowid) as nb";
2403 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contrat as c";
2404 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON c.fk_soc = s.rowid";
2405 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
2406 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2407 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
2408 $sanitizedclause =
"AND";
2410 $sql .=
" ".$sanitizedclause.
" c.entity = ".((int)
$conf->entity);
2412 $resql = $this->db->query($sql);
2414 while ($obj = $this->db->fetch_object($resql)) {
2415 $this->nb[
"contracts"] = $obj->nb;
2417 $this->db->free($resql);
2421 $this->error = $this->db->error();
2459 global $user, $langs,
$conf;
2464 $sql =
"SELECT rowid";
2465 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
2466 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
2467 $sql .=
" AND tosell = 1";
2468 $sql .= $this->db->plimit(100);
2470 $resql = $this->db->query($sql);
2472 $num_prods = $this->db->num_rows($resql);
2474 while ($i < $num_prods) {
2476 $row = $this->db->fetch_row($resql);
2477 $prodids[$i] = $row[0];
2483 $this->specimen = 1;
2485 $this->
ref =
'SPECIMEN';
2486 $this->ref_customer =
'SPECIMENCUST';
2487 $this->ref_supplier =
'SPECIMENSUPP';
2490 $this->date_creation = (
dol_now() - 3600 * 24 * 7);
2491 $this->date_contrat =
dol_now();
2492 $this->commercial_signature_id = 1;
2493 $this->commercial_suivi_id = 1;
2494 $this->note_private =
'This is a comment (private)';
2495 $this->note_public =
'This is a comment (public)';
2496 $this->fk_project = 0;
2500 while ($xnbp < $nbp) {
2503 $line->subprice = 100;
2504 $line->tva_tx = 19.6;
2505 $line->remise_percent = 10;
2506 $line->total_ht = 90;
2507 $line->total_ttc = 107.64;
2508 $line->total_tva = 17.64;
2509 $line->date_start =
dol_now() - 500000;
2510 $line->date_start_real =
dol_now() - 200000;
2511 $line->date_end =
dol_now() + 500000;
2512 $line->date_end_real =
dol_now() - 100000;
2513 if ($num_prods > 0) {
2514 $prodid = mt_rand(1, $num_prods);
2515 $line->fk_product = $prodids[$prodid];
2517 $this->lines[$xnbp] = $line;
2543 $ticket =
new Ticket($this->db);
2544 $nbTicket = $ticket->fetchAll($user,
'ASC',
't.datec', 0, 0, 0, array(
't.fk_contract' => $this->
id));
2546 return ($nbTicket < 0 ? $nbTicket : $ticket->lines);
2561 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
2568 if (!empty($this->model_pdf)) {
2569 $modele = $this->model_pdf;
2575 if (empty($modele)) {
2578 $langs->load(
"contracts");
2579 $outputlangs->load(
"products");
2581 $modelpath =
"core/modules/contract/doc/";
2582 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2628 public function createFromClone(
User $user, $socid = 0, $notrigger = 0)
2630 global
$db, $langs,
$conf, $hookmanager, $extrafields;
2636 $this->
fetch($this->
id);
2639 $clonedObj = clone $this;
2640 $clonedObj->socid = $socid;
2644 $objsoc =
new Societe($this->db);
2646 $objsoc->fetch($clonedObj->socid);
2649 $clonedObj->statut = 0;
2650 $clonedObj->status = 0;
2652 if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
2653 $extrafields->fetch_name_optionals_label($this->table_element);
2654 foreach ($clonedObj->array_options as $key => $option) {
2655 $shortkey = preg_replace(
'/options_/',
'', $key);
2656 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
2657 unset($clonedObj->array_options[$key]);
2663 $this->error =
'ErrorSetupNotComplete';
2669 require_once DOL_DOCUMENT_ROOT.
"/core/modules/contract/" .
getDolGlobalString(
'CONTRACT_ADDON').
'.php';
2671 $modContract =
new $obj();
2672 '@phan-var-force ModelNumRefContracts $modContract';
2674 $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2677 foreach ($this->lines as $line) {
2678 $line->fetch_optionals($line->id);
2682 $clonedObj->context[
'createfromclone'] =
'createfromclone';
2683 $result = $clonedObj->create($user);
2689 if ($this->socid == $clonedObj->socid) {
2690 if ($clonedObj->copy_linked_contact($this,
'external') < 0) {
2697 foreach ($this->lines as $line) {
2698 $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);
2708 if (is_object($hookmanager)) {
2709 $parameters = array(
2711 'clonedObj' => $clonedObj
2714 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $clonedObj, $action);
2722 unset($clonedObj->context[
'createfromclone']);
2726 $this->db->commit();
2727 return $clonedObj->id;
2729 $this->db->rollback();
2746 global $langs, $user;
2748 $langs->load(
"agenda");
2758 $contractlineprocessed = array();
2759 $contractignored = array();
2760 $contracterror = array();
2764 $sql =
'SELECT c.rowid, c.ref_customer, cd.rowid as lid, cd.date_fin_validite, p.duration';
2765 $sql .=
' FROM '.MAIN_DB_PREFIX.
'contrat as c, '.MAIN_DB_PREFIX.
'contratdet as cd';
2766 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON p.rowid = cd.fk_product';
2767 $sql .=
' WHERE cd.fk_contrat = c.rowid';
2768 $sql .=
" AND date_format(cd.date_fin_validite, '%Y-%m-%d') <= date_format('".$this->db->idate($enddatetoscan).
"', '%Y-%m-%d')";
2769 $sql .=
" AND cd.statut = 4";
2770 if ($thirdparty_id > 0) {
2771 $sql .=
" AND c.fk_soc = ".((int) $thirdparty_id);
2775 $resql = $this->db->query($sql);
2777 $num = $this->db->num_rows($resql);
2779 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2780 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
2784 $obj = $this->db->fetch_object($resql);
2786 if (!empty($contractlineprocessed[$obj->lid]) || !empty($contractignored[$obj->rowid]) || !empty($contracterror[$obj->rowid])) {
2796 $this->errors[] =
'Failed to load contract with id='.$obj->rowid;
2800 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);
2803 $expirationdate = $this->db->jdate($obj->date_fin_validite);
2804 $duration_value = preg_replace(
'/[^0-9]/',
'', $obj->duration);
2805 $duration_unit = preg_replace(
'/\d/',
'', $obj->duration);
2809 $object->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 1);
2812 if (isset(
$object->linkedObjects[
'facture']) && is_array(
$object->linkedObjects[
'facture']) && count(
$object->linkedObjects[
'facture']) > 0) {
2814 usort(
$object->linkedObjects[
'facture'], array(
'Contrat',
'contractCmpDate'));
2817 $someinvoicenotpaid = 0;
2818 foreach (
$object->linkedObjects[
'facture'] as $idinvoice => $invoice) {
2823 if (empty($invoice->paye)) {
2824 $someinvoicenotpaid++;
2827 if ($someinvoicenotpaid) {
2828 $this->output .=
'Contract '.$object->ref.
' is qualified for renewal but there is '.$someinvoicenotpaid.
' invoice(s) unpayed so we cancel renewal'.
"\n";
2834 if ($expirationdate && $expirationdate < $enddatetoscan) {
2835 dol_syslog(
"Define the newdate of end of services from expirationdate=".$expirationdate);
2836 $newdate = $expirationdate;
2838 while ($newdate < $enddatetoscan && $protecti < 1000) {
2843 if ($protecti < 1000) {
2849 $errorforlocaltransaction = 0;
2851 $label =
'Renewal of contrat '.$object->ref.
' line '.$obj->lid;
2852 $comment =
'Renew date of contract '.$object->ref.
' line '.$obj->lid.
' by doAutoRenewContracts';
2854 $sqlupdate =
'UPDATE '.MAIN_DB_PREFIX.
"contratdet SET date_fin_validite = '".$this->db->idate($newdate).
"'";
2855 $sqlupdate .=
' WHERE rowid = '.((int) $obj->lid);
2856 $resqlupdate = $this->db->query($sqlupdate);
2858 $contractlineprocessed[$obj->lid] =
$object->ref;
2861 $sqltoupdatecontract =
"UPDATE ".MAIN_DB_PREFIX.
"contrat";
2862 $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.
")";
2863 $sqltoupdatecontract .=
" WHERE rowid = ".((int)
$object->id);
2864 $resqltoupdatecontract = $this->db->query($sqltoupdatecontract);
2865 if (!$resqltoupdatecontract) {
2866 $this->error = $this->db->lasterror();
2867 $this->db->rollback();
2871 $actioncode =
'RENEW_CONTRACT';
2876 $actioncomm->type_code =
'AC_OTH_AUTO';
2877 $actioncomm->code =
'AC_'.$actioncode;
2878 $actioncomm->label = $label;
2879 $actioncomm->datep = $now;
2880 $actioncomm->datef = $now;
2881 $actioncomm->percentage = -1;
2882 $actioncomm->socid =
$object->socid;
2883 $actioncomm->authorid = $user->id;
2884 $actioncomm->userownerid = $user->id;
2885 $actioncomm->fk_element =
$object->id;
2886 $actioncomm->elementid =
$object->id;
2887 $actioncomm->elementtype =
'contract';
2888 $actioncomm->note_private = $comment;
2890 $ret = $actioncomm->create($user);
2895 $errorforlocaltransaction++;
2896 $this->error = $this->db->lasterror();
2899 if (! $errorforlocaltransaction) {
2900 $this->db->commit();
2902 $this->db->rollback();
2906 $this->error =
"Bad value for newdate in doAutoRenewContracts - expirationdate=".$expirationdate.
" enddatetoscan=".$enddatetoscan.
" duration_value=".$duration_value.
" duration_unit=".$duration_value;
2915 $this->error = $this->db->lasterror();
2918 $this->output .= count($contractlineprocessed).
' contract line(s) with end date before '.
dol_print_date($enddatetoscan,
'day').
' were renewed'.(count($contractlineprocessed) > 0 ?
' : '.implode(
',', $contractlineprocessed) :
'');
2920 return ($error ? 1 : 0);
2932 if ($a->date == $b->date) {
2933 return strcmp((
string) $a->id, (
string) $b->id);
2935 return ($a->date < $b->date) ? -1 : 1;
2949 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
2951 $return =
'<div class="box-flex-item box-flex-grow-zero">';
2952 $return .=
'<div class="info-box info-box-sm">';
2953 $return .=
'<span class="info-box-icon bg-infobox-action">';
2955 $return .=
'</span>';
2956 $return .=
'<div class="info-box-content">';
2957 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->
getNomUrl() .
'</span>';
2958 if ($selected >= 0) {
2959 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
2961 if (!empty($arraydata[
'thirdparty']) && $arraydata[
'thirdparty'] instanceof
Societe) {
2962 $tmpthirdparty = $arraydata[
'thirdparty'];
2963 '@phan-var-force Societe $tmpthirdparty';
2964 $return .=
'<br><div class="info-box-label inline-block valignmiddle">'.$tmpthirdparty->getNomUrl(1).
'</div>';
2966 $return .=
'<br><span class="opacitymedium valignmiddle">'.$langs->trans(
"DateContract").
' : </span><span class="info-box-label valignmiddle">'.
dol_print_date($this->date_contrat,
'day').
'</span>';
2967 $return .=
'<br><div class="info-box-status valignmiddle">'.$this->getLibStatut(7).
'</div>';
2968 $return .=
'</div>';
2969 $return .=
'</div>';
2970 $return .=
'</div>';
2984 $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,";
2985 $sql .=
" SUM(cd.total_localtax1) as total_localtax1, SUM(cd.total_localtax2) as total_localtax2";
2986 $sql .=
" FROM ".MAIN_DB_PREFIX.
"contratdet as cd";
2987 $sql .=
" WHERE cd.fk_contrat =".((int) $this->
id);
2989 $sql .=
" AND cd.statut = ".((int) $statut);
2991 $sql .=
" AND cd.date_fin_validite < '".$this->db->idate(
dol_now()).
"'";
2993 $sql .=
" AND cd.date_fin_validite >= '".$this->db->idate(
dol_now()).
"'";
2996 $ret = $this->db->query($sql);
2997 $response = array();
2999 $obj = $this->db->fetch_object($ret);
3000 $response[
'total_qty'] = $obj->total_qty;
3001 $response[
'total_ht'] = $obj->total_ht;
3002 $response[
'total_tva'] = $obj->total_tva;
3003 $response[
'total_localtax1'] = $obj->total_localtax1;
3004 $response[
'total_localtax2'] = $obj->total_localtax2;
3005 $response[
'total_ttc'] = $obj->total_ttc;
3008 $this->error = $this->db->lasterror();
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
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
static contractCmpDate($a, $b)
Used to sort lines by date.
getTotalizedLines($statut, int $expired)
Return totalized lines.
fetch($id, $ref='', $ref_customer='', $ref_supplier='', $noextrafields=0, $nolines=0)
Load a contract from database.
loadStateBoard()
Load the indicators this->nb for state board.
update_statut($user)
Update statut of contract according to services.
closeAll(User $user, $notrigger=0, $comment='', $nofetchlines=0)
Close all lines of a contract.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_start_real='', $date_end_real='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Update a contract line.
getTicketsArray()
Create an array of associated tickets.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
active_line($user, $line_id, $date_start, $date_end='', $comment='')
Activate a contract line.
getTooltipContentArray($params)
getTooltipContentArray
getLinesArray()
Create an array of order lines.
validate(User $user, $force_number='', $notrigger=0)
Validate a contract.
getIdBillingContact()
Return id des contacts clients de facturation.
initAsSpecimen()
Initialise an instance with random values.
close_line($user, $line_id, $date_end, $comment='')
Close a contract line.
reopen($user, $notrigger=0)
Unvalidate a contract.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
deleteLine($idline, User $user)
Delete a contract line.
array_detail($status=-1)
Return list of line rowid.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht=0, $array_options=array(), $fk_unit=null, $rang=0)
Insert contract line into database.
update($user, $notrigger=0)
Update object into database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getListOfContracts($option='all', $status=[], $product_categories=[], $line_status=[])
Return list of other contracts for the same company than current contract.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
LibStatut($status, $mode)
Return the label of a given contrat status.
activateAll($user, $date_start='', $notrigger=0, $comment='', $date_end='')
Open all lines of a contract.
__construct($db)
Constructor.
doAutoRenewContracts($thirdparty_id=0, $delayindaysshort=0)
Action executed by scheduler CAN BE A CRON TASK Loop on each contract lines and update the end of dat...
getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
info($id)
Charge les information d'ordre info dans l'objet contrat.
getLibStatut($mode)
Return label of a contract status.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetch_lines($only_services=0, $loadalsotranslation=0, $noextrafields=0)
Load lines array into this->lines.
getIdServiceContact()
Return id des contacts clients de prestation.
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)
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.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
Class to generate the form for creating a new ticket.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.