Completed
Branch develop (f8a444)
by
unknown
32:44
created

Fichinter::delete()   F

Complexity

Conditions 22
Paths 7291

Size

Total Lines 103
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 51
nc 7291
nop 2
dl 0
loc 103
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2002-2003 Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2004-2014 Laurent Destailleur  <[email protected]>
4
 * Copyright (C) 2005-2012 Regis Houssin        <[email protected]>
5
 * Copyright (C) 2011-2013 Juanjo Menent        <[email protected]>
6
 * Copyright (C) 2015      Marcos García        <[email protected]>
7
 * Copyright (C) 2015      Charlie Benke        <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
/**
24
 * 	\file       htdocs/fichinter/class/fichinter.class.php
25
 * 	\ingroup    ficheinter
26
 * 	\brief      Fichier de la classe des gestion des fiches interventions
27
 */
28
require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
29
require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php';
30
31
32
/**
33
 *	Class to manage interventions
34
 */
35
class Fichinter extends CommonObject
36
{
37
	public $element='fichinter';
38
	public $table_element='fichinter';
39
	public $fk_element='fk_fichinter';
40
	public $table_element_line='fichinterdet';
41
	public $picto = 'intervention';
42
43
	/**
44
	 * {@inheritdoc}
45
	 */
46
	protected $table_ref_field = 'ref';
47
48
	var $socid;		// Id client
49
50
	var $author;
51
	var $datec;
52
	var $datev;
53
	var $dateo;
54
	var $datee;
55
	var $datet;
56
	var $datem;
57
	var $duration;
58
	var $statut;		// 0=draft, 1=validated, 2=invoiced, 3=Terminate
59
	var $description;
60
	var $fk_contrat;
61
	var $extraparams=array();
62
63
	var $lines = array();
64
65
	/**
66
	 * Draft status
67
	 */
68
	const STATUS_DRAFT = 0;
69
	/**
70
	 * Validated status
71
	 */
72
	const STATUS_VALIDATED = 1;
73
	/**
74
	 * Billed
75
	 */
76
	const STATUS_BILLED = 2;
77
	/**
78
	 * Closed
79
	 */
80
	const STATUS_CLOSED = 3;
81
82
	/**
83
	 *	Constructor
84
	 *
85
	 *  @param	DoliDB	$db		Database handler
86
	 */
87
	function __construct($db)
88
	{
89
		$this->db = $db;
90
		$this->products = array();
91
		$this->fk_project = 0;
92
		$this->fk_contrat = 0;
93
		$this->statut = 0;
94
95
		// List of language codes for status
96
		$this->statuts[0]='Draft';
97
		$this->statuts[1]='Validated';
98
		$this->statuts[2]='StatusInterInvoiced';
99
		$this->statuts[3]='Done';
100
		$this->statuts_short[0]='Draft';
101
		$this->statuts_short[1]='Validated';
102
		$this->statuts_short[2]='StatusInterInvoiced';
103
		$this->statuts_short[3]='Done';
104
		$this->statuts_logo[0]='statut0';
105
		$this->statuts_logo[1]='statut1';
106
		$this->statuts_logo[2]='statut6';
107
		$this->statuts_logo[3]='statut6';
108
	}
109
110
	/**
111
	 *  Load indicators into this->nb for board
112
	 *
113
	 *  @return     int         <0 if KO, >0 if OK
114
	 */
115
	function load_state_board()
116
	{
117
		global $user;
118
119
		$this->nb=array();
120
		$clause = "WHERE";
121
122
		$sql = "SELECT count(fi.rowid) as nb";
123
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as fi";
124
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON fi.fk_soc = s.rowid";
125
		if (!$user->rights->societe->client->voir && !$user->societe_id)
126
		{
127
			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
128
			$sql.= " WHERE sc.fk_user = " .$user->id;
129
			$clause = "AND";
130
		}
131
		$sql.= " ".$clause." fi.entity IN (".getEntity($this->element, 1).")";
132
133
		$resql=$this->db->query($sql);
134
		if ($resql)
135
		{
136
			while ($obj=$this->db->fetch_object($resql))
137
			{
138
				$this->nb["fichinters"]=$obj->nb;
139
			}
140
			$this->db->free($resql);
141
			return 1;
142
		}
143
		else
144
		{
145
			dol_print_error($this->db);
146
			$this->error=$this->db->error();
147
			return -1;
148
		}
149
	}
150
151
	/**
152
	 *	Create an intervention into data base
153
	 *
154
	 *  @param		User	$user 		Objet user that make creation
155
	 *	@param		int		$notrigger	Disable all triggers
156
	 *	@return		int		<0 if KO, >0 if OK
157
	 */
158
	function create($user, $notrigger=0)
159
	{
160
		global $conf, $user, $langs;
161
162
		dol_syslog(get_class($this)."::create ref=".$this->ref);
163
164
		// Check parameters
165
		if (! empty($this->ref))	// We check that ref is not already used
166
		{
167
			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
168
			if ($result > 0)
169
			{
170
				$this->error='ErrorRefAlreadyExists';
171
				dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
172
				$this->db->rollback();
173
				return -1;
174
			}
175
		}
176
		if (! is_numeric($this->duration)) $this->duration = 0;
177
178
		if ($this->socid <= 0)
179
		{
180
			$this->error='ErrorBadParameterForFunc';
181
			dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR);
182
			return -1;
183
		}
184
185
		$soc = new Societe($this->db);
186
		$result=$soc->fetch($this->socid);
187
188
		$now=dol_now();
189
190
		$this->db->begin();
191
192
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter (";
193
		$sql.= "fk_soc";
194
		$sql.= ", datec";
195
		$sql.= ", ref";
196
		$sql.= ", entity";
197
		$sql.= ", fk_user_author";
198
		$sql.= ", fk_user_modif";
199
		$sql.= ", description";
200
		$sql.= ", model_pdf";
201
		$sql.= ", fk_projet";
202
		$sql.= ", fk_contrat";
203
		$sql.= ", fk_statut";
204
		$sql.= ", note_private";
205
		$sql.= ", note_public";
206
		$sql.= ") ";
207
		$sql.= " VALUES (";
208
		$sql.= $this->socid;
209
		$sql.= ", '".$this->db->idate($now)."'";
210
		$sql.= ", '".$this->db->escape($this->ref)."'";
211
		$sql.= ", ".$conf->entity;
212
		$sql.= ", ".$user->id;
213
		$sql.= ", ".$user->id;
214
		$sql.= ", ".($this->description?"'".$this->db->escape($this->description)."'":"null");
215
		$sql.= ", '".$this->db->escape($this->modelpdf)."'";
216
		$sql.= ", ".($this->fk_project ? $this->fk_project : 0);
217
		$sql.= ", ".($this->fk_contrat ? $this->fk_contrat : 0);
218
		$sql.= ", ".$this->statut;
219
		$sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
220
		$sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
221
		$sql.= ")";
222
223
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
224
		$result=$this->db->query($sql);
225
		if ($result)
226
		{
227
			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."fichinter");
228
229
			if ($this->id)
230
			{
231
				$this->ref='(PROV'.$this->id.')';
232
				$sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
233
234
				dol_syslog(get_class($this)."::create", LOG_DEBUG);
235
				$resql=$this->db->query($sql);
236
				if (! $resql) $error++;
0 ignored issues
show
Bug introduced by
The variable $error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
237
			}
238
239
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
240
			{
241
				$result=$this->insertExtraFields();
242
				if ($result < 0)
243
				{
244
					$error++;
245
				}
246
			}
247
248
			// Add linked object
249
			if (! $error && $this->origin && $this->origin_id)
250
			{
251
				$ret = $this->add_object_linked();
252
				if (! $ret)	dol_print_error($this->db);
253
			}
254
255
256
			if (! $notrigger)
257
			{
258
				// Call trigger
259
				$result=$this->call_trigger('FICHINTER_CREATE',$user);
260
				if ($result < 0) { $error++; }
261
				// End call triggers
262
			}
263
264
			if (! $error)
265
			{
266
				$this->db->commit();
267
				return $this->id;
268
			}
269
			else
270
			{
271
				$this->db->rollback();
272
				$this->error=join(',',$this->errors);
273
				dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR);
274
				return -1;
275
			}
276
		}
