Completed
Branch develop (bccfa3)
by
unknown
31:46
created

Fichinter::initAsSpecimen()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 22
nc 2
nop 0
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
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
	 *	Constructor
67
	 *
68
	 *  @param	DoliDB	$db		Database handler
69
 	 */
70
	function __construct($db)
71
	{
72
		$this->db = $db;
73
		$this->products = array();
74
		$this->fk_project = 0;
75
		$this->fk_contrat = 0;
76
		$this->statut = 0;
77
78
		// List of language codes for status
79
		$this->statuts[0]='Draft';
80
		$this->statuts[1]='Validated';
81
		$this->statuts[2]='StatusInterInvoiced';
82
		$this->statuts[3]='Done';
83
		$this->statuts_short[0]='Draft';
84
		$this->statuts_short[1]='Validated';
85
		$this->statuts_short[2]='StatusInterInvoiced';
86
		$this->statuts_short[3]='Done';
87
		$this->statuts_logo[0]='statut0';
88
		$this->statuts_logo[1]='statut1';
89
		$this->statuts_logo[2]='statut6';
90
		$this->statuts_logo[3]='statut6';
91
	}
92
93
	/**
94
	 *  Load indicators into this->nb for board
95
	 *
96
	 *  @return     int         <0 if KO, >0 if OK
97
	 */
98
	function load_state_board()
99
	{
100
		global $user;
101
102
		$this->nb=array();
103
		$clause = "WHERE";
104
105
		$sql = "SELECT count(fi.rowid) as nb";
106
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as fi";
107
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON fi.fk_soc = s.rowid";
108
		if (!$user->rights->societe->client->voir && !$user->societe_id)
109
		{
110
			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
111
			$sql.= " WHERE sc.fk_user = " .$user->id;
112
			$clause = "AND";
113
		}
114
		$sql.= " ".$clause." fi.entity IN (".getEntity($this->element, 1).")";
115
116
		$resql=$this->db->query($sql);
117
		if ($resql)
118
		{
119
			while ($obj=$this->db->fetch_object($resql))
120
			{
121
				$this->nb["fichinters"]=$obj->nb;
122
			}
123
			$this->db->free($resql);
124
			return 1;
125
		}
126
		else
127
		{
128
			dol_print_error($this->db);
129
			$this->error=$this->db->error();
130
			return -1;
131
		}
132
	}
133
134
	/**
135
	 *	Create an intervention into data base
136
	 *
137
	 *  @param		User	$user 		Objet user that make creation
138
     *	@param		int		$notrigger	Disable all triggers
139
	 *	@return		int		<0 if KO, >0 if OK
140
	 */
141
	function create($user, $notrigger=0)
142
	{
143
		global $conf, $user, $langs;
144
145
		dol_syslog(get_class($this)."::create ref=".$this->ref);
146
147
		// Check parameters
148
		if (! empty($this->ref))	// We check that ref is not already used
149
		{
150
			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
151
			if ($result > 0)
152
			{
153
				$this->error='ErrorRefAlreadyExists';
154
				dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
155
				$this->db->rollback();
156
				return -1;
157
			}
158
		}
159
		if (! is_numeric($this->duration)) $this->duration = 0;
160
161
		if ($this->socid <= 0)
162
		{
163
			$this->error='ErrorBadParameterForFunc';
164
			dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR);
165
			return -1;
166
		}
167
168
		$soc = new Societe($this->db);
169
		$result=$soc->fetch($this->socid);
170
171
		$now=dol_now();
172
173
		$this->db->begin();
174
175
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter (";
176
		$sql.= "fk_soc";
177
		$sql.= ", datec";
178
		$sql.= ", ref";
179
		$sql.= ", entity";
180
		$sql.= ", fk_user_author";
181
		$sql.= ", fk_user_modif";
182
		$sql.= ", description";
183
		$sql.= ", model_pdf";
184
		$sql.= ", fk_projet";
185
		$sql.= ", fk_contrat";
186
		$sql.= ", fk_statut";
187
		$sql.= ", note_private";
188
		$sql.= ", note_public";
189
		$sql.= ") ";
190
		$sql.= " VALUES (";
191
		$sql.= $this->socid;
192
		$sql.= ", '".$this->db->idate($now)."'";
193
		$sql.= ", '".$this->db->escape($this->ref)."'";
194
		$sql.= ", ".$conf->entity;
195
		$sql.= ", ".$user->id;
196
		$sql.= ", ".$user->id;
197
		$sql.= ", ".($this->description?"'".$this->db->escape($this->description)."'":"null");
198
		$sql.= ", '".$this->db->escape($this->modelpdf)."'";
199
		$sql.= ", ".($this->fk_project ? $this->fk_project : 0);
200
		$sql.= ", ".($this->fk_contrat ? $this->fk_contrat : 0);
201
		$sql.= ", ".$this->statut;
202
		$sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
203
		$sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
204
		$sql.= ")";
205
206
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
207
		$result=$this->db->query($sql);
208
		if ($result)
209
		{
210
			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."fichinter");
211
212
			if ($this->id)
213
			{
214
				$this->ref='(PROV'.$this->id.')';
215
				$sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->ref."' WHERE rowid=".$this->id;
216
217
				dol_syslog(get_class($this)."::create", LOG_DEBUG);
218
				$resql=$this->db->query($sql);
219
				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...
220
			}
221
222
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
223
            {
224
            	$result=$this->insertExtraFields();
225
            	if ($result < 0)
226
            	{
227
            		$error++;
228
            	}
229
            }
230
231
			// Add linked object
232
			if (! $error && $this->origin && $this->origin_id)
233
			{
234
				$ret = $this->add_object_linked();
235
				if (! $ret)	dol_print_error($this->db);
236
			}
237
238
239
            if (! $notrigger)
240
            {
241
                // Call trigger
242
                $result=$this->call_trigger('FICHINTER_CREATE',$user);
243
                if ($result < 0) { $error++; }
244
                // End call triggers
245
            }
246
247
			if (! $error)
248
			{
249
				$this->db->commit();
250
				return $this->id;
251
			}
252
			else
253
			{
254
				$this->db->rollback();
255
				$this->error=join(',',$this->errors);
256
				dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR);
257
				return -1;
258
			}
