Passed
Pull Request — master (#2)
by
unknown
26:19
created

Holiday   F

Complexity

Total Complexity 300

Size/Duplication

Total Lines 2145
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 1066
dl 0
loc 2145
rs 1.336
c 0
b 0
f 0
wmc 300

33 Methods

Rating   Name   Duplication   Size   Complexity  
A initAsSpecimen() 0 17 1
B getNextNumRef() 0 51 6
B fetchLog() 0 66 6
A updateBalance() 0 19 2
F update() 0 103 20
D verifDateHolidayCP() 0 70 38
A fetch_users_approver_holiday() 0 32 3
D LibStatut() 0 55 39
B addLogCP() 0 59 7
A getLibStatut() 0 3 1
F approve() 0 103 20
B fetchAll() 0 115 7
A updateConfCP() 0 14 2
A verifNbUsers() 0 5 2
A getConfCP() 0 44 5
C validate() 0 60 14
A selectStatutCP() 0 25 3
A createCPusers() 0 26 5
A getTypes() 0 27 6
B fetch() 0 73 5
C getNomUrl() 0 27 12
A getCPforUser() 0 19 4
A countActiveUsersWithoutCP() 0 11 1
C create() 0 75 17
C updateSoldeCP() 0 139 16
A getCheckOption() 0 15 3
F fetchUsers() 0 207 22
B fetchByUser() 0 118 7
A countActiveUsers() 0 10 1
C verifDateHolidayForTimestamp() 0 53 15
A deleteCPuser() 0 7 1
A __construct() 0 3 1
B delete() 0 42 8

How to fix   Complexity   

Complex Class

Complex classes like Holiday often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Holiday, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* Copyright (C) 2011		Dimitri Mouillard	<[email protected]>
3
 * Copyright (C) 2012-2014	Laurent Destailleur	<[email protected]>
4
 * Copyright (C) 2012-2016	Regis Houssin		<[email protected]>
5
 * Copyright (C) 2013		Florian Henry		<[email protected]>
6
 * Copyright (C) 2016       Juanjo Menent       <[email protected]>
7
 * Copyright (C) 2018       Frédéric France         <[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       holiday.class.php
25
 *    \ingroup    holiday
26
 *    \brief      Class file of the module paid holiday.
27
 */
28
require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
29
30
31
/**
32
 *	Class of the module paid holiday. Developed by Teclib ( http://www.teclib.com/ )
33
 */
34
class Holiday extends CommonObject
35
{
36
	/**
37
	 * @var string ID to identify managed object
38
	 */
39
	public $element='holiday';
40
41
	/**
42
	 * @var string Name of table without prefix where object is stored
43
	 */
44
	public $table_element='holiday';
45
46
	/**
47
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
	 * @var int
49
	 */
50
	public $ismultientitymanaged = 0;
51
52
	/**
53
	 * @var int Field with ID of parent key if this field has a parent
54
	 */
55
	public $fk_element = 'fk_holiday';
56
57
	public $picto = 'holiday';
58
59
	/**
60
	 * @deprecated
61
	 * @see $id
62
	 */
63
	public $rowid;
64
65
	/**
66
	 * @var int User ID
67
	 */
68
	public $fk_user;
69
70
	public $date_create='';
71
72
	/**
73
	 * @var string description
74
	 */
75
	public $description;
76
77
	public $date_debut='';			// Date start in PHP server TZ
78
	public $date_fin='';			// Date end in PHP server TZ
79
	public $date_debut_gmt='';		// Date start in GMT
80
	public $date_fin_gmt='';		// Date end in GMT
81
	public $halfday='';				// 0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
82
	public $statut='';				// 1=draft, 2=validated, 3=approved
83
84
	/**
85
     * @var int ID
86
     */
87
	public $fk_validator;
88
89
	public $date_valid='';
90
91
	/**
92
     * @var int ID
93
     */
94
	public $fk_user_valid;
95
96
	public $date_refuse='';
97
98
	/**
99
     * @var int ID
100
     */
101
	public $fk_user_refuse;
102
103
	public $date_cancel='';
104
105
	/**
106
     * @var int ID
107
     */
108
	public $fk_user_cancel;
109
110
	public $detail_refuse='';
111
112
	/**
113
     * @var int ID
114
     */
115
	public $fk_type;
116
117
	public $holiday = array();
118
	public $events = array();
119
	public $logs = array();
120
121
	public $optName = '';
122
	public $optValue = '';
123
	public $optRowid = '';
124
125
	/**
126
	 * Draft status
127
	 */
128
	const STATUS_DRAFT = 1;
129
	/**
130
	 * Validated status
131
	 */
132
	const STATUS_VALIDATED = 2;
133
	/**
134
	 * Approved
135
	 */
136
	const STATUS_APPROVED = 3;
137
	/**
138
	 * Canceled
139
	 */
140
	const STATUS_CANCELED = 4;
141
	/**
142
	 * Refused
143
	 */
144
	const STATUS_REFUSED = 5;
145
146
147
	/**
148
	 *   Constructor
149
	 *
150
	 *   @param		DoliDB		$db      Database handler
151
	 */
152
	function __construct($db)
153
	{
154
		$this->db = $db;
155
	}
156
157
158
	/**
159
	 *  Returns the reference to the following non used Order depending on the active numbering module
160
	 *  defined into HOLIDAY_ADDON
161
	 *
162
	 *	@param	Societe		$objsoc     third party object
163
	 *  @return string      			Holiday free reference
164
	 */
165
	function getNextNumRef($objsoc)
166
	{
167
		global $langs, $conf;
168
		$langs->load("order");
169
170
		if (empty($conf->global->HOLIDAY_ADDON))
171
		{
172
			$conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
173
		}
174
175
		if (! empty($conf->global->HOLIDAY_ADDON))
176
		{
177
			$mybool=false;
178
179
			$file = $conf->global->HOLIDAY_ADDON.".php";
180
			$classname = $conf->global->HOLIDAY_ADDON;
181
182
			// Include file with class
183
			$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
184
			foreach ($dirmodels as $reldir)
185
			{
186
				$dir = dol_buildpath($reldir."core/modules/holiday/");
187
188
				// Load file with numbering class (if found)
189
				$mybool|=@include_once $dir.$file;
190
			}
191
192
			if ($mybool === false)
193
			{
194
				dol_print_error('',"Failed to include file ".$file);
195
				return '';
196
			}
197
198
			$obj = new $classname();
199
			$numref = $obj->getNextValue($objsoc,$this);
200
201
			if ($numref != "")
202
			{
203
				return $numref;
204
			}
205
			else
206
			{
207
				$this->error=$obj->error;
208
				//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
209
				return "";
210
			}
211
		}
212
		else
213
		{
214
			print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
215
			return "";
216
		}
217
	}
218
219
	/**
220
	 * Update balance of vacations and check table of users for holidays is complete. If not complete.
221
	 *
222
	 * @return	int			<0 if KO, >0 if OK
223
	 */
224
	function updateBalance()
225
	{
226
		$this->db->begin();
227
228
		// Update sold of vocations
229
		$result = $this->updateSoldeCP();
230
231
		// Check nb of users into table llx_holiday_users and update with empty lines
232
		//if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
233
234
		if ($result >= 0)
235
		{
236
			$this->db->commit();
237
			return 1;
238
		}
239
		else
240
		{
241
			$this->db->rollback();
242
			return -1;
243
		}
244
	}
245
246
	/**
247
	 *   Créer un congés payés dans la base de données
248
	 *
249
	 *   @param		User	$user        	User that create
250
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
251
	 *   @return    int			         	<0 if KO, Id of created object if OK
252
	 */
253
	function create($user, $notrigger=0)
254
	{
255
		global $conf;
256
		$error=0;
257
258
		$now=dol_now();
259
260
		// Check parameters
261
		if (empty($this->fk_user) || ! is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error="ErrorBadParameterFkUser"; return -1; }
262
		if (empty($this->fk_validator) || ! is_numeric($this->fk_validator) || $this->fk_validator < 0)  { $this->error="ErrorBadParameterFkValidator"; return -1; }
263
		if (empty($this->fk_type) || ! is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error="ErrorBadParameterFkType"; return -1; }
264
265
		// Insert request
266
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
267
		$sql.= "fk_user,";
268
		$sql.= "date_create,";
269
		$sql.= "description,";
270
		$sql.= "date_debut,";
271
		$sql.= "date_fin,";
272
		$sql.= "halfday,";
273
		$sql.= "statut,";
274
		$sql.= "fk_validator,";
275
		$sql.= "fk_type,";
276
		$sql.= "fk_user_create,";
277
		$sql.= "entity";
278
		$sql.= ") VALUES (";
279
		$sql.= "'".$this->db->escape($this->fk_user)."',";
280
		$sql.= " '".$this->db->idate($now)."',";
281
		$sql.= " '".$this->db->escape($this->description)."',";
282
		$sql.= " '".$this->db->idate($this->date_debut)."',";
283
		$sql.= " '".$this->db->idate($this->date_fin)."',";
284
		$sql.= " ".$this->halfday.",";
285
		$sql.= " '1',";
286
		$sql.= " '".$this->db->escape($this->fk_validator)."',";
287
		$sql.= " ".$this->fk_type.",";
288
		$sql.= " ".$user->id.",";
289
		$sql.= " ".$conf->entity;
290
		$sql.= ")";
291
292
		$this->db->begin();
293
294
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
295
		$resql=$this->db->query($sql);
296
		if (! $resql) {
297
			$error++; $this->errors[]="Error ".$this->db->lasterror();
298
		}
299
300
		if (! $error)
301
		{
302
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
303
304
			if (! $notrigger)
305
			{
306
				// Call trigger
307
				$result=$this->call_trigger('HOLIDAY_CREATE',$user);
308
				if ($result < 0) { $error++; }
309
				// End call triggers
310
			}
311
		}
312
313
		// Commit or rollback
314
		if ($error)
315
		{
316
			foreach($this->errors as $errmsg)
317
			{
318
				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
319
				$this->error.=($this->error?', '.$errmsg:$errmsg);
320
			}
321
			$this->db->rollback();
322
			return -1*$error;
323
		}
324
		else
325
		{
326
			$this->db->commit();
327
			return $this->id;
328
		}
329
	}
330
331
332
	/**
333
	 *	Load object in memory from database
334
	 *
335
	 *  @param	int		$id         Id object
336
	 *  @param	string	$ref        Ref object
337
	 *  @return int         		<0 if KO, >0 if OK
338
	 */
339
	function fetch($id, $ref='')
340
	{
341
		global $langs;
342
343
		$sql = "SELECT";
344
		$sql.= " cp.rowid,";
345
		$sql.= " cp.ref,";
346
		$sql.= " cp.fk_user,";
347
		$sql.= " cp.date_create,";
348
		$sql.= " cp.description,";
349
		$sql.= " cp.date_debut,";
350
		$sql.= " cp.date_fin,";
351
		$sql.= " cp.halfday,";
352
		$sql.= " cp.statut,";
353
		$sql.= " cp.fk_validator,";
354
		$sql.= " cp.date_valid,";
355
		$sql.= " cp.fk_user_valid,";
356
		$sql.= " cp.date_refuse,";
357
		$sql.= " cp.fk_user_refuse,";
358
		$sql.= " cp.date_cancel,";
359
		$sql.= " cp.fk_user_cancel,";
360
		$sql.= " cp.detail_refuse,";
361
		$sql.= " cp.note_private,";
362
		$sql.= " cp.note_public,";
363
		$sql.= " cp.fk_user_create,";
364
		$sql.= " cp.fk_type,";
365
		$sql.= " cp.entity";
366
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp";
367
		if ($id > 0) $sql.= " WHERE cp.rowid = ".$id;
368
		else $sql.=" WHERE cp.ref = '".$this->db->escape($ref)."'";
369
370
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
371
		$resql=$this->db->query($sql);
372
		if ($resql)
373
		{
374
			if ($this->db->num_rows($resql))
375
			{
376
				$obj = $this->db->fetch_object($resql);
377
378
				$this->id    = $obj->rowid;
379
				$this->rowid = $obj->rowid;	// deprecated
380
				$this->ref   = ($obj->ref?$obj->ref:$obj->rowid);
381
				$this->fk_user = $obj->fk_user;
382
				$this->date_create = $this->db->jdate($obj->date_create);
383
				$this->description = $obj->description;
384
				$this->date_debut = $this->db->jdate($obj->date_debut);
385
				$this->date_fin = $this->db->jdate($obj->date_fin);
386
				$this->date_debut_gmt = $this->db->jdate($obj->date_debut,1);
387
				$this->date_fin_gmt = $this->db->jdate($obj->date_fin,1);
388
				$this->halfday = $obj->halfday;
389
				$this->statut = $obj->statut;
390
				$this->fk_validator = $obj->fk_validator;
391
				$this->date_valid = $this->db->jdate($obj->date_valid);
392
				$this->fk_user_valid = $obj->fk_user_valid;
393
				$this->date_refuse = $this->db->jdate($obj->date_refuse);
394
				$this->fk_user_refuse = $obj->fk_user_refuse;
395
				$this->date_cancel = $this->db->jdate($obj->date_cancel);
396
				$this->fk_user_cancel = $obj->fk_user_cancel;
397
				$this->detail_refuse = $obj->detail_refuse;
398
				$this->note_private = $obj->note_private;
399
				$this->note_public = $obj->note_public;
400
				$this->fk_user_create = $obj->fk_user_create;
401
				$this->fk_type = $obj->fk_type;
402
				$this->entity = $obj->entity;
403
			}
404
			$this->db->free($resql);
405
406
			return 1;
407
		}
408
		else
409
		{
410
			$this->error="Error ".$this->db->lasterror();
411
			return -1;
412
		}
413
	}
414
415
	/**
416
	 *	List holidays for a particular user or list of users
417
	 *
418
	 *  @param		int|string		$user_id    ID of user to list, or comma separated list of IDs of users to list
419
	 *  @param      string			$order      Sort order
420
	 *  @param      string			$filter     SQL Filter
421
	 *  @return     int      					-1 if KO, 1 if OK, 2 if no result
422
	 */
423
	function fetchByUser($user_id, $order='', $filter='')
424
	{
425
		global $langs, $conf;
426
427
		$sql = "SELECT";
428
		$sql.= " cp.rowid,";
429
		$sql.= " cp.ref,";
430
431
		$sql.= " cp.fk_user,";
432
		$sql.= " cp.fk_type,";
433
		$sql.= " cp.date_create,";
434
		$sql.= " cp.description,";
435
		$sql.= " cp.date_debut,";
436
		$sql.= " cp.date_fin,";
437
		$sql.= " cp.halfday,";
438
		$sql.= " cp.statut,";
439
		$sql.= " cp.fk_validator,";
440
		$sql.= " cp.date_valid,";
441
		$sql.= " cp.fk_user_valid,";
442
		$sql.= " cp.date_refuse,";
443
		$sql.= " cp.fk_user_refuse,";
444
		$sql.= " cp.date_cancel,";
445
		$sql.= " cp.fk_user_cancel,";
446
		$sql.= " cp.detail_refuse,";
447
448
		$sql.= " uu.lastname as user_lastname,";
449
		$sql.= " uu.firstname as user_firstname,";
450
		$sql.= " uu.login as user_login,";
451
		$sql.= " uu.statut as user_statut,";
452
		$sql.= " uu.photo as user_photo,";
453
454
		$sql.= " ua.lastname as validator_lastname,";
455
		$sql.= " ua.firstname as validator_firstname,";
456
		$sql.= " ua.login as validator_login,";
457
		$sql.= " ua.statut as validator_statut,";
458
		$sql.= " ua.photo as validator_photo";
459
460
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
461
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
462
		$sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack pour la recherche sur le tableau
463
		$sql.= " AND cp.fk_user IN (".$user_id.")";
464
465
		// Selection filter
466
		if(!empty($filter)) {
467
			$sql.= $filter;
468
		}
469
470
		// Order of display of the result
471
		if(!empty($order)) {
472
			$sql.= $order;
473
		}
474
475
		dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
476
		$resql=$this->db->query($sql);
477
478
		// If no SQL error
479
		if ($resql) {
480
481
			$i = 0;
482
			$tab_result = $this->holiday;
483
			$num = $this->db->num_rows($resql);
484
485
			// If no registration
486
			if(!$num) {
487
				return 2;
488
			}
489
490
			// List the records and add them to the table
491
			while($i < $num) {
492
493
				$obj = $this->db->fetch_object($resql);
494
495
				$tab_result[$i]['rowid'] = $obj->rowid;
496
				$tab_result[$i]['ref'] = ($obj->ref?$obj->ref:$obj->rowid);
497
498
				$tab_result[$i]['fk_user'] = $obj->fk_user;
499
				$tab_result[$i]['fk_type'] = $obj->fk_type;
500
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
501
				$tab_result[$i]['description'] = $obj->description;
502
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
503
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
504
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1);
505
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1);
506
				$tab_result[$i]['halfday'] = $obj->halfday;
507
				$tab_result[$i]['statut'] = $obj->statut;
508
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
509
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
510
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
511
				$tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
512
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
513
				$tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
514
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
515
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
516
517
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
518
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
519
				$tab_result[$i]['user_login'] = $obj->user_login;
520
				$tab_result[$i]['user_statut'] = $obj->user_statut;
521
				$tab_result[$i]['user_photo'] = $obj->user_photo;
522
523
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
524
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
525
				$tab_result[$i]['validator_login'] = $obj->validator_login;
526
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
527
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
528
529
				$i++;
530
			}
531
532
			// Returns 1 with the filled array
533
			$this->holiday = $tab_result;
534
			return 1;
535
		}
536
		else
537
		{
538
			// SQL Error
539
			$this->error="Error ".$this->db->lasterror();
540
			return -1;
541
		}
542
	}
543
544
	/**
545
	 *	List all holidays of all users
546
	 *
547
	 *  @param      string	$order      Sort order
548
	 *  @param      string	$filter     SQL Filter
549
	 *  @return     int      			-1 if KO, 1 if OK, 2 if no result
550
	 */
551
	function fetchAll($order,$filter)
552
	{
553
		global $langs;
554
555
		$sql = "SELECT";
556
		$sql.= " cp.rowid,";
557
		$sql.= " cp.ref,";
558
559
		$sql.= " cp.fk_user,";
560
		$sql.= " cp.fk_type,";
561
		$sql.= " cp.date_create,";
562
		$sql.= " cp.description,";
563
		$sql.= " cp.date_debut,";
564
		$sql.= " cp.date_fin,";
565
		$sql.= " cp.halfday,";
566
		$sql.= " cp.statut,";
567
		$sql.= " cp.fk_validator,";
568
		$sql.= " cp.date_valid,";
569
		$sql.= " cp.fk_user_valid,";
570
		$sql.= " cp.date_refuse,";
571
		$sql.= " cp.fk_user_refuse,";
572
		$sql.= " cp.date_cancel,";
573
		$sql.= " cp.fk_user_cancel,";
574
		$sql.= " cp.detail_refuse,";
575
576
		$sql.= " uu.lastname as user_lastname,";
577
		$sql.= " uu.firstname as user_firstname,";
578
		$sql.= " uu.login as user_login,";
579
		$sql.= " uu.statut as user_statut,";
580
		$sql.= " uu.photo as user_photo,";
581
582
		$sql.= " ua.lastname as validator_lastname,";
583
		$sql.= " ua.firstname as validator_firstname,";
584
		$sql.= " ua.login as validator_login,";
585
		$sql.= " ua.statut as validator_statut,";
586
		$sql.= " ua.photo as validator_photo";
587
588
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
589
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
590
		$sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau
591
592
		// Selection filtering
593
		if(!empty($filter)) {
594
			$sql.= $filter;
595
		}
596
597
		// order of display
598
		if(!empty($order)) {
599
			$sql.= $order;
600
		}
601
602
		dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
603
		$resql=$this->db->query($sql);
604
605
		// If no SQL error
606
		if ($resql) {
607
608
			$i = 0;
609
			$tab_result = $this->holiday;
610
			$num = $this->db->num_rows($resql);
611
612
			// If no registration
613
			if(!$num) {
614
				return 2;
615
			}
616
617
			// List the records and add them to the table
618
			while($i < $num) {
619
620
				$obj = $this->db->fetch_object($resql);
621
622
				$tab_result[$i]['rowid'] = $obj->rowid;
623
				$tab_result[$i]['ref'] = ($obj->ref?$obj->ref:$obj->rowid);
624
				$tab_result[$i]['fk_user'] = $obj->fk_user;
625
				$tab_result[$i]['fk_type'] = $obj->fk_type;
626
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
627
				$tab_result[$i]['description'] = $obj->description;
628
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
629
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
630
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1);
631
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1);
632
				$tab_result[$i]['halfday'] = $obj->halfday;
633
				$tab_result[$i]['statut'] = $obj->statut;
634
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
635
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
636
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
637
				$tab_result[$i]['date_refuse'] = $obj->date_refuse;
638
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
639
				$tab_result[$i]['date_cancel'] = $obj->date_cancel;
640
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
641
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
642
643
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
644
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
645
				$tab_result[$i]['user_login'] = $obj->user_login;
646
				$tab_result[$i]['user_statut'] = $obj->user_statut;
647
				$tab_result[$i]['user_photo'] = $obj->user_photo;
648
649
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
650
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
651
				$tab_result[$i]['validator_login'] = $obj->validator_login;
652
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
653
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
654
655
				$i++;
656
			}
657
			// Returns 1 and adds the array to the variable
658
			$this->holiday = $tab_result;
659
			return 1;
660
		}
