Passed
Branch develop (eee49b)
by
unknown
28:04
created

Holiday::addLogCP()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 57
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 37
nc 17
nop 5
dl 0
loc 57
rs 8.3946
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

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