259
		}
260
		else
261
		{
262
			$this->error=$this->db->error();
263
			$this->db->rollback();
264
			return -1;
265
		}
266
267
	}
268
269
	/**
270
	 *	Update an intervention
271
	 *
272
	 *	@param		User	$user 		Objet user that make creation
273
     *	@param		int		$notrigger	Disable all triggers
274
	 *	@return		int		<0 if KO, >0 if OK
275
	 */
276
	function update($user, $notrigger=0)
277
	{
278
	 	if (! is_numeric($this->duration)) {
279
	 		$this->duration = 0;
280
	 	}
281
	 	if (! dol_strlen($this->fk_project)) {
282
	 		$this->fk_project = 0;
283
	 	}
284
285
		$this->db->begin();
286
287
		$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter SET ";
288
		$sql.= "description  = '".$this->db->escape($this->description)."'";
289
		$sql.= ", duree = ".$this->duration;
290
		$sql.= ", fk_projet = ".$this->fk_project;
291
		$sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
292
		$sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
293
		$sql.= ", fk_user_modif = ".$user->id;
294
		$sql.= " WHERE rowid = ".$this->id;
295
296
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
297
		if ($this->db->query($sql))
298
		{
299
300
			if (! $notrigger)
301
			{
302
                // Call trigger
303
                $result=$this->call_trigger('FICHINTER_MODIFY',$user);
304
                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...
305
                // End call triggers
306
			}
307
308
			$this->db->commit();
309
			return 1;
310
		}
311
		else
312
		{
313
			$this->error=$this->db->error();
314
			$this->db->rollback();
315
			return -1;
316
		}
317
	}
318
319
	/**
320
	 *	Fetch a intervention
321
	 *
322
	 *	@param		int		$rowid		Id of intervention
323
	 *	@param		string	$ref		Ref of intervention
324
	 *	@return		int					<0 if KO, >0 if OK
325
	 */
326
	function fetch($rowid,$ref='')
327
	{
328
		$sql = "SELECT f.rowid, f.ref, f.description, f.fk_soc, f.fk_statut,";
329
		$sql.= " f.datec, f.dateo, f.datee, f.datet, f.fk_user_author,";
330
		$sql.= " f.date_valid as datev,";
331
		$sql.= " f.tms as datem,";
332
		$sql.= " f.duree, f.fk_projet, f.note_public, f.note_private, f.model_pdf, f.extraparams, fk_contrat";
333
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f";
334
		if ($ref) $sql.= " WHERE f.ref='".$this->db->escape($ref)."'";
335
		else $sql.= " WHERE f.rowid=".$rowid;
336
337
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
338
		$resql=$this->db->query($sql);
339
		if ($resql)
340
		{
341
			if ($this->db->num_rows($resql))
342
			{
343
				$obj = $this->db->fetch_object($resql);
344
345
				$this->id           = $obj->rowid;
346
				$this->ref          = $obj->ref;
347
				$this->description  = $obj->description;
348
				$this->socid        = $obj->fk_soc;
349
				$this->statut       = $obj->fk_statut;
350
				$this->duration     = $obj->duree;
351
				$this->datec        = $this->db->jdate($obj->datec);
352
				$this->datee        = $this->db->jdate($obj->dateo);
353
				$this->dateo        = $this->db->jdate($obj->datee);
354
				$this->datet        = $this->db->jdate($obj->datet);
355
				$this->datev        = $this->db->jdate($obj->datev);
356
				$this->datem        = $this->db->jdate($obj->datem);
357
				$this->fk_project   = $obj->fk_projet;
358
				$this->note_public  = $obj->note_public;
359
				$this->note_private = $obj->note_private;
360
				$this->modelpdf     = $obj->model_pdf;
361
				$this->fk_contrat	= $obj->fk_contrat;
362
363
				$this->user_creation= $obj->fk_user_author;
364
				
365
				$this->extraparams	= (array) json_decode($obj->extraparams, true);
366
367
				if ($this->statut == 0) $this->brouillon = 1;
368
369
				require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
370
				$extrafields=new ExtraFields($this->db);
371
				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
372
				$this->fetch_optionals($this->id,$extralabels);
373
374
				/*
375
				 * Lines
376
				*/
377
				$result=$this->fetch_lines();
378
				if ($result < 0)
379
				{
380
					return -3;
381
				}
382
				$this->db->free($resql);
383
				return 1;
384
			}
385
		}
386
		else
387
		{
388
			$this->error=$this->db->lasterror();
389
			return -1;
390
		}
391
	}
392
393
	/**
394
	 *	Set status to draft
395
	 *
396
	 *	@param		User	$user	User that set draft
397
	 *	@return		int			<0 if KO, >0 if OK
398
	 */
399
	function setDraft($user)
400
	{
401
		global $langs, $conf;
402
403
		if ($this->statut != 0)
404
		{
405
			$this->db->begin();
406
407
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
408
			$sql.= " SET fk_statut = 0";
409
			$sql.= " WHERE rowid = ".$this->id;
410
			$sql.= " AND entity = ".$conf->entity;
411
412
			dol_syslog("Fichinter::setDraft", LOG_DEBUG);
413
			$resql=$this->db->query($sql);
414
			if ($resql)
415
			{
416
				$this->db->commit();
417
				return 1;
418
			}
419
			else
420
			{
421
				$this->db->rollback();
422
				$this->error=$this->db->lasterror();
423
				return -1;
424
			}
425
		}
426
	}