661
		else
662
		{
663
			// SQL Error
664
			$this->error="Error ".$this->db->lasterror();
665
			return -1;
666
		}
667
	}
668
669
670
	/**
671
	 *	Validate leave request
672
	 *
673
	 *  @param	User	$user        	User that validate
674
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
675
	 *  @return int         			<0 if KO, >0 if OK
676
	 */
677
	function validate($user=null, $notrigger=0)
678
	{
679
		global $conf, $langs;
680
		$error=0;
681
682
		// Define new ref
683
		if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id))
684
		{
685
			$num = $this->getNextNumRef(null);
686
		}
687
		else
688
		{
689
			$num = $this->ref;
690
		}
691
		$this->newref = $num;
692
693
		// Update status
694
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
695
		if(!empty($this->statut) && is_numeric($this->statut)) {
696
			$sql.= " statut = ".$this->statut.",";
697
		} else {
698
			$error++;
699
		}
700
		$sql.= " ref = '".$num."'";
701
		$sql.= " WHERE rowid= ".$this->id;
702
703
		$this->db->begin();
704
705
		dol_syslog(get_class($this)."::validate", LOG_DEBUG);
706
		$resql = $this->db->query($sql);
707
		if (! $resql) {
708
			$error++; $this->errors[]="Error ".$this->db->lasterror();
709
		}