277
		else
278
		{
279
			$this->error=$this->db->error();
280
			$this->db->rollback();
281
			return -1;
282
		}
283
284
	}
285
286
	/**
287
	 *	Update an intervention
288
	 *
289
	 *	@param		User	$user 		Objet user that make creation
290
	 *	@param		int		$notrigger	Disable all triggers
291
	 *	@return		int		<0 if KO, >0 if OK
292
	 */
293
	function update($user, $notrigger=0)
294
	{
295
	 	if (! is_numeric($this->duration)) {
296
	 		$this->duration = 0;
297
	 	}
298
	 	if (! dol_strlen($this->fk_project)) {
299
	 		$this->fk_project = 0;
300
	 	}
301
302
		$this->db->begin();
303
304
		$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter SET ";
305
		$sql.= "description  = '".$this->db->escape($this->description)."'";
306
		$sql.= ", duree = ".$this->duration;
307
		$sql.= ", fk_projet = ".$this->fk_project;
308
		$sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
309
		$sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
310
		$sql.= ", fk_user_modif = ".$user->id;
311
		$sql.= " WHERE rowid = ".$this->id;
312
313
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
314
		if ($this->db->query($sql))
315
		{
316
317
			if (! $notrigger)
318
			{
319
				// Call trigger
320
				$result=$this->call_trigger('FICHINTER_MODIFY',$user);
321
				if ($result < 0) { $error++; $this->db->rollback(); return -1; }
0 ignored issues
show
Bug introduced by
The variable $error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
322
				// End call triggers
323
			}
324
325
			$this->db->commit();
326
			return 1;
327
		}
328
		else
329
		{
330
			$this->error=$this->db->error();
331
			$this->db->rollback();
332
			return -1;
333
		}
334
	}
335
336
	/**
337
	 *	Fetch a intervention
338
	 *
339
	 *	@param		int		$rowid		Id of intervention
340
	 *	@param		string	$ref		Ref of intervention
341
	 *	@return		int					<0 if KO, >0 if OK
342
	 */
343
	function fetch($rowid,$ref='')
344
	{
345
		$sql = "SELECT f.rowid, f.ref, f.description, f.fk_soc, f.fk_statut,";
346
		$sql.= " f.datec, f.dateo, f.datee, f.datet, f.fk_user_author,";
347
		$sql.= " f.date_valid as datev,";
348
		$sql.= " f.tms as datem,";
349
		$sql.= " f.duree, f.fk_projet, f.note_public, f.note_private, f.model_pdf, f.extraparams, fk_contrat";
350
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f";
351
		if ($ref) $sql.= " WHERE f.ref='".$this->db->escape($ref)."'";
352
		else $sql.= " WHERE f.rowid=".$rowid;
353
354
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
355
		$resql=$this->db->query($sql);
356
		if ($resql)
357
		{
358
			if ($this->db->num_rows($resql))
359
			{
360
				$obj = $this->db->fetch_object($resql);
361
362
				$this->id           = $obj->rowid;
363
				$this->ref          = $obj->ref;
364
				$this->description  = $obj->description;
365
				$this->socid        = $obj->fk_soc;
366
				$this->statut       = $obj->fk_statut;
367
				$this->duration     = $obj->duree;
368
				$this->datec        = $this->db->jdate($obj->datec);
369
				$this->datee        = $this->db->jdate($obj->dateo);
370
				$this->dateo        = $this->db->jdate($obj->datee);
371
				$this->datet        = $this->db->jdate($obj->datet);
372
				$this->datev        = $this->db->jdate($obj->datev);
373
				$this->datem        = $this->db->jdate($obj->datem);
374
				$this->fk_project   = $obj->fk_projet;
375
				$this->note_public  = $obj->note_public;
376
				$this->note_private = $obj->note_private;
377
				$this->modelpdf     = $obj->model_pdf;
378
				$this->fk_contrat	= $obj->fk_contrat;
379
380
				$this->user_creation= $obj->fk_user_author;
381
382
				$this->extraparams	= (array) json_decode($obj->extraparams, true);
383
384
				if ($this->statut == 0) $this->brouillon = 1;
385
386
				require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
387
				$extrafields=new ExtraFields($this->db);
388
				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
389
				$this->fetch_optionals($this->id,$extralabels);
390
391
				/*
392
				 * Lines
393
				*/
394
				$result=$this->fetch_lines();
395
				if ($result < 0)
396
				{
397
					return -3;
398
				}
399
				$this->db->free($resql);
400
				return 1;
401
			}
402
		}
403
		else
404
		{
405
			$this->error=$this->db->lasterror();
406
			return -1;
407
		}
408
	}