427
428
	/**
429
	 *	Validate a intervention
430
	 *
431
	 *	@param		User		$user		User that validate
432
     *  @param		int			$notrigger	1=Does not execute triggers, 0= execute triggers
433
	 *	@return		int						<0 if KO, >0 if OK
434
	 */
435
	function setValid($user, $notrigger=0)
436
	{
437
		global $conf;
438
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
439
440
		$error=0;
441
442
		if ($this->statut != 1)
443
		{
444
			$this->db->begin();
445
446
			$now=dol_now();
447
448
			// Define new ref
449
			if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
450
			{
451
				$num = $this->getNextNumRef($this->thirdparty);
452
			}
453
			else
454
			{
455
				$num = $this->ref;
456
			}
457
            $this->newref = $num;
458
459
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
460
			$sql.= " SET fk_statut = 1";
461
			$sql.= ", ref = '".$num."'";
462
			$sql.= ", date_valid = '".$this->db->idate($now)."'";
463
			$sql.= ", fk_user_valid = ".$user->id;
464
			$sql.= " WHERE rowid = ".$this->id;
465
			$sql.= " AND entity = ".$conf->entity;
466
			$sql.= " AND fk_statut = 0";
467
468
			dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
469
			$resql=$this->db->query($sql);
470
			if (! $resql)
471
			{
472
				dol_print_error($this->db);
473
				$error++;
474
			}
475
476
			if (! $error && ! $notrigger)
477
			{
478
                // Call trigger
479
                $result=$this->call_trigger('FICHINTER_VALIDATE',$user);
480
                if ($result < 0) { $error++; }
481
                // End call triggers
482
			}
483
484
			if (! $error)
485
			{
486
				$this->oldref = $this->ref;
487
488
				// Rename directory if dir was a temporary ref
489
				if (preg_match('/^[\(]?PROV/i', $this->ref))
490
				{
491
					// Rename of object directory ($this->ref = old ref, $num = new ref)
492
					// to  not lose the linked files
493
					$oldref = dol_sanitizeFileName($this->ref);
494
					$newref = dol_sanitizeFileName($num);
495
					$dirsource = $conf->ficheinter->dir_output.'/'.$oldref;
496
					$dirdest = $conf->ficheinter->dir_output.'/'.$newref;
497
					if (file_exists($dirsource))
498
					{
499
						dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest);
500
501
						if (@rename($dirsource, $dirdest))
502
						{
503
	                        dol_syslog("Rename ok");
504
	                        // Rename docs starting with $oldref with $newref
505
	                        $listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
506
	                        foreach($listoffiles as $fileentry)
507
	                        {
508
	                        	$dirsource=$fileentry['name'];
509
	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
510
	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
511
	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
512
	                        	@rename($dirsource, $dirdest);
513
	                        }
514
						}
515
					}
516
				}
517
			}
518
519
			// Set new ref and define current statut
520
			if (! $error)
521
			{
522
				$this->ref = $num;
523
				$this->statut=1;
524
				$this->brouillon=0;
525
				$this->date_validation=$now;
526
			}
527
528
			if (! $error)
529
			{
530
				$this->db->commit();
531
				return 1;
532
			}
533
			else
534
			{
535
				$this->db->rollback();
536
				dol_syslog(get_class($this)."::setValid ".$this->error,LOG_ERR);
537
				return -1;
538
			}
539
		}
540
	}
541
542
	/**
543
	 *	Returns amount based on user thm
544
	 *
545
	 *	@return     float amount
546
	 */
547
	function getAmount() {
548
		global $db;
549
		
550
		$amount = 0;
551
		
552
		$this->author = new User($db);
553
		$this->author->fetch($this->user_creation);
554
		
555
		$thm = $this->author->thm;
556
		
557
		foreach($this->lines as &$line) {
558
			
559
			$amount+=$line->qty * $thm;
560
			
561
		}
562
		
563
		return $amount;
564
	}
565
	
566
	/**
567
	 *	Returns the label status
568
	 *
569
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
570
	 *	@return     string      		Label
571
	 */
572
	function getLibStatut($mode=0)
573
	{
574
		return $this->LibStatut($this->statut,$mode);
575
	}
576
577
	/**
578
	 *	Returns the label of a statut
579
	 *
580
	 *	@param      int		$statut     id statut
581
	 *	@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
582
	 *	@return     string      		Label
583
	 */
584
	function LibStatut($statut,$mode=0)
585
	{
586
		global $langs;
587
588
		if ($mode == 0)
589
			return $langs->trans($this->statuts[$statut]);
590
		if ($mode == 1)
591
			return $langs->trans($this->statuts_short[$statut]);
592
		if ($mode == 2)
593
			return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]).' '.$langs->trans($this->statuts_short[$statut]);
594
		if ($mode == 3)
595
			return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]);
596
		if ($mode == 4)
597
			return img_picto($langs->trans($this->statuts_short[$statut]),$this->statuts_logo[$statut]).' '.$langs->trans($this->statuts[$statut]);
598
		if ($mode == 5)
599
			return '<span class="hideonsmartphone">'.$langs->trans($this->statuts_short[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]);
600
		if ($mode == 6)
601
		    return '<span class="hideonsmartphone">'.$langs->trans($this->statuts[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]);
602
		
603
		return '';
604
	}
605
606
	/**
607
	 *	Return clicable name (with picto eventually)
608
	 *
609
	 *	@param		int		$withpicto		0=_No picto, 1=Includes the picto in the linkn, 2=Picto only
610
	 *	@param		string	$option			Options
611
	 *	@return		string					String with URL
612
	 */