710
711
		if (! $error)
712
		{
713
			if (! $notrigger)
714
			{
715
				// Call trigger
716
				$result=$this->call_trigger('HOLIDAY_VALIDATE',$user);
717
				if ($result < 0) { $error++; }
718
				// End call triggers
719
			}
720
		}
721
722
		// Commit or rollback
723
		if ($error)
724
		{
725
			foreach($this->errors as $errmsg)
726
			{
727
				dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
728
				$this->error.=($this->error?', '.$errmsg:$errmsg);
729
			}
730
			$this->db->rollback();
731
			return -1*$error;
732
		}
733
		else
734
		{
735
			$this->db->commit();
736
			return 1;
737
		}
738
	}
739
740
741
	/**
742
	 *	Approve leave request
743
	 *
744
	 *  @param	User	$user        	User that approve
745
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
746
	 *  @return int         			<0 if KO, >0 if OK
747
	 */
748
	function approve($user=null, $notrigger=0)
749
	{
750
		global $conf, $langs;
751
		$error=0;
752
753
		// Update request
754
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
755
756
		$sql.= " description= '".$this->db->escape($this->description)."',";
757
758
		if(!empty($this->date_debut)) {
759
			$sql.= " date_debut = '".$this->db->idate($this->date_debut)."',";
760
		} else {
761
			$error++;
762
		}
763
		if(!empty($this->date_fin)) {
764
			$sql.= " date_fin = '".$this->db->idate($this->date_fin)."',";
765
		} else {
766
			$error++;
767
		}
768
		$sql.= " halfday = ".$this->halfday.",";
769
		if(!empty($this->statut) && is_numeric($this->statut)) {
770
			$sql.= " statut = ".$this->statut.",";
771
		} else {
772
			$error++;
773
		}
774
		if(!empty($this->fk_validator)) {
775
			$sql.= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
776
		} else {
777
			$error++;
778
		}
779
		if(!empty($this->date_valid)) {
780
			$sql.= " date_valid = '".$this->db->idate($this->date_valid)."',";
781
		} else {
782
			$sql.= " date_valid = NULL,";
783
		}
784
		if(!empty($this->fk_user_valid)) {
785
			$sql.= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
786
		} else {
787
			$sql.= " fk_user_valid = NULL,";
788
		}
789
		if(!empty($this->date_refuse)) {
790
			$sql.= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
791
		} else {
792
			$sql.= " date_refuse = NULL,";
793
		}
794
		if(!empty($this->fk_user_refuse)) {
795
			$sql.= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
796
		} else {
797
			$sql.= " fk_user_refuse = NULL,";
798
		}
799
		if(!empty($this->date_cancel)) {
800
			$sql.= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
801
		} else {
802
			$sql.= " date_cancel = NULL,";
803
		}
804
		if(!empty($this->fk_user_cancel)) {
805
			$sql.= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
806
		} else {
807
			$sql.= " fk_user_cancel = NULL,";
808
		}
809
		if(!empty($this->detail_refuse)) {
810
			$sql.= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
811
		} else {
812
			$sql.= " detail_refuse = NULL";
813
		}
814
815
		$sql.= " WHERE rowid= ".$this->id;
816
817
		$this->db->begin();
818
819
		dol_syslog(get_class($this)."::approve", LOG_DEBUG);
820
		$resql = $this->db->query($sql);
821
		if (! $resql) {
822
			$error++; $this->errors[]="Error ".$this->db->lasterror();
823
		}
824
825
		if (! $error)
826
		{
827
			if (! $notrigger)
828
			{
829
				// Call trigger
830
				$result=$this->call_trigger('HOLIDAY_APPROVE',$user);
831
				if ($result < 0) { $error++; }
832
				// End call triggers
833
			}
834
		}
835
836
		// Commit or rollback
837
		if ($error)
838
		{
839
			foreach($this->errors as $errmsg)
840
			{
841
				dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
842
				$this->error.=($this->error?', '.$errmsg:$errmsg);
843
			}
844
			$this->db->rollback();
845
			return -1*$error;
846
		}
847
		else
848
		{
849
			$this->db->commit();
850
			return 1;
851
		}
852
	}