409
410
	/**
411
	 *	Set status to draft
412
	 *
413
	 *	@param		User	$user	User that set draft
414
	 *	@return		int			<0 if KO, >0 if OK
415
	 */
416
	function setDraft($user)
417
	{
418
		global $langs, $conf;
419
420
		if ($this->statut != 0)
421
		{
422
			$this->db->begin();
423
424
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
425
			$sql.= " SET fk_statut = 0";
426
			$sql.= " WHERE rowid = ".$this->id;
427
			$sql.= " AND entity = ".$conf->entity;
428
429
			dol_syslog("Fichinter::setDraft", LOG_DEBUG);
430
			$resql=$this->db->query($sql);
431
			if ($resql)
432
			{
433
				$this->db->commit();
434
				return 1;
435
			}
436
			else
437
			{
438
				$this->db->rollback();
439
				$this->error=$this->db->lasterror();
440
				return -1;
441
			}
442
		}
443
	}
444
445
	/**
446
	 *	Validate a intervention
447
	 *
448
	 *	@param		User		$user		User that validate
449
	 *  @param		int			$notrigger	1=Does not execute triggers, 0= execute triggers
450
	 *	@return		int						<0 if KO, >0 if OK
451
	 */
452
	function setValid($user, $notrigger=0)
453
	{
454
		global $conf;
455
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
456
457
		$error=0;
458
459
		if ($this->statut != 1)
460
		{
461
			$this->db->begin();
462
463
			$now=dol_now();
464
465
			// Define new ref
466
			if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
467
			{
468
				$num = $this->getNextNumRef($this->thirdparty);
469
			}
470
			else
471
			{
472
				$num = $this->ref;
473
			}
474
			$this->newref = $num;
475
476
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
477
			$sql.= " SET fk_statut = 1";
478
			$sql.= ", ref = '".$num."'";
479
			$sql.= ", date_valid = '".$this->db->idate($now)."'";
480
			$sql.= ", fk_user_valid = ".$user->id;
481
			$sql.= " WHERE rowid = ".$this->id;
482
			$sql.= " AND entity = ".$conf->entity;
483
			$sql.= " AND fk_statut = 0";
484
485
			dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
486
			$resql=$this->db->query($sql);
487
			if (! $resql)
488
			{
489
				dol_print_error($this->db);
490
				$error++;
491
			}
492
493
			if (! $error && ! $notrigger)
494
			{
495
				// Call trigger
496
				$result=$this->call_trigger('FICHINTER_VALIDATE',$user);
497
				if ($result < 0) { $error++; }
498
				// End call triggers
499
			}
500
501
			if (! $error)
502
			{
503
				$this->oldref = $this->ref;
504
505
				// Rename directory if dir was a temporary ref
506
				if (preg_match('/^[\(]?PROV/i', $this->ref))
507
				{
508
					// Rename of object directory ($this->ref = old ref, $num = new ref)
509
					// to  not lose the linked files
510
					$oldref = dol_sanitizeFileName($this->ref);
511
					$newref = dol_sanitizeFileName($num);
512
					$dirsource = $conf->ficheinter->dir_output.'/'.$oldref;
513
					$dirdest = $conf->ficheinter->dir_output.'/'.$newref;
514
					if (file_exists($dirsource))
515
					{
516
						dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest);
517
518
						if (@rename($dirsource, $dirdest))
519
						{
520
							dol_syslog("Rename ok");
521
							// Rename docs starting with $oldref with $newref
522
							$listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
523
							foreach($listoffiles as $fileentry)
524
							{
525
								$dirsource=$fileentry['name'];
526
								$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
527
								$dirsource=$fileentry['path'].'/'.$dirsource;
528
								$dirdest=$fileentry['path'].'/'.$dirdest;
529
								@rename($dirsource, $dirdest);
530
							}
531
						}
532
					}
533
				}
534
			}
535
536
			// Set new ref and define current statut
537
			if (! $error)
538
			{
539
				$this->ref = $num;
540
				$this->statut=1;
541
				$this->brouillon=0;
542
				$this->date_validation=$now;
543
			}
544
545
			if (! $error)
546
			{
547
				$this->db->commit();
548
				return 1;
549
			}
550
			else
551
			{
552
				$this->db->rollback();
553
				dol_syslog(get_class($this)."::setValid ".$this->error,LOG_ERR);
554
				return -1;
555
			}
556
		}
557
	}
558
559
	/**
560
	 *	Returns amount based on user thm
561
	 *
562
	 *	@return     float 		Amount
563
	 */
564
	function getAmount()
565
	{
566
		global $db;
567
568
		$amount = 0;
569
570
		$this->author = new User($db);
571
		$this->author->fetch($this->user_creation);
572
573
		$thm = $this->author->thm;
574
575
		foreach($this->lines as $line) {
576
			$amount += ($line->duration / 60 / 60 * $thm);
577
		}
578
579
		return price2num($amount, 'MT');
580
	}
581
582
583
	/**
584
	 *  Create a document onto disk according to template module.
585
	 *
586
	 *  @param      string                  $modele         Force model to use ('' to not force)
587
	 *  @param      Translate               $outputlangs    Object langs to use for output
588
	 *  @param      int                     $hidedetails    Hide details of lines
589
	 *  @param      int                     $hidedesc       Hide description
590
	 *  @param      int                     $hideref        Hide ref
591
	 *  @return     int                                     0 if KO, 1 if OK
592
	 */
593
	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
594
	{
595
		global $conf,$langs;
596
597
		$langs->load("interventions");
598
599
		if (! dol_strlen($modele)) {
600
601
			$modele = 'soleil';
602
603
			if ($this->modelpdf) {
604
				$modele = $this->modelpdf;
605
			} elseif (! empty($conf->global->FICHEINTER_ADDON_PDF)) {
606
				$modele = $conf->global->FICHEINTER_ADDON_PDF;
607
			}
608
		}
609
610
		$modelpath = "core/modules/fichinter/doc/";
611
612
		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
613
	}