613
	function getNomUrl($withpicto=0,$option='')
614
	{
615
		global $langs;
616
617
		$result='';
618
        $label = '<u>' . $langs->trans("ShowIntervention") . '</u>';
619
        if (! empty($this->ref))
620
            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> '.$this->ref;
621
622
        $link = '<a href="'.DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
623
		$linkend='</a>';
624
625
		$picto='intervention';
626
627
628
        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
629
		if ($withpicto && $withpicto != 2) $result.=' ';
630
		if ($withpicto != 2) $result.=$link.$this->ref.$linkend;
631
		return $result;
632
	}
633
634
635
	/**
636
	 *	Returns the next non used reference of intervention
637
	 *	depending on the module numbering assets within FICHEINTER_ADDON
638
	 *
639
	 *	@param	    Societe		$soc		Thirdparty object
640
	 *	@return     string					Free reference for intervention
641
	 */
642
	function getNextNumRef($soc)
643
	{
644
		global $conf, $db, $langs;
645
		$langs->load("interventions");
646
647
		if (! empty($conf->global->FICHEINTER_ADDON))
648
		{
649
			$mybool = false;
650
651
			$file = "mod_".$conf->global->FICHEINTER_ADDON.".php";
652
			$classname = "mod_".$conf->global->FICHEINTER_ADDON;
653
654
			// Include file with class
655
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
656
657
			foreach ($dirmodels as $reldir) {
658
659
				$dir = dol_buildpath($reldir."core/modules/fichinter/");
660
661
				// Load file with numbering class (if found)
662
				$mybool|=@include_once $dir.$file;
663
			}
664
665
			if (! $mybool)
666
			{
667
				dol_print_error('',"Failed to include file ".$file);
668
				return '';
669
			}
670
671
			$obj = new $classname();
672
			$numref = "";
673
			$numref = $obj->getNextValue($soc,$this);
674
675
			if ( $numref != "")
676
			{
677
				return $numref;
678
			}
679
			else
680
			{
681
				dol_print_error($db,"Fichinter::getNextNumRef ".$obj->error);
682
				return "";
683
			}
684
		}
685
		else
686
		{
687
			$langs->load("errors");
688
			print $langs->trans("Error")." ".$langs->trans("Error_FICHEINTER_ADDON_NotDefined");
689
			return "";
690
		}
691
	}
692
693
	/**
694
	 * 	Load information on object
695
	 *
696
	 *	@param	int		$id      Id of object
697
	 *	@return	void
698
	 */
699
	function info($id)
700
	{
701
		global $conf;
702
703
		$sql = "SELECT f.rowid,";
704
		$sql.= " f.datec,";
705
		$sql.= " f.tms as date_modification,";
706
		$sql.= " f.date_valid as datev,";
707
		$sql.= " f.fk_user_author,";
708
		$sql.= " f.fk_user_modif as fk_user_modification,";
709
		$sql.= " f.fk_user_valid";
710
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f";
711
		$sql.= " WHERE f.rowid = ".$id;
712
		$sql.= " AND f.entity = ".$conf->entity;
713
714
		$resql = $this->db->query($sql);
715
		if ($resql)
716
		{
717
			if ($this->db->num_rows($resql))
718
			{
719
				$obj = $this->db->fetch_object($resql);
720
721
				$this->id                = $obj->rowid;
722
723
				$this->date_creation     = $this->db->jdate($obj->datec);
724
				$this->date_modification = $this->db->jdate($obj->date_modification);
725
				$this->date_validation   = $this->db->jdate($obj->datev);
726
727
				$cuser = new User($this->db);
728
				$cuser->fetch($obj->fk_user_author);
729
				$this->user_creation     = $cuser;
730
731
				if ($obj->fk_user_valid)
732
				{
733
					$vuser = new User($this->db);
734
					$vuser->fetch($obj->fk_user_valid);
735
					$this->user_validation     = $vuser;
736
				}
737
				if ($obj->fk_user_modification)
738
				{
739
					$muser = new User($this->db);
740
					$muser->fetch($obj->fk_user_modification);
741
					$this->user_modification   = $muser;
742
				}
743
744
			}
745
			$this->db->free($resql);
746
		}
747
		else
748
		{
749
			dol_print_error($this->db);
750
		}
751
	}
752
753
	/**
754
	 *	Delete intervetnion
755
	 *
756
	 *	@param      User	$user			Object user who delete
757
	 *	@param		int		$notrigger		Disable trigger
758
	 *	@return		int						<0 if KO, >0 if OK
759
	 */
760
	function delete($user, $notrigger=0)