853
854
	/**
855
	 *	Update database
856
	 *
857
	 *  @param	User	$user        	User that modify
858
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
859
	 *  @return int         			<0 if KO, >0 if OK
860
	 */
861
	function update($user=null, $notrigger=0)
862
	{
863
		global $conf, $langs;
864
		$error=0;
865
866
		// Update request
867
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
868
869
		$sql.= " description= '".$this->db->escape($this->description)."',";
870
871
		if(!empty($this->date_debut)) {
872
			$sql.= " date_debut = '".$this->db->idate($this->date_debut)."',";
873
		} else {
874
			$error++;
875
		}
876
		if(!empty($this->date_fin)) {
877
			$sql.= " date_fin = '".$this->db->idate($this->date_fin)."',";
878
		} else {
879
			$error++;
880
		}
881
		$sql.= " halfday = ".$this->halfday.",";
882
		if(!empty($this->statut) && is_numeric($this->statut)) {
883
			$sql.= " statut = ".$this->statut.",";
884
		} else {
885
			$error++;
886
		}
887
		if(!empty($this->fk_validator)) {
888
			$sql.= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
889
		} else {
890
			$error++;
891
		}
892
		if(!empty($this->date_valid)) {
893
			$sql.= " date_valid = '".$this->db->idate($this->date_valid)."',";
894
		} else {
895
			$sql.= " date_valid = NULL,";
896
		}
897
		if(!empty($this->fk_user_valid)) {
898
			$sql.= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
899
		} else {
900
			$sql.= " fk_user_valid = NULL,";
901
		}
902
		if(!empty($this->date_refuse)) {
903
			$sql.= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
904
		} else {
905
			$sql.= " date_refuse = NULL,";
906
		}
907
		if(!empty($this->fk_user_refuse)) {
908
			$sql.= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
909
		} else {
910
			$sql.= " fk_user_refuse = NULL,";
911
		}
912
		if(!empty($this->date_cancel)) {
913
			$sql.= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
914
		} else {
915
			$sql.= " date_cancel = NULL,";
916
		}
917
		if(!empty($this->fk_user_cancel)) {
918
			$sql.= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
919
		} else {
920
			$sql.= " fk_user_cancel = NULL,";
921
		}
922
		if(!empty($this->detail_refuse)) {
923
			$sql.= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
924
		} else {
925
			$sql.= " detail_refuse = NULL";
926
		}
927
928
		$sql.= " WHERE rowid= ".$this->id;
929
930
		$this->db->begin();
931
932
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
933
		$resql = $this->db->query($sql);
934
		if (! $resql) {
935
			$error++; $this->errors[]="Error ".$this->db->lasterror();
936
		}
937
938
		if (! $error)
939
		{
940
			if (! $notrigger)
941
			{
942
				// Call trigger
943
				$result=$this->call_trigger('HOLIDAY_MODIFY',$user);
944
				if ($result < 0) { $error++; }
945
				// End call triggers
946
			}
947
		}
948
949
		// Commit or rollback
950
		if ($error)
951
		{
952
			foreach($this->errors as $errmsg)
953
			{
954
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
955
				$this->error.=($this->error?', '.$errmsg:$errmsg);
956
			}
957
			$this->db->rollback();
958
			return -1*$error;
959
		}
960
		else
961
		{
962
			$this->db->commit();
963
			return 1;
964
		}
965
	}
966
967
968
	/**
969
	 *   Delete object in database
970
	 *
971
	 *	 @param		User	$user        	User that delete
972
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
973
	 *	 @return	int						<0 if KO, >0 if OK
974
	 */
975
	function delete($user, $notrigger=0)
976
	{
977
		global $conf, $langs;
978
		$error=0;
979
980
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
981
		$sql.= " WHERE rowid=".$this->id;
982
983
		$this->db->begin();
984
985
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
986
		$resql = $this->db->query($sql);
987
		if (! $resql) {
988
			$error++; $this->errors[]="Error ".$this->db->lasterror();
989
		}
990
991
		if (! $error)
992
		{
993
			if (! $notrigger)
994
			{
995
				// Call trigger
996
				$result=$this->call_trigger('HOLIDAY_DELETE',$user);
997
				if ($result < 0) { $error++; }
998
				// End call triggers
999
			}
1000
		}
1001
1002
		// Commit or rollback
1003
		if ($error)
1004
		{
1005
			foreach($this->errors as $errmsg)
1006
			{
1007
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1008
				$this->error.=($this->error?', '.$errmsg:$errmsg);
1009
			}
1010
			$this->db->rollback();
1011
			return -1*$error;
1012
		}
1013
		else
1014
		{
1015
			$this->db->commit();
1016
			return 1;
1017
		}
1018
	}
1019
1020
	/**
1021
	 *	Check if a user is on holiday (partially or completely) into a period.
1022
	 *  This function can be used to avoid to have 2 leave requests on same period for example.
1023
	 *  Warning: It consumes a lot of memory because it load in ->holiday all holiday of a dedicated user at each call.
1024
	 *
1025
	 * 	@param 	int		$fk_user		Id user
1026
	 * 	@param 	date	$dateStart		Start date of period to check
1027
	 * 	@param 	date	$dateEnd		End date of period to check
1028
	 *  @param	int		$halfday		Tag to define how start and end the period to check:
1029
	 *  	    						0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
1030
	 * 	@return boolean					False = New range overlap an existing holiday, True = no overlapping (is never on holiday during checked period).
1031
	 *  @see verifDateHolidayForTimestamp
1032
	 */
1033
	function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday=0)
1034
	{
1035
		$this->fetchByUser($fk_user,'','');
1036
1037
		foreach($this->holiday as $infos_CP)
1038
		{
1039
			if ($infos_CP['statut'] == 4) continue;		// ignore not validated holidays
1040
			if ($infos_CP['statut'] == 5) continue;		// ignore not validated holidays
1041
			/*
1042
			 var_dump("--");
1043
			 var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1044
			 var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1045
			 */
1046
1047
			if ($halfday == 0)
1048
			{
1049
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1050
				{
1051
					return false;
1052
				}
1053
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1054
				{
1055
					return false;
1056
				}
1057
			}
1058
			elseif ($halfday == -1)
1059
			{
1060
				// new start afternoon, new end afternoon
1061
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1062
				{
1063
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1064
				}
1065
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1066
				{
1067
					if ($dateStart < $dateEnd) return false;
1068
					if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1069
				}
1070
			}
1071
			elseif ($halfday == 1)
1072
			{
1073
				// new start morning, new end morning
1074
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1075
				{
1076
					if ($dateStart < $dateEnd) return false;
1077
					if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1078
				}
1079
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1080
				{
1081
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1082
				}
1083
			}
1084
			elseif ($halfday == 2)
1085
			{
1086
				// new start afternoon, new end morning
1087
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1088
				{
1089
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1090
				}
1091
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1092
				{
1093
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1094
				}
1095
			}
1096
			else
1097
			{
1098
				dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1099
			}
1100
		}
1101
1102
		return true;
1103
	}
1104
1105
1106
	/**
1107
	 *	Check that a user is not on holiday for a particular timestamp
1108
	 *
1109
	 * 	@param 	int			$fk_user				Id user
1110
	 *  @param	timestamp	$timestamp				Time stamp date for a day (YYYY-MM-DD) without hours  (= 12:00AM in english and not 12:00PM that is 12:00)
1111
	 *  @param	string		$status					Filter on holiday status. '-1' = no filter.
1112
	 * 	@return array								array('morning'=> ,'afternoon'=> ), Boolean is true if user is available for day timestamp.
1113
	 *  @see verifDateHolidayCP
1114
	 */
1115
	function verifDateHolidayForTimestamp($fk_user, $timestamp, $status='-1')