614
615
	/**
616
	 *	Returns the label status
617
	 *
618
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
619
	 *	@return     string      		Label
620
	 */
621
	function getLibStatut($mode=0)
622
	{
623
		return $this->LibStatut($this->statut,$mode);
624
	}
625
626
	/**
627
	 *	Returns the label of a statut
628
	 *
629
	 *	@param      int		$statut     id statut
630
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
631
	 *	@return     string      		Label
632
	 */
633
	function LibStatut($statut,$mode=0)
634
	{
635
		global $langs;
636
637
		if ($mode == 0)
638
			return $langs->trans($this->statuts[$statut]);
639
		if ($mode == 1)
640
			return $langs->trans($this->statuts_short[$statut]);
641
		if ($mode == 2)
642
			return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]).' '.$langs->trans($this->statuts_short[$statut]);
643
		if ($mode == 3)
644
			return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]);
645
		if ($mode == 4)
646
			return img_picto($langs->trans($this->statuts_short[$statut]),$this->statuts_logo[$statut]).' '.$langs->trans($this->statuts[$statut]);
647
		if ($mode == 5)
648
			return '<span class="hideonsmartphone">'.$langs->trans($this->statuts_short[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]);
649
		if ($mode == 6)
650
			return '<span class="hideonsmartphone">'.$langs->trans($this->statuts[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]);
651
652
		return '';
653
	}
654
655
	/**
656
	 *	Return clicable name (with picto eventually)
657
	 *
658
	 *	@param		int		$withpicto					0=_No picto, 1=Includes the picto in the linkn, 2=Picto only
659
	 *	@param		string	$option						Options
660
	 *  @param	    int   	$notooltip					1=Disable tooltip
661
	 *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
662
	 *	@return		string								String with URL
663
	 */
664
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
665
	{
666
		global $conf, $langs;
667
668
		$result='';
669
670
		$label = '<u>' . $langs->trans("ShowIntervention") . '</u>';
671
		if (! empty($this->ref))
672
			$label .= '<br><b>' . $langs->trans('Ref') . ':</b> '.$this->ref;
673
674
		$url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id;
675
676
		if ($option !== 'nolink')
677
		{
678
			// Add param to save lastsearch_values or not
679
			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
680
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
681
			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
682
	   	}
683
684
		$linkclose='';
685
		if (empty($notooltip))
686
		{
687
			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
688
			{
689
				$label=$langs->trans("ShowIntervention");
690
				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
691
			}
692
			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
693
			$linkclose.=' class="classfortooltip"';
694
		}
695
696
		$linkstart = '<a href="'.$url.'"';
697
		$linkstart.=$linkclose.'>';
698
		$linkend='</a>';
699
700
		$result .= $linkstart;
701
		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
702
		if ($withpicto != 2) $result.= $this->ref;
703
		$result .= $linkend;
704
705
		return $result;
706
	}
707
708
709
	/**
710
	 *	Returns the next non used reference of intervention
711
	 *	depending on the module numbering assets within FICHEINTER_ADDON
712
	 *
713
	 *	@param	    Societe		$soc		Thirdparty object
714
	 *	@return     string					Free reference for intervention
715
	 */
716
	function getNextNumRef($soc)
717
	{
718
		global $conf, $db, $langs;
719
		$langs->load("interventions");
720
721
		if (! empty($conf->global->FICHEINTER_ADDON))
722
		{
723
			$mybool = false;
724
725
			$file = "mod_".$conf->global->FICHEINTER_ADDON.".php";
726
			$classname = "mod_".$conf->global->FICHEINTER_ADDON;
727
728
			// Include file with class
729
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
730
731
			foreach ($dirmodels as $reldir) {
732
733
				$dir = dol_buildpath($reldir."core/modules/fichinter/");
734
735
				// Load file with numbering class (if found)
736
				$mybool|=@include_once $dir.$file;
737
			}
738
739
			if (! $mybool)
740
			{
741
				dol_print_error('',"Failed to include file ".$file);
742
				return '';
743
			}
744
745
			$obj = new $classname();
746
			$numref = "";
747
			$numref = $obj->getNextValue($soc,$this);
748
749
			if ( $numref != "")
750
			{
751
				return $numref;
752
			}
753
			else
754
			{
755
				dol_print_error($db,"Fichinter::getNextNumRef ".$obj->error);
756
				return "";
757
			}
758
		}
759
		else
760
		{
761
			$langs->load("errors");
762
			print $langs->trans("Error")." ".$langs->trans("Error_FICHEINTER_ADDON_NotDefined");
763
			return "";
764
		}
765
	}
766
767
	/**
768
	 * 	Load information on object
769
	 *
770
	 *	@param	int		$id      Id of object
771
	 *	@return	void
772
	 */
773
	function info($id)
774
	{
775
		global $conf;
776
777
		$sql = "SELECT f.rowid,";
778
		$sql.= " f.datec,";
779
		$sql.= " f.tms as date_modification,";
780
		$sql.= " f.date_valid as datev,";
781
		$sql.= " f.fk_user_author,";
782
		$sql.= " f.fk_user_modif as fk_user_modification,";
783
		$sql.= " f.fk_user_valid";
784
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f";
785
		$sql.= " WHERE f.rowid = ".$id;
786
		$sql.= " AND f.entity = ".$conf->entity;
787
788
		$resql = $this->db->query($sql);
789
		if ($resql)
790
		{
791
			if ($this->db->num_rows($resql))
792
			{
793
				$obj = $this->db->fetch_object($resql);
794
795
				$this->id                = $obj->rowid;
796
797
				$this->date_creation     = $this->db->jdate($obj->datec);
798
				$this->date_modification = $this->db->jdate($obj->date_modification);
799
				$this->date_validation   = $this->db->jdate($obj->datev);
800
801
				$cuser = new User($this->db);
802
				$cuser->fetch($obj->fk_user_author);
803
				$this->user_creation     = $cuser;
804
805
				if ($obj->fk_user_valid)
806
				{
807
					$vuser = new User($this->db);
808
					$vuser->fetch($obj->fk_user_valid);
809
					$this->user_validation     = $vuser;
810
				}
811
				if ($obj->fk_user_modification)
812
				{
813
					$muser = new User($this->db);
814
					$muser->fetch($obj->fk_user_modification);
815
					$this->user_modification   = $muser;
816
				}
817
818
			}
819
			$this->db->free($resql);
820
		}
821
		else
822
		{
823
			dol_print_error($this->db);
824
		}
825
	}