761
	{
762
		global $conf,$langs;
763
        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
764
765
		$error=0;
766
767
		$this->db->begin();
768
769
		// Delete linked object
770
		$res = $this->deleteObjectLinked();
771
		if ($res < 0) $error++;
772
773
		// Delete linked contacts
774
		$res = $this->delete_linked_contact();
775
		if ($res < 0)
776
		{
777
			$this->error='ErrorFailToDeleteLinkedContact';
778
			$error++;
779
		}
780
781
		if ($error)
782
		{
783
			$this->db->rollback();
784
			return -1;
785
		}
786
787
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet";
788
		$sql.= " WHERE fk_fichinter = ".$this->id;
789
790
		dol_syslog("Fichinter::delete", LOG_DEBUG);
791
		if ( $this->db->query($sql) )
792
		{
793
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter";
794
			$sql.= " WHERE rowid = ".$this->id;
795
			$sql.= " AND entity = ".$conf->entity;
796
797
			dol_syslog("Fichinter::delete", LOG_DEBUG);
798
			if ( $this->db->query($sql) )
799
			{
800
801
				// Remove directory with files
802
				$fichinterref = dol_sanitizeFileName($this->ref);
803
				if ($conf->ficheinter->dir_output)
804
				{
805
					$dir = $conf->ficheinter->dir_output . "/" . $fichinterref ;
806
					$file = $conf->ficheinter->dir_output . "/" . $fichinterref . "/" . $fichinterref . ".pdf";
807
					if (file_exists($file))
808
					{
809
						dol_delete_preview($this);
810
811
						if (! dol_delete_file($file,0,0,0,$this)) // For triggers
812
						{
813
							$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
814
							return 0;
815
						}
816
					}
817
					if (file_exists($dir))
818
					{
819
						if (! dol_delete_dir_recursive($dir))
820
						{
821
							$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
822
							return 0;
823
						}
824
					}
825
				}
826
827
				if (! $notrigger)
828
				{
829
                    // Call trigger
830
                    $result=$this->call_trigger('FICHINTER_DELETE',$user);
831
                    if ($result < 0) { $error++; $this->db->rollback(); return -1; }
832
                    // End call triggers
833
				}
834
835
				$this->db->commit();
836
				return 1;
837
			}
838
			else
839
			{
840
				$this->error=$this->db->lasterror();
841
				$this->db->rollback();
842
				return -2;
843
			}
844
		}
845
		else
846
		{
847
			$this->error=$this->db->lasterror();
848
			$this->db->rollback();
849
			return -1;
850
		}
851
	}
852
853
	/**
854
	 *	Defines a delivery date of intervention
855
	 *
856
	 *	@param      User	$user				Object user who define
857
	 *	@param      date	$date_delivery   	date of delivery
858
	 *	@return     int							<0 if ko, >0 if ok
859
	 */
860
	function set_date_delivery($user, $date_delivery)
861
	{
862
		global $conf;
863
864
		if ($user->rights->ficheinter->creer)
865
		{
866
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
867
			$sql.= " SET datei = '".$this->db->idate($date_delivery)."'";
868
			$sql.= " WHERE rowid = ".$this->id;
869
			$sql.= " AND entity = ".$conf->entity;
870
			$sql.= " AND fk_statut = 0";
871
872
			if ($this->db->query($sql))
873
			{
874
				$this->date_delivery = $date_delivery;
875
				return 1;
876
			}
877
			else
878
			{
879
				$this->error=$this->db->error();
880
				dol_syslog("Fichinter::set_date_delivery Erreur SQL");
881
				return -1;
882
			}
883
		}
884
	}
885
886
	/**
887
	 *	Define the label of the intervention
888
	 *
889
	 *	@param      User	$user			Object user who modify
890
	 *	@param      string	$description    description
891
	 *	@return     int						<0 if KO, >0 if OK
892
	 */
893
	function set_description($user, $description)
894
	{
895
		global $conf;
896
897
		if ($user->rights->ficheinter->creer)
898
		{
899
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
900
			$sql.= " SET description = '".$this->db->escape($description)."',";
901
			$sql.= " fk_user_modif = ".$user->id;
902
			$sql.= " WHERE rowid = ".$this->id;
903
			$sql.= " AND entity = ".$conf->entity;
904
905
			if ($this->db->query($sql))
906
			{
907
				$this->description = $description;
908
				return 1;
909
			}
910
			else
911
			{
912
				$this->error=$this->db->error();
913
				dol_syslog("Fichinter::set_description Erreur SQL");
914
				return -1;
915
			}
916
		}
917
	}
918
919
920
	/**
921
	 *	Link intervention to a contract
922
	 *
923
	 *	@param      User	$user			Object user who modify
924
	 *	@param      int		$contractid		Description
925
	 *	@return     int						<0 if ko, >0 if ok
926
	 */
927
	function set_contrat($user, $contractid)
928
	{
929
		global $conf;
930
931
		if ($user->rights->ficheinter->creer)
932
		{
933
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter ";
934
			$sql.= " SET fk_contrat = '".$contractid."'";
935
			$sql.= " WHERE rowid = ".$this->id;
936
			$sql.= " AND entity = ".$conf->entity;
937
938
			if ($this->db->query($sql))
939
			{
940
				$this->fk_contrat = $contractid;
941
				return 1;
942
			}
943
			else
944
			{
945
				$this->error=$this->db->error();
946
				return -1;
947
			}
948
		}
949
		return -2;
950
	}
951
952
	
953
954
    /**
955
     *	Load an object from its id and create a new one in database
956
     *
957
     *	@param		int			$socid			Id of thirdparty
958
     *	@return		int							New id of clone
959
     */
960
    function createFromClone($socid=0)