1116
	{
1117
		global $langs, $conf;
1118
1119
		$isavailablemorning=true;
1120
		$isavailableafternoon=true;
1121
1122
		$sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut";
1123
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1124
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
1125
		$sql.= " AND cp.fk_user = ".(int) $fk_user;
1126
		$sql.= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1127
		if ($status != '-1') $sql.=" AND cp.statut IN (".$this->db->escape($status).")";
1128
1129
		$resql = $this->db->query($sql);
1130
		if ($resql)
1131
		{
1132
			$num_rows = $this->db->num_rows($resql);	// Note, we can have 2 records if on is morning and the other one is afternoon
1133
			if ($num_rows > 0)
1134
			{
1135
				$arrayofrecord=array();
1136
				$i=0;
1137
				while ($i < $num_rows)
1138
				{
1139
					$obj = $this->db->fetch_object($resql);
1140
1141
					// Note: $obj->halfday is  0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning
1142
					$arrayofrecord[$obj->rowid]=array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday);
1143
					$i++;
1144
				}
1145
1146
				// We found a record, user is on holiday by default, so is not available is true.
1147
				$isavailablemorning = true;
1148
				foreach($arrayofrecord as $record)
1149
				{
1150
					if ($timestamp == $record['date_start'] && $record['halfday'] == 2)  continue;
1151
					if ($timestamp == $record['date_start'] && $record['halfday'] == -1) continue;
1152
					$isavailablemorning = false;
1153
					break;
1154
				}
1155
				$isavailableafternoon = true;
1156
				foreach($arrayofrecord as $record)
1157
				{
1158
					if ($timestamp == $record['date_end'] && $record['halfday'] == 2) continue;
1159
					if ($timestamp == $record['date_end'] && $record['halfday'] == 1) continue;
1160
					$isavailableafternoon = false;
1161
					break;
1162
				}
1163
			}
1164
		}
1165
		else dol_print_error($this->db);
1166
1167
		return array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon);
1168
	}
1169
1170
1171
	/**
1172
	 *	Return clicable name (with picto eventually)
1173
	 *
1174
	 *	@param	int			$withpicto					0=_No picto, 1=Includes the picto in the linkn, 2=Picto only
1175
	 *  @param  int     	$save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1176
	 *	@return	string									String with URL
1177
	 */
1178
	function getNomUrl($withpicto=0, $save_lastsearch_value=-1)
1179
	{
1180
		global $langs;
1181
1182
		$result='';
1183
1184
		$label=$langs->trans("Show").': '.$this->ref;
1185
1186
		$url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1187
1188
		//if ($option != 'nolink')
1189
		//{
1190
		// Add param to save lastsearch_values or not
1191
		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1192
		if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1193
		if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1194
		//}
1195
1196
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1197
		$linkend='</a>';
1198
1199
		$result .= $linkstart;
1200
		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $notooltip seems to be never defined.
Loading history...
1201
		if ($withpicto != 2) $result.= $this->ref;
1202
		$result .= $linkend;
1203
1204
		return $result;
1205
	}
1206
1207
1208
	/**
1209
	 *	Returns the label status
1210
	 *
1211
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1212
	 *	@return     string      		Label
1213
	 */
1214
	function getLibStatut($mode=0)
1215
	{
1216
		return $this->LibStatut($this->statut, $mode, $this->date_debut);
1217
	}
1218
1219
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1220
	/**
1221
	 *	Returns the label of a statut
1222
	 *
1223
	 *	@param      int		$statut     id statut
1224
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1225
	 *  @param		date	$startdate	Date holiday should start
1226
	 *	@return     string      		Label
1227
	 */
1228
	function LibStatut($statut, $mode=0, $startdate='')
1229
	{
1230
        // phpcs:enable
1231
		global $langs;
1232
1233
		if ($mode == 0)
1234
		{
1235
			if ($statut == 1) return $langs->trans('DraftCP');
1236
			elseif ($statut == 2) return $langs->trans('ToReviewCP');
1237
			elseif ($statut == 3) return $langs->trans('ApprovedCP');
1238
			elseif ($statut == 4) return $langs->trans('CancelCP');
1239
			elseif ($statut == 5) return $langs->trans('RefuseCP');
1240
		}
1241
		elseif ($mode == 2)
1242
		{
1243
			$pictoapproved='statut6';
1244
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
1245
			if ($statut == 1) return img_picto($langs->trans('DraftCP'),'statut0').' '.$langs->trans('DraftCP');				// Draft
1246
			elseif ($statut == 2) return img_picto($langs->trans('ToReviewCP'),'statut1').' '.$langs->trans('ToReviewCP');		// Waiting approval
1247
			elseif ($statut == 3) return img_picto($langs->trans('ApprovedCP'),$pictoapproved).' '.$langs->trans('ApprovedCP');
1248
			elseif ($statut == 4) return img_picto($langs->trans('CancelCP'),'statut5').' '.$langs->trans('CancelCP');
1249
			elseif ($statut == 5) return img_picto($langs->trans('RefuseCP'),'statut5').' '.$langs->trans('RefuseCP');
1250
		}
1251
		elseif ($mode == 3)
1252
		{
1253
			$pictoapproved='statut6';
1254
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
1255
			if ($statut == 1) return img_picto($langs->trans('DraftCP'),'statut0');
1256
			elseif ($statut == 2) return img_picto($langs->trans('ToReviewCP'),'statut1');
1257
			elseif ($statut == 3) return img_picto($langs->trans('ApprovedCP'),$pictoapproved);
1258
			elseif ($statut == 4) return img_picto($langs->trans('CancelCP'),'statut5');
1259
			elseif ($statut == 5) return img_picto($langs->trans('RefuseCP'),'statut5');
1260
		}
1261
		elseif ($mode == 5)
1262
		{
1263
			$pictoapproved='statut6';
1264
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
1265
			if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0');				// Draft
1266
			elseif ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1');		// Waiting approval
1267
			elseif ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved);
1268
			elseif ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5');
1269
			elseif ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5');
1270
		}
1271
		elseif ($mode == 6)
1272
		{
1273
			$pictoapproved='statut6';
1274
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
1275
			if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0');				// Draft
1276
			elseif ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1');		// Waiting approval
1277
			elseif ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved);
1278
			elseif ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5');
1279
			elseif ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5');
1280
		}
1281
1282
		else return $statut;
1283
	}
1284
1285
1286
	/**
1287
	 *   Affiche un select HTML des statuts de congés payés
1288
	 *
1289
	 *   @param 	int		$selected   	Id of preselected status
1290
	 *   @param		string	$htmlname		Name of HTML select field
1291
	 *   @return    string					Show select of status
1292
	 */
1293
    function selectStatutCP($selected='', $htmlname='select_statut')
1294
    {
1295
1296
		global $langs;
1297
1298
		// Liste des statuts
1299
		$name = array('DraftCP','ToReviewCP','ApprovedCP','CancelCP','RefuseCP');
1300
		$nb = count($name)+1;
1301
1302
		// Select HTML
1303
		$statut = '<select name="'.$htmlname.'" class="flat">'."\n";
1304
		$statut.= '<option value="-1">&nbsp;</option>'."\n";
1305
1306
		// Boucle des statuts
1307
		for($i=1; $i < $nb; $i++) {
1308
			if($i==$selected) {
1309
				$statut.= '<option value="'.$i.'" selected>'.$langs->trans($name[$i-1]).'</option>'."\n";
1310
			}
1311
			else {
1312
				$statut.= '<option value="'.$i.'">'.$langs->trans($name[$i-1]).'</option>'."\n";
1313
			}
1314
		}
1315
1316
		$statut.= '</select>'."\n";
1317
		print $statut;
1318
	}
1319
1320
	/**
1321
	 *  Met à jour une option du module Holiday Payés
1322
	 *
1323
	 *  @param	string	$name       name du paramètre de configuration
1324
	 *  @param	string	$value      vrai si mise à jour OK sinon faux
1325
	 *  @return boolean				ok or ko
1326
	 */
1327
    function updateConfCP($name,$value)
1328
    {
1329
1330
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1331
		$sql.= " value = '".$value."'";
1332
		$sql.= " WHERE name = '".$name."'";
1333
1334
		dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG);
1335
		$result = $this->db->query($sql);
1336
		if($result) {
1337
			return true;
1338
		}
1339
1340
		return false;
1341
	}
1342
1343
	/**
1344
	 *  Return value of a conf parameterfor leave module
1345
	 *  TODO Move this into llx_const table
1346
	 *
1347
	 *  @param	string	$name                 Name of parameter
1348
	 *  @param  string  $createifnotfound     'stringvalue'=Create entry with string value if not found. For example 'YYYYMMDDHHMMSS'.
1349
	 *  @return string      		          Value of parameter. Example: 'YYYYMMDDHHMMSS' or < 0 if error
1350
	 */
1351
	function getConfCP($name, $createifnotfound='')
