1<?php
2/* Copyright (C) 2003-2005  Rodolphe Quiedeville	<rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2015  Laurent Destailleur		<eldy@users.sourceforge.net>
4 * Copyright (C) 2009-2012  Regis Houssin			<regis.houssin@capnetworks.com>
5 * Copyright (C) 2010-2011  Juanjo Menent			<jmenent@2byte.es>
6 * Copyright (C) 2012       Cedric Salvador			<csalvador@gpcsolutions.fr>
7 * Copyright (C) 2013       Florian Henry			<florian.henry@open-concept.pro>
8 * Copyright (C) 2015       Marcos García			<marcosgdf@gmail.com>
9 * Copyright (C) 2016-2018  Charlie Benke			<charlie@patas-monkey.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 */
24
25/**
26 *  \file       htdocs/fichinter/class/fichinterrec.class.php
27 *  \ingroup    facture
28 *  \brief      Fichier de la classe des factures recurentes
29 */
30
31require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
32require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
33require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
34
35
36/**
37 *	Classe de gestion des factures recurrentes/Modeles
38 */
39class FichinterRec extends Fichinter
40{
41	public $element = 'fichinterrec';
42	public $table_element = 'fichinter_rec';
43	public $table_element_line = 'fichinter_rec';
44
45	/**
46	 * @var string Fieldname with ID of parent key if this field has a parent
47	 */
48	public $fk_element = 'fk_fichinter';
49
50	/**
51	 * {@inheritdoc}
52	 */
53	protected $table_ref_field = 'titre';
54
55	/**
56	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
57	 */
58	public $picto = 'intervention';
59
60	/**
61	 * @var string title
62	 */
63	public $title;
64	public $number;
65	public $date;
66	public $amount;
67	public $remise;
68	public $tva;
69	public $total;
70
71	/**
72	 * @var int Proposal Id
73	 */
74	public $propalid;
75
76	public $date_last_gen;
77	public $date_when;
78
79	/**
80	 * @var int number of generation done
81	 */
82	public $nb_gen_done;
83
84	/**
85	 * @var int number of maximum generation
86	 */
87	public $nb_gen_max;
88
89	/**
90	 * int rank
91	 */
92	public $rang;
93	public $special_code;
94
95	public $usenewprice = 0;
96
97	/**
98	 *	Constructor
99	 *
100	 * 	@param		DoliDB		$db		Database handler
101	 */
102	public function __construct($db)
103	{
104		$this->db = $db;
105
106		//status dans l'ordre de l'intervention
107		$this->statuts[0] = 'Draft';
108		$this->statuts[1] = 'Closed';
109
110		$this->statuts_short[0] = 'Draft';
111		$this->statuts_short[1] = 'Closed';
112
113		$this->statuts_logo[0] = 'statut0';
114		$this->statuts_logo[1] = 'statut1';
115	}
116
117	/**
118	 *	Returns the label status
119	 *
120	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
121	 *	@return     string              Label
122	 */
123	public function getLibStatut($mode = 0)
124	{
125		return $this->LibStatut($this->statut, $mode);
126	}
127
128
129	/**
130	 *  Create a predefined fichinter
131	 *
132	 *  @param      User    $user       User object
133	 *  @param      int     $notrigger  no trigger
134	 *  @return     int                 <0 if KO, id of fichinter if OK
135	 */
136	public function create($user, $notrigger = 0)
137	{
138		global $conf;
139
140		$error = 0;
141		$now = dol_now();
142
143		// Clean parameters
144		$this->title = trim($this->title);
145		$this->description = trim($this->description);
146
147
148		$this->db->begin();
149
150		// Load fichinter model
151		$fichintsrc = new Fichinter($this->db);
152
153		$result = $fichintsrc->fetch($this->id_origin);
154		$result = $fichintsrc->fetch_lines(1); // to get all lines
155
156
157		if ($result > 0) {
158			// On positionne en mode brouillon la facture
159			$this->brouillon = 1;
160
161			$sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter_rec (";
162			$sql .= "titre";
163			$sql .= ", fk_soc";
164			$sql .= ", entity";
165			$sql .= ", datec";
166			$sql .= ", duree";
167			$sql .= ", description";
168			$sql .= ", note_private";
169			$sql .= ", note_public";
170			$sql .= ", fk_user_author";
171			$sql .= ", fk_projet";
172			$sql .= ", fk_contrat";
173			$sql .= ", modelpdf";
174
175			$sql .= ", frequency";
176			$sql .= ", unit_frequency";
177			$sql .= ", date_when";
178			$sql .= ", date_last_gen";
179			$sql .= ", nb_gen_done";
180			$sql .= ", nb_gen_max";
181			// $sql.= ", auto_validate";
182
183			$sql .= ") VALUES (";
184			$sql .= "'".$this->db->escape($this->title)."'";
185			$sql .= ", ".($this->socid > 0 ? $this->socid : 'null');
186			$sql .= ", ".$conf->entity;
187			$sql .= ", '".$this->db->idate($now)."'";
188			$sql .= ", ".(!empty($fichintsrc->duration) ? $fichintsrc->duration : '0');
189			$sql .= ", ".(!empty($this->description) ? ("'".$this->db->escape($this->description)."'") : "null");
190			$sql .= ", ".(!empty($fichintsrc->note_private) ? ("'".$this->db->escape($fichintsrc->note_private)."'") : "null");
191			$sql .= ", ".(!empty($fichintsrc->note_public) ? ("'".$this->db->escape($fichintsrc->note_public)."'") : "null");
192			$sql .= ", ".$user->id;
193			// si c'est la même société on conserve les liens vers le projet et le contrat
194			if ($this->socid == $fichintsrc->socid) {
195				$sql .= ", ".(!empty($fichintsrc->fk_project) ? $fichintsrc->fk_project : "null");
196				$sql .= ", ".(!empty($fichintsrc->fk_contrat) ? $fichintsrc->fk_contrat : "null");
197			} else {
198				$sql .= ", null, null";
199			}
200
201			$sql .= ", ".(!empty($fichintsrc->model_pdf) ? "'".$this->db->escape($fichintsrc->model_pdf)."'" : "''");
202
203			// récurrence
204			$sql .= ", ".(!empty($this->frequency) ? $this->frequency : "null");
205			$sql .= ", '".$this->db->escape($this->unit_frequency)."'";
206			$sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'null');
207			$sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'null');
208			$sql .= ", 0"; // we start à 0
209			$sql .= ", ".$this->nb_gen_max;
210			// $sql.= ", ".$this->auto_validate;
211			$sql .= ")";
212
213			if ($this->db->query($sql)) {
214				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
215
216				/*
217                 * Lines
218                 */
219				$num = count($fichintsrc->lines);
220				for ($i = 0; $i < $num; $i++) {
221					//var_dump($fichintsrc->lines[$i]);
222					$result_insert = $this->addline(
223						$fichintsrc->lines[$i]->desc,
224						$fichintsrc->lines[$i]->duration,
225						$fichintsrc->lines[$i]->datei,
226						$fichintsrc->lines[$i]->rang,
227						$fichintsrc->lines[$i]->subprice,
228						$fichintsrc->lines[$i]->qty,
229						$fichintsrc->lines[$i]->tva_tx,
230						$fichintsrc->lines[$i]->fk_product,
231						$fichintsrc->lines[$i]->remise_percent,
232						'HT',
233						0,
234						'',
235						0,
236						$fichintsrc->lines[$i]->product_type,
237						$fichintsrc->lines[$i]->special_code,
238						$fichintsrc->lines[$i]->label,
239						$fichintsrc->lines[$i]->fk_unit
240					);
241
242					if ($result_insert < 0)
243						$error++;
244				}
245
246				if ($error)
247					$this->db->rollback();
248				else {
249					$this->db->commit();
250					return $this->id;
251				}
252			} else {
253				$this->error = $this->db->error().' sql='.$sql;
254				$this->db->rollback();
255				return -2;
256			}
257		} else {
258			$this->db->rollback();
259			return -1;
260		}
261	}
262
263
264	/**
265	 *	Get the template of intervention object and lines
266	 *
267	 *	@param	  int		$rowid	   	Id of object to load
268	 * 	@param		string	$ref			Reference of fichinter
269	 * 	@param		string	$ref_ext		External reference of fichinter
270	 *	@return	 int		 			>0 if OK, <0 if KO, 0 if not found
271	 */
272	public function fetch($rowid = 0, $ref = '', $ref_ext = '')
273	{
274		$sql = 'SELECT f.titre as title, f.fk_soc';
275		$sql .= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description';
276		$sql .= ', f.note_private, f.note_public, f.fk_user_author';
277		$sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.auto_validate';
278		$sql .= ', f.note_private, f.note_public, f.fk_user_author';
279		$sql .= ' FROM '.MAIN_DB_PREFIX.'fichinter_rec as f';
280		if ($rowid > 0) $sql .= ' WHERE f.rowid='.$rowid;
281		elseif ($ref) $sql .= " WHERE f.titre='".$this->db->escape($ref)."'";
282
283		dol_syslog(get_class($this)."::fetch rowid=".$rowid, LOG_DEBUG);
284
285		$result = $this->db->query($sql);
286		if ($result) {
287			if ($this->db->num_rows($result)) {
288				$obj = $this->db->fetch_object($result);
289
290				$this->id = $rowid;
291				$this->titre				= $obj->title;
292				$this->title				= $obj->title;
293				$this->ref = $obj->title;
294				$this->description = $obj->description;
295				$this->datec				= $obj->datec;
296				$this->duration = $obj->duree;
297				$this->socid				= $obj->fk_soc;
298				$this->statut = 0;
299				$this->fk_project			= $obj->fk_projet;
300				$this->fk_contrat			= $obj->fk_contrat;
301				$this->note_private = $obj->note_private;
302				$this->note_public			= $obj->note_public;
303				$this->user_author			= $obj->fk_user_author;
304				$this->model_pdf			= $obj->model_pdf;
305				$this->modelpdf				= $obj->model_pdf; // deprecated
306				$this->rang = $obj->rang;
307				$this->special_code = $obj->special_code;
308				$this->frequency			= $obj->frequency;
309				$this->unit_frequency = $obj->unit_frequency;
310				$this->date_when			= $this->db->jdate($obj->date_when);
311				$this->date_last_gen		= $this->db->jdate($obj->date_last_gen);
312				$this->nb_gen_done = $obj->nb_gen_done;
313				$this->nb_gen_max = $obj->nb_gen_max;
314				$this->auto_validate		= $obj->auto_validate;
315
316				$this->brouillon = 1;
317
318				// Lines
319				$result = $this->fetch_lines();
320				if ($result < 0) {
321					$this->error = $this->db->error();
322					return -3;
323				}
324				return 1;
325			} else {
326				$this->error = 'Interventional with id '.$rowid.' not found sql='.$sql;
327				dol_syslog(get_class($this).'::Fetch Error '.$this->error, LOG_ERR);
328				return -2;
329			}
330		} else {
331			$this->error = $this->db->error();
332			return -1;
333		}
334	}
335
336
337	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
338	/**
339	 *  Load all lines of template of intervention into this->lines
340	 *
341	 *  @param   int	$sall   sall
342	 *  @return	 int            1 if OK, < 0 if KO
343	 */
344	public function fetch_lines($sall = 0)
345	{
346		// phpcs:enable
347		$sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, ';
348		$sql .= ' l.price, l.qty, l.tva_tx, l.remise, l.remise_percent, l.subprice, l.duree, ';
349		$sql .= ' l.total_ht, l.total_tva, l.total_ttc,';
350		$sql .= ' l.rang, l.special_code,';
351		$sql .= ' l.fk_unit, p.ref as product_ref, p.fk_product_type as fk_product_type,';
352		$sql .= ' p.label as product_label, p.description as product_desc';
353		$sql .= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_rec as l';
354		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
355		$sql .= ' WHERE l.fk_fichinter = '.$this->id;
356
357		dol_syslog('FichInter-rec::fetch_lines', LOG_DEBUG);
358		$result = $this->db->query($sql);
359		if ($result) {
360			$num = $this->db->num_rows($result);
361			$i = 0;
362			while ($i < $num) {
363				$objp = $this->db->fetch_object($result);
364				$line = new FichinterLigne($this->db);
365
366				$line->id = $objp->rowid;
367				$line->label = $objp->custom_label; // Label line
368				$line->desc = $objp->description; // Description line
369				$line->product_type = $objp->product_type; // Type of line
370				$line->product_ref = $objp->product_ref; // Ref product
371				$line->product_label = $objp->product_label; // Label product
372				$line->product_desc = $objp->product_desc; // Description product
373				$line->fk_product_type = $objp->fk_product_type; // Type of product
374				$line->qty = $objp->qty;
375				$line->duree = $objp->duree;
376				$line->duration = $objp->duree;
377				$line->datei = $objp->date;
378				$line->subprice = $objp->subprice;
379				$line->tva_tx = $objp->tva_tx;
380				$line->remise_percent = $objp->remise_percent;
381				$line->fk_remise_except = $objp->fk_remise_except;
382				$line->fk_product = $objp->fk_product;
383				$line->date_start = $objp->date_start;
384				$line->date_end = $objp->date_end;
385				$line->date_start = $objp->date_start;
386				$line->date_end = $objp->date_end;
387				$line->info_bits = $objp->info_bits;
388				$line->total_ht = $objp->total_ht;
389				$line->total_tva = $objp->total_tva;
390				$line->total_ttc = $objp->total_ttc;
391				$line->code_ventilation = $objp->fk_code_ventilation;
392				$line->rang = $objp->rang;
393				$line->special_code = $objp->special_code;
394				$line->fk_unit = $objp->fk_unit;
395
396				// Ne plus utiliser
397				$line->price = $objp->price;
398				$line->remise = $objp->remise;
399
400				$this->lines[$i] = $line;
401
402				$i++;
403			}
404
405			$this->db->free($result);
406			return 1;
407		} else {
408			$this->error = $this->db->error();
409			return -3;
410		}
411	}
412
413
414	/**
415	 * 	Delete template fichinter rec
416	 *
417	 *	@param	 	int		$rowid	  	    Id of fichinter rec to delete. If empty, we delete current instance of fichinter rec
418	 *	@param		int		$notrigger	    1=Does not execute triggers, 0= execute triggers
419	 *	@param		int		$idwarehouse    Id warehouse to use for stock change.
420	 *	@return		int						<0 if KO, >0 if OK
421	 */
422	public function delete($rowid = 0, $notrigger = 0, $idwarehouse = -1)
423	{
424		if (empty($rowid)) $rowid = $this->id;
425
426		dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG);
427
428		$error = 0;
429		$this->db->begin();
430
431		$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet_rec WHERE fk_fichinter = ".$rowid;
432		dol_syslog($sql);
433		if ($this->db->query($sql)) {
434			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter_rec WHERE rowid = ".$rowid;
435			dol_syslog($sql);
436			if (!$this->db->query($sql)) {
437				$this->error = $this->db->lasterror();
438				$error = -1;
439			}
440		} else {
441			$this->error = $this->db->lasterror();
442			$error = -2;
443		}
444
445		if (!$error) {
446			$this->db->commit();
447			return 1;
448		} else {
449			$this->db->rollback();
450			return $error;
451		}
452	}
453
454
455	/**
456	 *  Add a line to fichinter rec
457	 *
458	 *  @param		string		$desc               Description de la ligne
459	 *  @param		integer		$duration           Durée
460	 *  @param		string	    $datei				Date
461	 *  @param	    int			$rang			    Position of line
462	 *  @param		double		$pu_ht			    Unit price without tax (> 0 even for credit note)
463	 *  @param		double		$qty			 	Quantity
464	 *  @param		double		$txtva		   	    Forced VAT rate, otherwise -1
465	 *  @param		int			$fk_product	  	    Id of predefined product/service
466	 *  @param		double		$remise_percent  	Percentage of discount on line
467	 *  @param		string		$price_base_type	HT or TTC
468	 *  @param		int			$info_bits			Bits for type of lines
469	 *  @param		int			$fk_remise_except   Id discount
470	 *  @param		double		$pu_ttc			    Unit price with tax (> 0 even for credit note)
471	 *  @param		int			$type				Type of line (0=product, 1=service)
472	 *  @param		int			$special_code		Special code
473	 *  @param		string		$label				Label of the line
474	 *  @param		string		$fk_unit			Unit
475	 *  @return		int			 				    <0 if KO, Id of line if OK
476	 */
477	public function addline($desc, $duration, $datei, $rang = -1, $pu_ht = 0, $qty = 0, $txtva = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $special_code = 0, $label = '', $fk_unit = null)
478	{
479		global $mysoc;
480
481		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
482
483		// Check parameters
484		if ($type < 0) return -1;
485
486		if ($this->brouillon) {
487			// Clean parameters
488			$remise_percent = price2num($remise_percent);
489			$qty = price2num($qty);
490			if (!$qty) $qty = 1;
491			if (!$info_bits) $info_bits = 0;
492			$pu_ht = price2num($pu_ht);
493			$pu_ttc = price2num($pu_ttc);
494			if (!preg_match('/\((.*)\)/', $txtva)) {
495				$txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
496			}
497
498			if ($price_base_type == 'HT') {
499				$pu = $pu_ht;
500			} else {
501				$pu = $pu_ttc;
502			}
503
504			// Calcul du total TTC et de la TVA pour la ligne a partir de
505			// qty, pu, remise_percent et txtva
506			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
507			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
508			$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, 0, 0, 0, $price_base_type, $info_bits, $type, $mysoc);
509
510			$total_ht  = $tabprice[0];
511			$total_tva = $tabprice[1];
512			$total_ttc = $tabprice[2];
513
514			$product_type = $type;
515			if ($fk_product) {
516				$product = new Product($this->db);
517				$result = $product->fetch($fk_product);
518				$product_type = $product->type;
519			}
520
521			$sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinterdet_rec (";
522			$sql .= "fk_fichinter";
523			$sql .= ", label";
524			$sql .= ", description";
525			$sql .= ", date";
526			$sql .= ", duree";
527			//$sql.= ", price";
528			//$sql.= ", qty";
529			//$sql.= ", tva_tx";
530			$sql .= ", fk_product";
531			$sql .= ", product_type";
532			$sql .= ", remise_percent";
533			//$sql.= ", subprice";
534			$sql .= ", remise";
535			$sql .= ", total_ht";
536			$sql .= ", total_tva";
537			$sql .= ", total_ttc";
538			$sql .= ", rang";
539			//$sql.= ", special_code";
540			$sql .= ", fk_unit";
541			$sql .= ") VALUES (";
542			$sql .= (int) $this->id;
543			$sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
544			$sql .= ", ".(!empty($desc) ? "'".$this->db->escape($desc)."'" : "null");
545			$sql .= ", ".(!empty($datei) ? "'".$this->db->idate($datei)."'" : "null");
546			$sql .= ", ".$duration;
547			//$sql.= ", ".price2num($pu_ht);
548			//$sql.= ", ".(!empty($qty)? $qty :(!empty($duration)? $duration :"null"));
549			//$sql.= ", ".price2num($txtva);
550			$sql .= ", ".(!empty($fk_product) ? $fk_product : "null");
551			$sql .= ", ".$product_type;
552			$sql .= ", ".(!empty($remise_percent) ? $remise_percent : "null");
553			//$sql.= ", '".price2num($pu_ht)."'";
554			$sql .= ", null";
555			$sql .= ", '".price2num($total_ht)."'";
556			$sql .= ", '".price2num($total_tva)."'";
557			$sql .= ", '".price2num($total_ttc)."'";
558			$sql .= ", ".(int) $rang;
559			//$sql.= ", ".$special_code;
560			$sql .= ", ".(!empty($fk_unit) ? $fk_unit : "null");
561			$sql .= ")";
562
563			dol_syslog(get_class($this)."::addline", LOG_DEBUG);
564			if ($this->db->query($sql)) {
565				return 1;
566			} else {
567				$this->error = $this->db->lasterror();
568				return -1;
569			}
570		}
571	}
572
573
574	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
575	/**
576	 *	Rend la fichinter automatique
577	 *
578	 *	@param		User	$user		User object
579	 *	@param		int		$freq		Freq
580	 *	@param		string	$courant	Courant
581	 *	@return		int					0 if OK, <0 if KO
582	 */
583	public function set_auto($user, $freq, $courant)
584	{
585		// phpcs:enable
586		if ($user->rights->fichinter->creer) {
587			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter_rec ";
588			$sql .= " SET frequency='".$this->db->escape($freq)."'";
589			$sql .= ", date_last_gen='".$this->db->escape($courant)."'";
590			$sql .= " WHERE rowid = ".$this->id;
591
592			$resql = $this->db->query($sql);
593
594			if ($resql) {
595				$this->frequency = $freq;
596				$this->date_last_gen = $courant;
597				return 0;
598			} else {
599				dol_print_error($this->db);
600				return -1;
601			}
602		} else {
603			return -2;
604		}
605	}
606
607	/**
608	 *  Return clicable name (with picto eventually)
609	 *
610	 *  @param	int		$withpicto      Add picto into link
611	 *  @param  string	$option		    Where point the link
612	 *  @param  int		$max			Maxlength of ref
613	 *  @param  int		$short		    1=Return just URL
614	 *  @param  string   $moretitle     Add more text to title tooltip
615	 *  @return string 					String with URL
616	 */
617	public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '')
618	{
619		global $langs;
620
621		$result = '';
622		$label = $langs->trans("ShowInterventionModel").': '.$this->ref;
623
624		$url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id;
625
626		if ($short) return $url;
627
628		$picto = 'intervention';
629
630		$link = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
631		$linkend = '</a>';
632
633		if ($withpicto) {
634			$result .= $link.img_object($label, $picto, 'class="classfortooltip"').$linkend;
635		}
636		if ($withpicto && $withpicto != 2) {
637			$result .= ' ';
638		}
639		if ($withpicto != 2) {
640			$result .= $link.$this->ref.$linkend;
641		}
642		return $result;
643	}
644
645
646	/**
647	 *  Initialise an instance with random values.
648	 *  Used to build previews or test instances.
649	 *	id must be 0 if object instance is a specimen.
650	 *
651	 *	@param	string		$option		''=Create a specimen fichinter with lines, 'nolines'=No lines
652	 *  @return	void
653	 */
654	public function initAsSpecimen($option = '')
655	{
656		global $user, $langs, $conf;
657
658		$now = dol_now();
659		$arraynow = dol_getdate($now);
660		$nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
661
662		parent::initAsSpecimen($option);
663
664		$this->usenewprice = 1;
665	}
666
667	/**
668	 * Function used to replace a thirdparty id with another one.
669	 *
670	 * @param DoliDB $db Database handler
671	 * @param int $origin_id Old thirdparty id
672	 * @param int $dest_id New thirdparty id
673	 * @return bool
674	 */
675	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
676	{
677		$tables = array('fichinter_rec');
678
679		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
680	}
681
682
683	/**
684	 *	Update frequency and unit
685	 *
686	 *	@param	 	int		$frequency		value of frequency
687	 *	@param	 	string	$unit 			unit of frequency  (d, m, y)
688	 *	@return		int						<0 if KO, >0 if OK
689	 */
690	public function setFrequencyAndUnit($frequency, $unit)
691	{
692		if (!$this->table_element) {
693			dol_syslog(get_class($this)."::setFrequencyAndUnit called with table_element not defined", LOG_ERR);
694			return -1;
695		}
696
697		if (!empty($frequency) && empty($unit)) {
698			dol_syslog(get_class($this)."::setFrequencyAndUnit called with frequency defined but unit not ", LOG_ERR);
699			return -2;
700		}
701
702		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
703		$sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null');
704		if (!empty($unit)) {
705			$sql .= ', unit_frequency = "'.$this->db->escape($unit).'"';
706		}
707		$sql .= ' WHERE rowid = '.$this->id;
708
709		dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
710		if ($this->db->query($sql)) {
711			$this->frequency = $frequency;
712			if (!empty($unit)) $this->unit_frequency = $unit;
713			return 1;
714		} else {
715			dol_print_error($this->db);
716			return -1;
717		}
718	}
719
720	/**
721	 *	Update the next date of execution
722	 *
723	 *	@param	 	datetime	$date					date of execution
724	 *	@param	 	int			$increment_nb_gen_done	0 do nothing more, >0 increment nb_gen_done
725	 *	@return		int									<0 if KO, >0 if OK
726	 */
727	public function setNextDate($date, $increment_nb_gen_done = 0)
728	{
729		if (!$this->table_element) {
730			dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR);
731			return -1;
732		}
733		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
734		$sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
735		if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1';
736		$sql .= ' WHERE rowid = '.$this->id;
737
738		dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
739		if ($this->db->query($sql)) {
740			$this->date_when = $date;
741			if ($increment_nb_gen_done > 0) $this->nb_gen_done++;
742			return 1;
743		} else {
744			dol_print_error($this->db);
745			return -1;
746		}
747	}
748
749	/**
750	 *	Update the maximum period
751	 *
752	 *	@param	 	int		$nb		number of maximum period
753	 *	@return		int				<0 if KO, >0 if OK
754	 */
755	public function setMaxPeriod($nb)
756	{
757		if (!$this->table_element) {
758			dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR);
759			return -1;
760		}
761
762		if (empty($nb)) $nb = 0;
763
764		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
765		$sql .= ' SET nb_gen_max = '.$nb;
766		$sql .= ' WHERE rowid = '.$this->id;
767
768		dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
769		if ($this->db->query($sql)) {
770			$this->nb_gen_max = $nb;
771			return 1;
772		} else {
773			dol_print_error($this->db);
774			return -1;
775		}
776	}
777
778	/**
779	 *	Update the auto validate fichinter
780	 *
781	 *	@param	 	int		$validate		0 to create in draft, 1 to create and validate fichinter
782	 *	@return		int						<0 if KO, >0 if OK
783	 */
784	public function setAutoValidate($validate)
785	{
786		if (!$this->table_element) {
787			dol_syslog(get_class($this)."::setAutoValidate called with property table_element not defined", LOG_ERR);
788			return -1;
789		}
790
791		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
792		$sql .= ' SET auto_validate = '.$validate;
793		$sql .= ' WHERE rowid = '.$this->id;
794
795		dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
796		if ($this->db->query($sql)) {
797			$this->auto_validate = $validate;
798			return 1;
799		} else {
800			dol_print_error($this->db);
801			return -1;
802		}
803	}
804
805	/**
806	 *	Update the Number of Generation Done
807	 *
808	 *	@return		int						<0 if KO, >0 if OK
809	 */
810	public function updateNbGenDone()
811	{
812		if (!$this->table_element) {
813			dol_syslog(get_class($this)."::updateNbGenDone called with property table_element not defined", LOG_ERR);
814			return -1;
815		}
816
817		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
818		$sql .= ' SET nb_gen_done = nb_gen_done + 1';
819		$sql .= ' , date_last_gen = now()';
820		// si on et arrivé à la fin des génération
821		if ($this->nb_gen_max == $this->nb_gen_done + 1)
822			$sql .= ' , statut = 1';
823
824		$sql .= ' WHERE rowid = '.$this->id;
825
826		dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
827		if ($this->db->query($sql)) {
828			$this->nb_gen_done = $this->nb_gen_done + 1;
829			$this->nb_gen_done = dol_now();
830			return 1;
831		} else {
832			dol_print_error($this->db);
833			return -1;
834		}
835	}
836}
837