961
    {
962
        global $user,$hookmanager;
963
964
        $error=0;
965
966
        $this->context['createfromclone'] = 'createfromclone';
967
968
        $this->db->begin();
969
970
		// get extrafields so they will be clone
971
		foreach($this->lines as $line)
972
			$line->fetch_optionals($line->rowid);
973
974
        // Load source object
975
        $objFrom = clone $this;
976
977
        // Change socid if needed
978
        if (! empty($socid) && $socid != $this->socid)
979
        {
980
            $objsoc = new Societe($this->db);
981
982
            if ($objsoc->fetch($socid)>0)
983
            {
984
                $this->socid 				= $objsoc->id;
985
                //$this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
986
                //$this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
987
                $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...
988
                $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...
989
            }
990
991
            // TODO Change product price if multi-prices
992
        }
993
994
        $this->id=0;
995
		$this->ref = '';
996
        $this->statut=0;
997
998
        // Clear fields
999
        $this->user_author_id     = $user->id;
1000
        $this->user_valid         = '';
1001
        $this->date_creation      = '';
1002
        $this->date_validation    = '';
1003
        $this->ref_client         = '';
1004
		
1005
        // Create clone
1006
        $result=$this->create($user);
1007
        if ($result < 0) $error++;
1008
1009
        if (! $error)
1010
        {
1011
            // Add lines because it is not included into create function
1012
            foreach ($this->lines as $line)
1013
            {
1014
            	$this->addline($user, $this->id, $line->desc, $line->datei, $line->duration);
1015
            }
1016
            
1017
        	// Hook of thirdparty module
1018
            if (is_object($hookmanager))
1019
            {
1020
                $parameters=array('objFrom'=>$objFrom);
1021
                $action='';
1022
                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1023
                if ($reshook < 0) $error++;
1024
            }
1025
1026
            // Call trigger
1027
            $result=$this->call_trigger('INTERVENTION_CLONE',$user);
1028
            if ($result < 0) $error++;
1029
            // End call triggers
1030
        }
1031
1032
        unset($this->context['createfromclone']);
1033
1034
        // End
1035
        if (! $error)
1036
        {
1037
            $this->db->commit();
1038
            return $this->id;
1039
        }
1040
        else
1041
        {
1042
            $this->db->rollback();
1043
            return -1;
1044
        }
1045
    }
1046
	
1047
	
1048
	/**
1049
	 *	Adding a line of intervention into data base
1050
	 *
1051
	 *  @param      user	$user					User that do the action
1052
	 *	@param    	int		$fichinterid			Id of intervention
1053
	 *	@param    	string	$desc					Line description
1054
	 *	@param      date	$date_intervention  	Intervention date
1055
	 *	@param      int		$duration            	Intervention duration
1056
	 *  @param		array	$array_options			Array option
1057
	 *	@return    	int             				>0 if ok, <0 if ko
1058
	 */
1059
	function addline($user,$fichinterid, $desc, $date_intervention, $duration, $array_options='')
1060
	{
1061
		dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration");
1062
1063
		if ($this->statut == 0)
1064
		{
1065
			$this->db->begin();
1066
1067
			// Insertion ligne
1068
			$line=new FichinterLigne($this->db);
1069
1070
			$line->fk_fichinter = $fichinterid;
1071
			$line->desc         = $desc;
1072
			$line->datei        = $date_intervention;
1073
			$line->duration     = $duration;
1074
1075
			if (is_array($array_options) && count($array_options)>0) {
1076
				$line->array_options=$array_options;
1077
			}
1078
1079
			$result=$line->insert($user);
1080
1081
			if ($result >= 0)
1082
			{
1083
				$this->db->commit();
1084
				return 1;
1085
			}
1086
			else
1087
			{
1088
				$this->error=$this->db->error();
1089
				$this->db->rollback();
1090
				return -1;
1091
			}
1092
		}
1093
	}
1094
1095
1096
	/**
1097
	 *  Initialise an instance with random values.
1098
	 *  Used to build previews or test instances.
1099
	 *	id must be 0 if object instance is a specimen.
1100
	 *
1101
	 *  @return	void
1102
	 */
1103
	function initAsSpecimen()
1104
	{
1105
		global $user,$langs,$conf;
1106
1107
		$now=dol_now();
1108
1109
		// Initialise parametres
1110
		$this->id=0;
1111
		$this->ref = 'SPECIMEN';
1112
		$this->specimen=1;
1113
		$this->socid = 1;
1114
		$this->datec = $now;
1115
		$this->note_private='Private note';
1116
		$this->note_public='SPECIMEN';
1117
		$this->duration = 0;
1118
		$nbp = 25;
1119
		$xnbp = 0;
1120
		while ($xnbp < $nbp)
1121
		{
1122
			$line=new FichinterLigne($this->db);
1123
			$line->desc=$langs->trans("Description")." ".$xnbp;
1124
			$line->datei=($now-3600*(1+$xnbp));
1125
			$line->duration=600;
1126
			$line->fk_fichinter=0;
1127
			$this->lines[$xnbp]=$line;
1128
			$xnbp++;
1129
1130
			$this->duration+=$line->duration;
1131
		}
1132
	}
1133
1134
	/**
1135
	 *	Load array lines ->lines
1136
	 *
1137
	 *	@return		int		<0 if KO, >0 if OK
1138
	 */
1139
	function fetch_lines()
1140
	{
1141
		$sql = 'SELECT rowid, description, duree, date, rang';
1142
		$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet';
1143
		$sql.=' WHERE fk_fichinter = '.$this->id .' ORDER BY rang ASC, date ASC' ;
1144
1145
		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1146
		$resql=$this->db->query($sql);
1147
		if ($resql)
1148
		{
1149
			$num = $this->db->num_rows($resql);
1150
			$i = 0;
1151
			while ($i < $num)
1152
			{
1153
				$objp = $this->db->fetch_object($resql);
1154
1155
				$line = new FichinterLigne($this->db);
1156
				$line->id = $objp->rowid;
1157
				$line->desc = $objp->description;
1158
				$line->duration = $objp->duree;
1159
				//For invoicing we calculing hours
1160
				$line->qty = round($objp->duree/3600,2);
1161
				$line->date	= $this->db->jdate($objp->date);
1162
				$line->datei = $this->db->jdate($objp->date);
1163
				$line->rang	= $objp->rang;
1164
				$line->product_type = 1;
1165
1166
				$this->lines[$i] = $line;
1167
1168
				$i++;
1169
			}
1170
			$this->db->free($resql);
1171
1172
			return 1;
1173
		}
1174
		else
1175
		{
1176
			$this->error=$this->db->error();
1177
			return -1;
1178
		}
1179
	}