1352
	{
1353
		$sql = "SELECT value";
1354
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_config";
1355
		$sql.= " WHERE name = '".$this->db->escape($name)."'";
1356
1357
		dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1358
		$result = $this->db->query($sql);
1359
1360
		if($result) {
1361
1362
			$obj = $this->db->fetch_object($result);
1363
			// Return value
1364
			if (empty($obj))
1365
			{
1366
				if ($createifnotfound)
1367
				{
1368
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1369
					$sql.= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1370
					$result = $this->db->query($sql);
1371
					if ($result)
1372
					{
1373
						return $createifnotfound;
1374
					}
1375
					else
1376
					{
1377
						$this->error=$this->db->lasterror();
1378
						return -2;
1379
					}
1380
				}
1381
				else
1382
				{
1383
					return '';
1384
				}
1385
			}
1386
			else
1387
			{
1388
				return $obj->value;
1389
			}
1390
		} else {
1391
1392
			// Erreur SQL
1393
			$this->error=$this->db->lasterror();
1394
			return -1;
1395
		}
1396
	}
1397
1398
	/**
1399
	 *	Met à jour le timestamp de la dernière mise à jour du solde des CP
1400
	 *
1401
	 *	@param		int		$userID		Id of user
1402
	 *	@param		int		$nbHoliday	Nb of days
1403
	 *  @param		int		$fk_type	Type of vacation
1404
	 *  @return     int					0=Nothing done, 1=OK, -1=KO
1405
	 */
1406
	function updateSoldeCP($userID='',$nbHoliday='', $fk_type='')