826
827
	/**
828
	 *	Delete intervetnion
829
	 *
830
	 *	@param      User	$user			Object user who delete
831
	 *	@param		int		$notrigger		Disable trigger
832
	 *	@return		int						<0 if KO, >0 if OK
833
	 */
834
	function delete($user, $notrigger=0)
835
	{
836
		global $conf,$langs;
837
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
838
839
		$error=0;
840
841
		$this->db->begin();
842
843
		if (! $error && ! $notrigger)
844
		{
845
			// Call trigger
846
			$result=$this->call_trigger('FICHINTER_DELETE',$user);
847
			if ($result < 0) { $error++; $this->db->rollback(); return -1; }
848
			// End call triggers
849
		}
850
851
		// Delete linked object
852
		if (! $error)
853
		{
854
			$res = $this->deleteObjectLinked();
855
			if ($res < 0) $error++;
856
		}
857
858
		// Delete linked contacts
859
		if (! $error)
860
		{
861
			$res = $this->delete_linked_contact();
862
			if ($res < 0)
863
			{
864
				$this->error='ErrorFailToDeleteLinkedContact';
865
				$error++;
866
			}
867
		}
868
869
		if (! $error)
870
		{
871
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet";
872
			$sql.= " WHERE fk_fichinter = ".$this->id;
873
874
			$resql = $this->db->query($sql);
875
			if (! $resql) $error++;
876
		}
877
878
		if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
879
		{
880
			// Remove extrafields
881
			$res = $this->deleteExtraFields();
882
			if ($res < 0) $error++;
883
		}
884
885
		if (! $error)
886
		{
887
			// Delete object
888
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter";
889
			$sql.= " WHERE rowid = ".$this->id;
890
			$sql.= " AND entity = ".$conf->entity;
891
892
			dol_syslog("Fichinter::delete", LOG_DEBUG);
893
			$resql = $this->db->query($sql);
894
			if (! $resql) $error++;
895
		}
896
897
		if (! $error)
898
		{
899
			// Remove directory with files
900
			$fichinterref = dol_sanitizeFileName($this->ref);
901
			if ($conf->ficheinter->dir_output)
902
			{
903
				$dir = $conf->ficheinter->dir_output . "/" . $fichinterref ;
904
				$file = $conf->ficheinter->dir_output . "/" . $fichinterref . "/" . $fichinterref . ".pdf";
905
				if (file_exists($file))
906
				{
907
					dol_delete_preview($this);
908
909
					if (! dol_delete_file($file,0,0,0,$this)) // For triggers
910
					{
911
						$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
912
						return 0;
913
					}
914
				}
915
				if (file_exists($dir))
916
				{
917
					if (! dol_delete_dir_recursive($dir))
918
					{
919
						$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
920
						return 0;
921
					}
922
				}
923
			}
924
		}
925
926
		if (! $error)
927
		{
928
			$this->db->commit();
929
			return 1;
930
		}
931
		else
932
		{
933
			$this->db->rollback();
934
			return -1;
935
		}
936
	}
937
938
	/**
939
	 *	Defines a delivery date of intervention
940
	 *
941
	 *	@param      User	$user				Object user who define
942
	 *	@param      date	$date_delivery   	date of delivery
943
	 *	@return     int							<0 if ko, >0 if ok
944
	 */
945
	function set_date_delivery($user, $date_delivery)
946
	{
947
		global $conf;
948
949
		if ($user->rights->ficheinter->creer)
950
		{
951
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
952
			$sql.= " SET datei = '".$this->db->idate($date_delivery)."'";
953
			$sql.= " WHERE rowid = ".$this->id;
954
			$sql.= " AND entity = ".$conf->entity;
955
			$sql.= " AND fk_statut = 0";
956
957
			if ($this->db->query($sql))
958
			{
959
				$this->date_delivery = $date_delivery;
960
				return 1;
961
			}
962
			else
963
			{
964
				$this->error=$this->db->error();
965
				dol_syslog("Fichinter::set_date_delivery Erreur SQL");
966
				return -1;
967
			}
968
		}
969
	}
970
971
	/**
972
	 *	Define the label of the intervention
973
	 *
974
	 *	@param      User	$user			Object user who modify
975
	 *	@param      string	$description    description
976
	 *	@return     int						<0 if KO, >0 if OK
977
	 */
978
	function set_description($user, $description)
979
	{
980
		global $conf;
981
982
		if ($user->rights->ficheinter->creer)
983
		{
984
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
985
			$sql.= " SET description = '".$this->db->escape($description)."',";
986
			$sql.= " fk_user_modif = ".$user->id;
987
			$sql.= " WHERE rowid = ".$this->id;
988
			$sql.= " AND entity = ".$conf->entity;
989
990
			if ($this->db->query($sql))
991
			{
992
				$this->description = $description;
993
				return 1;
994
			}
995
			else
996
			{
997
				$this->error=$this->db->error();
998
				dol_syslog("Fichinter::set_description Erreur SQL");
999
				return -1;
1000
			}
1001
		}
1002
	}
1003
1004
1005
	/**
1006
	 *	Link intervention to a contract
1007
	 *
1008
	 *	@param      User	$user			Object user who modify
1009
	 *	@param      int		$contractid		Description
1010
	 *	@return     int						<0 if ko, >0 if ok
1011
	 */
1012
	function set_contrat($user, $contractid)
1013
	{
1014
		global $conf;
1015
1016
		if ($user->rights->ficheinter->creer)
1017
		{
1018
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
1019
			$sql.= " SET fk_contrat = '".$contractid."'";
1020
			$sql.= " WHERE rowid = ".$this->id;
1021
			$sql.= " AND entity = ".$conf->entity;
1022
1023
			if ($this->db->query($sql))
1024
			{
1025
				$this->fk_contrat = $contractid;
1026
				return 1;
1027
			}
1028
			else
1029
			{
1030
				$this->error=$this->db->error();
1031
				return -1;
1032
			}
1033
		}
1034
		return -2;
1035
	}
