Completed
Branch develop (a0152f)
by
unknown
34:49
created

Fichinter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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