1407
	{
1408
		global $user, $langs;
1409
1410
		$error = 0;
1411
1412
		if (empty($userID) && empty($nbHoliday) && empty($fk_type))
1413
		{
1414
			$langs->load("holiday");
1415
1416
			// Si mise à jour pour tout le monde en début de mois
1417
			$now=dol_now();
1418
1419
			$month = date('m',$now);
1420
			$newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S');
1421
1422
			// Get month of last update
1423
			$lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate);
1424
			$monthLastUpdate = $lastUpdate[4].$lastUpdate[5];
1425
			//print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit;
1426
1427
			// Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp
1428
			if ($month != $monthLastUpdate)
1429
			{
1430
				$this->db->begin();
1431
1432
				$users = $this->fetchUsers(false,false);
1433
				$nbUser = count($users);
1434
1435
				$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1436
				$sql.= " value = '".$this->db->escape($newdateforlastupdate)."'";
1437
				$sql.= " WHERE name = 'lastUpdate'";
1438
				$result = $this->db->query($sql);
1439
1440
				$typeleaves=$this->getTypes(1,1);
1441
				foreach($typeleaves as $key => $val)
1442
				{
1443
					// On ajoute x jours à chaque utilisateurs
1444
					$nb_holiday = $val['newByMonth'];
1445
					if (empty($nb_holiday)) $nb_holiday=0;
1446
1447
					if ($nb_holiday > 0)
1448
					{
1449
						dol_syslog("We update leavefor everybody for type ".$key, LOG_DEBUG);
1450
1451
						$i = 0;
1452
						while ($i < $nbUser)
1453
						{
1454
							$now_holiday = $this->getCPforUser($users[$i]['rowid'], $val['rowid']);
1455
							$new_solde = $now_holiday + $nb_holiday;
1456
1457
							// We add a log for each user
1458
							$this->addLogCP($user->id, $users[$i]['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $new_solde, $val['rowid']);
1459
1460
							$i++;
1461
						}
1462
1463
						// Now we update counter for all users at once
1464
						$sql2 = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1465
						$sql2.= " nb_holiday = nb_holiday + ".$nb_holiday;
1466
						$sql2.= " WHERE fk_type = ".$val['rowid'];
1467
1468
						$result= $this->db->query($sql2);
1469
1470
						if (! $result)
1471
						{
1472
							dol_print_error($this->db);
1473
							break;
1474
						}
1475
					}
1476
					else dol_syslog("No change for leave of type ".$key, LOG_DEBUG);
1477
				}
1478
1479
				if ($result)
1480
				{
1481
					$this->db->commit();
1482
					return 1;
1483
				}
1484
				else
1485
				{
1486
					$this->db->rollback();
1487
					return -1;
1488
				}
1489
			}
1490
1491
			return 0;
1492
		}
1493
		else
1494
		{
1495
			// Mise à jour pour un utilisateur
1496
			$nbHoliday = price2num($nbHoliday,5);
1497
1498
			$sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1499
			$sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type;
1500
			$resql = $this->db->query($sql);
1501
			if ($resql)
1502
			{
1503
				$num = $this->db->num_rows($resql);
1504
1505
				if ($num > 0)
1506
				{
1507
					// Update for user
1508
					$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1509
					$sql.= " nb_holiday = ".$nbHoliday;
1510
					$sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type;
1511
					$result = $this->db->query($sql);
1512
					if (! $result)
1513
					{
1514
						$error++;
1515
						$this->errors[]=$this->db->lasterror();
1516
					}
1517
				}
1518
				else
1519
				{
1520
					// Insert for user
1521
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1522
					$sql.= $nbHoliday;
1523
					$sql.= ", '".$userID."', ".$fk_type.")";
1524
					$result = $this->db->query($sql);
1525
					if (! $result)
1526
					{
1527
						$error++;
1528
						$this->errors[]=$this->db->lasterror();
1529
					}
1530
				}
1531
			}
1532
			else
1533
			{
1534
				$this->errors[]=$this->db->lasterror();
1535
				$error++;
1536
			}
1537
1538
			if (! $error)
1539
			{
1540
				return 1;
1541
			}
1542
			else
1543
			{
1544
				return -1;
1545
			}
1546
		}
1547
	}
1548
1549
	/**
1550
	 *	Retourne un checked si vrai
1551
	 *
1552
	 *  @param	string	$name       name du paramètre de configuration
1553
	 *  @return string      		retourne checked si > 0
1554
	 */
1555
    function getCheckOption($name)
1556
    {
1557
1558
		$sql = "SELECT value";
1559
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_config";
1560
		$sql.= " WHERE name = '".$name."'";
1561
1562
		$result = $this->db->query($sql);
1563
1564
		if($result) {
1565
			$obj = $this->db->fetch_object($result);
1566
1567
			// Si la valeur est 1 on retourne checked
1568
			if($obj->value) {
1569
				return 'checked';
1570
			}
1571
		}
1572
	}
1573
1574
1575
	/**
1576
	 *  Créer les entrées pour chaque utilisateur au moment de la configuration
1577
	 *
1578
	 *  @param	boolean		$single		Single
1579
	 *  @param	int			$userid		Id user
1580
	 *  @return void
1581
	 */
1582
	function createCPusers($single=false,$userid='')
1583
	{
1584
		// Si c'est l'ensemble des utilisateurs à ajouter
1585
		if (! $single)
1586
		{
1587
			dol_syslog(get_class($this).'::createCPusers');
1588
			$arrayofusers = $this->fetchUsers(false,true);
1589
1590
			foreach($arrayofusers as $users)
0 ignored issues
show
Bug introduced by
The expression $arrayofusers of type integer is not traversable.
Loading history...
1591
			{
1592
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1593
				$sql.= " (fk_user, nb_holiday)";
1594
				$sql.= " VALUES ('".$users['rowid']."','0')";
1595
1596
				$resql=$this->db->query($sql);
1597
				if (! $resql) dol_print_error($this->db);
1598
			}
1599
		}
1600
		else
1601
		{
1602
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1603
			$sql.= " (fk_user, nb_holiday)";
1604
			$sql.= " VALUES ('".$userid."','0')";
1605
1606
			$resql=$this->db->query($sql);
1607
			if (! $resql) dol_print_error($this->db);
1608
		}
1609
	}
1610
1611
	/**
1612
	 *  Supprime un utilisateur du module Congés Payés
1613
	 *
1614
	 *  @param	int		$user_id        ID de l'utilisateur à supprimer
1615
	 *  @return boolean      			Vrai si pas d'erreur, faut si Erreur
1616
	 */
1617
    function deleteCPuser($user_id)
1618
    {
1619
1620
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users";
1621
		$sql.= " WHERE fk_user = '".$user_id."'";
1622
1623
		$this->db->query($sql);
1624
	}
1625
1626
1627
	/**
1628
	 *  Retourne le solde de congés payés pour un utilisateur
1629
	 *
1630
	 *  @param	int		$user_id    ID de l'utilisateur
1631
	 *  @param	int		$fk_type	Filter on type
1632
	 *  @return float        		Retourne le solde de congés payés de l'utilisateur
1633
	 */
1634
	function getCPforUser($user_id, $fk_type=0)
1635
	{
1636
		$sql = "SELECT nb_holiday";
1637
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users";
1638
		$sql.= " WHERE fk_user = '".$user_id."'";
1639
		if ($fk_type > 0) $sql.=" AND fk_type = ".$fk_type;
1640
1641
		dol_syslog(get_class($this).'::getCPforUser', LOG_DEBUG);
1642
		$result = $this->db->query($sql);
1643
		if($result)
1644
		{
1645
			$obj = $this->db->fetch_object($result);
1646
			//return number_format($obj->nb_holiday,2);
1647
			if ($obj) return $obj->nb_holiday;
1648
			else return null;
1649
		}
1650
		else
1651
		{
1652
			return null;
1653
		}
1654
	}
1655
1656
	/**
1657
	 *    Get list of Users or list of vacation balance.
1658
	 *
1659
	 *    @param      boolean			$stringlist	    If true return a string list of id. If false, return an array with detail.
1660
	 *    @param      boolean   		$type			If true, read Dolibarr user list, if false, return vacation balance list.
1661
	 *    @param      string            $filters        Filters
1662
	 *    @return     array|string|int      			Return an array
1663
	 */
1664
	function fetchUsers($stringlist=true, $type=true, $filters='')
1665
	{
1666
		global $conf;
1667
1668
		dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1669
1670
		if ($stringlist)
1671
		{
1672
			if ($type)
1673
			{
1674
				// Si utilisateur de Dolibarr
1675
1676
				$sql = "SELECT u.rowid";
1677
				$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1678
1679
				if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1680
				{
1681
					$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1682
					$sql.= " WHERE (ug.fk_user = u.rowid";
1683
					$sql.= " AND ug.entity = ".$conf->entity.")";
1684
					$sql.= " OR u.admin = 1";
1685
				}
1686
				else
1687
				{
1688
					$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1689
				}
1690
				$sql.= " AND u.statut > 0";
1691
				if ($filters) $sql.=$filters;
1692
1693
				$resql=$this->db->query($sql);
1694
1695
				// Si pas d'erreur SQL
1696
				if ($resql) {
1697
1698
					$i = 0;
1699
					$num = $this->db->num_rows($resql);
1700
					$stringlist = '';
1701
1702
					// Boucles du listage des utilisateurs
1703
					while($i < $num)
1704
					{
1705
						$obj = $this->db->fetch_object($resql);
1706
1707
						if ($i == 0) {
1708
							$stringlist.= $obj->rowid;
1709
						} else {
1710
							$stringlist.= ', '.$obj->rowid;
1711
						}
1712
1713
						$i++;
1714
					}
1715
					// Retoune le tableau des utilisateurs
1716
					return $stringlist;
1717
				}
1718
				else
1719
				{
1720
					// Erreur SQL
1721
					$this->error="Error ".$this->db->lasterror();
1722
					return -1;
1723
				}
1724
			}
1725
			else
1726
			{
1727
				// We want only list of vacation balance for user ids
1728
				$sql = "SELECT DISTINCT cpu.fk_user";
1729
				$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1730
				$sql.= " WHERE cpu.fk_user = u.user";
1731
				if ($filters) $sql.=$filters;
1732
1733
				$resql=$this->db->query($sql);
1734
1735
				// Si pas d'erreur SQL
1736
				if ($resql) {
1737
1738
					$i = 0;
1739
					$num = $this->db->num_rows($resql);
1740
					$stringlist = '';
1741
1742
					// Boucles du listage des utilisateurs
1743
					while($i < $num)
1744
					{
1745
						$obj = $this->db->fetch_object($resql);
1746
1747
						if($i == 0) {
1748
							$stringlist.= $obj->fk_user;
1749
						} else {
1750
							$stringlist.= ', '.$obj->fk_user;
1751
						}
1752
1753
						$i++;
1754
					}
1755
					// Retoune le tableau des utilisateurs
1756
					return $stringlist;
1757
				}
1758
				else
1759
				{
1760
					// Erreur SQL
1761
					$this->error="Error ".$this->db->lasterror();
1762
					return -1;
1763
				}
1764
			}
1765
		}
1766
		else
1767
		{ // Si faux donc return array
1768
1769
			// List for Dolibarr users
1770
			if ($type)
1771
			{
1772
				$sql = "SELECT u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1773
				$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1774
1775
				if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1776
				{
1777
					$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1778
					$sql.= " WHERE (ug.fk_user = u.rowid";
1779
					$sql.= " AND ug.entity = ".$conf->entity.")";
1780
					$sql.= " OR u.admin = 1";
1781
				}
1782
				else
1783
					$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1784
1785
					$sql.= " AND u.statut > 0";
1786
					if ($filters) $sql.=$filters;
1787
1788
					$resql=$this->db->query($sql);
1789
1790
					// Si pas d'erreur SQL
1791
					if ($resql)
1792
					{
1793
						$i = 0;
1794
						$tab_result = $this->holiday;
1795
						$num = $this->db->num_rows($resql);
1796
1797
						// Boucles du listage des utilisateurs
1798
						while($i < $num) {
1799
1800
							$obj = $this->db->fetch_object($resql);
1801
1802
							$tab_result[$i]['rowid'] = $obj->rowid;
1803
							$tab_result[$i]['name'] = $obj->lastname;       // deprecated
1804
							$tab_result[$i]['lastname'] = $obj->lastname;
1805
							$tab_result[$i]['firstname'] = $obj->firstname;
1806
							$tab_result[$i]['gender'] = $obj->gender;
1807
							$tab_result[$i]['status'] = $obj->statut;
1808
							$tab_result[$i]['employee'] = $obj->employee;
1809
							$tab_result[$i]['photo'] = $obj->photo;
1810
							$tab_result[$i]['fk_user'] = $obj->fk_user;
1811
							//$tab_result[$i]['type'] = $obj->type;
1812
							//$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1813
1814
							$i++;
1815
						}
1816
						// Retoune le tableau des utilisateurs
1817
						return $tab_result;
1818
					}
1819
					else
1820
					{
1821
						// Erreur SQL
1822
						$this->errors[]="Error ".$this->db->lasterror();
1823
						return -1;
1824
					}
1825
			}
1826
			else
1827
			{
1828
				// List of vacation balance users
1829
				$sql = "SELECT cpu.fk_user, cpu.fk_type, cpu.nb_holiday, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1830
				$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1831
				$sql.= " WHERE cpu.fk_user = u.rowid";
1832
				if ($filters) $sql.=$filters;
1833
1834
				$resql=$this->db->query($sql);
1835
1836
				// Si pas d'erreur SQL
1837
				if ($resql)
1838
				{
1839
					$i = 0;
1840
					$tab_result = $this->holiday;
1841
					$num = $this->db->num_rows($resql);
1842
1843
					// Boucles du listage des utilisateurs
1844
					while($i < $num)
1845
					{
1846
						$obj = $this->db->fetch_object($resql);
1847
1848
						$tab_result[$i]['rowid'] = $obj->fk_user;
1849
						$tab_result[$i]['name'] = $obj->lastname;			// deprecated
1850
						$tab_result[$i]['lastname'] = $obj->lastname;
1851
						$tab_result[$i]['firstname'] = $obj->firstname;
1852
						$tab_result[$i]['gender'] = $obj->gender;
1853
						$tab_result[$i]['status'] = $obj->statut;
1854
						$tab_result[$i]['employee'] = $obj->employee;
1855
						$tab_result[$i]['photo'] = $obj->photo;
1856
						$tab_result[$i]['fk_user'] = $obj->fk_user;
1857
1858
						$tab_result[$i]['type'] = $obj->type;
1859
						$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1860
1861
						$i++;
1862
					}
1863
					// Retoune le tableau des utilisateurs
1864
					return $tab_result;
1865
				}
1866
				else
1867
				{
1868
					// Erreur SQL
1869
					$this->error="Error ".$this->db->lasterror();
1870
					return -1;
1871
				}
1872
			}
1873
		}
1874
	}
1875
1876
1877
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1878
	/**
1879
	 * Return list of people with permission to validate leave requests.
1880
	 * Search for permission "approve leave requests"
1881
	 *
1882
	 * @return  array       Array of user ids
1883
	 */
1884
	function fetch_users_approver_holiday()
1885
	{
1886
        // phpcs:enable
1887
		$users_validator=array();
1888
1889
		$sql = "SELECT DISTINCT ur.fk_user";
1890
		$sql.= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1891
		$sql.= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'";                                              // Permission 'Approve';
1892
		$sql.= "UNION";
1893
		$sql.= " SELECT DISTINCT ugu.fk_user";
1894
		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1895
		$sql.= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'";       // Permission 'Approve';
1896
		//print $sql;
1897
1898
		dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
1899
		$result = $this->db->query($sql);
1900
		if($result)
1901
		{
1902
			$num_lignes = $this->db->num_rows($result); $i = 0;
1903
			while ($i < $num_lignes)
1904
			{
1905
				$objp = $this->db->fetch_object($result);
1906
				array_push($users_validator,$objp->fk_user);
1907
				$i++;
1908
			}
1909
			return $users_validator;
1910
		}
1911
		else
1912
		{
1913
			$this->error=$this->db->lasterror();
1914
			dol_syslog(get_class($this)."::fetch_users_approver_holiday  Error ".$this->error, LOG_ERR);
1915
			return -1;
1916
		}
1917
	}
1918
1919
1920
	/**
1921
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr
1922
	 *
1923
	 *  @return     int      retourne le nombre d'utilisateur
1924
	 */
1925
	function countActiveUsers()
1926
	{
1927
		$sql = "SELECT count(u.rowid) as compteur";
1928
		$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1929
		$sql.= " WHERE u.statut > 0";
1930
1931
		$result = $this->db->query($sql);
1932
		$objet = $this->db->fetch_object($result);
1933
1934
		return $objet->compteur;
1935
	}
1936
	/**
1937
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr sans CP
1938
	 *
1939
	 *  @return     int      retourne le nombre d'utilisateur
1940
	 */
1941
    function countActiveUsersWithoutCP()
1942
    {
1943
1944
		$sql = "SELECT count(u.rowid) as compteur";
1945
		$sql.= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
1946
		$sql.= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
1947
1948
		$result = $this->db->query($sql);
1949
		$objet = $this->db->fetch_object($result);
1950
1951
		return $objet->compteur;
1952
	}
1953
1954
	/**
1955
	 *  Compare le nombre d'utilisateur actif de Dolibarr à celui des utilisateurs des congés payés
1956
	 *
1957
	 *  @param    int	$userDolibarrWithoutCP	Number of active users in Dolibarr without holidays
1958
	 *  @param    int	$userCP    				Number of active users into table of holidays
1959
	 *  @return   int							<0 if KO, >0 if OK
1960
	 */
1961
	function verifNbUsers($userDolibarrWithoutCP, $userCP)
1962
	{
1963
		if (empty($userCP)) $userCP=0;
1964
		dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
1965
		return 1;
1966
	}
1967
1968
1969
	/**
1970
	 * addLogCP
1971
	 *
1972
	 * @param 	int		$fk_user_action		Id user creation
1973
	 * @param 	int		$fk_user_update		Id user update
1974
	 * @param 	string	$label				Label
1975
	 * @param 	int		$new_solde			New value
1976
	 * @param	int		$fk_type			Type of vacation
1977
	 * @return 	int							Id of record added, 0 if nothing done, < 0 if KO
1978
	 */
1979
	function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
1980
	{
1981
		global $conf, $langs;
1982
1983
		$error=0;
1984
1985
		$prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5);
1986
		$new_solde = price2num($new_solde, 5);
1987
		//print "$prev_solde == $new_solde";
1988
1989
		if ($prev_solde == $new_solde) return 0;
1990
1991
		$this->db->begin();
1992
1993
		// Insert request
1994
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
1995
		$sql.= "date_action,";
1996
		$sql.= "fk_user_action,";
1997
		$sql.= "fk_user_update,";
1998
		$sql.= "type_action,";
1999
		$sql.= "prev_solde,";
2000
		$sql.= "new_solde,";
2001
		$sql.= "fk_type";
2002
		$sql.= ") VALUES (";
2003
		$sql.= " '".$this->db->idate(dol_now())."',";
2004
		$sql.= " '".$fk_user_action."',";
2005
		$sql.= " '".$fk_user_update."',";
2006
		$sql.= " '".$this->db->escape($label)."',";
2007
		$sql.= " '".$prev_solde."',";
2008
		$sql.= " '".$new_solde."',";
2009
		$sql.= " ".$fk_type;
2010
		$sql.= ")";
2011
2012
		$resql=$this->db->query($sql);
2013
		if (! $resql)
2014
		{
2015
			$error++; $this->errors[]="Error ".$this->db->lasterror();
2016
		}
2017
2018
		if (! $error)
2019
		{
2020
			$this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
2021
		}
2022
2023
		// Commit or rollback
2024
		if ($error)
2025
		{
2026
			foreach($this->errors as $errmsg)
2027
			{
2028
				dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
2029
				$this->error.=($this->error?', '.$errmsg:$errmsg);
2030
			}
2031
			$this->db->rollback();
2032
			return -1*$error;
2033
		}
2034
		else
2035
		{
2036
			$this->db->commit();
2037
			return $this->optRowid;
2038
		}
2039
	}