1036
1037
1038
1039
	/**
1040
	 *	Load an object from its id and create a new one in database
1041
	 *
1042
	 *	@param		int			$socid			Id of thirdparty
1043
	 *	@return		int							New id of clone
1044
	 */
1045
	function createFromClone($socid=0)
1046
	{
1047
		global $user,$hookmanager;
1048
1049
		$error=0;
1050
1051
		$this->context['createfromclone'] = 'createfromclone';
1052
1053
		$this->db->begin();
1054
1055
		// get extrafields so they will be clone
1056
		foreach($this->lines as $line)
1057
			$line->fetch_optionals($line->rowid);
1058
1059
		// Load source object
1060
		$objFrom = clone $this;
1061
1062
		// Change socid if needed
1063
		if (! empty($socid) && $socid != $this->socid)
1064
		{
1065
			$objsoc = new Societe($this->db);
1066
1067
			if ($objsoc->fetch($socid)>0)
1068
			{
1069
				$this->socid 				= $objsoc->id;
1070
				//$this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1071
				//$this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1072
				$this->fk_project			= '';
1 ignored issue
show
Documentation Bug introduced by
The property $fk_project was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1073
				$this->fk_delivery_address	= '';
1 ignored issue
show
Documentation Bug introduced by
The property $fk_delivery_address was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1074
			}
1075
1076
			// TODO Change product price if multi-prices
1077
		}
1078
1079
		$this->id=0;
1080
		$this->ref = '';
1081
		$this->statut=0;
1082
1083
		// Clear fields
1084
		$this->user_author_id     = $user->id;
1085
		$this->user_valid         = '';
1086
		$this->date_creation      = '';
1087
		$this->date_validation    = '';
1088
		$this->ref_client         = '';
1089
1090
		// Create clone
1091
		$result=$this->create($user);
1092
		if ($result < 0) $error++;
1093
1094
		if (! $error)
1095
		{
1096
			// Add lines because it is not included into create function
1097
			foreach ($this->lines as $line)
1098
			{
1099
				$this->addline($user, $this->id, $line->desc, $line->datei, $line->duration);
1100
			}
1101
1102
			// Hook of thirdparty module
1103
			if (is_object($hookmanager))
1104
			{
1105
				$parameters=array('objFrom'=>$objFrom);
1106
				$action='';
1107
				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1108
				if ($reshook < 0) $error++;
1109
			}
1110
1111
			// Call trigger
1112
			$result=$this->call_trigger('INTERVENTION_CLONE',$user);
1113
			if ($result < 0) $error++;
1114
			// End call triggers
1115
		}
1116
1117
		unset($this->context['createfromclone']);
1118
1119
		// End
1120
		if (! $error)
1121
		{
1122
			$this->db->commit();
1123
			return $this->id;
1124
		}
1125
		else
1126
		{
1127
			$this->db->rollback();
1128
			return -1;
1129
		}
1130
	}
1131
1132
1133
	/**
1134
	 *	Adding a line of intervention into data base
1135
	 *
1136
	 *  @param      user	$user					User that do the action
1137
	 *	@param    	int		$fichinterid			Id of intervention
1138
	 *	@param    	string	$desc					Line description
1139
	 *	@param      date	$date_intervention  	Intervention date
1140
	 *	@param      int		$duration            	Intervention duration
1141
	 *  @param		array	$array_options			Array option
1142
	 *	@return    	int             				>0 if ok, <0 if ko
1143
	 */
1144
	function addline($user,$fichinterid, $desc, $date_intervention, $duration, $array_options='')
1145
	{
1146
		dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration");
1147
1148
		if ($this->statut == 0)
1149
		{
1150
			$this->db->begin();
1151
1152
			// Insertion ligne
1153
			$line=new FichinterLigne($this->db);
1154
1155
			$line->fk_fichinter = $fichinterid;
1156
			$line->desc         = $desc;
1157
			$line->datei        = $date_intervention;
1158
			$line->duration     = $duration;
1159
1160
			if (is_array($array_options) && count($array_options)>0) {
1161
				$line->array_options=$array_options;
1162
			}
1163
1164
			$result=$line->insert($user);
1165
1166
			if ($result >= 0)
1167
			{
1168
				$this->db->commit();
1169
				return 1;
1170
			}
1171
			else
1172
			{
1173
				$this->error=$this->db->error();
1174
				$this->db->rollback();
1175
				return -1;
1176
			}
1177
		}
1178
	}
1179
1180
1181
	/**
1182
	 *  Initialise an instance with random values.
1183
	 *  Used to build previews or test instances.
1184
	 *	id must be 0 if object instance is a specimen.
1185
	 *
1186
	 *  @return	void
1187
	 */
1188
	function initAsSpecimen()
1189
	{
1190
		global $user,$langs,$conf;
1191
1192
		$now=dol_now();
1193
1194
		// Initialise parametres
1195
		$this->id=0;
1196
		$this->ref = 'SPECIMEN';
1197
		$this->specimen=1;
1198
		$this->socid = 1;
1199
		$this->datec = $now;
1200
		$this->note_private='Private note';
1201
		$this->note_public='SPECIMEN';
1202
		$this->duration = 0;
1203
		$nbp = 25;
1204
		$xnbp = 0;
1205
		while ($xnbp < $nbp)
1206
		{
1207
			$line=new FichinterLigne($this->db);
1208
			$line->desc=$langs->trans("Description")." ".$xnbp;
1209
			$line->datei=($now-3600*(1+$xnbp));
1210
			$line->duration=600;
1211
			$line->fk_fichinter=0;
1212
			$this->lines[$xnbp]=$line;
1213
			$xnbp++;
1214
1215
			$this->duration+=$line->duration;
1216
		}
1217
	}
1218
1219
	/**
1220
	 *	Load array lines ->lines
1221
	 *
1222
	 *	@return		int		<0 if KO, >0 if OK
1223
	 */
1224
	function fetch_lines()