1180
1181
	/**
1182
	 * Function used to replace a thirdparty id with another one.
1183
	 *
1184
	 * @param DoliDB $db Database handler
1185
	 * @param int $origin_id Old thirdparty id
1186
	 * @param int $dest_id New thirdparty id
1187
	 * @return bool
1188
	 */
1189
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1190
	{
1191
		$tables = array(
1192
			'fichinter'
1193
		);
1194
1195
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1196
	}
1197
}
1198
1199
/**
1200
 *	Classe permettant la gestion des lignes d'intervention
1201
 */
1202
class FichinterLigne extends CommonObjectLine
1203
{
1204
	var $db;
1205
	var $error;
1206
1207
	// From llx_fichinterdet
1208
	var $fk_fichinter;
1209
	var $desc;          	// Description ligne
1210
	var $datei;           // Date intervention
1211
	var $duration;        // Duree de l'intervention
1212
	var $rang = 0;
1213
1214
	public $element='fichinterdet';
1215
	public $table_element='fichinterdet';
1216
	public $fk_element='fk_fichinter';
1217
1218
	/**
1219
	 *	Constructor
1220
	 *
1221
	 *	@param	DoliDB	$db		Database handler
1222
	 */
1223
	function __construct($db)
1224
	{
1225
		$this->db = $db;
1226
	}
1227
1228
	/**
1229
	 *	Retrieve the line of intervention
1230
	 *
1231
	 *	@param  int		$rowid		Line id
1232
	 *	@return	int					<0 if KO, >0 if OK
1233
	 */
1234
	function fetch($rowid)
1235
	{
1236
		$sql = 'SELECT ft.rowid, ft.fk_fichinter, ft.description, ft.duree, ft.rang,';
1237
		$sql.= ' ft.date as datei';
1238
		$sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft';
1239
		$sql.= ' WHERE ft.rowid = '.$rowid;
1240
1241
		dol_syslog("FichinterLigne::fetch", LOG_DEBUG);
1242
		$result = $this->db->query($sql);
1243
		if ($result)
1244
		{
1245
			$objp = $this->db->fetch_object($result);
1246
			$this->rowid          	= $objp->rowid;
1247
			$this->id 				= $objp->rowid;
1248
			$this->fk_fichinter   	= $objp->fk_fichinter;
1249
			$this->datei			= $this->db->jdate($objp->datei);
1250
			$this->desc           	= $objp->description;
1251
			$this->duration       	= $objp->duree;
1252
			$this->rang           	= $objp->rang;
1253
1254
			$this->db->free($result);
1255
			return 1;
1256
		}
1257
		else
1258
		{
1259
			$this->error=$this->db->error().' sql='.$sql;
1260
			return -1;
1261
		}
1262
	}
1263
1264
	/**
1265
	 *	Insert the line into database
1266
	 *
1267
	 *	@param		User	$user 		Objet user that make creation
1268
     *	@param		int		$notrigger	Disable all triggers
1269
	 *	@return		int		<0 if ko, >0 if ok
1270
	 */
1271
	function insert($user, $notrigger=0)
1272
	{
1273
		global $langs,$conf;
1274
1275
		dol_syslog("FichinterLigne::insert rang=".$this->rang);
1276
1277
		$this->db->begin();
1278
1279
		$rangToUse=$this->rang;
1280
		if ($rangToUse == -1)
1281
		{
1282
			// Recupere rang max de la ligne d'intervention dans $rangmax
1283
			$sql = 'SELECT max(rang) as max FROM '.MAIN_DB_PREFIX.'fichinterdet';
1284
			$sql.= ' WHERE fk_fichinter ='.$this->fk_fichinter;
1285
			$resql = $this->db->query($sql);
1286
			if ($resql)
1287
			{
1288
				$obj = $this->db->fetch_object($resql);
1289
				$rangToUse = $obj->max + 1;
1290
			}
1291
			else
1292
			{
1293
				dol_print_error($this->db);
1294
				$this->db->rollback();
1295
				return -1;
1296
			}
1297
		}
1298
1299
		// Insertion dans base de la ligne
1300
		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'fichinterdet';
1301
		$sql.= ' (fk_fichinter, description, date, duree, rang)';
1302
		$sql.= " VALUES (".$this->fk_fichinter.",";
1303
		$sql.= " '".$this->db->escape($this->desc)."',";
1304
		$sql.= " '".$this->db->idate($this->datei)."',";
1305
		$sql.= " ".$this->duration.",";
1306
		$sql.= ' '.$rangToUse;
1307
		$sql.= ')';
1308
1309
		dol_syslog("FichinterLigne::insert", LOG_DEBUG);
1310
		$resql=$this->db->query($sql);
1311
		if ($resql)
1312
		{
1313
			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet');
1314
1315
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1316
            {
1317
            	$this->id=$this->rowid;
1318
            	$result=$this->insertExtraFields();
1319
            	if ($result < 0)
1320
            	{
1321
            		$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...
1322
            	}
1323
            }
1324
1325
1326
			$result=$this->update_total();
1327
1328
			if ($result > 0)
1329
			{
1330
				$this->rang=$rangToUse;
1331
1332
				if (! $notrigger)
1333
				{
1334
                    // Call trigger
1335
                    $result=$this->call_trigger('LINEFICHINTER_CREATE',$user);
1336
                    if ($result < 0) { $error++; }
1337
                    // End call triggers
1338
				}
1339
			}
1340
1341
			if (!$error) {
1342
				$this->db->commit();
1343
				return $result;
1344
			}
1345
			else
1346
			{
1347
				$this->db->rollback();
1348
				return -1;
1349
			}
1350
		}
1351
		else
1352
		{
1353
			$this->error=$this->db->error()." sql=".$sql;
1354
			$this->db->rollback();
1355
			return -1;
1356
		}
1357
	}
1358
1359
1360
	/**
1361
	 *	Update intervention into database
1362
	 *
1363
	 *	@param		User	$user 		Objet user that make creation
1364
     *	@param		int		$notrigger	Disable all triggers
1365
	 *	@return		int		<0 if ko, >0 if ok
1366
	 */
1367
	function update($user,$notrigger=0)
1368
	{
1369
		global $langs,$conf;
1370
1371
		$this->db->begin();
1372
1373
		// Mise a jour ligne en base
1374
		$sql = "UPDATE ".MAIN_DB_PREFIX."fichinterdet SET";
1375
		$sql.= " description='".$this->db->escape($this->desc)."'";
1376
		$sql.= ",date='".$this->db->idate($this->datei)."'";
1377
		$sql.= ",duree=".$this->duration;
1378
		$sql.= ",rang='".$this->rang."'";
1379
		$sql.= " WHERE rowid = ".$this->rowid;
1380
1381
		dol_syslog("FichinterLigne::update", LOG_DEBUG);
1382
		$resql=$this->db->query($sql);
1383
		if ($resql)
1384
		{
1385
1386
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1387
        	{
1388
        		$this->id=$this->rowid;
1389
        		$result=$this->insertExtraFields();
1390
        		if ($result < 0)
1391
        		{
1392
        			$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...
1393
        		}
1394
        	}
1395
1396
			$result=$this->update_total();
1397
			if ($result > 0)
1398
			{
1399
1400
				if (! $notrigger)
1401
				{
1402
                    // Call trigger
1403
                    $result=$this->call_trigger('LINEFICHINTER_UPDATE',$user);
1404
                    if ($result < 0) { $error++; }
1405
                    // End call triggers
1406
				}
1407
			}
1408
1409
			if (!$error)
1410
			{
1411
				$this->db->commit();
1412
				return $result;
1413
			}
1414
			else
1415
			{
1416
				$this->error=$this->db->lasterror();
1417
				$this->db->rollback();
1418
				return -1;
1419
			}
1420
		}
1421
		else
1422
		{
1423
			$this->error=$this->db->lasterror();
1424
			$this->db->rollback();
1425
			return -1;
1426
		}
1427
	}
1428
1429
	/**
1430
	 *	Update total duration into llx_fichinter
1431
	 *
1432
	 *	@return		int		<0 si ko, >0 si ok
1433
	 */
1434
	function update_total()
1435
	{
1436
		global $conf;
1437
1438
		$this->db->begin();
1439
1440
		$sql = "SELECT SUM(duree) as total_duration, min(date) as dateo, max(date) as datee ";
1441
		$sql.= " FROM ".MAIN_DB_PREFIX."fichinterdet";
1442
		$sql.= " WHERE fk_fichinter=".$this->fk_fichinter;
1443
1444
		dol_syslog("FichinterLigne::update_total", LOG_DEBUG);
1445
		$resql=$this->db->query($sql);
1446
		if ($resql)
1447
		{
1448
			$obj=$this->db->fetch_object($resql);
1449
			$total_duration=0;
1450
			if (!empty($obj->total_duration)) $total_duration = $obj->total_duration;
1451
1452
			$sql = "UPDATE ".MAIN_DB_PREFIX."fichinter";
1453
			$sql.= " SET duree = ".$total_duration;
1454
			$sql.= " , dateo = ".(! empty($obj->dateo)?"'".$this->db->idate($obj->dateo)."'":"null");
1455
			$sql.= " , datee = ".(! empty($obj->datee)?"'".$this->db->idate($obj->datee)."'":"null");
1456
			$sql.= " WHERE rowid = ".$this->fk_fichinter;
1457
			$sql.= " AND entity = ".$conf->entity;
1458
1459
			dol_syslog("FichinterLigne::update_total", LOG_DEBUG);
1460
			$resql=$this->db->query($sql);
1461
			if ($resql)
1462
			{
1463
				$this->db->commit();
1464
				return 1;
1465
			}
1466
			else
1467
			{
1468
				$this->error=$this->db->error();
1469
				$this->db->rollback();
1470
				return -2;
1471
			}
1472
		}
1473
		else
1474
		{
1475
			$this->error=$this->db->error();
1476
			$this->db->rollback();
1477
			return -1;
1478
		}
1479
	}
1480
1481
	/**
1482
	 *	Delete a intervention line
1483
	 *
1484
	 *	@param		User	$user 		Objet user that make creation
1485
     *	@param		int		$notrigger	Disable all triggers
1486
	 *	@return     int		>0 if ok, <0 if ko
1487
	 */
1488
	function deleteline($user,$notrigger=0)
1489
	{
1490
		global $langs,$conf;
1491
1492
		if ($this->statut == 0)
1493
		{
1494
			dol_syslog(get_class($this)."::deleteline lineid=".$this->rowid);
1495
			$this->db->begin();
1496
1497
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->rowid;
1498
			$resql = $this->db->query($sql);
1499
1500
			if ($resql)
1501
			{
1502
				$result = $this->update_total();
1503
				if ($result > 0)
1504
				{
1505
					if (! $notrigger)
1506
					{
1507
                        // Call trigger
1508
                        $result=$this->call_trigger('LINEFICHINTER_DELETE',$user);
1509
                        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...
1510
                        // End call triggers
1511
					}
1512
1513
                    $this->db->commit();
1514
                    return $result;
1515
				}
1516
				else
1517
				{
1518
					$this->db->rollback();
1519
					return -1;
1520
				}
1521
			}
1522
			else
1523
			{
1524
				$this->error=$this->db->error()." sql=".$sql;
1525
				$this->db->rollback();
1526
				return -1;
1527
			}
1528
		}
1529
		else
1530
		{
1531
			return -2;
1532
		}
1533
	}
1534
1535
}
1536
1537