2040
2041
	/**
2042
	 *  Liste le log des congés payés
2043
	 *
2044
	 *  @param	string	$order      Filtrage par ordre
2045
	 *  @param  string	$filter     Filtre de séléction
2046
	 *  @return int         		-1 si erreur, 1 si OK et 2 si pas de résultat
2047
	 */
2048
	function fetchLog($order,$filter)
2049
	{
2050
		global $langs;
2051
2052
		$sql = "SELECT";
2053
		$sql.= " cpl.rowid,";
2054
		$sql.= " cpl.date_action,";
2055
		$sql.= " cpl.fk_user_action,";
2056
		$sql.= " cpl.fk_user_update,";
2057
		$sql.= " cpl.type_action,";
2058
		$sql.= " cpl.prev_solde,";
2059
		$sql.= " cpl.new_solde,";
2060
		$sql.= " cpl.fk_type";
2061
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
2062
		$sql.= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
2063
2064
		// Filtrage de séléction
2065
		if(!empty($filter)) {
2066
			$sql.= " ".$filter;
2067
		}
2068
2069
		// Ordre d'affichage
2070
		if(!empty($order)) {
2071
			$sql.= " ".$order;
2072
		}
2073
2074
		dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
2075
		$resql=$this->db->query($sql);
2076
2077
		// Si pas d'erreur SQL
2078
		if ($resql) {
2079
2080
			$i = 0;
2081
			$tab_result = $this->logs;
2082
			$num = $this->db->num_rows($resql);
2083
2084
			// Si pas d'enregistrement
2085
			if(!$num) {
2086
				return 2;
2087
			}
2088
2089
			// On liste les résultats et on les ajoutent dans le tableau
2090
			while($i < $num) {
2091
2092
				$obj = $this->db->fetch_object($resql);
2093
2094
				$tab_result[$i]['rowid'] = $obj->rowid;
2095
				$tab_result[$i]['date_action'] = $obj->date_action;
2096
				$tab_result[$i]['fk_user_action'] = $obj->fk_user_action;
2097
				$tab_result[$i]['fk_user_update'] = $obj->fk_user_update;
2098
				$tab_result[$i]['type_action'] = $obj->type_action;
2099
				$tab_result[$i]['prev_solde'] = $obj->prev_solde;
2100
				$tab_result[$i]['new_solde'] = $obj->new_solde;
2101
				$tab_result[$i]['fk_type'] = $obj->fk_type;
2102
2103
				$i++;
2104
			}
2105
			// Retourne 1 et ajoute le tableau à la variable
2106
			$this->logs = $tab_result;
2107
			return 1;
2108
		}
2109
		else
2110
		{
2111
			// Erreur SQL
2112
			$this->error="Error ".$this->db->lasterror();
2113
			return -1;
2114
		}
2115
	}
2116
2117
2118
	/**
2119
	 *  Return array with list of types
2120
	 *
2121
	 *  @param		int		$active		Status of type. -1 = Both
2122
	 *  @param		int		$affect		Filter on affect (a request will change sold or not). -1 = Both
2123
	 *  @return     array	    		Return array with list of types
2124
	 */
2125
	function getTypes($active=-1, $affect=-1)
2126
	{
2127
		global $mysoc;
2128
2129
		$sql = "SELECT rowid, code, label, affect, delay, newByMonth";
2130
		$sql.= " FROM " . MAIN_DB_PREFIX . "c_holiday_types";
2131
		$sql.= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')';
2132
		if ($active >= 0) $sql.=" AND active = ".((int) $active);
2133
		if ($affect >= 0) $sql.=" AND affect = ".((int) $affect);
2134
2135
		$result = $this->db->query($sql);
2136
		if ($result)
2137
		{
2138
			$num = $this->db->num_rows($result);
2139
			if ($num)
2140
			{
2141
				while ($obj = $this->db->fetch_object($result))
2142
				{
2143
					$types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth);
2144
				}
2145
2146
				return $types;
2147
			}
2148
		}
2149
		else dol_print_error($this->db);
2150
2151
		return array();
2152
	}
2153
2154
2155
	/**
2156
	 *  Initialise an instance with random values.
2157
	 *  Used to build previews or test instances.
2158
	 *	id must be 0 if object instance is a specimen.
2159
	 *
2160
	 *  @return	void
2161
	 */
2162
	function initAsSpecimen()
2163
	{
2164
		global $user,$langs;
2165
2166
		// Initialise parameters
2167
		$this->id=0;
2168
		$this->specimen=1;
2169
2170
		$this->fk_user=1;
2171
		$this->description='SPECIMEN description';
2172
		$this->date_debut=dol_now();
2173
		$this->date_fin=dol_now()+(24*3600);
2174
		$this->date_valid=dol_now();
2175
		$this->fk_validator=1;
2176
		$this->halfday=0;
2177
		$this->fk_type=1;
2178
		$this->statut=Holiday::STATUS_VALIDATED;
2179
	}
2180
}
2181