1225
	{
1226
		$sql = 'SELECT rowid, description, duree, date, rang';
1227
		$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet';
1228
		$sql.=' WHERE fk_fichinter = '.$this->id .' ORDER BY rang ASC, date ASC' ;
1229
1230
		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1231
		$resql=$this->db->query($sql);
1232
		if ($resql)
1233
		{
1234
			$num = $this->db->num_rows($resql);
1235
			$i = 0;
1236
			while ($i < $num)
1237
			{
1238
				$objp = $this->db->fetch_object($resql);
1239
1240
				$line = new FichinterLigne($this->db);
1241
				$line->id = $objp->rowid;
1242
				$line->desc = $objp->description;
1243
				$line->duration = $objp->duree;
1244
				//For invoicing we calculing hours
1245
				$line->qty = round($objp->duree/3600,2);
1246
				$line->date	= $this->db->jdate($objp->date);
1247
				$line->datei = $this->db->jdate($objp->date);
1248
				$line->rang	= $objp->rang;
1249
				$line->product_type = 1;
1250
1251
				$this->lines[$i] = $line;
1252
1253
				$i++;
1254
			}
1255
			$this->db->free($resql);
1256
1257
			return 1;
1258
		}
1259
		else
1260
		{
1261
			$this->error=$this->db->error();
1262
			return -1;
1263
		}
1264
	}
1265
1266
	/**
1267
	 * Function used to replace a thirdparty id with another one.
1268
	 *
1269
	 * @param DoliDB $db Database handler
1270
	 * @param int $origin_id Old thirdparty id
1271
	 * @param int $dest_id New thirdparty id
1272
	 * @return bool
1273
	 */
1274
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1275
	{
1276
		$tables = array(
1277
			'fichinter'
1278
		);
1279
1280
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1281
	}
1282
}
1283
1284
/**
1285
 *	Classe permettant la gestion des lignes d'intervention
1286
 */
1287
class FichinterLigne extends CommonObjectLine
1288
{
1289
	var $db;
1290
	var $error;
1291
1292
	// From llx_fichinterdet
1293
	var $fk_fichinter;
1294
	var $desc;          	// Description ligne
1295
	var $datei;           // Date intervention
1296
	var $duration;        // Duree de l'intervention
1297
	var $rang = 0;
1298
1299
	public $element='fichinterdet';
1300
	public $table_element='fichinterdet';
1301
	public $fk_element='fk_fichinter';
1302
1303
	/**
1304
	 *	Constructor
1305
	 *
1306
	 *	@param	DoliDB	$db		Database handler
1307
	 */
1308
	function __construct($db)
1309
	{
1310
		$this->db = $db;
1311
	}
1312
1313
	/**
1314
	 *	Retrieve the line of intervention
1315
	 *
1316
	 *	@param  int		$rowid		Line id
1317
	 *	@return	int					<0 if KO, >0 if OK
1318
	 */
1319
	function fetch($rowid)
1320
	{
1321
		$sql = 'SELECT ft.rowid, ft.fk_fichinter, ft.description, ft.duree, ft.rang,';
1322
		$sql.= ' ft.date as datei';
1323
		$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
1324
		$sql.= ' WHERE ft.rowid = '.$rowid;
1325
1326
		dol_syslog("FichinterLigne::fetch", LOG_DEBUG);
1327
		$result = $this->db->query($sql);
1328
		if ($result)
1329
		{
1330
			$objp = $this->db->fetch_object($result);
1331
			$this->rowid          	= $objp->rowid;
1332
			$this->id 				= $objp->rowid;
1333
			$this->fk_fichinter   	= $objp->fk_fichinter;
1334
			$this->datei			= $this->db->jdate($objp->datei);
1335
			$this->desc           	= $objp->description;
1336
			$this->duration       	= $objp->duree;
1337
			$this->rang           	= $objp->rang;
1338
1339
			$this->db->free($result);
1340
			return 1;
1341
		}
1342
		else
1343
		{
1344
			$this->error=$this->db->error().' sql='.$sql;
1345
			return -1;
1346
		}
1347
	}
1348
1349
	/**
1350
	 *	Insert the line into database
1351
	 *
1352
	 *	@param		User	$user 		Objet user that make creation
1353
	 *	@param		int		$notrigger	Disable all triggers
1354
	 *	@return		int		<0 if ko, >0 if ok
1355
	 */
1356
	function insert($user, $notrigger=0)
1357
	{
1358
		global $langs,$conf;
1359
1360
		dol_syslog("FichinterLigne::insert rang=".$this->rang);
1361
1362
		$this->db->begin();
1363
1364
		$rangToUse=$this->rang;
1365
		if ($rangToUse == -1)
1366
		{
1367
			// Recupere rang max de la ligne d'intervention dans $rangmax
1368
			$sql = 'SELECT max(rang) as max FROM '.MAIN_DB_PREFIX.'fichinterdet';
1369
			$sql.= ' WHERE fk_fichinter ='.$this->fk_fichinter;
1370
			$resql = $this->db->query($sql);
1371
			if ($resql)
1372
			{
1373
				$obj = $this->db->fetch_object($resql);
1374
				$rangToUse = $obj->max + 1;
1375
			}
1376
			else
1377
			{
1378
				dol_print_error($this->db);
1379
				$this->db->rollback();
1380
				return -1;
1381
			}
1382
		}
1383
1384
		// Insertion dans base de la ligne
1385
		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'fichinterdet';
1386
		$sql.= ' (fk_fichinter, description, date, duree, rang)';
1387
		$sql.= " VALUES (".$this->fk_fichinter.",";
1388
		$sql.= " '".$this->db->escape($this->desc)."',";
1389
		$sql.= " '".$this->db->idate($this->datei)."',";
1390
		$sql.= " ".$this->duration.",";
1391
		$sql.= ' '.$rangToUse;
1392
		$sql.= ')';
1393
1394
		dol_syslog("FichinterLigne::insert", LOG_DEBUG);
1395
		$resql=$this->db->query($sql);
1396
		if ($resql)
1397
		{
1398
			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet');
1399
1400
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1401
			{
1402
				$this->id=$this->rowid;
1403
				$result=$this->insertExtraFields();
1404
				if ($result < 0)
1405
				{
1406
					$error++;
0 ignored issues
show
Bug introduced by
The variable $error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1407
				}
1408
			}
1409
1410
1411
			$result=$this->update_total();
1412
1413
			if ($result > 0)
1414
			{
1415
				$this->rang=$rangToUse;
1416
1417
				if (! $notrigger)
1418
				{
1419
					// Call trigger
1420
					$result=$this->call_trigger('LINEFICHINTER_CREATE',$user);
1421
					if ($result < 0) { $error++; }
1422
					// End call triggers
1423
				}
1424
			}
1425
1426
			if (!$error) {
1427
				$this->db->commit();
1428
				return $result;
1429
			}
1430
			else
1431
			{
1432
				$this->db->rollback();
1433
				return -1;
1434
			}
1435
		}
1436
		else
1437
		{
1438
			$this->error=$this->db->error()." sql=".$sql;
1439
			$this->db->rollback();
1440
			return -1;
1441
		}
1442
	}
1443
1444
1445
	/**
1446
	 *	Update intervention into database
1447
	 *
1448
	 *	@param		User	$user 		Objet user that make creation
1449
	 *	@param		int		$notrigger	Disable all triggers
1450
	 *	@return		int		<0 if ko, >0 if ok
1451
	 */
1452
	function update($user,$notrigger=0)
1453
	{
1454
		global $langs,$conf;
1455
1456
		$this->db->begin();
1457
1458
		// Mise a jour ligne en base
1459
		$sql = "UPDATE ".MAIN_DB_PREFIX."fichinterdet SET";
1460
		$sql.= " description='".$this->db->escape($this->desc)."'";
1461
		$sql.= ",date='".$this->db->idate($this->datei)."'";
1462
		$sql.= ",duree=".$this->duration;
1463
		$sql.= ",rang='".$this->db->escape($this->rang)."'";
1464
		$sql.= " WHERE rowid = ".$this->rowid;
1465
1466
		dol_syslog("FichinterLigne::update", LOG_DEBUG);
1467
		$resql=$this->db->query($sql);
1468
		if ($resql)
1469
		{
1470
1471
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1472
			{
1473
				$this->id=$this->rowid;
1474
				$result=$this->insertExtraFields();
1475
				if ($result < 0)
1476
				{
1477
					$error++;
0 ignored issues
show
Bug introduced by
The variable $error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1478
				}
1479
			}
1480
1481
			$result=$this->update_total();
1482
			if ($result > 0)
1483
			{
1484
1485
				if (! $notrigger)
1486
				{
1487
					// Call trigger
1488
					$result=$this->call_trigger('LINEFICHINTER_UPDATE',$user);
1489
					if ($result < 0) { $error++; }
1490
					// End call triggers
1491
				}
1492
			}
1493
1494
			if (!$error)
1495
			{
1496
				$this->db->commit();
1497
				return $result;
1498
			}
1499
			else
1500
			{
1501
				$this->error=$this->db->lasterror();
1502
				$this->db->rollback();
1503
				return -1;
1504
			}
1505
		}
1506
		else
1507
		{
1508
			$this->error=$this->db->lasterror();
1509
			$this->db->rollback();
1510
			return -1;
1511
		}
1512
	}
1513
1514
	/**
1515
	 *	Update total duration into llx_fichinter
1516
	 *
1517
	 *	@return		int		<0 si ko, >0 si ok
1518
	 */
1519
	function update_total()
1520
	{
1521
		global $conf;
1522
1523
		$this->db->begin();
1524
1525
		$sql = "SELECT SUM(duree) as total_duration, min(date) as dateo, max(date) as datee ";
1526
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinterdet";
1527
		$sql.= " WHERE fk_fichinter=".$this->fk_fichinter;
1528
1529
		dol_syslog("FichinterLigne::update_total", LOG_DEBUG);
1530
		$resql=$this->db->query($sql);
1531
		if ($resql)
1532
		{
1533
			$obj=$this->db->fetch_object($resql);
1534
			$total_duration=0;
1535
			if (!empty($obj->total_duration)) $total_duration = $obj->total_duration;
1536
1537
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
1538
			$sql.= " SET duree = ".$total_duration;
1539
			$sql.= " , dateo = ".(! empty($obj->dateo)?"'".$this->db->idate($obj->dateo)."'":"null");
1540
			$sql.= " , datee = ".(! empty($obj->datee)?"'".$this->db->idate($obj->datee)."'":"null");
1541
			$sql.= " WHERE rowid = ".$this->fk_fichinter;
1542
			$sql.= " AND entity = ".$conf->entity;
1543
1544
			dol_syslog("FichinterLigne::update_total", LOG_DEBUG);
1545
			$resql=$this->db->query($sql);
1546
			if ($resql)
1547
			{
1548
				$this->db->commit();
1549
				return 1;
1550
			}
1551
			else
1552
			{
1553
				$this->error=$this->db->error();
1554
				$this->db->rollback();
1555
				return -2;
1556
			}
1557
		}
1558
		else
1559
		{
1560
			$this->error=$this->db->error();
1561
			$this->db->rollback();
1562
			return -1;
1563
		}
1564
	}
1565
1566
	/**
1567
	 *	Delete a intervention line
1568
	 *
1569
	 *	@param		User	$user 		Objet user that make creation
1570
	 *	@param		int		$notrigger	Disable all triggers
1571
	 *	@return     int		>0 if ok, <0 if ko
1572
	 */
1573
	function deleteline($user,$notrigger=0)
1574
	{
1575
		global $langs,$conf;
1576
1577
		$error=0;
1578
1579
		if ($this->statut == 0)
1580
		{
1581
			dol_syslog(get_class($this)."::deleteline lineid=".$this->rowid);
1582
			$this->db->begin();
1583
1584
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->rowid;
1585
			$resql = $this->db->query($sql);
1586
1587
			if ($resql)
1588
			{
1589
				$result = $this->update_total();
1590
				if ($result > 0)
1591
				{
1592
					if (! $notrigger)
1593
					{
1594
						// Call trigger
1595
						$result=$this->call_trigger('LINEFICHINTER_DELETE',$user);
1596
						if ($result < 0) { $error++; $this->db->rollback(); return -1; }
1597
						// End call triggers
1598
					}
1599
1600
					$this->db->commit();
1601
					return $result;
1602
				}
1603
				else
1604
				{
1605
					$this->db->rollback();
1606
					return -1;
1607
				}
1608
			}
1609
			else
1610
			{
1611
				$this->error=$this->db->error()." sql=".$sql;
1612
				$this->db->rollback();
1613
				return -1;
1614
			}
1615
		}
1616
		else
1617
		{
1618
			return -2;
1619
		}
1620
	}
1621
1622
}
1623
1624